{"hunk": {"id": 0, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-apollo/server/main.js", "type": "replace", "edit_start_line_idx": 24}, "file": "import { Meteor } from 'meteor/meteor';\nimport { LinksCollection } from '/imports/api/links';\n\nasync function insertLink({ title, url }) {\n await LinksCollection.insertAsync({ title, url, createdAt: new Date() });\n}\n\nMeteor.startup(async () => {\n // If the Links collection is empty, add some data.\n if (LinksCollection.find().count() === 0) {\n await insertLink({\n title: 'Do the Tutorial',\n url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n });\n\n await insertLink({\n title: 'Follow the Guide',\n url: 'http://guide.meteor.com',\n });\n\n await insertLink({\n title: 'Read the Docs',\n url: 'https://docs.meteor.com',\n });\n\n await insertLink({\n title: 'Discussions',\n url: 'https://forums.meteor.com',\n });\n }\n});\n", "file_path": "tools/static-assets/skel-typescript/server/main.ts", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.9900028705596924, 0.2479565590620041, 0.0001766245113685727, 0.0008233974222093821, 0.4284208118915558]} {"hunk": {"id": 0, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-apollo/server/main.js", "type": "replace", "edit_start_line_idx": 24}, "file": "import {LooseParser} from \"./state\"\nimport {isDummy} from \"./parseutil\"\nimport {getLineInfo, tokTypes as tt} from \"../index\"\n\nconst lp = LooseParser.prototype\n\nlp.parseTopLevel = function() {\n let node = this.startNodeAt(this.options.locations ? [0, getLineInfo(this.input, 0)] : 0)\n node.body = []\n while (this.tok.type !== tt.eof) node.body.push(this.parseStatement())\n this.last = this.tok\n if (this.options.ecmaVersion >= 6) {\n node.sourceType = this.options.sourceType\n }\n return this.finishNode(node, \"Program\")\n}\n\nlp.parseStatement = function() {\n let starttype = this.tok.type, node = this.startNode(), kind\n\n if (this.toks.isLet()) {\n starttype = tt._var\n kind = \"let\"\n }\n\n switch (starttype) {\n case tt._break: case tt._continue:\n this.next()\n let isBreak = starttype === tt._break\n if (this.semicolon() || this.canInsertSemicolon()) {\n node.label = null\n } else {\n node.label = this.tok.type === tt.name ? this.parseIdent() : null\n this.semicolon()\n }\n return this.finishNode(node, isBreak ? \"BreakStatement\" : \"ContinueStatement\")\n\n case tt._debugger:\n this.next()\n this.semicolon()\n return this.finishNode(node, \"DebuggerStatement\")\n\n case tt._do:\n this.next()\n node.body = this.parseStatement()\n node.test = this.eat(tt._while) ? this.parseParenExpression() : this.dummyIdent()\n this.semicolon()\n return this.finishNode(node, \"DoWhileStatement\")\n\n case tt._for:\n this.next()\n this.pushCx()\n this.expect(tt.parenL)\n if (this.tok.type === tt.semi) return this.parseFor(node, null)\n let isLet = this.toks.isLet()\n if (isLet || this.tok.type === tt._var || this.tok.type === tt._const) {\n let init = this.parseVar(true, isLet ? \"let\" : this.tok.value)\n if (init.declarations.length === 1 && (this.tok.type === tt._in || this.isContextual(\"of\"))) {\n return this.parseForIn(node, init)\n }\n return this.parseFor(node, init)\n }\n let init = this.parseExpression(true)\n if (this.tok.type === tt._in || this.isContextual(\"of\"))\n return this.parseForIn(node, this.toAssignable(init))\n return this.parseFor(node, init)\n\n case tt._function:\n this.next()\n return this.parseFunction(node, true)\n\n case tt._if:\n this.next()\n node.test = this.parseParenExpression()\n node.consequent = this.parseStatement()\n node.alternate = this.eat(tt._else) ? this.parseStatement() : null\n return this.finishNode(node, \"IfStatement\")\n\n case tt._return:\n this.next()\n if (this.eat(tt.semi) || this.canInsertSemicolon()) node.argument = null\n else { node.argument = this.parseExpression(); this.semicolon() }\n return this.finishNode(node, \"ReturnStatement\")\n\n case tt._switch:\n let blockIndent = this.curIndent, line = this.curLineStart\n this.next()\n node.discriminant = this.parseParenExpression()\n node.cases = []\n this.pushCx()\n this.expect(tt.braceL)\n\n let cur\n while (!this.closes(tt.braceR, blockIndent, line, true)) {\n if (this.tok.type === tt._case || this.tok.type === tt._default) {\n let isCase = this.tok.type === tt._case\n if (cur) this.finishNode(cur, \"SwitchCase\")\n node.cases.push(cur = this.startNode())\n cur.consequent = []\n this.next()\n if (isCase) cur.test = this.parseExpression()\n else cur.test = null\n this.expect(tt.colon)\n } else {\n if (!cur) {\n node.cases.push(cur = this.startNode())\n cur.consequent = []\n cur.test = null\n }\n cur.consequent.push(this.parseStatement())\n }\n }\n if (cur) this.finishNode(cur, \"SwitchCase\")\n this.popCx()\n this.eat(tt.braceR)\n return this.finishNode(node, \"SwitchStatement\")\n\n case tt._throw:\n this.next()\n node.argument = this.parseExpression()\n this.semicolon()\n return this.finishNode(node, \"ThrowStatement\")\n\n case tt._try:\n this.next()\n node.block = this.parseBlock()\n node.handler = null\n if (this.tok.type === tt._catch) {\n let clause = this.startNode()\n this.next()\n this.expect(tt.parenL)\n clause.param = this.toAssignable(this.parseExprAtom(), true)\n this.expect(tt.parenR)\n clause.body = this.parseBlock()\n node.handler = this.finishNode(clause, \"CatchClause\")\n }\n node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null\n if (!node.handler && !node.finalizer) return node.block\n return this.finishNode(node, \"TryStatement\")\n\n case tt._var:\n case tt._const:\n return this.parseVar(false, kind || this.tok.value)\n\n case tt._while:\n this.next()\n node.test = this.parseParenExpression()\n node.body = this.parseStatement()\n return this.finishNode(node, \"WhileStatement\")\n\n case tt._with:\n this.next()\n node.object = this.parseParenExpression()\n node.body = this.parseStatement()\n return this.finishNode(node, \"WithStatement\")\n\n case tt.braceL:\n return this.parseBlock()\n\n case tt.semi:\n this.next()\n return this.finishNode(node, \"EmptyStatement\")\n\n case tt._class:\n return this.parseClass(true)\n\n case tt._import:\n return this.parseImport()\n\n case tt._export:\n return this.parseExport()\n\n default:\n if (this.toks.isAsyncFunction()) {\n this.next()\n this.next()\n return this.parseFunction(node, true, true)\n }\n let expr = this.parseExpression()\n if (isDummy(expr)) {\n this.next()\n if (this.tok.type === tt.eof) return this.finishNode(node, \"EmptyStatement\")\n return this.parseStatement()\n } else if (starttype === tt.name && expr.type === \"Identifier\" && this.eat(tt.colon)) {\n node.body = this.parseStatement()\n node.label = expr\n return this.finishNode(node, \"LabeledStatement\")\n } else {\n node.expression = expr\n this.semicolon()\n return this.finishNode(node, \"ExpressionStatement\")\n }\n }\n}\n\nlp.parseBlock = function() {\n let node = this.startNode()\n this.pushCx()\n this.expect(tt.braceL)\n let blockIndent = this.curIndent, line = this.curLineStart\n node.body = []\n while (!this.closes(tt.braceR, blockIndent, line, true))\n node.body.push(this.parseStatement())\n this.popCx()\n this.eat(tt.braceR)\n return this.finishNode(node, \"BlockStatement\")\n}\n\nlp.parseFor = function(node, init) {\n node.init = init\n node.test = node.update = null\n if (this.eat(tt.semi) && this.tok.type !== tt.semi) node.test = this.parseExpression()\n if (this.eat(tt.semi) && this.tok.type !== tt.parenR) node.update = this.parseExpression()\n this.popCx()\n this.expect(tt.parenR)\n node.body = this.parseStatement()\n return this.finishNode(node, \"ForStatement\")\n}\n\nlp.parseForIn = function(node, init) {\n let type = this.tok.type === tt._in ? \"ForInStatement\" : \"ForOfStatement\"\n this.next()\n node.left = init\n node.right = this.parseExpression()\n this.popCx()\n this.expect(tt.parenR)\n node.body = this.parseStatement()\n return this.finishNode(node, type)\n}\n\nlp.parseVar = function(noIn, kind) {\n let node = this.startNode()\n node.kind = kind\n this.next()\n node.declarations = []\n do {\n let decl = this.startNode()\n decl.id = this.options.ecmaVersion >= 6 ? this.toAssignable(this.parseExprAtom(), true) : this.parseIdent()\n decl.init = this.eat(tt.eq) ? this.parseMaybeAssign(noIn) : null\n node.declarations.push(this.finishNode(decl, \"VariableDeclarator\"))\n } while (this.eat(tt.comma))\n if (!node.declarations.length) {\n let decl = this.startNode()\n decl.id = this.dummyIdent()\n node.declarations.push(this.finishNode(decl, \"VariableDeclarator\"))\n }\n if (!noIn) this.semicolon()\n return this.finishNode(node, \"VariableDeclaration\")\n}\n\nlp.parseClass = function(isStatement) {\n let node = this.startNode()\n this.next()\n if (this.tok.type === tt.name) node.id = this.parseIdent()\n else if (isStatement) node.id = this.dummyIdent()\n else node.id = null\n node.superClass = this.eat(tt._extends) ? this.parseExpression() : null\n node.body = this.startNode()\n node.body.body = []\n this.pushCx()\n let indent = this.curIndent + 1, line = this.curLineStart\n this.eat(tt.braceL)\n if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart }\n while (!this.closes(tt.braceR, indent, line)) {\n if (this.semicolon()) continue\n let method = this.startNode(), isGenerator, isAsync\n if (this.options.ecmaVersion >= 6) {\n method.static = false\n isGenerator = this.eat(tt.star)\n }\n this.parsePropertyName(method)\n if (isDummy(method.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue }\n if (method.key.type === \"Identifier\" && !method.computed && method.key.name === \"static\" &&\n (this.tok.type != tt.parenL && this.tok.type != tt.braceL)) {\n method.static = true\n isGenerator = this.eat(tt.star)\n this.parsePropertyName(method)\n } else {\n method.static = false\n }\n if (!method.computed &&\n method.key.type === \"Identifier\" && method.key.name === \"async\" && this.tok.type !== tt.parenL &&\n !this.canInsertSemicolon()) {\n this.parsePropertyName(method)\n isAsync = true\n } else {\n isAsync = false\n }\n if (this.options.ecmaVersion >= 5 && method.key.type === \"Identifier\" &&\n !method.computed && (method.key.name === \"get\" || method.key.name === \"set\") &&\n this.tok.type !== tt.parenL && this.tok.type !== tt.braceL) {\n method.kind = method.key.name\n this.parsePropertyName(method)\n method.value = this.parseMethod(false)\n } else {\n if (!method.computed && !method.static && !isGenerator && !isAsync && (\n method.key.type === \"Identifier\" && method.key.name === \"constructor\" ||\n method.key.type === \"Literal\" && method.key.value === \"constructor\")) {\n method.kind = \"constructor\"\n } else {\n method.kind = \"method\"\n }\n method.value = this.parseMethod(isGenerator, isAsync)\n }\n node.body.body.push(this.finishNode(method, \"MethodDefinition\"))\n }\n this.popCx()\n if (!this.eat(tt.braceR)) {\n // If there is no closing brace, make the node span to the start\n // of the next token (this is useful for Tern)\n this.last.end = this.tok.start\n if (this.options.locations) this.last.loc.end = this.tok.loc.start\n }\n this.semicolon()\n this.finishNode(node.body, \"ClassBody\")\n return this.finishNode(node, isStatement ? \"ClassDeclaration\" : \"ClassExpression\")\n}\n\nlp.parseFunction = function(node, isStatement, isAsync) {\n let oldInAsync = this.inAsync\n this.initFunction(node)\n if (this.options.ecmaVersion >= 6) {\n node.generator = this.eat(tt.star)\n }\n if (this.options.ecmaVersion >= 8) {\n node.async = !!isAsync\n }\n if (this.tok.type === tt.name) node.id = this.parseIdent()\n else if (isStatement) node.id = this.dummyIdent()\n this.inAsync = node.async\n node.params = this.parseFunctionParams()\n node.body = this.parseBlock()\n this.inAsync = oldInAsync\n return this.finishNode(node, isStatement ? \"FunctionDeclaration\" : \"FunctionExpression\")\n}\n\nlp.parseExport = function() {\n let node = this.startNode()\n this.next()\n if (this.eat(tt.star)) {\n node.source = this.eatContextual(\"from\") ? this.parseExprAtom() : this.dummyString()\n return this.finishNode(node, \"ExportAllDeclaration\")\n }\n if (this.eat(tt._default)) {\n // export default (function foo() {}) // This is FunctionExpression.\n let isParenL = this.tok.type === tt.parenL\n let expr = this.parseMaybeAssign()\n if (!isParenL && expr.id) {\n switch (expr.type) {\n case \"FunctionExpression\": expr.type = \"FunctionDeclaration\"; break\n case \"ClassExpression\": expr.type = \"ClassDeclaration\"; break\n }\n }\n node.declaration = expr\n this.semicolon()\n return this.finishNode(node, \"ExportDefaultDeclaration\")\n }\n if (this.tok.type.keyword || this.toks.isLet() || this.toks.isAsyncFunction()) {\n node.declaration = this.parseStatement()\n node.specifiers = []\n node.source = null\n } else {\n node.declaration = null\n node.specifiers = this.parseExportSpecifierList()\n node.source = this.eatContextual(\"from\") ? this.parseExprAtom() : null\n this.semicolon()\n }\n return this.finishNode(node, \"ExportNamedDeclaration\")\n}\n\nlp.parseImport = function() {\n let node = this.startNode()\n this.next()\n if (this.tok.type === tt.string) {\n node.specifiers = []\n node.source = this.parseExprAtom()\n node.kind = ''\n } else {\n let elt\n if (this.tok.type === tt.name && this.tok.value !== \"from\") {\n elt = this.startNode()\n elt.local = this.parseIdent()\n this.finishNode(elt, \"ImportDefaultSpecifier\")\n this.eat(tt.comma)\n }\n node.specifiers = this.parseImportSpecifierList()\n node.source = this.eatContextual(\"from\") && this.tok.type == tt.string ? this.parseExprAtom() : this.dummyString()\n if (elt) node.specifiers.unshift(elt)\n }\n this.semicolon()\n return this.finishNode(node, \"ImportDeclaration\")\n}\n\nlp.parseImportSpecifierList = function() {\n let elts = []\n if (this.tok.type === tt.star) {\n let elt = this.startNode()\n this.next()\n elt.local = this.eatContextual(\"as\") ? this.parseIdent() : this.dummyIdent()\n elts.push(this.finishNode(elt, \"ImportNamespaceSpecifier\"))\n } else {\n let indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart\n this.pushCx()\n this.eat(tt.braceL)\n if (this.curLineStart > continuedLine) continuedLine = this.curLineStart\n while (!this.closes(tt.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) {\n let elt = this.startNode()\n if (this.eat(tt.star)) {\n elt.local = this.eatContextual(\"as\") ? this.parseIdent() : this.dummyIdent()\n this.finishNode(elt, \"ImportNamespaceSpecifier\")\n } else {\n if (this.isContextual(\"from\")) break\n elt.imported = this.parseIdent()\n if (isDummy(elt.imported)) break\n elt.local = this.eatContextual(\"as\") ? this.parseIdent() : elt.imported\n this.finishNode(elt, \"ImportSpecifier\")\n }\n elts.push(elt)\n this.eat(tt.comma)\n }\n this.eat(tt.braceR)\n this.popCx()\n }\n return elts\n}\n\nlp.parseExportSpecifierList = function() {\n let elts = []\n let indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart\n this.pushCx()\n this.eat(tt.braceL)\n if (this.curLineStart > continuedLine) continuedLine = this.curLineStart\n while (!this.closes(tt.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) {\n if (this.isContextual(\"from\")) break\n let elt = this.startNode()\n elt.local = this.parseIdent()\n if (isDummy(elt.local)) break\n elt.exported = this.eatContextual(\"as\") ? this.parseIdent() : elt.local\n this.finishNode(elt, \"ExportSpecifier\")\n elts.push(elt)\n this.eat(tt.comma)\n }\n this.eat(tt.braceR)\n this.popCx()\n return elts\n}\n", "file_path": "tools/tests/apps/modules/packages/modules-test-package/node_modules/acorn/src/loose/statement.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.0001788317458704114, 0.0001750691735651344, 0.00016697359387762845, 0.0001752664684318006, 2.49162894760957e-06]} {"hunk": {"id": 0, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-apollo/server/main.js", "type": "replace", "edit_start_line_idx": 24}, "file": "global.Buffer = global.Buffer || require(\"buffer\").Buffer;\nmodule.exports = require(\"crypto-browserify\");\n", "file_path": "npm-packages/meteor-node-stubs/wrappers/crypto.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.0001730589719954878, 0.0001730589719954878, 0.0001730589719954878, 0.0001730589719954878, 0.0]} {"hunk": {"id": 0, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-apollo/server/main.js", "type": "replace", "edit_start_line_idx": 24}, "file": "console.warn(\n \"The `facebook` package has been deprecated.\\n\" +\n \"\\n\" +\n \"To use the `Facebook` symbol, add the `facebook-oauth` package\\n\" +\n \"and import from it.\\n\" +\n \"\\n\" +\n \"If you need the Blaze OAuth configuration UI, add\\n\" +\n \"`facebook-config-ui` alongside `accounts-ui`.\"\n);\n", "file_path": "packages/deprecated/facebook/deprecation_notice.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00017031581955961883, 0.00017031581955961883, 0.00017031581955961883, 0.00017031581955961883, 0.0]} {"hunk": {"id": 1, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-full/imports/startup/server/fixtures.js", "type": "replace", "edit_start_line_idx": 19}, "file": "// Fill the DB with example data on startup\n\nimport { Meteor } from 'meteor/meteor';\nimport { Links } from '../../api/links/links.js';\n\nasync function insertLink({ title, url }) {\n await Links.insertAsync({ title, url, createdAt: new Date() });\n}\n\nMeteor.startup(async () => {\n // If the Links collection is empty, add some data.\n if (Links.find().count() === 0) {\n await insertLink({\n title: 'Do the Tutorial',\n url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n });\n\n await insertLink({\n title: 'Follow the Guide',\n url: 'http://guide.meteor.com',\n });\n\n await insertLink({\n title: 'Read the Docs',\n url: 'https://docs.meteor.com',\n });\n\n await insertLink({\n title: 'Discussions',\n url: 'https://forums.meteor.com',\n });\n }\n});\n", "file_path": "tools/static-assets/skel-full/imports/startup/server/fixtures.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.8406789302825928, 0.21966272592544556, 0.00017200529691763222, 0.018899967893958092, 0.3588419556617737]} {"hunk": {"id": 1, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-full/imports/startup/server/fixtures.js", "type": "replace", "edit_start_line_idx": 19}, "file": "// This exports object was created in pre.js. Now copy the `_` object from it\n// into the package-scope variable `_`, which will get exported.\n_ = exports._;\n", "file_path": "packages/underscore/post.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00017393160669598728, 0.00017393160669598728, 0.00017393160669598728, 0.00017393160669598728, 0.0]} {"hunk": {"id": 1, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-full/imports/startup/server/fixtures.js", "type": "replace", "edit_start_line_idx": 19}, "file": "import {reservedWords, keywords} from \"./identifier\"\nimport {types as tt} from \"./tokentype\"\nimport {lineBreak} from \"./whitespace\"\nimport {getOptions} from \"./options\"\n\n// Registered plugins\nexport const plugins = {}\n\nfunction keywordRegexp(words) {\n return new RegExp(\"^(\" + words.replace(/ /g, \"|\") + \")$\")\n}\n\nexport class Parser {\n constructor(options, input, startPos) {\n this.options = options = getOptions(options)\n this.sourceFile = options.sourceFile\n this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5])\n let reserved = \"\"\n if (!options.allowReserved) {\n for (let v = options.ecmaVersion;; v--)\n if (reserved = reservedWords[v]) break\n if (options.sourceType == \"module\") reserved += \" await\"\n }\n this.reservedWords = keywordRegexp(reserved)\n let reservedStrict = (reserved ? reserved + \" \" : \"\") + reservedWords.strict\n this.reservedWordsStrict = keywordRegexp(reservedStrict)\n this.reservedWordsStrictBind = keywordRegexp(reservedStrict + \" \" + reservedWords.strictBind)\n this.input = String(input)\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n this.containsEsc = false\n\n // Load plugins\n this.loadPlugins(options.plugins)\n\n // Set up token state\n\n // The current position of the tokenizer in the input.\n if (startPos) {\n this.pos = startPos\n this.lineStart = this.input.lastIndexOf(\"\\n\", startPos - 1) + 1\n this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length\n } else {\n this.pos = this.lineStart = 0\n this.curLine = 1\n }\n\n // Properties of the current token:\n // Its type\n this.type = tt.eof\n // For tokens that include more information than their type, the value\n this.value = null\n // Its start and end offset\n this.start = this.end = this.pos\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n this.startLoc = this.endLoc = this.curPosition()\n\n // Position information for the previous token\n this.lastTokEndLoc = this.lastTokStartLoc = null\n this.lastTokStart = this.lastTokEnd = this.pos\n\n // The context stack is used to superficially track syntactic\n // context to predict whether a regular expression is allowed in a\n // given position.\n this.context = this.initialContext()\n this.exprAllowed = true\n\n // Figure out if it's a module code.\n this.strict = this.inModule = options.sourceType === \"module\"\n\n // Used to signify the start of a potential arrow function\n this.potentialArrowAt = -1\n\n // Flags to track whether we are in a function, a generator, an async function.\n this.inFunction = this.inGenerator = this.inAsync = false\n // Positions to delayed-check that yield/await does not exist in default parameters.\n this.yieldPos = this.awaitPos = 0\n // Labels in scope.\n this.labels = []\n\n // If enabled, skip leading hashbang line.\n if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!')\n this.skipLineComment(2)\n }\n\n // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them\n isKeyword(word) { return this.keywords.test(word) }\n isReservedWord(word) { return this.reservedWords.test(word) }\n\n extend(name, f) {\n this[name] = f(this[name])\n }\n\n loadPlugins(pluginConfigs) {\n for (let name in pluginConfigs) {\n let plugin = plugins[name]\n if (!plugin) throw new Error(\"Plugin '\" + name + \"' not found\")\n plugin(this, pluginConfigs[name])\n }\n }\n\n parse() {\n let node = this.options.program || this.startNode()\n this.nextToken()\n return this.parseTopLevel(node)\n }\n}\n", "file_path": "tools/tests/apps/modules/packages/modules-test-package/node_modules/acorn/src/state.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.0001744582987157628, 0.00017167018086183816, 0.00016207562293857336, 0.00017266828217543662, 3.2450213893753244e-06]} {"hunk": {"id": 1, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-full/imports/startup/server/fixtures.js", "type": "replace", "edit_start_line_idx": 19}, "file": "These packages are no longer actively maintained by Meteor Software. Seek\ncommunity alternatives instead.\n\nNote that these packages still exist in atmosphere, and you can still\nbuild a package that depends on one of them by specifying an explicit\npackage version.\n", "file_path": "packages/deprecated/README", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.0001652988576097414, 0.0001652988576097414, 0.0001652988576097414, 0.0001652988576097414, 0.0]} {"hunk": {"id": 2, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-react/server/main.js", "type": "replace", "edit_start_line_idx": 17}, "file": "import { Meteor } from 'meteor/meteor';\nimport { LinksCollection } from '/imports/api/links';\n\nasync function insertLink({ title, url }) {\n await LinksCollection.insertAsync({ title, url, createdAt: new Date() });\n}\n\nMeteor.startup(async () => {\n // If the Links collection is empty, add some data.\n if (LinksCollection.find().count() === 0) {\n await insertLink({\n title: 'Do the Tutorial',\n url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n });\n\n await insertLink({\n title: 'Follow the Guide',\n url: 'http://guide.meteor.com',\n });\n\n await insertLink({\n title: 'Read the Docs',\n url: 'https://docs.meteor.com',\n });\n\n await insertLink({\n title: 'Discussions',\n url: 'https://forums.meteor.com',\n });\n }\n});\n", "file_path": "tools/static-assets/skel-typescript/server/main.ts", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.9742137789726257, 0.24511779844760895, 0.00017881147505249828, 0.0030392948538064957, 0.42094749212265015]} {"hunk": {"id": 2, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-react/server/main.js", "type": "replace", "edit_start_line_idx": 17}, "file": "{\n \"format\": \"web-program-pre1\",\n \"version\": \"127.0.0.1_root_url\",\n \"cordovaCompatibilityVersions\": {\n \"android\": \"4017747ca6b4f460f33b121e439b7a11a070205a\",\n \"ios\": \"0abe549f2adbcf6cd295428aefea628ebe69666a\"\n },\n \"manifest\": []\n}\n", "file_path": "npm-packages/cordova-plugin-meteor-webapp/tests/fixtures/downloadable_versions/127.0.0.1_root_url/manifest.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00016865019279066473, 0.00016865019279066473, 0.00016865019279066473, 0.00016865019279066473, 0.0]} {"hunk": {"id": 2, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-react/server/main.js", "type": "replace", "edit_start_line_idx": 17}, "file": "---\ntitle: logging\ndescription: Documentation of Meteor's logging utility\n---\n\nThe `logging` package provides a standartised way for you to log and display in console various message from your application.\nThe added benefit is that among other data it will show you the location where the log was fired,\nthis is useful during debugging to quickly locate where the message is coming from.\n\nStart by installing the package:\n```shell\nmeteor add logging\n```\n\nYou can then import the utility anywhere in you code like this:\n```javascript\nimport { Log } from 'meteor/logging'\n```\n\nYou can then call the logging functions in one of the following ways:\n```javascript\nLog('starting up') // or Log.info('starting up')\nLog.error('error message')\nLog.warn('warning')\nLog.debug('this will show only in development')\n```\n\nBesides passing in strings, you can also pass in objects. This has few exceptions and special functions associated.\nFirst in the root of the object the following keys are not allowed: \n```javascript\n'time', 'timeInexact', 'level', 'file', 'line', 'program', 'originApp', 'satellite', 'stderr'\n```\n\nOn the other hand there is `message` and `app`, which are also reserved, but they will display in more prominent manner:\n```javascript\nLog.info({message: 'warning', app: 'DESKTOP', error: { property1: 'foo', property2: 'bar', property3: { foo: 'bar' }} })\n```\nwill turn into:\n```shell\nE20200519-17:57:41.655(9) [DESKTOP] (main.js:36) warning {\"error\":{\"property1\":\"foo\",\"property2\":\"bar\",\"property3\":{\"foo\":\"bar\"}}}\n```\n\nThe display of each log is color coded. Info is `blue`, warn is `magenta`, debug is `green` and error is in `red`.\n\n### Log.debug\nThe `Log.debug()` logging is different from the other calls as these messages will not be displayed in production.\n", "file_path": "docs/source/packages/logging.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00022308471670839936, 0.00017867707356344908, 0.00016242775018326938, 0.0001683567970758304, 2.246811709483154e-05]} {"hunk": {"id": 2, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-react/server/main.js", "type": "replace", "edit_start_line_idx": 17}, "file": "local\n", "file_path": "tools/tests/old/empty-app/.meteor/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.0001783998595783487, 0.0001783998595783487, 0.0001783998595783487, 0.0001783998595783487, 0.0]} {"hunk": {"id": 3, "code_window": ["\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-typescript/server/main.ts", "type": "replace", "edit_start_line_idx": 17}, "file": "import { Meteor } from 'meteor/meteor';\nimport { LinksCollection } from '/imports/api/links';\n\nasync function insertLink({ title, url }) {\n await LinksCollection.insertAsync({ title, url, createdAt: new Date() });\n}\n\nMeteor.startup(async () => {\n // If the Links collection is empty, add some data.\n if (LinksCollection.find().count() === 0) {\n await insertLink({\n title: 'Do the Tutorial',\n url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n });\n\n await insertLink({\n title: 'Follow the Guide',\n url: 'http://guide.meteor.com',\n });\n\n await insertLink({\n title: 'Read the Docs',\n url: 'https://docs.meteor.com',\n });\n\n await insertLink({\n title: 'Discussions',\n url: 'https://forums.meteor.com',\n });\n }\n});\n", "file_path": "tools/static-assets/skel-typescript/server/main.ts", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.9868729114532471, 0.25498783588409424, 0.0001729601644910872, 0.016452731564641, 0.4227447807788849]} {"hunk": {"id": 3, "code_window": ["\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-typescript/server/main.ts", "type": "replace", "edit_start_line_idx": 17}, "file": "import { Meteor } from \"meteor/meteor\";\nimport { Tinytest } from \"meteor/tinytest\";\n\nTinytest.add(\"coffeescript - presence\", function(test) {\n test.isTrue(Meteor.__COFFEESCRIPT_PRESENT);\n});\nTinytest.add(\"literate coffeescript - presence\", function(test) {\n test.isTrue(Meteor.__LITCOFFEESCRIPT_PRESENT);\n test.isTrue(Meteor.__COFFEEMDSCRIPT_PRESENT);\n});\n\nTinytest.add(\"coffeescript - exported variable\", function(test) {\n test.equal(COFFEESCRIPT_EXPORTED, 123);\n test.equal(Package['coffeescript-test-helper'].COFFEESCRIPT_EXPORTED, 123);\n test.equal(COFFEESCRIPT_EXPORTED_ONE_MORE, 234);\n test.equal(Package['coffeescript-test-helper'].COFFEESCRIPT_EXPORTED_ONE_MORE, 234);\n test.equal(COFFEESCRIPT_EXPORTED_WITH_BACKTICKS, 345);\n test.equal(Package['coffeescript-test-helper'].COFFEESCRIPT_EXPORTED_WITH_BACKTICKS, 345);\n});\n", "file_path": "packages/non-core/coffeescript/tests/coffeescript_tests.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00016820388555061072, 0.00016669355682097375, 0.00016518321353942156, 0.00016669355682097375, 1.5103360055945814e-06]} {"hunk": {"id": 3, "code_window": ["\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-typescript/server/main.ts", "type": "replace", "edit_start_line_idx": 17}, "file": "import assert from \"assert\";\nimport {\n checkWhere,\n checkPackageVars,\n} from \"./common\";\n\nexport const where = \"client\";\nexport * from \"./common\";\n\ncheckWhere(where);\n\nvar style = require(\"./css/imported.css\");\nif (! style) {\n require(\"./css/not-imported.css\");\n}\n\nClientPackageVar = \"client\";\ncheckPackageVars();\n", "file_path": "tools/tests/apps/modules/packages/modules-test-package/client.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.000174667700775899, 0.00017421090160496533, 0.00017375408788211644, 0.00017421090160496533, 4.5680644689127803e-07]} {"hunk": {"id": 3, "code_window": ["\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n", " title: 'Read the Docs',\n", " url: 'https://docs.meteor.com',\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-typescript/server/main.ts", "type": "replace", "edit_start_line_idx": 17}, "file": "---\ntitle: fetch\ndescription: Isomorphic modern/legacy/Node polyfill for WHATWG fetch().\n---\n\nThis package replaces the `http` package for HTTP calls. `fetch` package provides polyfill for the [WHATWG fetch specification](https://fetch.spec.whatwg.org/) for legacy browsers or defaults to the global class which is available in modern browsers and Node. It is recomended that you use this package for compatibility with non-modern browsers.\n\nFor more information we recommend [reading the MDN articles](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) about it as this article covers only basic usage in Meteor.\n\n## Usage\n### Installation\nTo add this package to an existing app, run the following command from\nyour app directory:\n\n```bash\nmeteor add fetch\n```\n\nTo add the `fetch` package to an existing package, include the\nstatement `api.use('fetch');` in the `Package.onUse` callback in your\n`package.js` file:\n\n```js\nPackage.onUse((api) => {\n api.use('fetch');\n});\n```\n\n## API\nYou can import `fetch`, `Headers`, `Request` and `Response` classes from `meteor/fetch`.\n\n```js\nimport { fetch, Headers, Request, Response } from 'meteor/fetch';\n```\n\nFor the most part though, you will only need to import `fetch` and `Headers`.\n\n```js\nimport { Meteor } from 'meteor/meteor';\nimport { fetch, Headers } from 'meteor/fetch';\n\nasync function postData (url, data) {\n try {\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: new Headers({\n Authorization: 'Bearer my-secret-key',\n 'Content-Type': 'application/json'\n }),\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match \"Content-Type\" header\n });\n const data = await response.json();\n return response(null, data);\n } catch (err) {\n return response(error, null);\n }\n}\n\nconst postDataCall = Meteor.wrapAsync(postData);\nconst results = postDataCall('https://www.example.org/statsSubmission', { totalUsers: 55 }));\n\n```\n", "file_path": "docs/source/packages/fetch.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00022166944108903408, 0.00018316011119168252, 0.00016358164430130273, 0.00017086707521229982, 2.1016398022766225e-05]} {"hunk": {"id": 4, "code_window": [" // If the Links collection is empty, add some data.\n", " if (Links.find().count() === 0) {\n", " await insertLink({\n", " title: 'Do the Tutorial',\n", " url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://vue-tutorial.meteor.com/',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 12}, "file": "import { Meteor } from 'meteor/meteor';\nimport Links from './collections/Links.js';\n\nasync function insertLink({ title, url }) {\n await Links.insertAsync({ title, url, createdAt: new Date() });\n}\n\nMeteor.startup(async () => {\n // If the Links collection is empty, add some data.\n if (Links.find().count() === 0) {\n await insertLink({\n title: 'Do the Tutorial',\n url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n });\n\n await insertLink({\n title: 'Follow the Guide',\n url: 'http://guide.meteor.com',\n });\n\n await insertLink({\n title: 'Read the Docs',\n url: 'https://docs.meteor.com',\n });\n\n await insertLink({\n title: 'Discussions',\n url: 'https://forums.meteor.com',\n });\n }\n});\n", "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.43007317185401917, 0.17888577282428741, 0.00017486585420556366, 0.14264751970767975, 0.18443873524665833]} {"hunk": {"id": 4, "code_window": [" // If the Links collection is empty, add some data.\n", " if (Links.find().count() === 0) {\n", " await insertLink({\n", " title: 'Do the Tutorial',\n", " url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://vue-tutorial.meteor.com/',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 12}, "file": "# Meteor packages used by this project, one per line.\n#\n# 'meteor add' and 'meteor remove' will edit this file for you,\n# but you can also edit it by hand.\n\nmeteor-base\nblaze-html-templates\nlocal-plugin\nlocal-plugin-2\n", "file_path": "tools/tests/apps/minifier-plugin-multiple-minifiers-for-js/.meteor/packages", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00029693046235479414, 0.00029693046235479414, 0.00029693046235479414, 0.00029693046235479414, 0.0]} {"hunk": {"id": 4, "code_window": [" // If the Links collection is empty, add some data.\n", " if (Links.find().count() === 0) {\n", " await insertLink({\n", " title: 'Do the Tutorial',\n", " url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://vue-tutorial.meteor.com/',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 12}, "file": "var system = require('system');\nvar webpage = require('webpage');\n\nif (system.args.length < 2) {\n throw new Error(\"Must pass URL argument to this script.\");\n}\n\nconsole.log(\"opening webpage\", system.args[1]);\n\nwebpage.create().open(system.args[1]);", "file_path": "tools/tool-testing/phantom/open-url.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00017465105338487774, 0.00017302398919127882, 0.00017139691044576466, 0.00017302398919127882, 1.6270714695565403e-06]} {"hunk": {"id": 4, "code_window": [" // If the Links collection is empty, add some data.\n", " if (Links.find().count() === 0) {\n", " await insertLink({\n", " title: 'Do the Tutorial',\n", " url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://vue-tutorial.meteor.com/',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 12}, "file": "// By default, we use the permessage-deflate extension with default\n// configuration. If $SERVER_WEBSOCKET_COMPRESSION is set, then it must be valid\n// JSON. If it represents a falsey value, then we do not use permessage-deflate\n// at all; otherwise, the JSON value is used as an argument to deflate's\n// configure method; see\n// https://github.com/faye/permessage-deflate-node/blob/master/README.md\n//\n// (We do this in an _.once instead of at startup, because we don't want to\n// crash the tool during isopacket load if your JSON doesn't parse. This is only\n// a problem because the tool has to load the DDP server code just in order to\n// be a DDP client; see https://github.com/meteor/meteor/issues/3452 .)\nvar websocketExtensions = _.once(function () {\n var extensions = [];\n\n var websocketCompressionConfig = process.env.SERVER_WEBSOCKET_COMPRESSION\n ? JSON.parse(process.env.SERVER_WEBSOCKET_COMPRESSION) : {};\n if (websocketCompressionConfig) {\n extensions.push(Npm.require('permessage-deflate').configure(\n websocketCompressionConfig\n ));\n }\n\n return extensions;\n});\n\nvar pathPrefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || \"\";\n\nStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // Because we are installing directly onto WebApp.httpServer instead of using\n // WebApp.app, we have to process the path prefix ourselves.\n self.prefix = pathPrefix + '/sockjs';\n RoutePolicy.declare(self.prefix + '/', 'network');\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n var serverOptions = {\n prefix: self.prefix,\n log: function() {},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 45000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n // Set the USE_JSESSIONID environment variable to enable setting the\n // JSESSIONID cookie. This is useful for setting up proxies with\n // session affinity.\n jsessionid: !!process.env.USE_JSESSIONID\n };\n\n // If you know your server environment (eg, proxies) will prevent websockets\n // from ever working, set $DISABLE_WEBSOCKETS and SockJS clients (ie,\n // browsers) will not waste time attempting to use them.\n // (Your server will still have a /websocket endpoint.)\n if (process.env.DISABLE_WEBSOCKETS) {\n serverOptions.websocket = false;\n } else {\n serverOptions.faye_server_options = {\n extensions: websocketExtensions()\n };\n }\n\n self.server = sockjs.createServer(serverOptions);\n\n // Install the sockjs handlers, but we want to keep around our own particular\n // request handler that adjusts idle timeouts while we have an outstanding\n // request. This compensates for the fact that sockjs removes all listeners\n // for \"request\" to add its own.\n WebApp.httpServer.removeListener(\n 'request', WebApp._timeoutAdjustmentRequestCallback);\n self.server.installHandlers(WebApp.httpServer);\n WebApp.httpServer.addListener(\n 'request', WebApp._timeoutAdjustmentRequestCallback);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n // sockjs sometimes passes us null instead of a socket object\n // so we need to guard against that. see:\n // https://github.com/sockjs/sockjs-node/issues/121\n // https://github.com/meteor/meteor/issues/10468\n if (!socket) return;\n\n // We want to make sure that if a client connects to us and does the initial\n // Websocket handshake but never gets to the DDP handshake, that we\n // eventually kill the socket. Once the DDP handshake happens, DDP\n // heartbeating will work. And before the Websocket handshake, the timeouts\n // we set at the server level in webapp_server.js will work. But\n // faye-websocket calls setTimeout(0) on any socket it takes over, so there\n // is an \"in between\" state where this doesn't happen. We work around this\n // by explicitly setting the socket timeout to a relatively large time here,\n // and setting it back to zero when we set up the heartbeat in\n // livedata_server.js.\n socket.setWebsocketTimeout = function (timeout) {\n if ((socket.protocol === 'websocket' ||\n socket.protocol === 'websocket-raw')\n && socket._session.recv) {\n socket._session.recv.connection.setTimeout(timeout);\n }\n };\n socket.setWebsocketTimeout(45 * 1000);\n\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n // only to send a message after connection on tests, useful for\n // socket-stream-client/server-tests.js\n if (process.env.TEST_METADATA && process.env.TEST_METADATA !== \"{}\") {\n socket.send(JSON.stringify({ testMessageOnConnect: true }));\n }\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\nObject.assign(StreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n var self = this;\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n ['request', 'upgrade'].forEach((event) => {\n var httpServer = WebApp.httpServer;\n var oldHttpServerListeners = httpServer.listeners(event).slice(0);\n httpServer.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n // TODO replace with url package\n var url = Npm.require('url');\n\n // Rewrite /websocket and /websocket/ urls to /sockjs/websocket while\n // preserving query string.\n var parsedUrl = url.parse(request.url);\n if (parsedUrl.pathname === pathPrefix + '/websocket' ||\n parsedUrl.pathname === pathPrefix + '/websocket/') {\n parsedUrl.pathname = self.prefix + '/websocket';\n request.url = url.format(parsedUrl);\n }\n _.each(oldHttpServerListeners, function(oldListener) {\n oldListener.apply(httpServer, args);\n });\n };\n httpServer.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/ddp-server/stream_server.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00030300000798888505, 0.00018338601512368768, 0.0001652815262787044, 0.00017142633441835642, 3.513470073812641e-05]} {"hunk": {"id": 5, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 17}, "file": "import { Meteor } from 'meteor/meteor';\nimport Links from './collections/Links.js';\n\nasync function insertLink({ title, url }) {\n await Links.insertAsync({ title, url, createdAt: new Date() });\n}\n\nMeteor.startup(async () => {\n // If the Links collection is empty, add some data.\n if (Links.find().count() === 0) {\n await insertLink({\n title: 'Do the Tutorial',\n url: 'https://www.meteor.com/tutorials/react/creating-an-app',\n });\n\n await insertLink({\n title: 'Follow the Guide',\n url: 'http://guide.meteor.com',\n });\n\n await insertLink({\n title: 'Read the Docs',\n url: 'https://docs.meteor.com',\n });\n\n await insertLink({\n title: 'Discussions',\n url: 'https://forums.meteor.com',\n });\n }\n});\n", "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.9900028705596924, 0.2479408085346222, 0.0001766245113685727, 0.0007919011986814439, 0.42842990159988403]} {"hunk": {"id": 5, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 17}, "file": "process.env.THROW_FROM_PACKAGE && Meteor.startup(function () {\n throw new Error(\"Should be line 2!\");\n});\n", "file_path": "tools/tests/apps/app-throws-error/packages/throwing-package/thrower.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00016534757742192596, 0.00016534757742192596, 0.00016534757742192596, 0.00016534757742192596, 0.0]} {"hunk": {"id": 5, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 17}, "file": "// This module exists so that it can be accessed directly via\n// require(\"meteor-babel/modern-versions.js\").get() without importing any\n// other modules, which can be expensive (10s of ms). Note that the\n// babel-preset-meteor/modern module has no top-level require calls, so\n// importing it should be very cheap.\nexports.get = function () {\n return require(\"babel-preset-meteor/modern\").minimumVersions;\n};\n", "file_path": "npm-packages/meteor-babel/modern-versions.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.00016405244241468608, 0.00016405244241468608, 0.00016405244241468608, 0.00016405244241468608, 0.0]} {"hunk": {"id": 5, "code_window": [" });\n", "\n", " await insertLink({\n", " title: 'Follow the Guide',\n", " url: 'http://guide.meteor.com',\n", " });\n", "\n", " await insertLink({\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" url: 'https://guide.meteor.com',\n"], "file_path": "tools/static-assets/skel-vue/imports/api/fixtures.js", "type": "replace", "edit_start_line_idx": 17}, "file": "# Meteor packages used by this project, one per line.\n# Check this file (and the other files in this directory) into your repository.\n#\n# 'meteor add' and 'meteor remove' will edit this file for you,\n# but you can also edit it by hand.\n\nmeteor # Shared foundation for all Meteor packages\nstatic-html # Define static page content in .html files\nstandard-minifier-css # CSS minifier run for production mode\nstandard-minifier-js # JS minifier run for production mode\nes5-shim # ECMAScript 5 compatibility for older browsers\necmascript # Enable ECMAScript2015+ syntax in app code\ntypescript # Enable TypeScript syntax in .ts and .tsx modules\nshell-server # Server-side component of the `meteor shell` command\nwebapp # Serves a Meteor app over HTTP\nserver-render # Support for server-side rendering\ntest-package\nautoupdate\n", "file_path": "tools/tests/apps/client-refresh/.meteor/packages", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/7abe8df1345a0eb93ca37d0c9a75ce484272226f", "dependency_score": [0.0011730347760021687, 0.0007117212517186999, 0.0002504077274352312, 0.0007117212517186999, 0.0004613135242834687]} {"hunk": {"id": 0, "code_window": ["## v.NEXT\n", "\n", "* Individual Meteor `self-test`'s can now be skipped by adjusting their\n", " `define` call to be prefixed by `skip`. For example,\n", " `selftest.skip.define('some test', ...` will skip running \"some test\".\n", " [PR #9579](https://github.com/meteor/meteor/pull/9579)\n"], "labels": ["keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.14.1.\n", "\n", "* The `optimism` npm package has been updated to version 0.4.0.\n", "\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 2}, "file": "// This file contains a package.json for the dependencies of the command-line\n// tool.\n\n// We put this in a JS file so that it can contain comments. It is processed\n// into a package.json file by generate-dev-bundle.sh.\n\nvar packageJson = {\n name: \"meteor-dev-bundle-tool\",\n private: true,\n dependencies: {\n // Explicit dependency because we are replacing it with a bundled version\n // and we want to make sure there are no dependencies on a higher version\n npm: \"5.6.0\",\n pacote: \"https://github.com/meteor/pacote/tarball/30973f140df79b647dbade03f2d6f19800c2609b\",\n \"node-gyp\": \"3.6.2\",\n \"node-pre-gyp\": \"0.6.36\",\n \"meteor-babel\": \"7.0.0-beta.38-2\",\n \"meteor-promise\": \"0.8.6\",\n promise: \"8.0.1\",\n reify: \"0.13.7\",\n fibers: \"2.0.0\",\n // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n \"@babel/runtime\": \"7.0.0-beta.38\",\n // For backwards compatibility with isopackets that still depend on\n // babel-runtime rather than @babel/runtime.\n \"babel-runtime\": \"7.0.0-beta.3\",\n // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n // in the package too) because we should consider using lodash instead\n // (and there are backwards-incompatible changes either way).\n underscore: \"1.5.2\",\n \"source-map-support\": \"https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e\",\n semver: \"5.4.1\",\n request: \"2.83.0\",\n fstream: \"https://github.com/meteor/fstream/tarball/cf4ea6c175355cec7bee38311e170d08c4078a5d\",\n tar: \"2.2.1\",\n kexec: \"3.0.0\",\n \"source-map\": \"0.5.3\",\n chalk: \"0.5.1\",\n sqlite3: \"3.1.8\",\n netroute: \"1.0.2\",\n \"http-proxy\": \"1.16.2\",\n \"wordwrap\": \"0.0.2\",\n \"moment\": \"2.20.1\",\n \"rimraf\": \"2.6.2\",\n \"glob\": \"7.1.2\",\n ignore: \"3.3.7\",\n // XXX: When we update this, see if it fixes this Github issue:\n // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the\n // workaround from the tool.\n \"commonmark\": \"0.15.0\",\n escope: \"3.6.0\",\n split2: \"2.2.0\",\n multipipe: \"2.0.1\",\n pathwatcher: \"7.1.1\",\n optimism: \"0.3.3\",\n 'lru-cache': '4.1.1',\n longjohn: '0.2.12'\n }\n};\n\nif (process.platform === 'win32') {\n // Remove dependencies that do not work on Windows\n delete packageJson.dependencies.netroute;\n delete packageJson.dependencies.kexec;\n}\n\nprocess.stdout.write(JSON.stringify(packageJson, null, 2) + '\\n');\n", "file_path": "scripts/dev-bundle-tool-package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00018889161583501846, 0.00017113052308559418, 0.00016545293328817934, 0.00016859197057783604, 7.541505510744173e-06]} {"hunk": {"id": 0, "code_window": ["## v.NEXT\n", "\n", "* Individual Meteor `self-test`'s can now be skipped by adjusting their\n", " `define` call to be prefixed by `skip`. For example,\n", " `selftest.skip.define('some test', ...` will skip running \"some test\".\n", " [PR #9579](https://github.com/meteor/meteor/pull/9579)\n"], "labels": ["keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.14.1.\n", "\n", "* The `optimism` npm package has been updated to version 0.4.0.\n", "\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 2}, "file": "\t/**\n\t * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.\n\t *\n\t * @codingstandard ftlabs-jsv2\n\t * @copyright The Financial Times Limited [All Rights Reserved]\n\t * @license MIT License (see LICENSE.txt)\n\t */\n\n\t/*jslint browser:true, node:true*/\n\t/*global define, Event, Node*/\n\n\n\t/**\n\t * Instantiate fast-clicking listeners on the specified layer.\n\t *\n\t * @constructor\n\t * @param {Element} layer The layer to listen on\n\t * @param {Object} [options={}] The options to override the defaults\n\t */\n\tfunction FastClick(layer, options) {\n 'use strict';\n\t\tvar oldOnClick;\n\n\t\toptions = options || {};\n\n\t\t/**\n\t\t * Whether a click is currently being tracked.\n\t\t *\n\t\t * @type boolean\n\t\t */\n\t\tthis.trackingClick = false;\n\n\n\t\t/**\n\t\t * Timestamp for when click tracking started.\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.trackingClickStart = 0;\n\n\n\t\t/**\n\t\t * The element being tracked for a click.\n\t\t *\n\t\t * @type EventTarget\n\t\t */\n\t\tthis.targetElement = null;\n\n\n\t\t/**\n\t\t * X-coordinate of touch start event.\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.touchStartX = 0;\n\n\n\t\t/**\n\t\t * Y-coordinate of touch start event.\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.touchStartY = 0;\n\n\n\t\t/**\n\t\t * ID of the last touch, retrieved from Touch.identifier.\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.lastTouchIdentifier = 0;\n\n\n\t\t/**\n\t\t * Touchmove boundary, beyond which a click will be cancelled.\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.touchBoundary = options.touchBoundary || 10;\n\n\n\t\t/**\n\t\t * The FastClick layer.\n\t\t *\n\t\t * @type Element\n\t\t */\n\t\tthis.layer = layer;\n\n\t\t/**\n\t\t * The minimum time between tap(touchstart and touchend) events\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.tapDelay = options.tapDelay || 200;\n\n\t\t/**\n\t\t * The maximum time for a tap\n\t\t *\n\t\t * @type number\n\t\t */\n\t\tthis.tapTimeout = options.tapTimeout || 700;\n\n\t\tif (FastClick.notNeeded(layer)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Some old versions of Android don't have Function.prototype.bind\n\t\tfunction bind(method, context) {\n\t\t\treturn function() { return method.apply(context, arguments); };\n\t\t}\n\n\n\t\tvar methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];\n\t\tvar context = this;\n\t\tfor (var i = 0, l = methods.length; i < l; i++) {\n\t\t\tcontext[methods[i]] = bind(context[methods[i]], context);\n\t\t}\n\n\t\t// Set up event handlers as required\n\t\tif (deviceIsAndroid) {\n\t\t\tlayer.addEventListener('mouseover', this.onMouse, true);\n\t\t\tlayer.addEventListener('mousedown', this.onMouse, true);\n\t\t\tlayer.addEventListener('mouseup', this.onMouse, true);\n\t\t}\n\n\t\tlayer.addEventListener('click', this.onClick, true);\n\t\tlayer.addEventListener('touchstart', this.onTouchStart, false);\n\t\tlayer.addEventListener('touchmove', this.onTouchMove, false);\n\t\tlayer.addEventListener('touchend', this.onTouchEnd, false);\n\t\tlayer.addEventListener('touchcancel', this.onTouchCancel, false);\n\n\t\t// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)\n\t\t// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick\n\t\t// layer when they are cancelled.\n\t\tif (!Event.prototype.stopImmediatePropagation) {\n\t\t\tlayer.removeEventListener = function(type, callback, capture) {\n\t\t\t\tvar rmv = Node.prototype.removeEventListener;\n\t\t\t\tif (type === 'click') {\n\t\t\t\t\trmv.call(layer, type, callback.hijacked || callback, capture);\n\t\t\t\t} else {\n\t\t\t\t\trmv.call(layer, type, callback, capture);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tlayer.addEventListener = function(type, callback, capture) {\n\t\t\t\tvar adv = Node.prototype.addEventListener;\n\t\t\t\tif (type === 'click') {\n\t\t\t\t\tadv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {\n\t\t\t\t\t\tif (!event.propagationStopped) {\n\t\t\t\t\t\t\tcallback(event);\n\t\t\t\t\t\t}\n\t\t\t\t\t}), capture);\n\t\t\t\t} else {\n\t\t\t\t\tadv.call(layer, type, callback, capture);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\t\t// If a handler is already declared in the element's onclick attribute, it will be fired before\n\t\t// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and\n\t\t// adding it as listener.\n\t\tif (typeof layer.onclick === 'function') {\n\n\t\t\t// Android browser on at least 3.2 requires a new reference to the function in layer.onclick\n\t\t\t// - the old one won't work if passed to addEventListener directly.\n\t\t\toldOnClick = layer.onclick;\n\t\t\tlayer.addEventListener('click', function(event) {\n\t\t\t\toldOnClick(event);\n\t\t\t}, false);\n\t\t\tlayer.onclick = null;\n\t\t}\n\t}\n\n\t/**\n\t* Windows Phone 8.1 fakes user agent string to look like Android and iPhone.\n\t*\n\t* @type boolean\n\t*/\n\tvar deviceIsWindowsPhone = navigator.userAgent.indexOf(\"Windows Phone\") >= 0;\n\n\t/**\n\t * Android requires exceptions.\n\t *\n\t * @type boolean\n\t */\n\tvar deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;\n\n\n\t/**\n\t * iOS requires exceptions.\n\t *\n\t * @type boolean\n\t */\n\tvar deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;\n\n\n\t/**\n\t * iOS 4 requires an exception for select elements.\n\t *\n\t * @type boolean\n\t */\n\tvar deviceIsIOS4 = deviceIsIOS && (/OS 4_\\d(_\\d)?/).test(navigator.userAgent);\n\n\n\t/**\n\t * iOS 6.0-7.* requires the target element to be manually derived\n\t *\n\t * @type boolean\n\t */\n\tvar deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\\d/).test(navigator.userAgent);\n\n\t/**\n\t * BlackBerry requires exceptions.\n\t *\n\t * @type boolean\n\t */\n\tvar deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;\n\n\t/**\n\t * Determine whether a given element requires a native click.\n\t *\n\t * @param {EventTarget|Element} target Target DOM element\n\t * @returns {boolean} Returns true if the element needs a native click\n\t */\n\tFastClick.prototype.needsClick = function(target) {\n\t\tswitch (target.nodeName.toLowerCase()) {\n\n\t\t// Don't send a synthetic click to disabled inputs (issue #62)\n\t\tcase 'button':\n\t\tcase 'select':\n\t\tcase 'textarea':\n\t\t\tif (target.disabled) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase 'input':\n\n\t\t\t// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)\n\t\t\tif ((deviceIsIOS && target.type === 'file') || target.disabled) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase 'label':\n\t\tcase 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames\n\t\tcase 'video':\n\t\t\treturn true;\n\t\t}\n\n\t\treturn (/\\bneedsclick\\b/).test(target.className);\n\t};\n\n\n\t/**\n\t * Determine whether a given element requires a call to focus to simulate click into element.\n\t *\n\t * @param {EventTarget|Element} target Target DOM element\n\t * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.\n\t */\n\tFastClick.prototype.needsFocus = function(target) {\n\t\tswitch (target.nodeName.toLowerCase()) {\n\t\tcase 'textarea':\n\t\t\treturn true;\n\t\tcase 'select':\n\t\t\treturn !deviceIsAndroid;\n\t\tcase 'input':\n\t\t\tswitch (target.type) {\n\t\t\tcase 'button':\n\t\t\tcase 'checkbox':\n\t\t\tcase 'file':\n\t\t\tcase 'image':\n\t\t\tcase 'radio':\n\t\t\tcase 'submit':\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// No point in attempting to focus disabled inputs\n\t\t\treturn !target.disabled && !target.readOnly;\n\t\tdefault:\n\t\t\treturn (/\\bneedsfocus\\b/).test(target.className);\n\t\t}\n\t};\n\n\n\t/**\n\t * Send a click event to the specified element.\n\t *\n\t * @param {EventTarget|Element} targetElement\n\t * @param {Event} event\n\t */\n\tFastClick.prototype.sendClick = function(targetElement, event) {\n\t\tvar clickEvent, touch;\n\n\t\t// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)\n\t\tif (document.activeElement && document.activeElement !== targetElement) {\n\t\t\tdocument.activeElement.blur();\n\t\t}\n\n\t\ttouch = event.changedTouches[0];\n\n\t\t// Synthesise a click event, with an extra attribute so it can be tracked\n\t\tclickEvent = document.createEvent('MouseEvents');\n\t\tclickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);\n\t\tclickEvent.forwardedTouchEvent = true;\n\t\ttargetElement.dispatchEvent(clickEvent);\n\t};\n\n\tFastClick.prototype.determineEventType = function(targetElement) {\n\n\t\t//Issue #159: Android Chrome Select Box does not open with a synthetic click event\n\t\tif (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {\n\t\t\treturn 'mousedown';\n\t\t}\n\n\t\treturn 'click';\n\t};\n\n\n\t/**\n\t * @param {EventTarget|Element} targetElement\n\t */\n\tFastClick.prototype.focus = function(targetElement) {\n\t\tvar length;\n\n\t\t// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.\n\t\tif (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {\n\t\t\tlength = targetElement.value.length;\n\t\t\ttargetElement.setSelectionRange(length, length);\n\t\t} else {\n\t\t\ttargetElement.focus();\n\t\t}\n\t};\n\n\n\t/**\n\t * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.\n\t *\n\t * @param {EventTarget|Element} targetElement\n\t */\n\tFastClick.prototype.updateScrollParent = function(targetElement) {\n\t\tvar scrollParent, parentElement;\n\n\t\tscrollParent = targetElement.fastClickScrollParent;\n\n\t\t// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the\n\t\t// target element was moved to another parent.\n\t\tif (!scrollParent || !scrollParent.contains(targetElement)) {\n\t\t\tparentElement = targetElement;\n\t\t\tdo {\n\t\t\t\tif (parentElement.scrollHeight > parentElement.offsetHeight) {\n\t\t\t\t\tscrollParent = parentElement;\n\t\t\t\t\ttargetElement.fastClickScrollParent = parentElement;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tparentElement = parentElement.parentElement;\n\t\t\t} while (parentElement);\n\t\t}\n\n\t\t// Always update the scroll top tracker if possible.\n\t\tif (scrollParent) {\n\t\t\tscrollParent.fastClickLastScrollTop = scrollParent.scrollTop;\n\t\t}\n\t};\n\n\n\t/**\n\t * @param {EventTarget} targetElement\n\t * @returns {Element|EventTarget}\n\t */\n\tFastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {\n\n\t\t// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.\n\t\tif (eventTarget.nodeType === Node.TEXT_NODE) {\n\t\t\treturn eventTarget.parentNode;\n\t\t}\n\n\t\treturn eventTarget;\n\t};\n\n\n\t/**\n\t * On touch start, record the position and scroll offset.\n\t *\n\t * @param {Event} event\n\t * @returns {boolean}\n\t */\n\tFastClick.prototype.onTouchStart = function(event) {\n\t\tvar targetElement, touch, selection;\n\n\t\t// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).\n\t\tif (event.targetTouches.length > 1) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttargetElement = this.getTargetElementFromEventTarget(event.target);\n\t\ttouch = event.targetTouches[0];\n\n\t\tif (deviceIsIOS) {\n\n\t\t\t// Only trusted events will deselect text on iOS (issue #49)\n\t\t\tselection = window.getSelection();\n\t\t\tif (selection.rangeCount && !selection.isCollapsed) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (!deviceIsIOS4) {\n\n\t\t\t\t// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):\n\t\t\t\t// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched\n\t\t\t\t// with the same identifier as the touch event that previously triggered the click that triggered the alert.\n\t\t\t\t// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an\n\t\t\t\t// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.\n\t\t\t\t// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,\n\t\t\t\t// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,\n\t\t\t\t// random integers, it's safe to to continue if the identifier is 0 here.\n\t\t\t\tif (touch.identifier && touch.identifier === this.lastTouchIdentifier) {\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tthis.lastTouchIdentifier = touch.identifier;\n\n\t\t\t\t// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:\n\t\t\t\t// 1) the user does a fling scroll on the scrollable layer\n\t\t\t\t// 2) the user stops the fling scroll with another tap\n\t\t\t\t// then the event.target of the last 'touchend' event will be the element that was under the user's finger\n\t\t\t\t// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check\n\t\t\t\t// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).\n\t\t\t\tthis.updateScrollParent(targetElement);\n\t\t\t}\n\t\t}\n\n\t\tthis.trackingClick = true;\n\t\tthis.trackingClickStart = event.timeStamp;\n\t\tthis.targetElement = targetElement;\n\n\t\tthis.touchStartX = touch.pageX;\n\t\tthis.touchStartY = touch.pageY;\n\n\t\t// Prevent phantom clicks on fast double-tap (issue #36)\n\t\tif ((event.timeStamp - this.lastClickTime) < this.tapDelay) {\n\t\t\tevent.preventDefault();\n\t\t}\n\n\t\treturn true;\n\t};\n\n\n\t/**\n\t * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.\n\t *\n\t * @param {Event} event\n\t * @returns {boolean}\n\t */\n\tFastClick.prototype.touchHasMoved = function(event) {\n\t\tvar touch = event.changedTouches[0], boundary = this.touchBoundary;\n\n\t\tif (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\n\t/**\n\t * Update the last position.\n\t *\n\t * @param {Event} event\n\t * @returns {boolean}\n\t */\n\tFastClick.prototype.onTouchMove = function(event) {\n\t\tif (!this.trackingClick) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// If the touch has moved, cancel the click tracking\n\t\tif (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {\n\t\t\tthis.trackingClick = false;\n\t\t\tthis.targetElement = null;\n\t\t}\n\n\t\treturn true;\n\t};\n\n\n\t/**\n\t * Attempt to find the labelled control for the given label element.\n\t *\n\t * @param {EventTarget|HTMLLabelElement} labelElement\n\t * @returns {Element|null}\n\t */\n\tFastClick.prototype.findControl = function(labelElement) {\n\n\t\t// Fast path for newer browsers supporting the HTML5 control attribute\n\t\tif (labelElement.control !== undefined) {\n\t\t\treturn labelElement.control;\n\t\t}\n\n\t\t// All browsers under test that support touch events also support the HTML5 htmlFor attribute\n\t\tif (labelElement.htmlFor) {\n\t\t\treturn document.getElementById(labelElement.htmlFor);\n\t\t}\n\n\t\t// If no for attribute exists, attempt to retrieve the first labellable descendant element\n\t\t// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label\n\t\treturn labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');\n\t};\n\n\n\t/**\n\t * On touch end, determine whether to send a click event at once.\n\t *\n\t * @param {Event} event\n\t * @returns {boolean}\n\t */\n\tFastClick.prototype.onTouchEnd = function(event) {\n\t\tvar forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;\n\n\t\tif (!this.trackingClick) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Prevent phantom clicks on fast double-tap (issue #36)\n\t\tif ((event.timeStamp - this.lastClickTime) < this.tapDelay) {\n\t\t\tthis.cancelNextClick = true;\n\t\t\treturn true;\n\t\t}\n\n\t\tif ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Reset to prevent wrong click cancel on input (issue #156).\n\t\tthis.cancelNextClick = false;\n\n\t\tthis.lastClickTime = event.timeStamp;\n\n\t\ttrackingClickStart = this.trackingClickStart;\n\t\tthis.trackingClick = false;\n\t\tthis.trackingClickStart = 0;\n\n\t\t// On some iOS devices, the targetElement supplied with the event is invalid if the layer\n\t\t// is performing a transition or scroll, and has to be re-detected manually. Note that\n\t\t// for this to function correctly, it must be called *after* the event target is checked!\n\t\t// See issue #57; also filed as rdar://13048589 .\n\t\tif (deviceIsIOSWithBadTarget) {\n\t\t\ttouch = event.changedTouches[0];\n\n\t\t\t// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null\n\t\t\ttargetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;\n\t\t\ttargetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;\n\t\t}\n\n\t\ttargetTagName = targetElement.tagName.toLowerCase();\n\t\tif (targetTagName === 'label') {\n\t\t\tforElement = this.findControl(targetElement);\n\t\t\tif (forElement) {\n\t\t\t\tthis.focus(targetElement);\n\t\t\t\tif (deviceIsAndroid) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\ttargetElement = forElement;\n\t\t\t}\n\t\t} else if (this.needsFocus(targetElement)) {\n\n\t\t\t// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.\n\t\t\t// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).\n\t\t\tif ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {\n\t\t\t\tthis.targetElement = null;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tthis.focus(targetElement);\n\t\t\tthis.sendClick(targetElement, event);\n\n\t\t\t// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.\n\t\t\t// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)\n\t\t\tif (!deviceIsIOS || targetTagName !== 'select') {\n\t\t\t\tthis.targetElement = null;\n\t\t\t\tevent.preventDefault();\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tif (deviceIsIOS && !deviceIsIOS4) {\n\n\t\t\t// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled\n\t\t\t// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).\n\t\t\tscrollParent = targetElement.fastClickScrollParent;\n\t\t\tif (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Prevent the actual click from going though - unless the target node is marked as requiring\n\t\t// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.\n\t\tif (!this.needsClick(targetElement)) {\n\t\t\tevent.preventDefault();\n\t\t\tthis.sendClick(targetElement, event);\n\t\t}\n\n\t\treturn false;\n\t};\n\n\n\t/**\n\t * On touch cancel, stop tracking the click.\n\t *\n\t * @returns {void}\n\t */\n\tFastClick.prototype.onTouchCancel = function() {\n\t\tthis.trackingClick = false;\n\t\tthis.targetElement = null;\n\t};\n\n\n\t/**\n\t * Determine mouse events which should be permitted.\n\t *\n\t * @param {Event} event\n\t * @returns {boolean}\n\t */\n\tFastClick.prototype.onMouse = function(event) {\n\n\t\t// If a target element was never set (because a touch event was never fired) allow the event\n\t\tif (!this.targetElement) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (event.forwardedTouchEvent) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Programmatically generated events targeting a specific element should be permitted\n\t\tif (!event.cancelable) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Derive and check the target element to see whether the mouse event needs to be permitted;\n\t\t// unless explicitly enabled, prevent non-touch click events from triggering actions,\n\t\t// to prevent ghost/doubleclicks.\n\t\tif (!this.needsClick(this.targetElement) || this.cancelNextClick) {\n\n\t\t\t// Prevent any user-added listeners declared on FastClick element from being fired.\n\t\t\tif (event.stopImmediatePropagation) {\n\t\t\t\tevent.stopImmediatePropagation();\n\t\t\t} else {\n\n\t\t\t\t// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)\n\t\t\t\tevent.propagationStopped = true;\n\t\t\t}\n\n\t\t\t// Cancel the event\n\t\t\tevent.stopPropagation();\n\t\t\tevent.preventDefault();\n\n\t\t\treturn false;\n\t\t}\n\n\t\t// If the mouse event is permitted, return true for the action to go through.\n\t\treturn true;\n\t};\n\n\n\t/**\n\t * On actual clicks, determine whether this is a touch-generated click, a click action occurring\n\t * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or\n\t * an actual click which should be permitted.\n\t *\n\t * @param {Event} event\n\t * @returns {boolean}\n\t */\n\tFastClick.prototype.onClick = function(event) {\n\t\tvar permitted;\n\n\t\t// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.\n\t\tif (this.trackingClick) {\n\t\t\tthis.targetElement = null;\n\t\t\tthis.trackingClick = false;\n\t\t\treturn true;\n\t\t}\n\n\t\t// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.\n\t\tif (event.target.type === 'submit' && event.detail === 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\tpermitted = this.onMouse(event);\n\n\t\t// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.\n\t\tif (!permitted) {\n\t\t\tthis.targetElement = null;\n\t\t}\n\n\t\t// If clicks are permitted, return true for the action to go through.\n\t\treturn permitted;\n\t};\n\n\n\t/**\n\t * Remove all FastClick's event listeners.\n\t *\n\t * @returns {void}\n\t */\n\tFastClick.prototype.destroy = function() {\n\t\tvar layer = this.layer;\n\n\t\tif (deviceIsAndroid) {\n\t\t\tlayer.removeEventListener('mouseover', this.onMouse, true);\n\t\t\tlayer.removeEventListener('mousedown', this.onMouse, true);\n\t\t\tlayer.removeEventListener('mouseup', this.onMouse, true);\n\t\t}\n\n\t\tlayer.removeEventListener('click', this.onClick, true);\n\t\tlayer.removeEventListener('touchstart', this.onTouchStart, false);\n\t\tlayer.removeEventListener('touchmove', this.onTouchMove, false);\n\t\tlayer.removeEventListener('touchend', this.onTouchEnd, false);\n\t\tlayer.removeEventListener('touchcancel', this.onTouchCancel, false);\n\t};\n\n\n\t/**\n\t * Check whether FastClick is needed.\n\t *\n\t * @param {Element} layer The layer to listen on\n\t */\n\tFastClick.notNeeded = function(layer) {\n\t\tvar metaViewport;\n\t\tvar chromeVersion;\n\t\tvar blackberryVersion;\n\t\tvar firefoxVersion;\n\n\t\t// Devices that don't support touch don't need FastClick\n\t\tif (typeof window.ontouchstart === 'undefined') {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Chrome version - zero for other browsers\n\t\tchromeVersion = +(/Chrome\\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];\n\n\t\tif (chromeVersion) {\n\n\t\t\tif (deviceIsAndroid) {\n\t\t\t\tmetaViewport = document.querySelector('meta[name=viewport]');\n\n\t\t\t\tif (metaViewport) {\n\t\t\t\t\t// Chrome on Android with user-scalable=\"no\" doesn't need FastClick (issue #89)\n\t\t\t\t\tif (metaViewport.content.indexOf('user-scalable=no') !== -1) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\t// Chrome 32 and above with width=device-width or less don't need FastClick\n\t\t\t\t\tif (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t// Chrome desktop doesn't need FastClick (issue #15)\n\t\t\t} else {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tif (deviceIsBlackBerry10) {\n\t\t\tblackberryVersion = navigator.userAgent.match(/Version\\/([0-9]*)\\.([0-9]*)/);\n\n\t\t\t// BlackBerry 10.3+ does not require Fastclick library.\n\t\t\t// https://github.com/ftlabs/fastclick/issues/251\n\t\t\tif (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {\n\t\t\t\tmetaViewport = document.querySelector('meta[name=viewport]');\n\n\t\t\t\tif (metaViewport) {\n\t\t\t\t\t// user-scalable=no eliminates click delay.\n\t\t\t\t\tif (metaViewport.content.indexOf('user-scalable=no') !== -1) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\t// width=device-width (or less than device-width) eliminates click delay.\n\t\t\t\t\tif (document.documentElement.scrollWidth <= window.outerWidth) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)\n\t\tif (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Firefox version - zero for other browsers\n\t\tfirefoxVersion = +(/Firefox\\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];\n\n\t\tif (firefoxVersion >= 27) {\n\t\t\t// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896\n\n\t\t\tmetaViewport = document.querySelector('meta[name=viewport]');\n\t\t\tif (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version\n\t\t// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx\n\t\tif (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\n\t/**\n\t * Factory method for creating a FastClick object\n\t *\n\t * @param {Element} layer The layer to listen on\n\t * @param {Object} [options={}] The options to override the defaults\n\t */\n\tFastClick.attach = function(layer, options) {\n\t\treturn new FastClick(layer, options);\n\t};\n\n\n\tif (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\n\t\t// AMD. Register as an anonymous module.\n\t\tdefine(function() {\n\t\t\treturn FastClick;\n\t\t});\n\t} else if (typeof module !== 'undefined' && module.exports) {\n\t\tmodule.exports = FastClick.attach;\n\t\tmodule.exports.FastClick = FastClick;\n\t} else {\n\t\twindow.FastClick = FastClick;\n\t}\n", "file_path": "packages/deprecated/fastclick/fastclick.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.0003370115882717073, 0.00016880914336070418, 0.00016365808551199734, 0.0001664314913796261, 1.8631311831995845e-05]} {"hunk": {"id": 0, "code_window": ["## v.NEXT\n", "\n", "* Individual Meteor `self-test`'s can now be skipped by adjusting their\n", " `define` call to be prefixed by `skip`. For example,\n", " `selftest.skip.define('some test', ...` will skip running \"some test\".\n", " [PR #9579](https://github.com/meteor/meteor/pull/9579)\n"], "labels": ["keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.14.1.\n", "\n", "* The `optimism` npm package has been updated to version 0.4.0.\n", "\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 2}, "file": "Package.describe({\n name: \"~package-name~\", // replaced via `Sandbox.prototype.createPackage`\n summary: \"Test package.\",\n version: \"1.0.0\",\n documentation: null\n});\n", "file_path": "tools/tests/packages/package-of-two-versions/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017057699733413756, 0.00017057699733413756, 0.00017057699733413756, 0.00017057699733413756, 0.0]} {"hunk": {"id": 0, "code_window": ["## v.NEXT\n", "\n", "* Individual Meteor `self-test`'s can now be skipped by adjusting their\n", " `define` call to be prefixed by `skip`. For example,\n", " `selftest.skip.define('some test', ...` will skip running \"some test\".\n", " [PR #9579](https://github.com/meteor/meteor/pull/9579)\n"], "labels": ["keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.14.1.\n", "\n", "* The `optimism` npm package has been updated to version 0.4.0.\n", "\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 2}, "file": "@el2-style: solid;\n@import \"../imports/dotdot.less\";\n", "file_path": "tools/tests/apps/caching-less/subdir/foo.import.less", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00016825216880533844, 0.00016825216880533844, 0.00016825216880533844, 0.00016825216880533844, 0.0]} {"hunk": {"id": 1, "code_window": ["{\n", " \"lockfileVersion\": 1,\n", " \"dependencies\": {\n", " \"acorn\": {\n", " \"version\": \"5.3.0\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz\",\n", " \"integrity\": \"sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==\"\n", " },\n", " \"minipass\": {\n", " \"version\": \"2.2.1\",\n", " \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.4.1.tgz\",\n", " \"integrity\": \"sha512-XLmq3H/BVvW6/GbxKryGxWORz1ebilSsUDlyC27bXhWGWAZWkGwS6FLHjOlwFXNFoWFQEO/Df4u0YYd0K3BQgQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 4}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"acorn\": {\n \"version\": \"5.3.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz\",\n \"integrity\": \"sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==\"\n },\n \"minipass\": {\n \"version\": \"2.2.1\",\n \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n \"integrity\": \"sha512-u1aUllxPJUI07cOqzR7reGmQxmCqlH88uIIsf6XZFEWgw7gXKpJdR+5R9Y3KEDmWYkdIz9wXZs3C0jOPxejk/Q==\"\n },\n \"minizlib\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/minizlib/-/minizlib-1.1.0.tgz\",\n \"integrity\": \"sha512-4T6Ur/GctZ27nHfpt9THOdRZNgyJ9FZchYO1ceg5S8Q3DNLCKYy44nCZzgCJgcvx2UM8czmqak5BCxJMrq37lA==\"\n },\n \"reify\": {\n \"version\": \"0.13.7\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.13.7.tgz\",\n \"integrity\": \"sha512-jA6C/TdOf0g1A9WlQL7enh8yfGXgCmU3qbOpgc98vzRNEgu4TrAnSGec+uLxHdci96lftdBow3q0X3pbXnzmGQ==\"\n },\n \"semver\": {\n \"version\": \"5.4.1\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.4.1.tgz\",\n \"integrity\": \"sha512-WfG/X9+oATh81XtllIo/I8gOiY9EXRdv1cQdyykeXK17YcUW3EXUAi2To4pcH6nZtJPr7ZOpM5OMyWJZm+8Rsg==\"\n },\n \"yallist\": {\n \"version\": \"3.0.2\",\n \"resolved\": \"https://registry.npmjs.org/yallist/-/yallist-3.0.2.tgz\",\n \"integrity\": \"sha1-hFK0u36Dx8GI2AQcGoN8dz1ti7k=\"\n }\n }\n}\n", "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.9934759736061096, 0.26300403475761414, 0.00019406377396080643, 0.029173070564866066, 0.4222135841846466]} {"hunk": {"id": 1, "code_window": ["{\n", " \"lockfileVersion\": 1,\n", " \"dependencies\": {\n", " \"acorn\": {\n", " \"version\": \"5.3.0\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz\",\n", " \"integrity\": \"sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==\"\n", " },\n", " \"minipass\": {\n", " \"version\": \"2.2.1\",\n", " \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.4.1.tgz\",\n", " \"integrity\": \"sha512-XLmq3H/BVvW6/GbxKryGxWORz1ebilSsUDlyC27bXhWGWAZWkGwS6FLHjOlwFXNFoWFQEO/Df4u0YYd0K3BQgQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 4}, "file": "/*\n * XXX Hack to make bootstrap work when bundled. This needs to be included\n * _after_ the standard bootstrap css files.\n *\n * After being bundled, all CSS is minified and served from the \"/\" dir.\n * Thus, we need to provide absolute paths to the icons here.\n */\n\n[class^=\"icon-\"],\n[class*=\" icon-\"] {\n background-image: url(\"/packages/bootstrap/img/glyphicons-halflings.png\");\n}\n/*\n * Selectors borrowed from bootstrap.css. For all releases of bootstrap, when\n * we upgrade, update this file to borrow the selectors from where bootstrap.css\n * references any .png. When we update to using .less instead, use the less\n * directives in a less file instead.\n */\n.icon-white,\n.nav-pills > .active > a > [class^=\"icon-\"],\n.nav-pills > .active > a > [class*=\" icon-\"],\n.nav-list > .active > a > [class^=\"icon-\"],\n.nav-list > .active > a > [class*=\" icon-\"],\n.navbar-inverse .nav > .active > a > [class^=\"icon-\"],\n.navbar-inverse .nav > .active > a > [class*=\" icon-\"],\n.dropdown-menu > li > a:hover > [class^=\"icon-\"],\n.dropdown-menu > li > a:focus > [class^=\"icon-\"],\n.dropdown-menu > li > a:hover > [class*=\" icon-\"],\n.dropdown-menu > li > a:focus > [class*=\" icon-\"],\n.dropdown-menu > .active > a > [class^=\"icon-\"],\n.dropdown-menu > .active > a > [class*=\" icon-\"],\n.dropdown-submenu:hover > a > [class^=\"icon-\"],\n.dropdown-submenu:focus > a > [class^=\"icon-\"],\n.dropdown-submenu:hover > a > [class*=\" icon-\"],\n.dropdown-submenu:focus > a > [class*=\" icon-\"] {\n background-image: url(\"/packages/bootstrap/img/glyphicons-halflings-white.png\");\n}\n", "file_path": "packages/deprecated/bootstrap/css/bootstrap-override.css", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017662806203588843, 0.00017142159049399197, 0.00016481129569001496, 0.00017212348757311702, 4.251189238857478e-06]} {"hunk": {"id": 1, "code_window": ["{\n", " \"lockfileVersion\": 1,\n", " \"dependencies\": {\n", " \"acorn\": {\n", " \"version\": \"5.3.0\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz\",\n", " \"integrity\": \"sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==\"\n", " },\n", " \"minipass\": {\n", " \"version\": \"2.2.1\",\n", " \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.4.1.tgz\",\n", " \"integrity\": \"sha512-XLmq3H/BVvW6/GbxKryGxWORz1ebilSsUDlyC27bXhWGWAZWkGwS6FLHjOlwFXNFoWFQEO/Df4u0YYd0K3BQgQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 4}, "file": "import {AccountsServer} from \"./accounts_server.js\";\n\n// XXX These should probably not actually be public?\n\nAccountsServer.prototype.urls = {\n resetPassword: function (token) {\n return Meteor.absoluteUrl('#/reset-password/' + token);\n },\n\n verifyEmail: function (token) {\n return Meteor.absoluteUrl('#/verify-email/' + token);\n },\n\n enrollAccount: function (token) {\n return Meteor.absoluteUrl('#/enroll-account/' + token);\n }\n};\n", "file_path": "packages/accounts-base/url_server.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.0001699924614513293, 0.00016747208428569138, 0.00016495169256813824, 0.00016747208428569138, 2.5203844415955245e-06]} {"hunk": {"id": 1, "code_window": ["{\n", " \"lockfileVersion\": 1,\n", " \"dependencies\": {\n", " \"acorn\": {\n", " \"version\": \"5.3.0\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz\",\n", " \"integrity\": \"sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==\"\n", " },\n", " \"minipass\": {\n", " \"version\": \"2.2.1\",\n", " \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.4.1.tgz\",\n", " \"integrity\": \"sha512-XLmq3H/BVvW6/GbxKryGxWORz1ebilSsUDlyC27bXhWGWAZWkGwS6FLHjOlwFXNFoWFQEO/Df4u0YYd0K3BQgQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 4}, "file": "import \"./accounts_tests.js\";\nimport \"./accounts_reconnect_tests.js\";\n", "file_path": "packages/accounts-base/server_tests.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017211982049047947, 0.00017211982049047947, 0.00017211982049047947, 0.00017211982049047947, 0.0]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/minizlib/-/minizlib-1.1.0.tgz\",\n", " \"integrity\": \"sha512-4T6Ur/GctZ27nHfpt9THOdRZNgyJ9FZchYO1ceg5S8Q3DNLCKYy44nCZzgCJgcvx2UM8czmqak5BCxJMrq37lA==\"\n", " },\n", " \"reify\": {\n", " \"version\": \"0.13.7\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.13.7.tgz\",\n", " \"integrity\": \"sha512-jA6C/TdOf0g1A9WlQL7enh8yfGXgCmU3qbOpgc98vzRNEgu4TrAnSGec+uLxHdci96lftdBow3q0X3pbXnzmGQ==\"\n", " },\n", " \"semver\": {\n", " \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.4.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"0.14.1\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.14.1.tgz\",\n", " \"integrity\": \"sha512-HAKYzqlCCWsfAcOTm8gsJZ6FE5I06kvjzHRQTCDD6xqUJaY8Mh4ve9oiCDe8yiYXOqZqpt03gn8yS4+bokRmhQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 19}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"acorn\": {\n \"version\": \"5.3.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz\",\n \"integrity\": \"sha512-Yej+zOJ1Dm/IMZzzj78OntP/r3zHEaKcyNoU2lAaxPtrseM6rF0xwqoz5Q5ysAiED9hTjI2hgtvLXitlCN1/Ug==\"\n },\n \"minipass\": {\n \"version\": \"2.2.1\",\n \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n \"integrity\": \"sha512-u1aUllxPJUI07cOqzR7reGmQxmCqlH88uIIsf6XZFEWgw7gXKpJdR+5R9Y3KEDmWYkdIz9wXZs3C0jOPxejk/Q==\"\n },\n \"minizlib\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/minizlib/-/minizlib-1.1.0.tgz\",\n \"integrity\": \"sha512-4T6Ur/GctZ27nHfpt9THOdRZNgyJ9FZchYO1ceg5S8Q3DNLCKYy44nCZzgCJgcvx2UM8czmqak5BCxJMrq37lA==\"\n },\n \"reify\": {\n \"version\": \"0.13.7\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.13.7.tgz\",\n \"integrity\": \"sha512-jA6C/TdOf0g1A9WlQL7enh8yfGXgCmU3qbOpgc98vzRNEgu4TrAnSGec+uLxHdci96lftdBow3q0X3pbXnzmGQ==\"\n },\n \"semver\": {\n \"version\": \"5.4.1\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.4.1.tgz\",\n \"integrity\": \"sha512-WfG/X9+oATh81XtllIo/I8gOiY9EXRdv1cQdyykeXK17YcUW3EXUAi2To4pcH6nZtJPr7ZOpM5OMyWJZm+8Rsg==\"\n },\n \"yallist\": {\n \"version\": \"3.0.2\",\n \"resolved\": \"https://registry.npmjs.org/yallist/-/yallist-3.0.2.tgz\",\n \"integrity\": \"sha1-hFK0u36Dx8GI2AQcGoN8dz1ti7k=\"\n }\n }\n}\n", "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.9710676670074463, 0.30186647176742554, 0.002027521375566721, 0.11718536168336868, 0.3974625766277313]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/minizlib/-/minizlib-1.1.0.tgz\",\n", " \"integrity\": \"sha512-4T6Ur/GctZ27nHfpt9THOdRZNgyJ9FZchYO1ceg5S8Q3DNLCKYy44nCZzgCJgcvx2UM8czmqak5BCxJMrq37lA==\"\n", " },\n", " \"reify\": {\n", " \"version\": \"0.13.7\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.13.7.tgz\",\n", " \"integrity\": \"sha512-jA6C/TdOf0g1A9WlQL7enh8yfGXgCmU3qbOpgc98vzRNEgu4TrAnSGec+uLxHdci96lftdBow3q0X3pbXnzmGQ==\"\n", " },\n", " \"semver\": {\n", " \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.4.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"0.14.1\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.14.1.tgz\",\n", " \"integrity\": \"sha512-HAKYzqlCCWsfAcOTm8gsJZ6FE5I06kvjzHRQTCDD6xqUJaY8Mh4ve9oiCDe8yiYXOqZqpt03gn8yS4+bokRmhQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 19}, "file": "import {isIdentifierStart, isIdentifierChar} from \"./identifier\"\nimport {types as tt, keywords as keywordTypes} from \"./tokentype\"\nimport {Parser} from \"./state\"\nimport {SourceLocation} from \"./locutil\"\nimport {lineBreak, lineBreakG, isNewLine, nonASCIIwhitespace} from \"./whitespace\"\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n constructor(p) {\n this.type = p.type\n this.value = p.value\n this.start = p.start\n this.end = p.end\n if (p.options.locations)\n this.loc = new SourceLocation(p, p.startLoc, p.endLoc)\n if (p.options.ranges)\n this.range = [p.start, p.end]\n }\n}\n\n// ## Tokenizer\n\nconst pp = Parser.prototype\n\n// Are we running under Rhino?\nconst isRhino = typeof Packages == \"object\" && Object.prototype.toString.call(Packages) == \"[object JavaPackage]\"\n\n// Move to the next token\n\npp.next = function() {\n if (this.options.onToken)\n this.options.onToken(new Token(this))\n\n this.lastTokEnd = this.end\n this.lastTokStart = this.start\n this.lastTokEndLoc = this.endLoc\n this.lastTokStartLoc = this.startLoc\n this.nextToken()\n}\n\npp.getToken = function() {\n this.next()\n return new Token(this)\n}\n\n// If we're in an ES6 environment, make parsers iterable\nif (typeof Symbol !== \"undefined\")\n pp[Symbol.iterator] = function () {\n let self = this\n return {next: function () {\n let token = self.getToken()\n return {\n done: token.type === tt.eof,\n value: token\n }\n }}\n }\n\n// Toggle strict mode. Re-reads the next number or string to please\n// pedantic tests (`\"use strict\"; 010;` should fail).\n\npp.setStrict = function(strict) {\n this.strict = strict\n if (this.type !== tt.num && this.type !== tt.string) return\n this.pos = this.start\n if (this.options.locations) {\n while (this.pos < this.lineStart) {\n this.lineStart = this.input.lastIndexOf(\"\\n\", this.lineStart - 2) + 1\n --this.curLine\n }\n }\n this.nextToken()\n}\n\npp.curContext = function() {\n return this.context[this.context.length - 1]\n}\n\n// Read a single token, updating the parser object's token-related\n// properties.\n\npp.nextToken = function() {\n let curContext = this.curContext()\n if (!curContext || !curContext.preserveSpace) this.skipSpace()\n\n this.start = this.pos\n if (this.options.locations) this.startLoc = this.curPosition()\n if (this.pos >= this.input.length) return this.finishToken(tt.eof)\n\n if (curContext.override) return curContext.override(this)\n else this.readToken(this.fullCharCodeAtPos())\n}\n\npp.readToken = function(code) {\n // Identifier or keyword. '\\uXXXX' sequences are allowed in\n // identifiers, so '\\' also dispatches to that.\n if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\\' */)\n return this.readWord()\n\n return this.getTokenFromCode(code)\n}\n\npp.fullCharCodeAtPos = function() {\n let code = this.input.charCodeAt(this.pos)\n if (code <= 0xd7ff || code >= 0xe000) return code\n let next = this.input.charCodeAt(this.pos + 1)\n return (code << 10) + next - 0x35fdc00\n}\n\npp.skipBlockComment = function() {\n let startLoc = this.options.onComment && this.curPosition()\n let start = this.pos, end = this.input.indexOf(\"*/\", this.pos += 2)\n if (end === -1) this.raise(this.pos - 2, \"Unterminated comment\")\n this.pos = end + 2\n if (this.options.locations) {\n lineBreakG.lastIndex = start\n let match\n while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {\n ++this.curLine\n this.lineStart = match.index + match[0].length\n }\n }\n if (this.options.onComment)\n this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,\n startLoc, this.curPosition())\n}\n\npp.skipLineComment = function(startSkip) {\n let start = this.pos\n let startLoc = this.options.onComment && this.curPosition()\n let ch = this.input.charCodeAt(this.pos+=startSkip)\n while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {\n ++this.pos\n ch = this.input.charCodeAt(this.pos)\n }\n if (this.options.onComment)\n this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,\n startLoc, this.curPosition())\n}\n\n// Called at the start of the parse and after every token. Skips\n// whitespace and comments, and.\n\npp.skipSpace = function() {\n loop: while (this.pos < this.input.length) {\n let ch = this.input.charCodeAt(this.pos)\n switch (ch) {\n case 32: case 160: // ' '\n ++this.pos\n break\n case 13:\n if (this.input.charCodeAt(this.pos + 1) === 10) {\n ++this.pos\n }\n case 10: case 8232: case 8233:\n ++this.pos\n if (this.options.locations) {\n ++this.curLine\n this.lineStart = this.pos\n }\n break\n case 47: // '/'\n switch (this.input.charCodeAt(this.pos + 1)) {\n case 42: // '*'\n this.skipBlockComment()\n break\n case 47:\n this.skipLineComment(2)\n break\n default:\n break loop\n }\n break\n default:\n if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {\n ++this.pos\n } else {\n break loop\n }\n }\n }\n}\n\n// Called at the end of every token. Sets `end`, `val`, and\n// maintains `context` and `exprAllowed`, and skips the space after\n// the token, so that the next one's `start` will point at the\n// right position.\n\npp.finishToken = function(type, val) {\n this.end = this.pos\n if (this.options.locations) this.endLoc = this.curPosition()\n let prevType = this.type\n this.type = type\n this.value = val\n\n this.updateContext(prevType)\n}\n\n// ### Token reading\n\n// This is the function that is called to fetch the next token. It\n// is somewhat obscure, because it works in character codes rather\n// than characters, and because operator parsing has been inlined\n// into it.\n//\n// All in the name of speed.\n//\npp.readToken_dot = function() {\n let next = this.input.charCodeAt(this.pos + 1)\n if (next >= 48 && next <= 57) return this.readNumber(true)\n let next2 = this.input.charCodeAt(this.pos + 2)\n if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'\n this.pos += 3\n return this.finishToken(tt.ellipsis)\n } else {\n ++this.pos\n return this.finishToken(tt.dot)\n }\n}\n\npp.readToken_slash = function() { // '/'\n let next = this.input.charCodeAt(this.pos + 1)\n if (this.exprAllowed) {++this.pos; return this.readRegexp()}\n if (next === 61) return this.finishOp(tt.assign, 2)\n return this.finishOp(tt.slash, 1)\n}\n\npp.readToken_mult_modulo_exp = function(code) { // '%*'\n let next = this.input.charCodeAt(this.pos + 1)\n let size = 1\n let tokentype = code === 42 ? tt.star : tt.modulo\n\n // exponentiation operator ** and **=\n if (this.options.ecmaVersion >= 7 && next === 42) {\n ++size\n tokentype = tt.starstar\n next = this.input.charCodeAt(this.pos + 2)\n }\n\n if (next === 61) return this.finishOp(tt.assign, size + 1)\n return this.finishOp(tokentype, size)\n}\n\npp.readToken_pipe_amp = function(code) { // '|&'\n let next = this.input.charCodeAt(this.pos + 1)\n if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)\n if (next === 61) return this.finishOp(tt.assign, 2)\n return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)\n}\n\npp.readToken_caret = function() { // '^'\n let next = this.input.charCodeAt(this.pos + 1)\n if (next === 61) return this.finishOp(tt.assign, 2)\n return this.finishOp(tt.bitwiseXOR, 1)\n}\n\npp.readToken_plus_min = function(code) { // '+-'\n let next = this.input.charCodeAt(this.pos + 1)\n if (next === code) {\n if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&\n lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {\n // A `-->` line comment\n this.skipLineComment(3)\n this.skipSpace()\n return this.nextToken()\n }\n return this.finishOp(tt.incDec, 2)\n }\n if (next === 61) return this.finishOp(tt.assign, 2)\n return this.finishOp(tt.plusMin, 1)\n}\n\npp.readToken_lt_gt = function(code) { // '<>'\n let next = this.input.charCodeAt(this.pos + 1)\n let size = 1\n if (next === code) {\n size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2\n if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)\n return this.finishOp(tt.bitShift, size)\n }\n if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&\n this.input.charCodeAt(this.pos + 3) == 45) {\n if (this.inModule) this.unexpected()\n // `\n", "file_path": ".github/ISSUE_TEMPLATE.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017053242481779307, 0.00016758123820181936, 0.00016318843699991703, 0.0001683020673226565, 2.9734835607087007e-06]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/minizlib/-/minizlib-1.1.0.tgz\",\n", " \"integrity\": \"sha512-4T6Ur/GctZ27nHfpt9THOdRZNgyJ9FZchYO1ceg5S8Q3DNLCKYy44nCZzgCJgcvx2UM8czmqak5BCxJMrq37lA==\"\n", " },\n", " \"reify\": {\n", " \"version\": \"0.13.7\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.13.7.tgz\",\n", " \"integrity\": \"sha512-jA6C/TdOf0g1A9WlQL7enh8yfGXgCmU3qbOpgc98vzRNEgu4TrAnSGec+uLxHdci96lftdBow3q0X3pbXnzmGQ==\"\n", " },\n", " \"semver\": {\n", " \"version\": \"5.4.1\",\n", " \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.4.1.tgz\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"version\": \"0.14.1\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.14.1.tgz\",\n", " \"integrity\": \"sha512-HAKYzqlCCWsfAcOTm8gsJZ6FE5I06kvjzHRQTCDD6xqUJaY8Mh4ve9oiCDe8yiYXOqZqpt03gn8yS4+bokRmhQ==\"\n"], "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 19}, "file": "# code-prettify\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/code-prettify) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/code-prettify)\n***\n\nThis internal Meteor package is now unnecessary and has been deprecated. To\ncontinue to use a working version of this package, please pin your package\nversion to 1.0.11 (e.g. meteor add code-prettify@=1.0.11). For details\nconcerning the deprecation of this package, see\n[issue 4445](https://github.com/meteor/meteor/issues/4445).\n", "file_path": "packages/deprecated/code-prettify/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017094594659283757, 0.00017094594659283757, 0.00017094594659283757, 0.00017094594659283757, 0.0]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " name: \"modules\",\n", " version: \"0.11.3\",\n", " summary: \"CommonJS module system\",\n", " documentation: \"README.md\"\n", "});\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" version: \"0.11.4\",\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 2}, "file": "// This file contains a package.json for the dependencies of the command-line\n// tool.\n\n// We put this in a JS file so that it can contain comments. It is processed\n// into a package.json file by generate-dev-bundle.sh.\n\nvar packageJson = {\n name: \"meteor-dev-bundle-tool\",\n private: true,\n dependencies: {\n // Explicit dependency because we are replacing it with a bundled version\n // and we want to make sure there are no dependencies on a higher version\n npm: \"5.6.0\",\n pacote: \"https://github.com/meteor/pacote/tarball/30973f140df79b647dbade03f2d6f19800c2609b\",\n \"node-gyp\": \"3.6.2\",\n \"node-pre-gyp\": \"0.6.36\",\n \"meteor-babel\": \"7.0.0-beta.38-2\",\n \"meteor-promise\": \"0.8.6\",\n promise: \"8.0.1\",\n reify: \"0.13.7\",\n fibers: \"2.0.0\",\n // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n \"@babel/runtime\": \"7.0.0-beta.38\",\n // For backwards compatibility with isopackets that still depend on\n // babel-runtime rather than @babel/runtime.\n \"babel-runtime\": \"7.0.0-beta.3\",\n // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n // in the package too) because we should consider using lodash instead\n // (and there are backwards-incompatible changes either way).\n underscore: \"1.5.2\",\n \"source-map-support\": \"https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e\",\n semver: \"5.4.1\",\n request: \"2.83.0\",\n fstream: \"https://github.com/meteor/fstream/tarball/cf4ea6c175355cec7bee38311e170d08c4078a5d\",\n tar: \"2.2.1\",\n kexec: \"3.0.0\",\n \"source-map\": \"0.5.3\",\n chalk: \"0.5.1\",\n sqlite3: \"3.1.8\",\n netroute: \"1.0.2\",\n \"http-proxy\": \"1.16.2\",\n \"wordwrap\": \"0.0.2\",\n \"moment\": \"2.20.1\",\n \"rimraf\": \"2.6.2\",\n \"glob\": \"7.1.2\",\n ignore: \"3.3.7\",\n // XXX: When we update this, see if it fixes this Github issue:\n // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the\n // workaround from the tool.\n \"commonmark\": \"0.15.0\",\n escope: \"3.6.0\",\n split2: \"2.2.0\",\n multipipe: \"2.0.1\",\n pathwatcher: \"7.1.1\",\n optimism: \"0.3.3\",\n 'lru-cache': '4.1.1',\n longjohn: '0.2.12'\n }\n};\n\nif (process.platform === 'win32') {\n // Remove dependencies that do not work on Windows\n delete packageJson.dependencies.netroute;\n delete packageJson.dependencies.kexec;\n}\n\nprocess.stdout.write(JSON.stringify(packageJson, null, 2) + '\\n');\n", "file_path": "scripts/dev-bundle-tool-package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00019460129260551184, 0.00017028381989803165, 0.00016544722893740982, 0.0001663930161157623, 9.951976608135737e-06]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " name: \"modules\",\n", " version: \"0.11.3\",\n", " summary: \"CommonJS module system\",\n", " documentation: \"README.md\"\n", "});\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" version: \"0.11.4\",\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 2}, "file": "console.warn(\n \"The `google` package has been deprecated.\\n\" +\n \"\\n\" +\n \"To use the `Google` symbol, add the `google-oauth` package\\n\" +\n \"and import from it.\\n\" +\n \"\\n\" +\n \"If you need the Blaze OAuth configuration UI, add\\n\" +\n \"`google-config-ui` alongside `accounts-ui`.\"\n);\n", "file_path": "packages/deprecated/google/deprecation_notice.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.0001688503398327157, 0.0001688503398327157, 0.0001688503398327157, 0.0001688503398327157, 0.0]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " name: \"modules\",\n", " version: \"0.11.3\",\n", " summary: \"CommonJS module system\",\n", " documentation: \"README.md\"\n", "});\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" version: \"0.11.4\",\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 2}, "file": "console.warn(\n \"The `twitter` package has been deprecated.\\n\" +\n \"\\n\" +\n \"To use the `Twitter` symbol, add the `twitter-oauth` package\\n\" +\n \"and import from it.\\n\" +\n \"\\n\" +\n \"If you need the Blaze OAuth configuration UI, add\\n\" +\n \"`twitter-config-ui` alongside `accounts-ui`.\"\n);\n", "file_path": "packages/deprecated/twitter/deprecation_notice.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00016778723511379212, 0.00016778723511379212, 0.00016778723511379212, 0.00016778723511379212, 0.0]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " name: \"modules\",\n", " version: \"0.11.3\",\n", " summary: \"CommonJS module system\",\n", " documentation: \"README.md\"\n", "});\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" version: \"0.11.4\",\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 2}, "file": "if (Meteor.isServer) {\n var passed = true;\n var expectText = \"Test\\n\";\n\n if (Assets.getText(\"test.txt\") !== expectText)\n throw new Error(\"getText test.txt does not match\");\n if (TestAsset.convert(Assets.getBinary(\"test.txt\"))\n !== expectText)\n throw new Error(\"getBinary test.txt does not match\");\n\n Assets.getText(\"test.txt\", function (err, result) {\n if (err || result !== expectText)\n throw new Error(\"async getText test.txt does not match\");\n Assets.getBinary(\"test.txt\", function (err, result) {\n if (err || TestAsset.convert(result) !== expectText)\n throw new Error(\"async getBinary test.txt does not match\");\n TestAsset.go(true /* exit when done */);\n });\n });\n}\n", "file_path": "tools/tests/old/app-with-private/main.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017816867330111563, 0.00017425553232897073, 0.00017199807916767895, 0.00017259987362194806, 2.7778874027717393e-06]} {"hunk": {"id": 4, "code_window": [" documentation: \"README.md\"\n", "});\n", "\n", "Npm.depends({\n", " reify: \"0.13.7\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "Package.describe({\n name: \"modules\",\n version: \"0.11.3\",\n summary: \"CommonJS module system\",\n documentation: \"README.md\"\n});\n\nNpm.depends({\n reify: \"0.13.7\"\n});\n\nPackage.onUse(function(api) {\n api.use(\"modules-runtime\");\n api.mainModule(\"client.js\", \"client\");\n api.mainModule(\"server.js\", \"server\");\n api.export(\"meteorInstall\");\n});\n", "file_path": "packages/modules/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.056004058569669724, 0.02989494800567627, 0.0037858355790376663, 0.02989494800567627, 0.026109110563993454]} {"hunk": {"id": 4, "code_window": [" documentation: \"README.md\"\n", "});\n", "\n", "Npm.depends({\n", " reify: \"0.13.7\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "", "file_path": "tools/tests/apps/build-errors/foo.awesome", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017712288536131382, 0.00017712288536131382, 0.00017712288536131382, 0.00017712288536131382, 0.0]} {"hunk": {"id": 4, "code_window": [" documentation: \"README.md\"\n", "});\n", "\n", "Npm.depends({\n", " reify: \"0.13.7\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "# github-oauth\n\nAn implementation of the GitHub OAuth flow. See the [Meteor Guide](https://guide.meteor.com/accounts.html) for more details.\n", "file_path": "packages/github-oauth/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017030721937771887, 0.00017030721937771887, 0.00017030721937771887, 0.00017030721937771887, 0.0]} {"hunk": {"id": 4, "code_window": [" documentation: \"README.md\"\n", "});\n", "\n", "Npm.depends({\n", " reify: \"0.13.7\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "export const packageName = \"bundle-visualizer\";\nexport const classPrefix = \"meteorBundleVisualizer\";\nexport const methodNameStats = `/__meteor__/${packageName}/stats`;\nexport const typeBundle = \"bundle\";\nexport const typePackage = \"package\";\nexport const typeNodeModules = \"node_modules\";\n\nfunction capitalizeFirstLetter(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nexport function prefixedClass(className) {\n return `${classPrefix}${capitalizeFirstLetter(className)}`;\n}\n", "file_path": "packages/non-core/bundle-visualizer/common.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.0027112362440675497, 0.0014411911834031343, 0.00017114606453105807, 0.0014411911834031343, 0.0012700450606644154]} {"hunk": {"id": 5, "code_window": [" \"meteor-babel\": \"7.0.0-beta.38-2\",\n", " \"meteor-promise\": \"0.8.6\",\n", " promise: \"8.0.1\",\n", " reify: \"0.13.7\",\n", " fibers: \"2.0.0\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.0.0-beta.38\",\n", " // For backwards compatibility with isopackets that still depend on\n", " // babel-runtime rather than @babel/runtime.\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "// This file contains a package.json for the dependencies of the command-line\n// tool.\n\n// We put this in a JS file so that it can contain comments. It is processed\n// into a package.json file by generate-dev-bundle.sh.\n\nvar packageJson = {\n name: \"meteor-dev-bundle-tool\",\n private: true,\n dependencies: {\n // Explicit dependency because we are replacing it with a bundled version\n // and we want to make sure there are no dependencies on a higher version\n npm: \"5.6.0\",\n pacote: \"https://github.com/meteor/pacote/tarball/30973f140df79b647dbade03f2d6f19800c2609b\",\n \"node-gyp\": \"3.6.2\",\n \"node-pre-gyp\": \"0.6.36\",\n \"meteor-babel\": \"7.0.0-beta.38-2\",\n \"meteor-promise\": \"0.8.6\",\n promise: \"8.0.1\",\n reify: \"0.13.7\",\n fibers: \"2.0.0\",\n // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n \"@babel/runtime\": \"7.0.0-beta.38\",\n // For backwards compatibility with isopackets that still depend on\n // babel-runtime rather than @babel/runtime.\n \"babel-runtime\": \"7.0.0-beta.3\",\n // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n // in the package too) because we should consider using lodash instead\n // (and there are backwards-incompatible changes either way).\n underscore: \"1.5.2\",\n \"source-map-support\": \"https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e\",\n semver: \"5.4.1\",\n request: \"2.83.0\",\n fstream: \"https://github.com/meteor/fstream/tarball/cf4ea6c175355cec7bee38311e170d08c4078a5d\",\n tar: \"2.2.1\",\n kexec: \"3.0.0\",\n \"source-map\": \"0.5.3\",\n chalk: \"0.5.1\",\n sqlite3: \"3.1.8\",\n netroute: \"1.0.2\",\n \"http-proxy\": \"1.16.2\",\n \"wordwrap\": \"0.0.2\",\n \"moment\": \"2.20.1\",\n \"rimraf\": \"2.6.2\",\n \"glob\": \"7.1.2\",\n ignore: \"3.3.7\",\n // XXX: When we update this, see if it fixes this Github issue:\n // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the\n // workaround from the tool.\n \"commonmark\": \"0.15.0\",\n escope: \"3.6.0\",\n split2: \"2.2.0\",\n multipipe: \"2.0.1\",\n pathwatcher: \"7.1.1\",\n optimism: \"0.3.3\",\n 'lru-cache': '4.1.1',\n longjohn: '0.2.12'\n }\n};\n\nif (process.platform === 'win32') {\n // Remove dependencies that do not work on Windows\n delete packageJson.dependencies.netroute;\n delete packageJson.dependencies.kexec;\n}\n\nprocess.stdout.write(JSON.stringify(packageJson, null, 2) + '\\n');\n", "file_path": "scripts/dev-bundle-tool-package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.9388132691383362, 0.14162814617156982, 0.00016561438678763807, 0.00016760862490627915, 0.3259354531764984]} {"hunk": {"id": 5, "code_window": [" \"meteor-babel\": \"7.0.0-beta.38-2\",\n", " \"meteor-promise\": \"0.8.6\",\n", " promise: \"8.0.1\",\n", " reify: \"0.13.7\",\n", " fibers: \"2.0.0\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.0.0-beta.38\",\n", " // For backwards compatibility with isopackets that still depend on\n", " // babel-runtime rather than @babel/runtime.\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "// These tests were written before rate-limit was factored outside of DDP Rate\n// Limiter and thus are structured with DDP method invocations in mind. These\n// rules still test abstract rate limit package behavior. The tests currently\n// implemented are:\n// * Empty rule set on RateLimiter construction\n// * Multiple inputs, only 1 that matches rule and reaches rate limit\n// * Multiple inputs, 1 hits rate limit, wait for reset, after which inputs\n// allowed\n// * 2 rules, 3 inputs where 2/3 match 1 rule and thus hit rate limit. Second\n// input matches another rule and hits rate limit while 3rd rule not rate\n// limited\n// * One rule affected by two inputs still throws\n// * Global rule triggers on any invocation after reaching limit\n// * Fuzzy rule matching triggers rate limit only when input has more keys than\n// rule\n// * matchRule tests that have various levels of similarity in input and rule\n// * generateKeyString tests for various matches creating appropriate string\n//\n// XXX These tests should be refactored to use Tinytest.add instead of\n// testAsyncMulti as they're all on the server. Any future tests should be\n// written that way.\nTinytest.add('rate limit tests - Check empty constructor creation',\n function (test) {\n r = new RateLimiter();\n test.equal(r.rules, {});\n});\n\nTinytest.add('rate limit tests - Check single rule with multiple ' +\n 'invocations, only 1 that matches',\n function (test) {\n r = new RateLimiter();\n var userIdOne = 1;\n var restrictJustUserIdOneRule = {\n userId: userIdOne,\n IPAddr: null,\n method: null\n };\n\n r.addRule(restrictJustUserIdOneRule, 1, 1000);\n var connectionHandle = createTempConnectionHandle(123, '127.0.0.1');\n var methodInvc1 = createTempMethodInvocation(userIdOne, connectionHandle,\n 'login');\n var methodInvc2 = createTempMethodInvocation(2, connectionHandle,\n 'login');\n for (var i = 0; i < 2; i++) {\n r.increment(methodInvc1);\n r.increment(methodInvc2);\n }\n test.equal(r.check(methodInvc1).allowed, false);\n test.equal(r.check(methodInvc2).allowed, true);\n });\n\ntestAsyncMulti(\"rate limit tests - Run multiple invocations and wait for one\" +\n \" to reset\", [\n function (test, expect) {\n var self = this;\n self.r = new RateLimiter();\n self.userIdOne = 1;\n self.userIdTwo = 2;\n self.restrictJustUserIdOneRule = {\n userId: self.userIdOne,\n IPAddr: null,\n method: null\n };\n self.r.addRule(self.restrictJustUserIdOneRule, 1, 500);\n self.connectionHandle = createTempConnectionHandle(123, '127.0.0.1')\n self.methodInvc1 = createTempMethodInvocation(self.userIdOne,\n self.connectionHandle, 'login');\n self.methodInvc2 = createTempMethodInvocation(self.userIdTwo,\n self.connectionHandle, 'login');\n for (var i = 0; i < 2; i++) {\n self.r.increment(self.methodInvc1);\n self.r.increment(self.methodInvc2);\n }\n test.equal(self.r.check(self.methodInvc1).allowed, false);\n test.equal(self.r.check(self.methodInvc2).allowed, true);\n Meteor.setTimeout(expect(function () {}), 1000);\n },\n function (test, expect) {\n var self = this;\n for (var i = 0; i < 100; i++) {\n self.r.increment(self.methodInvc2);\n }\n\n test.equal(self.r.check(self.methodInvc1).allowed, true);\n test.equal(self.r.check(self.methodInvc2).allowed, true);\n }\n]);\n\nTinytest.add('rate limit tests - Check two rules that affect same methodInvc' +\n ' still throw',\n function (test) {\n r = new RateLimiter();\n var loginMethodRule = {\n userId: null,\n IPAddr: null,\n method: 'login'\n };\n var onlyLimitEvenUserIdRule = {\n userId: function (userId) {\n return userId % 2 === 0\n },\n IPAddr: null,\n method: null\n };\n r.addRule(loginMethodRule, 10, 100);\n r.addRule(onlyLimitEvenUserIdRule, 4, 100);\n\n var connectionHandle = createTempConnectionHandle(1234, '127.0.0.1');\n var methodInvc1 = createTempMethodInvocation(1, connectionHandle,\n 'login');\n var methodInvc2 = createTempMethodInvocation(2, connectionHandle,\n 'login');\n var methodInvc3 = createTempMethodInvocation(3, connectionHandle,\n 'test');\n\n for (var i = 0; i < 5; i++) {\n r.increment(methodInvc1);\n r.increment(methodInvc2);\n r.increment(methodInvc3);\n };\n\n // After for loop runs, we only have 10 runs, so that's under the limit\n test.equal(r.check(methodInvc1).allowed, true);\n // However, this triggers userId rule since this userId is even\n test.equal(r.check(methodInvc2).allowed, false);\n test.equal(r.check(methodInvc2).allowed, false);\n\n // Running one more test causes it to be false, since we're at 11 now.\n r.increment(methodInvc1);\n test.equal(r.check(methodInvc1).allowed, false);\n // 3rd Method Invocation isn't affected by either rules.\n test.equal(r.check(methodInvc3).allowed, true);\n\n });\n\nTinytest.add('rate limit tests - Check one rule affected by two different ' +\n 'invocations',\n function (test) {\n r = new RateLimiter();\n var loginMethodRule = {\n userId: null,\n IPAddr: null,\n method: 'login'\n }\n r.addRule(loginMethodRule, 10, 10000);\n\n var connectionHandle = createTempConnectionHandle(1234, '127.0.0.1');\n var methodInvc1 = createTempMethodInvocation(1, connectionHandle,\n 'login');\n var methodInvc2 = createTempMethodInvocation(2, connectionHandle,\n 'login');\n\n for (var i = 0; i < 5; i++) {\n r.increment(methodInvc1);\n r.increment(methodInvc2);\n }\n // This throws us over the limit since both increment the login rule\n // counter\n r.increment(methodInvc1);\n\n test.equal(r.check(methodInvc1).allowed, false);\n test.equal(r.check(methodInvc2).allowed, false);\n });\n\nTinytest.add(\"rate limit tests - add global rule\", function (test) {\n r = new RateLimiter();\n var globalRule = {\n userId: null,\n IPAddr: null,\n method: null\n }\n r.addRule(globalRule, 1, 10000);\n\n var connectionHandle = createTempConnectionHandle(1234, '127.0.0.1');\n var connectionHandle2 = createTempConnectionHandle(1234, '127.0.0.2');\n\n var methodInvc1 = createTempMethodInvocation(1, connectionHandle,\n 'login');\n var methodInvc2 = createTempMethodInvocation(2, connectionHandle2,\n 'test');\n var methodInvc3 = createTempMethodInvocation(3, connectionHandle,\n 'user-accounts');\n\n // First invocation, all methods would still be allowed.\n r.increment(methodInvc2);\n test.equal(r.check(methodInvc1).allowed, true);\n test.equal(r.check(methodInvc2).allowed, true);\n test.equal(r.check(methodInvc3).allowed, true);\n // Second invocation, everything has reached common rate limit\n r.increment(methodInvc3);\n test.equal(r.check(methodInvc1).allowed, false);\n test.equal(r.check(methodInvc2).allowed, false);\n test.equal(r.check(methodInvc3).allowed, false);\n});\n\nTinytest.add('rate limit tests - Fuzzy rule match does not trigger rate limit',\n function (test) {\n r = new RateLimiter();\n var rule = {\n a: function (inp) {\n return inp % 3 == 0\n },\n b: 5,\n c: \"hi\",\n }\n r.addRule(rule, 1, 10000);\n var input = {\n a: 3,\n b: 5\n }\n for (var i = 0; i < 5; i++) {\n r.increment(input);\n }\n test.equal(r.check(input).allowed, true);\n var matchingInput = {\n a: 3,\n b: 5,\n c: \"hi\",\n d: 1\n }\n r.increment(matchingInput);\n r.increment(matchingInput);\n // Past limit so should be false\n test.equal(r.check(matchingInput).allowed, false);\n\n // Add secondary rule and check that longer time is returned when multiple\n // rules limits are hit\n var newRule = {\n a: function (inp) {\n return inp % 3 == 0\n },\n b: 5,\n c: \"hi\",\n d: 1\n }\n r.addRule(newRule, 1, 10);\n // First rule should still throw while second rule will trigger as well,\n // causing us to return longer time to reset to user\n r.increment(matchingInput);\n r.increment(matchingInput);\n test.equal(r.check(matchingInput).timeToReset > 50, true);\n }\n);\n\n\n/****** Test Our Helper Methods *****/\n\nTinytest.add(\"rate limit tests - test matchRule method\", function (test) {\n r = new RateLimiter();\n var globalRule = {\n userId: null,\n IPAddr: null,\n type: null,\n name: null\n }\n var globalRuleId = r.addRule(globalRule);\n\n var rateLimiterInput = {\n userId: 1023,\n IPAddr: \"127.0.0.1\",\n type: 'sub',\n name: 'getSubLists'\n };\n\n test.equal(r.rules[globalRuleId].match(rateLimiterInput), true);\n\n var oneNotNullRule = {\n userId: 102,\n IPAddr: null,\n type: null,\n name: null\n }\n\n var oneNotNullId = r.addRule(oneNotNullRule);\n test.equal(r.rules[oneNotNullId].match(rateLimiterInput), false);\n\n oneNotNullRule.userId = 1023;\n test.equal(r.rules[oneNotNullId].match(rateLimiterInput), true);\n\n var notCompleteInput = {\n userId: 102,\n IPAddr: '127.0.0.1'\n };\n test.equal(r.rules[globalRuleId].match(notCompleteInput), true);\n test.equal(r.rules[oneNotNullId].match(notCompleteInput), false);\n});\n\nTinytest.add('rate limit tests - test generateMethodKey string',\n function (test) {\n r = new RateLimiter();\n var globalRule = {\n userId: null,\n IPAddr: null,\n type: null,\n name: null\n }\n var globalRuleId = r.addRule(globalRule);\n\n var rateLimiterInput = {\n userId: 1023,\n IPAddr: \"127.0.0.1\",\n type: 'sub',\n name: 'getSubLists'\n };\n\n test.equal(r.rules[globalRuleId]._generateKeyString(rateLimiterInput), \"\");\n globalRule.userId = 1023;\n\n test.equal(r.rules[globalRuleId]._generateKeyString(rateLimiterInput),\n \"userId1023\");\n\n var ruleWithFuncs = {\n userId: function (input) {\n return input % 2 === 0\n },\n IPAddr: null,\n type: null\n };\n var funcRuleId = r.addRule(ruleWithFuncs);\n test.equal(r.rules[funcRuleId]._generateKeyString(rateLimiterInput), \"\");\n rateLimiterInput.userId = 1024;\n test.equal(r.rules[funcRuleId]._generateKeyString(rateLimiterInput),\n \"userId1024\");\n\n var multipleRules = ruleWithFuncs;\n multipleRules.IPAddr = '127.0.0.1';\n var multipleRuleId = r.addRule(multipleRules);\n test.equal(r.rules[multipleRuleId]._generateKeyString(rateLimiterInput),\n \"userId1024IPAddr127.0.0.1\")\n }\n);\n\nfunction createTempConnectionHandle(id, clientIP) {\n return {\n id: id,\n close: function () {\n self.close();\n },\n onClose: function (fn) {\n var cb = Meteor.bindEnvironment(fn, \"connection onClose callback\");\n if (self.inQueue) {\n self._closeCallbacks.push(cb);\n } else {\n // if we're already closed, call the callback.\n Meteor.defer(cb);\n }\n },\n clientAddress: clientIP,\n httpHeaders: null\n };\n}\n\nfunction createTempMethodInvocation(userId, connectionHandle, methodName) {\n var methodInv = new DDPCommon.MethodInvocation({\n isSimulation: false,\n userId: userId,\n setUserId: null,\n unblock: false,\n connection: connectionHandle,\n randomSeed: 1234\n });\n methodInv.method = methodName;\n return methodInv;\n}", "file_path": "packages/rate-limit/rate-limit-tests.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017613611998967826, 0.0001714397076284513, 0.0001637223904253915, 0.00017209633369930089, 2.9860759696020978e-06]} {"hunk": {"id": 5, "code_window": [" \"meteor-babel\": \"7.0.0-beta.38-2\",\n", " \"meteor-promise\": \"0.8.6\",\n", " promise: \"8.0.1\",\n", " reify: \"0.13.7\",\n", " fibers: \"2.0.0\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.0.0-beta.38\",\n", " // For backwards compatibility with isopackets that still depend on\n", " // babel-runtime rather than @babel/runtime.\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "# ecmascript-runtime-server\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/ecmascript-runtime-server) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/ecmascript-runtime-server)\n***\n\n[![Build Status](https://travis-ci.org/meteor/ecmascript-runtime.svg?branch=master)](https://travis-ci.org/meteor/ecmascript-runtime)\nPolyfills for new ECMAScript 2015 APIs like Map and Set\n", "file_path": "packages/ecmascript-runtime-server/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.0002317761245649308, 0.0002317761245649308, 0.0002317761245649308, 0.0002317761245649308, 0.0]} {"hunk": {"id": 5, "code_window": [" \"meteor-babel\": \"7.0.0-beta.38-2\",\n", " \"meteor-promise\": \"0.8.6\",\n", " promise: \"8.0.1\",\n", " reify: \"0.13.7\",\n", " fibers: \"2.0.0\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.0.0-beta.38\",\n", " // For backwards compatibility with isopackets that still depend on\n", " // babel-runtime rather than @babel/runtime.\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.14.1\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 19}, "file": ".build*\n", "file_path": "packages/browser-policy-content/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00016984227113425732, 0.00016984227113425732, 0.00016984227113425732, 0.00016984227113425732, 0.0]} {"hunk": {"id": 6, "code_window": [" \"commonmark\": \"0.15.0\",\n", " escope: \"3.6.0\",\n", " split2: \"2.2.0\",\n", " multipipe: \"2.0.1\",\n", " pathwatcher: \"7.1.1\",\n", " optimism: \"0.3.3\",\n", " 'lru-cache': '4.1.1',\n", " longjohn: '0.2.12'\n", " }\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" optimism: \"0.4.0\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 54}, "file": "Package.describe({\n name: \"modules\",\n version: \"0.11.3\",\n summary: \"CommonJS module system\",\n documentation: \"README.md\"\n});\n\nNpm.depends({\n reify: \"0.13.7\"\n});\n\nPackage.onUse(function(api) {\n api.use(\"modules-runtime\");\n api.mainModule(\"client.js\", \"client\");\n api.mainModule(\"server.js\", \"server\");\n api.export(\"meteorInstall\");\n});\n", "file_path": "packages/modules/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017266703071072698, 0.00017134204972535372, 0.0001700170832918957, 0.00017134204972535372, 1.3249737094156444e-06]} {"hunk": {"id": 6, "code_window": [" \"commonmark\": \"0.15.0\",\n", " escope: \"3.6.0\",\n", " split2: \"2.2.0\",\n", " multipipe: \"2.0.1\",\n", " pathwatcher: \"7.1.1\",\n", " optimism: \"0.3.3\",\n", " 'lru-cache': '4.1.1',\n", " longjohn: '0.2.12'\n", " }\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" optimism: \"0.4.0\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 54}, "file": "var Future = Npm.require('fibers/future');\n\nvar PHASE = {\n QUERYING: \"QUERYING\",\n FETCHING: \"FETCHING\",\n STEADY: \"STEADY\"\n};\n\n// Exception thrown by _needToPollQuery which unrolls the stack up to the\n// enclosing call to finishIfNeedToPollQuery.\nvar SwitchedToQuery = function () {};\nvar finishIfNeedToPollQuery = function (f) {\n return function () {\n try {\n f.apply(this, arguments);\n } catch (e) {\n if (!(e instanceof SwitchedToQuery))\n throw e;\n }\n };\n};\n\nvar currentId = 0;\n\n// OplogObserveDriver is an alternative to PollingObserveDriver which follows\n// the Mongo operation log instead of just re-polling the query. It obeys the\n// same simple interface: constructing it starts sending observeChanges\n// callbacks (and a ready() invocation) to the ObserveMultiplexer, and you stop\n// it by calling the stop() method.\nOplogObserveDriver = function (options) {\n var self = this;\n self._usesOplog = true; // tests look at this\n\n self._id = currentId;\n currentId++;\n\n self._cursorDescription = options.cursorDescription;\n self._mongoHandle = options.mongoHandle;\n self._multiplexer = options.multiplexer;\n\n if (options.ordered) {\n throw Error(\"OplogObserveDriver only supports unordered observeChanges\");\n }\n\n var sorter = options.sorter;\n // We don't support $near and other geo-queries so it's OK to initialize the\n // comparator only once in the constructor.\n var comparator = sorter && sorter.getComparator();\n\n if (options.cursorDescription.options.limit) {\n // There are several properties ordered driver implements:\n // - _limit is a positive number\n // - _comparator is a function-comparator by which the query is ordered\n // - _unpublishedBuffer is non-null Min/Max Heap,\n // the empty buffer in STEADY phase implies that the\n // everything that matches the queries selector fits\n // into published set.\n // - _published - Min Heap (also implements IdMap methods)\n\n var heapOptions = { IdMap: LocalCollection._IdMap };\n self._limit = self._cursorDescription.options.limit;\n self._comparator = comparator;\n self._sorter = sorter;\n self._unpublishedBuffer = new MinMaxHeap(comparator, heapOptions);\n // We need something that can find Max value in addition to IdMap interface\n self._published = new MaxHeap(comparator, heapOptions);\n } else {\n self._limit = 0;\n self._comparator = null;\n self._sorter = null;\n self._unpublishedBuffer = null;\n self._published = new LocalCollection._IdMap;\n }\n\n // Indicates if it is safe to insert a new document at the end of the buffer\n // for this query. i.e. it is known that there are no documents matching the\n // selector those are not in published or buffer.\n self._safeAppendToBuffer = false;\n\n self._stopped = false;\n self._stopHandles = [];\n\n Package.facts && Package.facts.Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-oplog\", 1);\n\n self._registerPhaseChange(PHASE.QUERYING);\n\n self._matcher = options.matcher;\n var projection = self._cursorDescription.options.fields || {};\n self._projectionFn = LocalCollection._compileProjection(projection);\n // Projection function, result of combining important fields for selector and\n // existing fields projection\n self._sharedProjection = self._matcher.combineIntoProjection(projection);\n if (sorter)\n self._sharedProjection = sorter.combineIntoProjection(self._sharedProjection);\n self._sharedProjectionFn = LocalCollection._compileProjection(\n self._sharedProjection);\n\n self._needToFetch = new LocalCollection._IdMap;\n self._currentlyFetching = null;\n self._fetchGeneration = 0;\n\n self._requeryWhenDoneThisQuery = false;\n self._writesToCommitWhenWeReachSteady = [];\n\n // If the oplog handle tells us that it skipped some entries (because it got\n // behind, say), re-poll.\n self._stopHandles.push(self._mongoHandle._oplogHandle.onSkippedEntries(\n finishIfNeedToPollQuery(function () {\n self._needToPollQuery();\n })\n ));\n\n forEachTrigger(self._cursorDescription, function (trigger) {\n self._stopHandles.push(self._mongoHandle._oplogHandle.onOplogEntry(\n trigger, function (notification) {\n Meteor._noYieldsAllowed(finishIfNeedToPollQuery(function () {\n var op = notification.op;\n if (notification.dropCollection || notification.dropDatabase) {\n // Note: this call is not allowed to block on anything (especially\n // on waiting for oplog entries to catch up) because that will block\n // onOplogEntry!\n self._needToPollQuery();\n } else {\n // All other operators should be handled depending on phase\n if (self._phase === PHASE.QUERYING) {\n self._handleOplogEntryQuerying(op);\n } else {\n self._handleOplogEntrySteadyOrFetching(op);\n }\n }\n }));\n }\n ));\n });\n\n // XXX ordering w.r.t. everything else?\n self._stopHandles.push(listenAll(\n self._cursorDescription, function (notification) {\n // If we're not in a pre-fire write fence, we don't have to do anything.\n var fence = DDPServer._CurrentWriteFence.get();\n if (!fence || fence.fired)\n return;\n\n if (fence._oplogObserveDrivers) {\n fence._oplogObserveDrivers[self._id] = self;\n return;\n }\n\n fence._oplogObserveDrivers = {};\n fence._oplogObserveDrivers[self._id] = self;\n\n fence.onBeforeFire(function () {\n var drivers = fence._oplogObserveDrivers;\n delete fence._oplogObserveDrivers;\n\n // This fence cannot fire until we've caught up to \"this point\" in the\n // oplog, and all observers made it back to the steady state.\n self._mongoHandle._oplogHandle.waitUntilCaughtUp();\n\n _.each(drivers, function (driver) {\n if (driver._stopped)\n return;\n\n var write = fence.beginWrite();\n if (driver._phase === PHASE.STEADY) {\n // Make sure that all of the callbacks have made it through the\n // multiplexer and been delivered to ObserveHandles before committing\n // writes.\n driver._multiplexer.onFlush(function () {\n write.committed();\n });\n } else {\n driver._writesToCommitWhenWeReachSteady.push(write);\n }\n });\n });\n }\n ));\n\n // When Mongo fails over, we need to repoll the query, in case we processed an\n // oplog entry that got rolled back.\n self._stopHandles.push(self._mongoHandle._onFailover(finishIfNeedToPollQuery(\n function () {\n self._needToPollQuery();\n })));\n\n // Give _observeChanges a chance to add the new ObserveHandle to our\n // multiplexer, so that the added calls get streamed.\n Meteor.defer(finishIfNeedToPollQuery(function () {\n self._runInitialQuery();\n }));\n};\n\n_.extend(OplogObserveDriver.prototype, {\n _addPublished: function (id, doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var fields = _.clone(doc);\n delete fields._id;\n self._published.set(id, self._sharedProjectionFn(doc));\n self._multiplexer.added(id, self._projectionFn(fields));\n\n // After adding this document, the published set might be overflowed\n // (exceeding capacity specified by limit). If so, push the maximum\n // element to the buffer, we might want to save it in memory to reduce the\n // amount of Mongo lookups in the future.\n if (self._limit && self._published.size() > self._limit) {\n // XXX in theory the size of published is no more than limit+1\n if (self._published.size() !== self._limit + 1) {\n throw new Error(\"After adding to published, \" +\n (self._published.size() - self._limit) +\n \" documents are overflowing the set\");\n }\n\n var overflowingDocId = self._published.maxElementId();\n var overflowingDoc = self._published.get(overflowingDocId);\n\n if (EJSON.equals(overflowingDocId, id)) {\n throw new Error(\"The document just added is overflowing the published set\");\n }\n\n self._published.remove(overflowingDocId);\n self._multiplexer.removed(overflowingDocId);\n self._addBuffered(overflowingDocId, overflowingDoc);\n }\n });\n },\n _removePublished: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._published.remove(id);\n self._multiplexer.removed(id);\n if (! self._limit || self._published.size() === self._limit)\n return;\n\n if (self._published.size() > self._limit)\n throw Error(\"self._published got too big\");\n\n // OK, we are publishing less than the limit. Maybe we should look in the\n // buffer to find the next element past what we were publishing before.\n\n if (!self._unpublishedBuffer.empty()) {\n // There's something in the buffer; move the first thing in it to\n // _published.\n var newDocId = self._unpublishedBuffer.minElementId();\n var newDoc = self._unpublishedBuffer.get(newDocId);\n self._removeBuffered(newDocId);\n self._addPublished(newDocId, newDoc);\n return;\n }\n\n // There's nothing in the buffer. This could mean one of a few things.\n\n // (a) We could be in the middle of re-running the query (specifically, we\n // could be in _publishNewResults). In that case, _unpublishedBuffer is\n // empty because we clear it at the beginning of _publishNewResults. In\n // this case, our caller already knows the entire answer to the query and\n // we don't need to do anything fancy here. Just return.\n if (self._phase === PHASE.QUERYING)\n return;\n\n // (b) We're pretty confident that the union of _published and\n // _unpublishedBuffer contain all documents that match selector. Because\n // _unpublishedBuffer is empty, that means we're confident that _published\n // contains all documents that match selector. So we have nothing to do.\n if (self._safeAppendToBuffer)\n return;\n\n // (c) Maybe there are other documents out there that should be in our\n // buffer. But in that case, when we emptied _unpublishedBuffer in\n // _removeBuffered, we should have called _needToPollQuery, which will\n // either put something in _unpublishedBuffer or set _safeAppendToBuffer\n // (or both), and it will put us in QUERYING for that whole time. So in\n // fact, we shouldn't be able to get here.\n\n throw new Error(\"Buffer inexplicably empty\");\n });\n },\n _changePublished: function (id, oldDoc, newDoc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._published.set(id, self._sharedProjectionFn(newDoc));\n var projectedNew = self._projectionFn(newDoc);\n var projectedOld = self._projectionFn(oldDoc);\n var changed = DiffSequence.makeChangedFields(\n projectedNew, projectedOld);\n if (!_.isEmpty(changed))\n self._multiplexer.changed(id, changed);\n });\n },\n _addBuffered: function (id, doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._unpublishedBuffer.set(id, self._sharedProjectionFn(doc));\n\n // If something is overflowing the buffer, we just remove it from cache\n if (self._unpublishedBuffer.size() > self._limit) {\n var maxBufferedId = self._unpublishedBuffer.maxElementId();\n\n self._unpublishedBuffer.remove(maxBufferedId);\n\n // Since something matching is removed from cache (both published set and\n // buffer), set flag to false\n self._safeAppendToBuffer = false;\n }\n });\n },\n // Is called either to remove the doc completely from matching set or to move\n // it to the published set later.\n _removeBuffered: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._unpublishedBuffer.remove(id);\n // To keep the contract \"buffer is never empty in STEADY phase unless the\n // everything matching fits into published\" true, we poll everything as\n // soon as we see the buffer becoming empty.\n if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer)\n self._needToPollQuery();\n });\n },\n // Called when a document has joined the \"Matching\" results set.\n // Takes responsibility of keeping _unpublishedBuffer in sync with _published\n // and the effect of limit enforced.\n _addMatching: function (doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var id = doc._id;\n if (self._published.has(id))\n throw Error(\"tried to add something already published \" + id);\n if (self._limit && self._unpublishedBuffer.has(id))\n throw Error(\"tried to add something already existed in buffer \" + id);\n\n var limit = self._limit;\n var comparator = self._comparator;\n var maxPublished = (limit && self._published.size() > 0) ?\n self._published.get(self._published.maxElementId()) : null;\n var maxBuffered = (limit && self._unpublishedBuffer.size() > 0)\n ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId())\n : null;\n // The query is unlimited or didn't publish enough documents yet or the\n // new document would fit into published set pushing the maximum element\n // out, then we need to publish the doc.\n var toPublish = ! limit || self._published.size() < limit ||\n comparator(doc, maxPublished) < 0;\n\n // Otherwise we might need to buffer it (only in case of limited query).\n // Buffering is allowed if the buffer is not filled up yet and all\n // matching docs are either in the published set or in the buffer.\n var canAppendToBuffer = !toPublish && self._safeAppendToBuffer &&\n self._unpublishedBuffer.size() < limit;\n\n // Or if it is small enough to be safely inserted to the middle or the\n // beginning of the buffer.\n var canInsertIntoBuffer = !toPublish && maxBuffered &&\n comparator(doc, maxBuffered) <= 0;\n\n var toBuffer = canAppendToBuffer || canInsertIntoBuffer;\n\n if (toPublish) {\n self._addPublished(id, doc);\n } else if (toBuffer) {\n self._addBuffered(id, doc);\n } else {\n // dropping it and not saving to the cache\n self._safeAppendToBuffer = false;\n }\n });\n },\n // Called when a document leaves the \"Matching\" results set.\n // Takes responsibility of keeping _unpublishedBuffer in sync with _published\n // and the effect of limit enforced.\n _removeMatching: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (! self._published.has(id) && ! self._limit)\n throw Error(\"tried to remove something matching but not cached \" + id);\n\n if (self._published.has(id)) {\n self._removePublished(id);\n } else if (self._unpublishedBuffer.has(id)) {\n self._removeBuffered(id);\n }\n });\n },\n _handleDoc: function (id, newDoc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var matchesNow = newDoc && self._matcher.documentMatches(newDoc).result;\n\n var publishedBefore = self._published.has(id);\n var bufferedBefore = self._limit && self._unpublishedBuffer.has(id);\n var cachedBefore = publishedBefore || bufferedBefore;\n\n if (matchesNow && !cachedBefore) {\n self._addMatching(newDoc);\n } else if (cachedBefore && !matchesNow) {\n self._removeMatching(id);\n } else if (cachedBefore && matchesNow) {\n var oldDoc = self._published.get(id);\n var comparator = self._comparator;\n var minBuffered = self._limit && self._unpublishedBuffer.size() &&\n self._unpublishedBuffer.get(self._unpublishedBuffer.minElementId());\n var maxBuffered;\n\n if (publishedBefore) {\n // Unlimited case where the document stays in published once it\n // matches or the case when we don't have enough matching docs to\n // publish or the changed but matching doc will stay in published\n // anyways.\n //\n // XXX: We rely on the emptiness of buffer. Be sure to maintain the\n // fact that buffer can't be empty if there are matching documents not\n // published. Notably, we don't want to schedule repoll and continue\n // relying on this property.\n var staysInPublished = ! self._limit ||\n self._unpublishedBuffer.size() === 0 ||\n comparator(newDoc, minBuffered) <= 0;\n\n if (staysInPublished) {\n self._changePublished(id, oldDoc, newDoc);\n } else {\n // after the change doc doesn't stay in the published, remove it\n self._removePublished(id);\n // but it can move into buffered now, check it\n maxBuffered = self._unpublishedBuffer.get(\n self._unpublishedBuffer.maxElementId());\n\n var toBuffer = self._safeAppendToBuffer ||\n (maxBuffered && comparator(newDoc, maxBuffered) <= 0);\n\n if (toBuffer) {\n self._addBuffered(id, newDoc);\n } else {\n // Throw away from both published set and buffer\n self._safeAppendToBuffer = false;\n }\n }\n } else if (bufferedBefore) {\n oldDoc = self._unpublishedBuffer.get(id);\n // remove the old version manually instead of using _removeBuffered so\n // we don't trigger the querying immediately. if we end this block\n // with the buffer empty, we will need to trigger the query poll\n // manually too.\n self._unpublishedBuffer.remove(id);\n\n var maxPublished = self._published.get(\n self._published.maxElementId());\n maxBuffered = self._unpublishedBuffer.size() &&\n self._unpublishedBuffer.get(\n self._unpublishedBuffer.maxElementId());\n\n // the buffered doc was updated, it could move to published\n var toPublish = comparator(newDoc, maxPublished) < 0;\n\n // or stays in buffer even after the change\n var staysInBuffer = (! toPublish && self._safeAppendToBuffer) ||\n (!toPublish && maxBuffered &&\n comparator(newDoc, maxBuffered) <= 0);\n\n if (toPublish) {\n self._addPublished(id, newDoc);\n } else if (staysInBuffer) {\n // stays in buffer but changes\n self._unpublishedBuffer.set(id, newDoc);\n } else {\n // Throw away from both published set and buffer\n self._safeAppendToBuffer = false;\n // Normally this check would have been done in _removeBuffered but\n // we didn't use it, so we need to do it ourself now.\n if (! self._unpublishedBuffer.size()) {\n self._needToPollQuery();\n }\n }\n } else {\n throw new Error(\"cachedBefore implies either of publishedBefore or bufferedBefore is true.\");\n }\n }\n });\n },\n _fetchModifiedDocuments: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._registerPhaseChange(PHASE.FETCHING);\n // Defer, because nothing called from the oplog entry handler may yield,\n // but fetch() yields.\n Meteor.defer(finishIfNeedToPollQuery(function () {\n while (!self._stopped && !self._needToFetch.empty()) {\n if (self._phase === PHASE.QUERYING) {\n // While fetching, we decided to go into QUERYING mode, and then we\n // saw another oplog entry, so _needToFetch is not empty. But we\n // shouldn't fetch these documents until AFTER the query is done.\n break;\n }\n\n // Being in steady phase here would be surprising.\n if (self._phase !== PHASE.FETCHING)\n throw new Error(\"phase in fetchModifiedDocuments: \" + self._phase);\n\n self._currentlyFetching = self._needToFetch;\n var thisGeneration = ++self._fetchGeneration;\n self._needToFetch = new LocalCollection._IdMap;\n var waiting = 0;\n var fut = new Future;\n // This loop is safe, because _currentlyFetching will not be updated\n // during this loop (in fact, it is never mutated).\n self._currentlyFetching.forEach(function (cacheKey, id) {\n waiting++;\n self._mongoHandle._docFetcher.fetch(\n self._cursorDescription.collectionName, id, cacheKey,\n finishIfNeedToPollQuery(function (err, doc) {\n try {\n if (err) {\n Meteor._debug(\"Got exception while fetching documents: \" +\n err);\n // If we get an error from the fetcher (eg, trouble\n // connecting to Mongo), let's just abandon the fetch phase\n // altogether and fall back to polling. It's not like we're\n // getting live updates anyway.\n if (self._phase !== PHASE.QUERYING) {\n self._needToPollQuery();\n }\n } else if (!self._stopped && self._phase === PHASE.FETCHING\n && self._fetchGeneration === thisGeneration) {\n // We re-check the generation in case we've had an explicit\n // _pollQuery call (eg, in another fiber) which should\n // effectively cancel this round of fetches. (_pollQuery\n // increments the generation.)\n self._handleDoc(id, doc);\n }\n } finally {\n waiting--;\n // Because fetch() never calls its callback synchronously,\n // this is safe (ie, we won't call fut.return() before the\n // forEach is done).\n if (waiting === 0)\n fut.return();\n }\n }));\n });\n fut.wait();\n // Exit now if we've had a _pollQuery call (here or in another fiber).\n if (self._phase === PHASE.QUERYING)\n return;\n self._currentlyFetching = null;\n }\n // We're done fetching, so we can be steady, unless we've had a\n // _pollQuery call (here or in another fiber).\n if (self._phase !== PHASE.QUERYING)\n self._beSteady();\n }));\n });\n },\n _beSteady: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._registerPhaseChange(PHASE.STEADY);\n var writes = self._writesToCommitWhenWeReachSteady;\n self._writesToCommitWhenWeReachSteady = [];\n self._multiplexer.onFlush(function () {\n _.each(writes, function (w) {\n w.committed();\n });\n });\n });\n },\n _handleOplogEntryQuerying: function (op) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._needToFetch.set(idForOp(op), op.ts.toString());\n });\n },\n _handleOplogEntrySteadyOrFetching: function (op) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var id = idForOp(op);\n // If we're already fetching this one, or about to, we can't optimize;\n // make sure that we fetch it again if necessary.\n if (self._phase === PHASE.FETCHING &&\n ((self._currentlyFetching && self._currentlyFetching.has(id)) ||\n self._needToFetch.has(id))) {\n self._needToFetch.set(id, op.ts.toString());\n return;\n }\n\n if (op.op === 'd') {\n if (self._published.has(id) ||\n (self._limit && self._unpublishedBuffer.has(id)))\n self._removeMatching(id);\n } else if (op.op === 'i') {\n if (self._published.has(id))\n throw new Error(\"insert found for already-existing ID in published\");\n if (self._unpublishedBuffer && self._unpublishedBuffer.has(id))\n throw new Error(\"insert found for already-existing ID in buffer\");\n\n // XXX what if selector yields? for now it can't but later it could\n // have $where\n if (self._matcher.documentMatches(op.o).result)\n self._addMatching(op.o);\n } else if (op.op === 'u') {\n // Is this a modifier ($set/$unset, which may require us to poll the\n // database to figure out if the whole document matches the selector) or\n // a replacement (in which case we can just directly re-evaluate the\n // selector)?\n var isReplace = !_.has(op.o, '$set') && !_.has(op.o, '$unset');\n // If this modifier modifies something inside an EJSON custom type (ie,\n // anything with EJSON$), then we can't try to use\n // LocalCollection._modify, since that just mutates the EJSON encoding,\n // not the actual object.\n var canDirectlyModifyDoc =\n !isReplace && modifierCanBeDirectlyApplied(op.o);\n\n var publishedBefore = self._published.has(id);\n var bufferedBefore = self._limit && self._unpublishedBuffer.has(id);\n\n if (isReplace) {\n self._handleDoc(id, _.extend({_id: id}, op.o));\n } else if ((publishedBefore || bufferedBefore) &&\n canDirectlyModifyDoc) {\n // Oh great, we actually know what the document is, so we can apply\n // this directly.\n var newDoc = self._published.has(id)\n ? self._published.get(id) : self._unpublishedBuffer.get(id);\n newDoc = EJSON.clone(newDoc);\n\n newDoc._id = id;\n try {\n LocalCollection._modify(newDoc, op.o);\n } catch (e) {\n if (e.name !== \"MinimongoError\")\n throw e;\n // We didn't understand the modifier. Re-fetch.\n self._needToFetch.set(id, op.ts.toString());\n if (self._phase === PHASE.STEADY) {\n self._fetchModifiedDocuments();\n }\n return;\n }\n self._handleDoc(id, self._sharedProjectionFn(newDoc));\n } else if (!canDirectlyModifyDoc ||\n self._matcher.canBecomeTrueByModifier(op.o) ||\n (self._sorter && self._sorter.affectedByModifier(op.o))) {\n self._needToFetch.set(id, op.ts.toString());\n if (self._phase === PHASE.STEADY)\n self._fetchModifiedDocuments();\n }\n } else {\n throw Error(\"XXX SURPRISING OPERATION: \" + op);\n }\n });\n },\n // Yields!\n _runInitialQuery: function () {\n var self = this;\n if (self._stopped)\n throw new Error(\"oplog stopped surprisingly early\");\n\n self._runQuery({initial: true}); // yields\n\n if (self._stopped)\n return; // can happen on queryError\n\n // Allow observeChanges calls to return. (After this, it's possible for\n // stop() to be called.)\n self._multiplexer.ready();\n\n self._doneQuerying(); // yields\n },\n\n // In various circumstances, we may just want to stop processing the oplog and\n // re-run the initial query, just as if we were a PollingObserveDriver.\n //\n // This function may not block, because it is called from an oplog entry\n // handler.\n //\n // XXX We should call this when we detect that we've been in FETCHING for \"too\n // long\".\n //\n // XXX We should call this when we detect Mongo failover (since that might\n // mean that some of the oplog entries we have processed have been rolled\n // back). The Node Mongo driver is in the middle of a bunch of huge\n // refactorings, including the way that it notifies you when primary\n // changes. Will put off implementing this until driver 1.4 is out.\n _pollQuery: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (self._stopped)\n return;\n\n // Yay, we get to forget about all the things we thought we had to fetch.\n self._needToFetch = new LocalCollection._IdMap;\n self._currentlyFetching = null;\n ++self._fetchGeneration; // ignore any in-flight fetches\n self._registerPhaseChange(PHASE.QUERYING);\n\n // Defer so that we don't yield. We don't need finishIfNeedToPollQuery\n // here because SwitchedToQuery is not thrown in QUERYING mode.\n Meteor.defer(function () {\n self._runQuery();\n self._doneQuerying();\n });\n });\n },\n\n // Yields!\n _runQuery: function (options) {\n var self = this;\n options = options || {};\n var newResults, newBuffer;\n\n // This while loop is just to retry failures.\n while (true) {\n // If we've been stopped, we don't have to run anything any more.\n if (self._stopped)\n return;\n\n newResults = new LocalCollection._IdMap;\n newBuffer = new LocalCollection._IdMap;\n\n // Query 2x documents as the half excluded from the original query will go\n // into unpublished buffer to reduce additional Mongo lookups in cases\n // when documents are removed from the published set and need a\n // replacement.\n // XXX needs more thought on non-zero skip\n // XXX 2 is a \"magic number\" meaning there is an extra chunk of docs for\n // buffer if such is needed.\n var cursor = self._cursorForQuery({ limit: self._limit * 2 });\n try {\n cursor.forEach(function (doc, i) { // yields\n if (!self._limit || i < self._limit) {\n newResults.set(doc._id, doc);\n } else {\n newBuffer.set(doc._id, doc);\n }\n });\n break;\n } catch (e) {\n if (options.initial && typeof(e.code) === 'number') {\n // This is an error document sent to us by mongod, not a connection\n // error generated by the client. And we've never seen this query work\n // successfully. Probably it's a bad selector or something, so we\n // should NOT retry. Instead, we should halt the observe (which ends\n // up calling `stop` on us).\n self._multiplexer.queryError(e);\n return;\n }\n\n // During failover (eg) if we get an exception we should log and retry\n // instead of crashing.\n Meteor._debug(\"Got exception while polling query: \" + e);\n Meteor._sleepForMs(100);\n }\n }\n\n if (self._stopped)\n return;\n\n self._publishNewResults(newResults, newBuffer);\n },\n\n // Transitions to QUERYING and runs another query, or (if already in QUERYING)\n // ensures that we will query again later.\n //\n // This function may not block, because it is called from an oplog entry\n // handler. However, if we were not already in the QUERYING phase, it throws\n // an exception that is caught by the closest surrounding\n // finishIfNeedToPollQuery call; this ensures that we don't continue running\n // close that was designed for another phase inside PHASE.QUERYING.\n //\n // (It's also necessary whenever logic in this file yields to check that other\n // phases haven't put us into QUERYING mode, though; eg,\n // _fetchModifiedDocuments does this.)\n _needToPollQuery: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (self._stopped)\n return;\n\n // If we're not already in the middle of a query, we can query now\n // (possibly pausing FETCHING).\n if (self._phase !== PHASE.QUERYING) {\n self._pollQuery();\n throw new SwitchedToQuery;\n }\n\n // We're currently in QUERYING. Set a flag to ensure that we run another\n // query when we're done.\n self._requeryWhenDoneThisQuery = true;\n });\n },\n\n // Yields!\n _doneQuerying: function () {\n var self = this;\n\n if (self._stopped)\n return;\n self._mongoHandle._oplogHandle.waitUntilCaughtUp(); // yields\n if (self._stopped)\n return;\n if (self._phase !== PHASE.QUERYING)\n throw Error(\"Phase unexpectedly \" + self._phase);\n\n Meteor._noYieldsAllowed(function () {\n if (self._requeryWhenDoneThisQuery) {\n self._requeryWhenDoneThisQuery = false;\n self._pollQuery();\n } else if (self._needToFetch.empty()) {\n self._beSteady();\n } else {\n self._fetchModifiedDocuments();\n }\n });\n },\n\n _cursorForQuery: function (optionsOverwrite) {\n var self = this;\n return Meteor._noYieldsAllowed(function () {\n // The query we run is almost the same as the cursor we are observing,\n // with a few changes. We need to read all the fields that are relevant to\n // the selector, not just the fields we are going to publish (that's the\n // \"shared\" projection). And we don't want to apply any transform in the\n // cursor, because observeChanges shouldn't use the transform.\n var options = _.clone(self._cursorDescription.options);\n\n // Allow the caller to modify the options. Useful to specify different\n // skip and limit values.\n _.extend(options, optionsOverwrite);\n\n options.fields = self._sharedProjection;\n delete options.transform;\n // We are NOT deep cloning fields or selector here, which should be OK.\n var description = new CursorDescription(\n self._cursorDescription.collectionName,\n self._cursorDescription.selector,\n options);\n return new Cursor(self._mongoHandle, description);\n });\n },\n\n\n // Replace self._published with newResults (both are IdMaps), invoking observe\n // callbacks on the multiplexer.\n // Replace self._unpublishedBuffer with newBuffer.\n //\n // XXX This is very similar to LocalCollection._diffQueryUnorderedChanges. We\n // should really: (a) Unify IdMap and OrderedDict into Unordered/OrderedDict\n // (b) Rewrite diff.js to use these classes instead of arrays and objects.\n _publishNewResults: function (newResults, newBuffer) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n\n // If the query is limited and there is a buffer, shut down so it doesn't\n // stay in a way.\n if (self._limit) {\n self._unpublishedBuffer.clear();\n }\n\n // First remove anything that's gone. Be careful not to modify\n // self._published while iterating over it.\n var idsToRemove = [];\n self._published.forEach(function (doc, id) {\n if (!newResults.has(id))\n idsToRemove.push(id);\n });\n _.each(idsToRemove, function (id) {\n self._removePublished(id);\n });\n\n // Now do adds and changes.\n // If self has a buffer and limit, the new fetched result will be\n // limited correctly as the query has sort specifier.\n newResults.forEach(function (doc, id) {\n self._handleDoc(id, doc);\n });\n\n // Sanity-check that everything we tried to put into _published ended up\n // there.\n // XXX if this is slow, remove it later\n if (self._published.size() !== newResults.size()) {\n throw Error(\n \"The Mongo server and the Meteor query disagree on how \" +\n \"many documents match your query. Maybe it is hitting a Mongo \" +\n \"edge case? The query is: \" +\n EJSON.stringify(self._cursorDescription.selector));\n }\n self._published.forEach(function (doc, id) {\n if (!newResults.has(id))\n throw Error(\"_published has a doc that newResults doesn't; \" + id);\n });\n\n // Finally, replace the buffer\n newBuffer.forEach(function (doc, id) {\n self._addBuffered(id, doc);\n });\n\n self._safeAppendToBuffer = newBuffer.size() < self._limit;\n });\n },\n\n // This stop function is invoked from the onStop of the ObserveMultiplexer, so\n // it shouldn't actually be possible to call it until the multiplexer is\n // ready.\n //\n // It's important to check self._stopped after every call in this file that\n // can yield!\n stop: function () {\n var self = this;\n if (self._stopped)\n return;\n self._stopped = true;\n _.each(self._stopHandles, function (handle) {\n handle.stop();\n });\n\n // Note: we *don't* use multiplexer.onFlush here because this stop\n // callback is actually invoked by the multiplexer itself when it has\n // determined that there are no handles left. So nothing is actually going\n // to get flushed (and it's probably not valid to call methods on the\n // dying multiplexer).\n _.each(self._writesToCommitWhenWeReachSteady, function (w) {\n w.committed(); // maybe yields?\n });\n self._writesToCommitWhenWeReachSteady = null;\n\n // Proactively drop references to potentially big things.\n self._published = null;\n self._unpublishedBuffer = null;\n self._needToFetch = null;\n self._currentlyFetching = null;\n self._oplogEntryHandle = null;\n self._listenersHandle = null;\n\n Package.facts && Package.facts.Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-oplog\", -1);\n },\n\n _registerPhaseChange: function (phase) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var now = new Date;\n\n if (self._phase) {\n var timeDiff = now - self._phaseStartTime;\n Package.facts && Package.facts.Facts.incrementServerFact(\n \"mongo-livedata\", \"time-spent-in-\" + self._phase + \"-phase\", timeDiff);\n }\n\n self._phase = phase;\n self._phaseStartTime = now;\n });\n }\n});\n\n// Does our oplog tailing code support this cursor? For now, we are being very\n// conservative and allowing only simple queries with simple options.\n// (This is a \"static method\".)\nOplogObserveDriver.cursorSupported = function (cursorDescription, matcher) {\n // First, check the options.\n var options = cursorDescription.options;\n\n // Did the user say no explicitly?\n // underscored version of the option is COMPAT with 1.2\n if (options.disableOplog || options._disableOplog)\n return false;\n\n // skip is not supported: to support it we would need to keep track of all\n // \"skipped\" documents or at least their ids.\n // limit w/o a sort specifier is not supported: current implementation needs a\n // deterministic way to order documents.\n if (options.skip || (options.limit && !options.sort)) return false;\n\n // If a fields projection option is given check if it is supported by\n // minimongo (some operators are not supported).\n if (options.fields) {\n try {\n LocalCollection._checkSupportedProjection(options.fields);\n } catch (e) {\n if (e.name === \"MinimongoError\") {\n return false;\n } else {\n throw e;\n }\n }\n }\n\n // We don't allow the following selectors:\n // - $where (not confident that we provide the same JS environment\n // as Mongo, and can yield!)\n // - $near (has \"interesting\" properties in MongoDB, like the possibility\n // of returning an ID multiple times, though even polling maybe\n // have a bug there)\n // XXX: once we support it, we would need to think more on how we\n // initialize the comparators when we create the driver.\n return !matcher.hasWhere() && !matcher.hasGeoQuery();\n};\n\nvar modifierCanBeDirectlyApplied = function (modifier) {\n return _.all(modifier, function (fields, operation) {\n return _.all(fields, function (value, field) {\n return !/EJSON\\$/.test(field);\n });\n });\n};\n\nMongoInternals.OplogObserveDriver = OplogObserveDriver;\n", "file_path": "packages/mongo/oplog_observe_driver.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00020418250642251223, 0.00016953090380411595, 0.00016010570107027888, 0.00016896839952096343, 6.1694422583968844e-06]} {"hunk": {"id": 6, "code_window": [" \"commonmark\": \"0.15.0\",\n", " escope: \"3.6.0\",\n", " split2: \"2.2.0\",\n", " multipipe: \"2.0.1\",\n", " pathwatcher: \"7.1.1\",\n", " optimism: \"0.3.3\",\n", " 'lru-cache': '4.1.1',\n", " longjohn: '0.2.12'\n", " }\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" optimism: \"0.4.0\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 54}, "file": "$el3-style = groove\n", "file_path": "tools/tests/apps/caching-stylus/imports/dotdot.styl", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00016958851483650506, 0.00016958851483650506, 0.00016958851483650506, 0.00016958851483650506, 0.0]} {"hunk": {"id": 6, "code_window": [" \"commonmark\": \"0.15.0\",\n", " escope: \"3.6.0\",\n", " split2: \"2.2.0\",\n", " multipipe: \"2.0.1\",\n", " pathwatcher: \"7.1.1\",\n", " optimism: \"0.3.3\",\n", " 'lru-cache': '4.1.1',\n", " longjohn: '0.2.12'\n", " }\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" optimism: \"0.4.0\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 54}, "file": "{\n \"name\": \"meteor-jsdoc\",\n \"version\": \"0.0.0\",\n \"lockfileVersion\": 1,\n \"requires\": true,\n \"dependencies\": {\n \"babel-eslint\": {\n \"version\": \"4.1.7\",\n \"resolved\": \"https://registry.npmjs.org/babel-eslint/-/babel-eslint-4.1.7.tgz\",\n \"integrity\": \"sha1-eSv6d/JwmvbyCtT3lswtzwtxMWU=\",\n \"requires\": {\n \"acorn-to-esprima\": \"2.0.8\",\n \"babel-traverse\": \"6.10.4\",\n \"babel-types\": \"6.11.1\",\n \"babylon\": \"6.8.4\",\n \"lodash.assign\": \"3.2.0\",\n \"lodash.pick\": \"3.1.0\"\n },\n \"dependencies\": {\n \"acorn-to-esprima\": {\n \"version\": \"2.0.8\",\n \"resolved\": \"https://registry.npmjs.org/acorn-to-esprima/-/acorn-to-esprima-2.0.8.tgz\",\n \"integrity\": \"sha1-AD8MZC65ITL0F9NwjxStqCrfLrE=\"\n },\n \"babel-traverse\": {\n \"version\": \"6.10.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.10.4.tgz\",\n \"integrity\": \"sha1-289B/x8y62FIWc6tSHEWDx8SDXg=\",\n \"requires\": {\n \"babel-code-frame\": \"6.11.0\",\n \"babel-messages\": \"6.8.0\",\n \"babel-runtime\": \"6.9.2\",\n \"babel-types\": \"6.11.1\",\n \"babylon\": \"6.8.4\",\n \"debug\": \"2.2.0\",\n \"globals\": \"8.18.0\",\n \"invariant\": \"2.2.1\",\n \"lodash\": \"4.13.1\"\n },\n \"dependencies\": {\n \"babel-code-frame\": {\n \"version\": \"6.11.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.11.0.tgz\",\n \"integrity\": \"sha1-kHLdI1P7D4W2tX0sl/DRNNGIrtg=\",\n \"requires\": {\n \"babel-runtime\": \"6.9.2\",\n \"chalk\": \"1.1.3\",\n \"esutils\": \"2.0.2\",\n \"js-tokens\": \"2.0.0\"\n },\n \"dependencies\": {\n \"chalk\": {\n \"version\": \"1.1.3\",\n \"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz\",\n \"integrity\": \"sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=\",\n \"requires\": {\n \"ansi-styles\": \"2.2.1\",\n \"escape-string-regexp\": \"1.0.5\",\n \"has-ansi\": \"2.0.0\",\n \"strip-ansi\": \"3.0.1\",\n \"supports-color\": \"2.0.0\"\n },\n \"dependencies\": {\n \"ansi-styles\": {\n \"version\": \"2.2.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz\",\n \"integrity\": \"sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=\"\n },\n \"escape-string-regexp\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz\",\n \"integrity\": \"sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=\"\n },\n \"has-ansi\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz\",\n \"integrity\": \"sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=\",\n \"requires\": {\n \"ansi-regex\": \"2.0.0\"\n },\n \"dependencies\": {\n \"ansi-regex\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz\",\n \"integrity\": \"sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=\"\n }\n }\n },\n \"strip-ansi\": {\n \"version\": \"3.0.1\",\n \"resolved\": \"https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz\",\n \"integrity\": \"sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=\",\n \"requires\": {\n \"ansi-regex\": \"2.0.0\"\n },\n \"dependencies\": {\n \"ansi-regex\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz\",\n \"integrity\": \"sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=\"\n }\n }\n },\n \"supports-color\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz\",\n \"integrity\": \"sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=\"\n }\n }\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"js-tokens\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-2.0.0.tgz\",\n \"integrity\": \"sha1-eZA/VWPud4zBFi5tzxoAJ8l/nLU=\"\n }\n }\n },\n \"babel-messages\": {\n \"version\": \"6.8.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-messages/-/babel-messages-6.8.0.tgz\",\n \"integrity\": \"sha1-v1BHNsqWfm1l7wrbWipflHyODrk=\",\n \"requires\": {\n \"babel-runtime\": \"6.9.2\"\n }\n },\n \"babel-runtime\": {\n \"version\": \"6.9.2\",\n \"resolved\": \"https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.9.2.tgz\",\n \"integrity\": \"sha1-1/45G8LMKbgIfB2bOYeJEun8/Vk=\",\n \"requires\": {\n \"core-js\": \"2.4.0\",\n \"regenerator-runtime\": \"0.9.5\"\n },\n \"dependencies\": {\n \"core-js\": {\n \"version\": \"2.4.0\",\n \"resolved\": \"https://registry.npmjs.org/core-js/-/core-js-2.4.0.tgz\",\n \"integrity\": \"sha1-30CKtG0Br/kcAcPnlxk11CLFT4E=\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.9.5\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.9.5.tgz\",\n \"integrity\": \"sha1-QD1tQKS9/5wzDdk5Lcuy2ai7ofw=\"\n }\n }\n },\n \"debug\": {\n \"version\": \"2.2.0\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-2.2.0.tgz\",\n \"integrity\": \"sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=\",\n \"requires\": {\n \"ms\": \"0.7.1\"\n },\n \"dependencies\": {\n \"ms\": {\n \"version\": \"0.7.1\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-0.7.1.tgz\",\n \"integrity\": \"sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=\"\n }\n }\n },\n \"globals\": {\n \"version\": \"8.18.0\",\n \"resolved\": \"https://registry.npmjs.org/globals/-/globals-8.18.0.tgz\",\n \"integrity\": \"sha1-k9SmK9ysOM+vr8R9awNHaMsP/LQ=\"\n },\n \"invariant\": {\n \"version\": \"2.2.1\",\n \"resolved\": \"https://registry.npmjs.org/invariant/-/invariant-2.2.1.tgz\",\n \"integrity\": \"sha1-sJcBBUdmjH4zcCjr6Bbr42yKjVQ=\",\n \"requires\": {\n \"loose-envify\": \"1.2.0\"\n },\n \"dependencies\": {\n \"loose-envify\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/loose-envify/-/loose-envify-1.2.0.tgz\",\n \"integrity\": \"sha1-aaZarT3lQs9O4PT+dOjjPHCcyw8=\",\n \"requires\": {\n \"js-tokens\": \"1.0.3\"\n },\n \"dependencies\": {\n \"js-tokens\": {\n \"version\": \"1.0.3\",\n \"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-1.0.3.tgz\",\n \"integrity\": \"sha1-FOVutoyPGpLEPVn1AU7CncIPKuE=\"\n }\n }\n }\n }\n },\n \"lodash\": {\n \"version\": \"4.13.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.13.1.tgz\",\n \"integrity\": \"sha1-g+SxCRP0hJbU0W/sSlYK8u50S2g=\"\n }\n }\n },\n \"babel-types\": {\n \"version\": \"6.11.1\",\n \"resolved\": \"https://registry.npmjs.org/babel-types/-/babel-types-6.11.1.tgz\",\n \"integrity\": \"sha1-o981W6uQ3c9mMYZAcXzywVTmZIo=\",\n \"requires\": {\n \"babel-runtime\": \"6.9.2\",\n \"babel-traverse\": \"6.10.4\",\n \"esutils\": \"2.0.2\",\n \"lodash\": \"4.13.1\",\n \"to-fast-properties\": \"1.0.2\"\n },\n \"dependencies\": {\n \"babel-runtime\": {\n \"version\": \"6.9.2\",\n \"resolved\": \"https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.9.2.tgz\",\n \"integrity\": \"sha1-1/45G8LMKbgIfB2bOYeJEun8/Vk=\",\n \"requires\": {\n \"core-js\": \"2.4.0\",\n \"regenerator-runtime\": \"0.9.5\"\n },\n \"dependencies\": {\n \"core-js\": {\n \"version\": \"2.4.0\",\n \"resolved\": \"https://registry.npmjs.org/core-js/-/core-js-2.4.0.tgz\",\n \"integrity\": \"sha1-30CKtG0Br/kcAcPnlxk11CLFT4E=\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.9.5\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.9.5.tgz\",\n \"integrity\": \"sha1-QD1tQKS9/5wzDdk5Lcuy2ai7ofw=\"\n }\n }\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"lodash\": {\n \"version\": \"4.13.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.13.1.tgz\",\n \"integrity\": \"sha1-g+SxCRP0hJbU0W/sSlYK8u50S2g=\"\n },\n \"to-fast-properties\": {\n \"version\": \"1.0.2\",\n \"resolved\": \"https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.2.tgz\",\n \"integrity\": \"sha1-8/XAw7pymafvmUJ+RGMyV63kMyA=\"\n }\n }\n },\n \"babylon\": {\n \"version\": \"6.8.4\",\n \"resolved\": \"https://registry.npmjs.org/babylon/-/babylon-6.8.4.tgz\",\n \"integrity\": \"sha1-CXMGuNq66VFZIlzymz6lWRIFMYA=\",\n \"requires\": {\n \"babel-runtime\": \"6.9.2\"\n },\n \"dependencies\": {\n \"babel-runtime\": {\n \"version\": \"6.9.2\",\n \"resolved\": \"https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.9.2.tgz\",\n \"integrity\": \"sha1-1/45G8LMKbgIfB2bOYeJEun8/Vk=\",\n \"requires\": {\n \"core-js\": \"2.4.0\",\n \"regenerator-runtime\": \"0.9.5\"\n },\n \"dependencies\": {\n \"core-js\": {\n \"version\": \"2.4.0\",\n \"resolved\": \"https://registry.npmjs.org/core-js/-/core-js-2.4.0.tgz\",\n \"integrity\": \"sha1-30CKtG0Br/kcAcPnlxk11CLFT4E=\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.9.5\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.9.5.tgz\",\n \"integrity\": \"sha1-QD1tQKS9/5wzDdk5Lcuy2ai7ofw=\"\n }\n }\n }\n }\n },\n \"lodash.assign\": {\n \"version\": \"3.2.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash.assign/-/lodash.assign-3.2.0.tgz\",\n \"integrity\": \"sha1-POnwI0tLIiPilrj6CsH+6OvKZPo=\",\n \"requires\": {\n \"lodash._baseassign\": \"3.2.0\",\n \"lodash._createassigner\": \"3.1.1\",\n \"lodash.keys\": \"3.1.2\"\n },\n \"dependencies\": {\n \"lodash._baseassign\": {\n \"version\": \"3.2.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz\",\n \"integrity\": \"sha1-jDigmVAPIVrQnlnxci/QxSv+Ck4=\",\n \"requires\": {\n \"lodash._basecopy\": \"3.0.1\",\n \"lodash.keys\": \"3.1.2\"\n },\n \"dependencies\": {\n \"lodash._basecopy\": {\n \"version\": \"3.0.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz\",\n \"integrity\": \"sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=\"\n }\n }\n },\n \"lodash._createassigner\": {\n \"version\": \"3.1.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz\",\n \"integrity\": \"sha1-g4pbri/aymOsIt7o4Z+k5taXCxE=\",\n \"requires\": {\n \"lodash._bindcallback\": \"3.0.1\",\n \"lodash._isiterateecall\": \"3.0.9\",\n \"lodash.restparam\": \"3.6.1\"\n },\n \"dependencies\": {\n \"lodash._bindcallback\": {\n \"version\": \"3.0.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz\",\n \"integrity\": \"sha1-5THCdkTPi1epnhftlbNcdIeJOS4=\"\n },\n \"lodash._isiterateecall\": {\n \"version\": \"3.0.9\",\n \"resolved\": \"https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz\",\n \"integrity\": \"sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=\"\n },\n \"lodash.restparam\": {\n \"version\": \"3.6.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz\",\n \"integrity\": \"sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=\"\n }\n }\n },\n \"lodash.keys\": {\n \"version\": \"3.1.2\",\n \"resolved\": \"https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz\",\n \"integrity\": \"sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=\",\n \"requires\": {\n \"lodash._getnative\": \"3.9.1\",\n \"lodash.isarguments\": \"3.0.8\",\n \"lodash.isarray\": \"3.0.4\"\n },\n \"dependencies\": {\n \"lodash._getnative\": {\n \"version\": \"3.9.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz\",\n \"integrity\": \"sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=\"\n },\n \"lodash.isarguments\": {\n \"version\": \"3.0.8\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.0.8.tgz\",\n \"integrity\": \"sha1-W/jaiH8B8qnknAoXXNrrMYoOQ9w=\"\n },\n \"lodash.isarray\": {\n \"version\": \"3.0.4\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz\",\n \"integrity\": \"sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=\"\n }\n }\n }\n }\n },\n \"lodash.pick\": {\n \"version\": \"3.1.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash.pick/-/lodash.pick-3.1.0.tgz\",\n \"integrity\": \"sha1-8lKoVbIEa2G805BLJvdr0u/GVVA=\",\n \"requires\": {\n \"lodash._baseflatten\": \"3.1.4\",\n \"lodash._bindcallback\": \"3.0.1\",\n \"lodash._pickbyarray\": \"3.0.2\",\n \"lodash._pickbycallback\": \"3.0.0\",\n \"lodash.restparam\": \"3.6.1\"\n },\n \"dependencies\": {\n \"lodash._baseflatten\": {\n \"version\": \"3.1.4\",\n \"resolved\": \"https://registry.npmjs.org/lodash._baseflatten/-/lodash._baseflatten-3.1.4.tgz\",\n \"integrity\": \"sha1-B3D/gBMa9uNPO1EXlqe6UhTmX/c=\",\n \"requires\": {\n \"lodash.isarguments\": \"3.0.8\",\n \"lodash.isarray\": \"3.0.4\"\n },\n \"dependencies\": {\n \"lodash.isarguments\": {\n \"version\": \"3.0.8\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.0.8.tgz\",\n \"integrity\": \"sha1-W/jaiH8B8qnknAoXXNrrMYoOQ9w=\"\n },\n \"lodash.isarray\": {\n \"version\": \"3.0.4\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz\",\n \"integrity\": \"sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=\"\n }\n }\n },\n \"lodash._bindcallback\": {\n \"version\": \"3.0.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz\",\n \"integrity\": \"sha1-5THCdkTPi1epnhftlbNcdIeJOS4=\"\n },\n \"lodash._pickbyarray\": {\n \"version\": \"3.0.2\",\n \"resolved\": \"https://registry.npmjs.org/lodash._pickbyarray/-/lodash._pickbyarray-3.0.2.tgz\",\n \"integrity\": \"sha1-H4mNlgfrVgsOFnOEt3x8bRCKpMU=\"\n },\n \"lodash._pickbycallback\": {\n \"version\": \"3.0.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash._pickbycallback/-/lodash._pickbycallback-3.0.0.tgz\",\n \"integrity\": \"sha1-/2G5oBens699MObFPeKK+hm4dQo=\",\n \"requires\": {\n \"lodash._basefor\": \"3.0.3\",\n \"lodash.keysin\": \"3.0.8\"\n },\n \"dependencies\": {\n \"lodash._basefor\": {\n \"version\": \"3.0.3\",\n \"resolved\": \"https://registry.npmjs.org/lodash._basefor/-/lodash._basefor-3.0.3.tgz\",\n \"integrity\": \"sha1-dVC06SGO8J+tJDQ7YSAhx5tMIMI=\"\n },\n \"lodash.keysin\": {\n \"version\": \"3.0.8\",\n \"resolved\": \"https://registry.npmjs.org/lodash.keysin/-/lodash.keysin-3.0.8.tgz\",\n \"integrity\": \"sha1-IsRJPrvtsUJ5YqVLRFssinZ/tH8=\",\n \"requires\": {\n \"lodash.isarguments\": \"3.0.8\",\n \"lodash.isarray\": \"3.0.4\"\n },\n \"dependencies\": {\n \"lodash.isarguments\": {\n \"version\": \"3.0.8\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.0.8.tgz\",\n \"integrity\": \"sha1-W/jaiH8B8qnknAoXXNrrMYoOQ9w=\"\n },\n \"lodash.isarray\": {\n \"version\": \"3.0.4\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz\",\n \"integrity\": \"sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=\"\n }\n }\n }\n }\n },\n \"lodash.restparam\": {\n \"version\": \"3.6.1\",\n \"resolved\": \"https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz\",\n \"integrity\": \"sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=\"\n }\n }\n }\n }\n },\n \"eslint\": {\n \"version\": \"0.22.1\",\n \"resolved\": \"https://registry.npmjs.org/eslint/-/eslint-0.22.1.tgz\",\n \"integrity\": \"sha1-VbrAiUWwrNoXRWINIKUqK6mH1m4=\",\n \"requires\": {\n \"chalk\": \"1.0.0\",\n \"concat-stream\": \"1.5.0\",\n \"debug\": \"2.2.0\",\n \"doctrine\": \"0.6.4\",\n \"escape-string-regexp\": \"1.0.3\",\n \"escope\": \"3.1.0\",\n \"espree\": \"2.0.3\",\n \"estraverse\": \"2.0.0\",\n \"estraverse-fb\": \"1.3.1\",\n \"globals\": \"6.4.1\",\n \"inquirer\": \"0.8.5\",\n \"is-my-json-valid\": \"2.12.0\",\n \"js-yaml\": \"3.3.1\",\n \"minimatch\": \"2.0.8\",\n \"mkdirp\": \"0.5.1\",\n \"object-assign\": \"2.1.1\",\n \"optionator\": \"0.5.0\",\n \"path-is-absolute\": \"1.0.0\",\n \"strip-json-comments\": \"1.0.2\",\n \"text-table\": \"0.2.0\",\n \"user-home\": \"1.1.1\",\n \"xml-escape\": \"1.0.0\"\n },\n \"dependencies\": {\n \"chalk\": {\n \"version\": \"1.0.0\",\n \"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-1.0.0.tgz\",\n \"integrity\": \"sha1-s89O0P9Tl8mcdbj2edsvUoMfltw=\",\n \"requires\": {\n \"ansi-styles\": \"2.0.1\",\n \"escape-string-regexp\": \"1.0.3\",\n \"has-ansi\": \"1.0.3\",\n \"strip-ansi\": \"2.0.1\",\n \"supports-color\": \"1.3.1\"\n },\n \"dependencies\": {\n \"ansi-styles\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.0.1.tgz\",\n \"integrity\": \"sha1-sDP1f5Pi0oreuLwRE4+hPaD9IKM=\"\n },\n \"has-ansi\": {\n \"version\": \"1.0.3\",\n \"resolved\": \"https://registry.npmjs.org/has-ansi/-/has-ansi-1.0.3.tgz\",\n \"integrity\": \"sha1-wLWxYV2eOCsP9nFp2We0JeSMpTg=\",\n \"requires\": {\n \"ansi-regex\": \"1.1.1\",\n \"get-stdin\": \"4.0.1\"\n },\n \"dependencies\": {\n \"ansi-regex\": {\n \"version\": \"1.1.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz\",\n \"integrity\": \"sha1-QchHGUZGN15qGl0Qw8oFTvn8mA0=\"\n },\n \"get-stdin\": {\n \"version\": \"4.0.1\",\n \"resolved\": \"https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz\",\n \"integrity\": \"sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=\"\n }\n }\n },\n \"strip-ansi\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.1.tgz\",\n \"integrity\": \"sha1-32LBqpTtLxFOHQ8h/R1QSCt5pg4=\",\n \"requires\": {\n \"ansi-regex\": \"1.1.1\"\n },\n \"dependencies\": {\n \"ansi-regex\": {\n \"version\": \"1.1.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz\",\n \"integrity\": \"sha1-QchHGUZGN15qGl0Qw8oFTvn8mA0=\"\n }\n }\n },\n \"supports-color\": {\n \"version\": \"1.3.1\",\n \"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-1.3.1.tgz\",\n \"integrity\": \"sha1-FXWN8J2P87SswwdTn6vicJXhBC0=\"\n }\n }\n },\n \"concat-stream\": {\n \"version\": \"1.5.0\",\n \"resolved\": \"https://registry.npmjs.org/concat-stream/-/concat-stream-1.5.0.tgz\",\n \"integrity\": \"sha1-U/fUPFHF5D+ByP3QMyHGMb5o1hE=\",\n \"requires\": {\n \"inherits\": \"2.0.1\",\n \"readable-stream\": \"2.0.1\",\n \"typedarray\": \"0.0.6\"\n },\n \"dependencies\": {\n \"inherits\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz\",\n \"integrity\": \"sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=\"\n },\n \"readable-stream\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.1.tgz\",\n \"integrity\": \"sha1-YzR5t70vvnoehpgltAoLMzufK/w=\",\n \"requires\": {\n \"core-util-is\": \"1.0.1\",\n \"inherits\": \"2.0.1\",\n \"isarray\": \"0.0.1\",\n \"process-nextick-args\": \"1.0.1\",\n \"string_decoder\": \"0.10.31\",\n \"util-deprecate\": \"1.0.1\"\n },\n \"dependencies\": {\n \"core-util-is\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz\",\n \"integrity\": \"sha1-awcIWu+aPMrG7lO/nT3wwVIaVTg=\"\n },\n \"isarray\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz\",\n \"integrity\": \"sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=\"\n },\n \"process-nextick-args\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.1.tgz\",\n \"integrity\": \"sha1-kYpatKd0Q0C4P/QWEBulPFxTGHk=\"\n },\n \"string_decoder\": {\n \"version\": \"0.10.31\",\n \"resolved\": \"https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz\",\n \"integrity\": \"sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=\"\n },\n \"util-deprecate\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.1.tgz\",\n \"integrity\": \"sha1-NVaj0TxMaqeYPX4kJUeBlxmbeIE=\"\n }\n }\n },\n \"typedarray\": {\n \"version\": \"0.0.6\",\n \"resolved\": \"https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz\",\n \"integrity\": \"sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=\"\n }\n }\n },\n \"debug\": {\n \"version\": \"2.2.0\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-2.2.0.tgz\",\n \"integrity\": \"sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=\",\n \"requires\": {\n \"ms\": \"0.7.1\"\n },\n \"dependencies\": {\n \"ms\": {\n \"version\": \"0.7.1\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-0.7.1.tgz\",\n \"integrity\": \"sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=\"\n }\n }\n },\n \"doctrine\": {\n \"version\": \"0.6.4\",\n \"resolved\": \"https://registry.npmjs.org/doctrine/-/doctrine-0.6.4.tgz\",\n \"integrity\": \"sha1-gUKEkalC7xiwSSBW7aOADu5X1h0=\",\n \"requires\": {\n \"esutils\": \"1.1.6\",\n \"isarray\": \"0.0.1\"\n },\n \"dependencies\": {\n \"esutils\": {\n \"version\": \"1.1.6\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-1.1.6.tgz\",\n \"integrity\": \"sha1-wBzKqa5LiXxtDD4hCuUvPHqEQ3U=\"\n },\n \"isarray\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz\",\n \"integrity\": \"sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=\"\n }\n }\n },\n \"escape-string-regexp\": {\n \"version\": \"1.0.3\",\n \"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.3.tgz\",\n \"integrity\": \"sha1-ni2LJbwlVcMzZyN1DgPwmcJzW7U=\"\n },\n \"escope\": {\n \"version\": \"3.1.0\",\n \"resolved\": \"https://registry.npmjs.org/escope/-/escope-3.1.0.tgz\",\n \"integrity\": \"sha1-kspI9ihrOA5DiOCRiKkEsPodm34=\",\n \"requires\": {\n \"es6-map\": \"0.1.1\",\n \"es6-weak-map\": \"0.1.4\",\n \"esrecurse\": \"3.1.1\",\n \"estraverse\": \"3.1.0\"\n },\n \"dependencies\": {\n \"es6-map\": {\n \"version\": \"0.1.1\",\n \"resolved\": \"https://registry.npmjs.org/es6-map/-/es6-map-0.1.1.tgz\",\n \"integrity\": \"sha1-uHkjnteBngsIxAum4Z+gR8p8jR0=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\",\n \"es6-iterator\": \"0.1.3\",\n \"es6-set\": \"0.1.1\",\n \"es6-symbol\": \"0.1.1\",\n \"event-emitter\": \"0.3.3\"\n },\n \"dependencies\": {\n \"d\": {\n \"version\": \"0.1.1\",\n \"resolved\": \"https://registry.npmjs.org/d/-/d-0.1.1.tgz\",\n \"integrity\": \"sha1-2hhMU10Y2O57oqoim5FACfrhEwk=\",\n \"requires\": {\n \"es5-ext\": \"0.10.7\"\n }\n },\n \"es5-ext\": {\n \"version\": \"0.10.7\",\n \"resolved\": \"https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.7.tgz\",\n \"integrity\": \"sha1-366lByEwEELi2JwXGdQ0k/qCFlY=\",\n \"requires\": {\n \"es6-iterator\": \"0.1.3\",\n \"es6-symbol\": \"2.0.1\"\n },\n \"dependencies\": {\n \"es6-symbol\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz\",\n \"integrity\": \"sha1-dhtcZ8/U8dGK+yNPaR1nhoLLO/M=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\"\n }\n }\n }\n },\n \"es6-iterator\": {\n \"version\": \"0.1.3\",\n \"resolved\": \"https://registry.npmjs.org/es6-iterator/-/es6-iterator-0.1.3.tgz\",\n \"integrity\": \"sha1-1vWLjE/EE8JJtLqhl2j45NfIlE4=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\",\n \"es6-symbol\": \"2.0.1\"\n },\n \"dependencies\": {\n \"es6-symbol\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz\",\n \"integrity\": \"sha1-dhtcZ8/U8dGK+yNPaR1nhoLLO/M=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\"\n }\n }\n }\n },\n \"es6-set\": {\n \"version\": \"0.1.1\",\n \"resolved\": \"https://registry.npmjs.org/es6-set/-/es6-set-0.1.1.tgz\",\n \"integrity\": \"sha1-SXzSNcmiaR9Mqg4z3XPvhr3nOKw=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\",\n \"es6-iterator\": \"0.1.3\",\n \"es6-symbol\": \"0.1.1\",\n \"event-emitter\": \"0.3.3\"\n }\n },\n \"es6-symbol\": {\n \"version\": \"0.1.1\",\n \"resolved\": \"https://registry.npmjs.org/es6-symbol/-/es6-symbol-0.1.1.tgz\",\n \"integrity\": \"sha1-nPf6su2v8bHaj+jmi/4/Wspsohg=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\"\n }\n },\n \"event-emitter\": {\n \"version\": \"0.3.3\",\n \"resolved\": \"https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.3.tgz\",\n \"integrity\": \"sha1-346AZUHGirj/IKeaGEG5GrqhvuQ=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\"\n }\n }\n }\n },\n \"es6-weak-map\": {\n \"version\": \"0.1.4\",\n \"resolved\": \"https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-0.1.4.tgz\",\n \"integrity\": \"sha1-cGzvnpmqI2undmwjnIueKG6n0ig=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\",\n \"es6-iterator\": \"0.1.3\",\n \"es6-symbol\": \"2.0.1\"\n },\n \"dependencies\": {\n \"d\": {\n \"version\": \"0.1.1\",\n \"resolved\": \"https://registry.npmjs.org/d/-/d-0.1.1.tgz\",\n \"integrity\": \"sha1-2hhMU10Y2O57oqoim5FACfrhEwk=\",\n \"requires\": {\n \"es5-ext\": \"0.10.7\"\n }\n },\n \"es5-ext\": {\n \"version\": \"0.10.7\",\n \"resolved\": \"https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.7.tgz\",\n \"integrity\": \"sha1-366lByEwEELi2JwXGdQ0k/qCFlY=\",\n \"requires\": {\n \"es6-iterator\": \"0.1.3\",\n \"es6-symbol\": \"2.0.1\"\n }\n },\n \"es6-iterator\": {\n \"version\": \"0.1.3\",\n \"resolved\": \"https://registry.npmjs.org/es6-iterator/-/es6-iterator-0.1.3.tgz\",\n \"integrity\": \"sha1-1vWLjE/EE8JJtLqhl2j45NfIlE4=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\",\n \"es6-symbol\": \"2.0.1\"\n }\n },\n \"es6-symbol\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz\",\n \"integrity\": \"sha1-dhtcZ8/U8dGK+yNPaR1nhoLLO/M=\",\n \"requires\": {\n \"d\": \"0.1.1\",\n \"es5-ext\": \"0.10.7\"\n }\n }\n }\n },\n \"esrecurse\": {\n \"version\": \"3.1.1\",\n \"resolved\": \"https://registry.npmjs.org/esrecurse/-/esrecurse-3.1.1.tgz\",\n \"integrity\": \"sha1-j+uWNpnU0bLWWlds1LEpZnKg8Ok=\",\n \"requires\": {\n \"estraverse\": \"3.1.0\"\n }\n },\n \"estraverse\": {\n \"version\": \"3.1.0\",\n \"resolved\": \"https://registry.npmjs.org/estraverse/-/estraverse-3.1.0.tgz\",\n \"integrity\": \"sha1-FeKKRGuLgrxwDMyLlseK9NoNbLo=\"\n }\n }\n },\n \"espree\": {\n \"version\": \"2.0.3\",\n \"resolved\": \"https://registry.npmjs.org/espree/-/espree-2.0.3.tgz\",\n \"integrity\": \"sha1-H73/YKQQvQ1Baxqz1iMNNLekUOE=\"\n },\n \"estraverse\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/estraverse/-/estraverse-2.0.0.tgz\",\n \"integrity\": \"sha1-WuRpYyQ2ACBmdMyySgnhZnT83KE=\"\n },\n \"estraverse-fb\": {\n \"version\": \"1.3.1\",\n \"resolved\": \"https://registry.npmjs.org/estraverse-fb/-/estraverse-fb-1.3.1.tgz\",\n \"integrity\": \"sha1-Fg51qA5gWwjOiUvM4v4+Qpq/kr8=\"\n },\n \"globals\": {\n \"version\": \"6.4.1\",\n \"resolved\": \"https://registry.npmjs.org/globals/-/globals-6.4.1.tgz\",\n \"integrity\": \"sha1-hJgDKzttHMge68X3lpDY/in6v08=\"\n },\n \"inquirer\": {\n \"version\": \"0.8.5\",\n \"resolved\": \"https://registry.npmjs.org/inquirer/-/inquirer-0.8.5.tgz\",\n \"integrity\": \"sha1-29dAz2yjtzEpamPOb22WGFHzNt8=\",\n \"requires\": {\n \"ansi-regex\": \"1.1.1\",\n \"chalk\": \"1.0.0\",\n \"cli-width\": \"1.0.1\",\n \"figures\": \"1.3.5\",\n \"lodash\": \"3.9.3\",\n \"readline2\": \"0.1.1\",\n \"rx\": \"2.5.3\",\n \"through\": \"2.3.7\"\n },\n \"dependencies\": {\n \"ansi-regex\": {\n \"version\": \"1.1.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz\",\n \"integrity\": \"sha1-QchHGUZGN15qGl0Qw8oFTvn8mA0=\"\n },\n \"cli-width\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/cli-width/-/cli-width-1.0.1.tgz\",\n \"integrity\": \"sha1-FNT2hwI02R6X992B52voJxQQoe8=\"\n },\n \"figures\": {\n \"version\": \"1.3.5\",\n \"resolved\": \"https://registry.npmjs.org/figures/-/figures-1.3.5.tgz\",\n \"integrity\": \"sha1-0aMfTh0sKTjs3lwGqhYTTPKfR3E=\"\n },\n \"lodash\": {\n \"version\": \"3.9.3\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-3.9.3.tgz\",\n \"integrity\": \"sha1-AVnoaDL+/8bWHYUrEqlTuZSWvTI=\"\n },\n \"readline2\": {\n \"version\": \"0.1.1\",\n \"resolved\": \"https://registry.npmjs.org/readline2/-/readline2-0.1.1.tgz\",\n \"integrity\": \"sha1-mUQ7pug7gw7zBRv9fcJBqCco1Wg=\",\n \"requires\": {\n \"mute-stream\": \"0.0.4\",\n \"strip-ansi\": \"2.0.1\"\n },\n \"dependencies\": {\n \"mute-stream\": {\n \"version\": \"0.0.4\",\n \"resolved\": \"https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.4.tgz\",\n \"integrity\": \"sha1-qSGZYKbV1dBGWXruUSUsZlX3F34=\"\n },\n \"strip-ansi\": {\n \"version\": \"2.0.1\",\n \"resolved\": \"https://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.1.tgz\",\n \"integrity\": \"sha1-32LBqpTtLxFOHQ8h/R1QSCt5pg4=\",\n \"requires\": {\n \"ansi-regex\": \"1.1.1\"\n }\n }\n }\n },\n \"rx\": {\n \"version\": \"2.5.3\",\n \"resolved\": \"https://registry.npmjs.org/rx/-/rx-2.5.3.tgz\",\n \"integrity\": \"sha1-Ia3H2A8CACr1Da6X/Z2/JIdV9WY=\"\n },\n \"through\": {\n \"version\": \"2.3.7\",\n \"resolved\": \"https://registry.npmjs.org/through/-/through-2.3.7.tgz\",\n \"integrity\": \"sha1-X8w2kP7S/fmMb8iLTSB6RiSsO4c=\"\n }\n }\n },\n \"is-my-json-valid\": {\n \"version\": \"2.12.0\",\n \"resolved\": \"https://registry.npmjs.org/is-my-json-valid/-/is-my-json-valid-2.12.0.tgz\",\n \"integrity\": \"sha1-j6bECLJr6VtFoj6PjEtGSlOHTSs=\",\n \"requires\": {\n \"generate-function\": \"2.0.0\",\n \"generate-object-property\": \"1.2.0\",\n \"jsonpointer\": \"1.1.0\",\n \"xtend\": \"4.0.0\"\n },\n \"dependencies\": {\n \"generate-function\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/generate-function/-/generate-function-2.0.0.tgz\",\n \"integrity\": \"sha1-aFj+fAlpt9TpCTM3ZHrHn2DfvnQ=\"\n },\n \"generate-object-property\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/generate-object-property/-/generate-object-property-1.2.0.tgz\",\n \"integrity\": \"sha1-nA4cQDCM6AT0eDYYuTf6iPmdUNA=\",\n \"requires\": {\n \"is-property\": \"1.0.2\"\n },\n \"dependencies\": {\n \"is-property\": {\n \"version\": \"1.0.2\",\n \"resolved\": \"https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz\",\n \"integrity\": \"sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ=\"\n }\n }\n },\n \"jsonpointer\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/jsonpointer/-/jsonpointer-1.1.0.tgz\",\n \"integrity\": \"sha1-w8cu+u07lxVBY9wB3TSeHP4PgPw=\"\n },\n \"xtend\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/xtend/-/xtend-4.0.0.tgz\",\n \"integrity\": \"sha1-i8Nv+Hrtvnzp6vC8o2sjVKdDhA8=\"\n }\n }\n },\n \"js-yaml\": {\n \"version\": \"3.3.1\",\n \"resolved\": \"https://registry.npmjs.org/js-yaml/-/js-yaml-3.3.1.tgz\",\n \"integrity\": \"sha1-yhrNNCPsJ10SFAp7q1HbAVugs8A=\",\n \"requires\": {\n \"argparse\": \"1.0.2\",\n \"esprima\": \"2.2.0\"\n },\n \"dependencies\": {\n \"argparse\": {\n \"version\": \"1.0.2\",\n \"resolved\": \"https://registry.npmjs.org/argparse/-/argparse-1.0.2.tgz\",\n \"integrity\": \"sha1-vPrjkFllbRlz0LnmoadBVLWpoTY=\",\n \"requires\": {\n \"lodash\": \"3.9.3\",\n \"sprintf-js\": \"1.0.2\"\n },\n \"dependencies\": {\n \"lodash\": {\n \"version\": \"3.9.3\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-3.9.3.tgz\",\n \"integrity\": \"sha1-AVnoaDL+/8bWHYUrEqlTuZSWvTI=\"\n },\n \"sprintf-js\": {\n \"version\": \"1.0.2\",\n \"resolved\": \"https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.2.tgz\",\n \"integrity\": \"sha1-EeTYT/MhRONbC/Omb4WH842PmXg=\"\n }\n }\n },\n \"esprima\": {\n \"version\": \"2.2.0\",\n \"resolved\": \"https://registry.npmjs.org/esprima/-/esprima-2.2.0.tgz\",\n \"integrity\": \"sha1-QpLB1o5Bc9gV+iKQ3Hr8ltgfzYM=\"\n }\n }\n },\n \"minimatch\": {\n \"version\": \"2.0.8\",\n \"resolved\": \"https://registry.npmjs.org/minimatch/-/minimatch-2.0.8.tgz\",\n \"integrity\": \"sha1-C8IPa/NXCmmO8N3/kCBjxsq9pr8=\",\n \"requires\": {\n \"brace-expansion\": \"1.1.0\"\n },\n \"dependencies\": {\n \"brace-expansion\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.0.tgz\",\n \"integrity\": \"sha1-ybfQPAPze8cEvhAOUitA249s/Nk=\",\n \"requires\": {\n \"balanced-match\": \"0.2.0\",\n \"concat-map\": \"0.0.1\"\n },\n \"dependencies\": {\n \"balanced-match\": {\n \"version\": \"0.2.0\",\n \"resolved\": \"https://registry.npmjs.org/balanced-match/-/balanced-match-0.2.0.tgz\",\n \"integrity\": \"sha1-OPZzDAOqttXtu1K9k0iF51bXFnQ=\"\n },\n \"concat-map\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz\",\n \"integrity\": \"sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=\"\n }\n }\n }\n }\n },\n \"mkdirp\": {\n \"version\": \"0.5.1\",\n \"resolved\": \"https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz\",\n \"integrity\": \"sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=\",\n \"requires\": {\n \"minimist\": \"0.0.8\"\n },\n \"dependencies\": {\n \"minimist\": {\n \"version\": \"0.0.8\",\n \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz\",\n \"integrity\": \"sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=\"\n }\n }\n },\n \"object-assign\": {\n \"version\": \"2.1.1\",\n \"resolved\": \"https://registry.npmjs.org/object-assign/-/object-assign-2.1.1.tgz\",\n \"integrity\": \"sha1-Q8NuXVaf+OSBbE76i+AtJpZ8GKo=\"\n },\n \"optionator\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/optionator/-/optionator-0.5.0.tgz\",\n \"integrity\": \"sha1-t1qJlaLUF98ltuTjhi9QqohlE2g=\",\n \"requires\": {\n \"deep-is\": \"0.1.3\",\n \"fast-levenshtein\": \"1.0.6\",\n \"levn\": \"0.2.5\",\n \"prelude-ls\": \"1.1.2\",\n \"type-check\": \"0.3.1\",\n \"wordwrap\": \"0.0.3\"\n },\n \"dependencies\": {\n \"deep-is\": {\n \"version\": \"0.1.3\",\n \"resolved\": \"https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz\",\n \"integrity\": \"sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=\"\n },\n \"fast-levenshtein\": {\n \"version\": \"1.0.6\",\n \"resolved\": \"https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-1.0.6.tgz\",\n \"integrity\": \"sha1-O+2xhOOflcsNiJKGiOax7jJzRGo=\"\n },\n \"levn\": {\n \"version\": \"0.2.5\",\n \"resolved\": \"https://registry.npmjs.org/levn/-/levn-0.2.5.tgz\",\n \"integrity\": \"sha1-uo0znQykphDjo/FFucr0iAcVUFQ=\",\n \"requires\": {\n \"prelude-ls\": \"1.1.2\",\n \"type-check\": \"0.3.1\"\n }\n },\n \"prelude-ls\": {\n \"version\": \"1.1.2\",\n \"resolved\": \"https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz\",\n \"integrity\": \"sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=\"\n },\n \"type-check\": {\n \"version\": \"0.3.1\",\n \"resolved\": \"https://registry.npmjs.org/type-check/-/type-check-0.3.1.tgz\",\n \"integrity\": \"sha1-kjOSPE2hdNCsVIDs/W74TDSetY0=\",\n \"requires\": {\n \"prelude-ls\": \"1.1.2\"\n }\n },\n \"wordwrap\": {\n \"version\": \"0.0.3\",\n \"resolved\": \"https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz\",\n \"integrity\": \"sha1-o9XabNXAvAAI03I0u68b7WMFkQc=\"\n }\n }\n },\n \"path-is-absolute\": {\n \"version\": \"1.0.0\",\n \"resolved\": \"https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.0.tgz\",\n \"integrity\": \"sha1-Jj2tpmqz8vsQv3+dJN2PPlcO+RI=\"\n },\n \"strip-json-comments\": {\n \"version\": \"1.0.2\",\n \"resolved\": \"https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.2.tgz\",\n \"integrity\": \"sha1-WkirlgI9usG3uND/q/b2PxZ3vp8=\"\n },\n \"text-table\": {\n \"version\": \"0.2.0\",\n \"resolved\": \"https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz\",\n \"integrity\": \"sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=\"\n },\n \"user-home\": {\n \"version\": \"1.1.1\",\n \"resolved\": \"https://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz\",\n \"integrity\": \"sha1-K1viOjK2Onyd640PKNSFcko98ZA=\"\n },\n \"xml-escape\": {\n \"version\": \"1.0.0\",\n \"resolved\": \"https://registry.npmjs.org/xml-escape/-/xml-escape-1.0.0.tgz\",\n \"integrity\": \"sha1-AJY9aXsq3wwYXE4E5zF0upsojrI=\"\n }\n }\n },\n \"eslint-plugin-react\": {\n \"version\": \"2.5.0\",\n \"resolved\": \"https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-2.5.0.tgz\",\n \"integrity\": \"sha1-b2DLrW/6HcTl2TkZtaHtZ1IubLc=\"\n }\n }\n}\n", "file_path": "scripts/admin/eslint/npm-shrinkwrap.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2cd5b5c6d9793813e35c091e539d18c0233c3bda", "dependency_score": [0.00017382997612003237, 0.0001687839103396982, 0.00016382859030272812, 0.00016860355390235782, 2.1965915948385373e-06]} {"hunk": {"id": 0, "code_window": ["\n", " // OK, wiped all packages, now let's go and check that everything is removed\n", " // except for the tool we are running right now and the latest tool. i.e. v1\n", " // and v3\n", " _.each(files.readdir(prefix), function (f) {\n", " if (f[0] === '.') return;\n", " if (process.platform === 'win32') {\n", " // this is a dir\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep"], "after_edit": [" var notHidden = function (f) { return f[0] !== '.'; };\n", " var meteorToolDirs = _.filter(files.readdir(prefix), notHidden);\n", " selftest.expectTrue(meteorToolDirs.length === 2);\n", " _.each(meteorToolDirs, function (f) {\n", " var fPath = files.pathJoin(prefix, f);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 114}, "file": "var selftest = require('../selftest.js');\nvar Sandbox = selftest.Sandbox;\nvar files = require(\"../files.js\");\nvar utils = require(\"../utils.js\");\nvar archinfo = require(\"../archinfo.js\");\nvar _ = require('underscore');\n\nselftest.define(\"wipe all packages\", function () {\n var s = new Sandbox({\n warehouse: {\n v1: { tool: \"meteor-tool@33.0.1\" },\n v2: { tool: \"meteor-tool@33.0.2\" },\n v3: { tool: \"meteor-tool@33.0.3\" }\n }\n });\n var meteorToolVersion = function (v) {\n return {\n _id: 'VID' + v.replace(/\\./g, ''),\n packageName: 'meteor-tool',\n testName: null,\n version: v,\n publishedBy: null,\n description: 'The Meteor command-line tool',\n git: undefined,\n dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } },\n source: null,\n lastUpdated: null,\n published: null,\n isTest: false,\n debugOnly: false,\n containsPlugins: false\n };\n };\n\n // insert the new tool versions into the catalog\n s.warehouseOfficialCatalog.insertData({\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n });\n\n // help warehouse faking by copying the meteor-tool 3 times and introducing 3\n // fake versions (identical in code to the one we are running)\n var latestMeteorToolVersion =\n files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/');\n latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3];\n\n var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool');\n var copyTool = function (srcVersion, dstVersion) {\n if (process.platform === 'win32') {\n // just copy the files\n files.cp_r(\n files.pathJoin(prefix, srcVersion),\n files.pathJoin(prefix, dstVersion), {\n preserveSymlinks: true\n });\n } else {\n // figure out what the symlink links to and copy the folder *and* the\n // symlink\n var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion));\n var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion);\n\n // copy the hidden folder\n files.cp_r(\n files.pathJoin(prefix, srcFullVersion),\n files.pathJoin(prefix, dstFullVersion), {\n preserveSymlinks: true\n });\n\n // link to it\n files.symlink(\n dstFullVersion,\n files.pathJoin(prefix, dstVersion));\n }\n\n var replaceVersionInFile = function (filename) {\n var filePath = files.pathJoin(prefix, dstVersion, filename);\n files.writeFile(\n filePath,\n files.readFile(filePath, 'utf8')\n .replace(new RegExp(srcVersion, 'g'), dstVersion));\n };\n\n // \"fix\" the isopack.json and unibuild.json files (they contain the versions)\n replaceVersionInFile('isopack.json');\n replaceVersionInFile('unipackage.json');\n };\n\n copyTool(latestMeteorToolVersion, '33.0.3');\n copyTool(latestMeteorToolVersion, '33.0.2');\n copyTool(latestMeteorToolVersion, '33.0.1');\n\n // since the warehouse faking system is weak and under-developed, add more\n // faking, such as making the v3 the latest version\n files.linkToMeteorScript(\n files.pathJoin(s.warehouse, 'packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(s.warehouse, 'meteor'));\n\n\n var run;\n\n run = s.run('--release', 'v1', 'admin', 'wipe-all-packages');\n run.waitSecs(15);\n run.expectExit(0);\n\n // OK, wiped all packages, now let's go and check that everything is removed\n // except for the tool we are running right now and the latest tool. i.e. v1\n // and v3\n _.each(files.readdir(prefix), function (f) {\n if (f[0] === '.') return;\n if (process.platform === 'win32') {\n // this is a dir\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n } else {\n // this is a symlink to a dir and this dir exists\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n }\n });\n\n // Check that all other packages are wiped\n _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n if (p[0] === '.') return;\n if (p === 'meteor-tool') return;\n var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n selftest.expectTrue(contents.length === 0);\n });\n});\n\n", "file_path": "tools/tests/wipe-all-packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.9980150461196899, 0.1674518883228302, 0.00016937182226683944, 0.0008473113994114101, 0.3493664562702179]} {"hunk": {"id": 0, "code_window": ["\n", " // OK, wiped all packages, now let's go and check that everything is removed\n", " // except for the tool we are running right now and the latest tool. i.e. v1\n", " // and v3\n", " _.each(files.readdir(prefix), function (f) {\n", " if (f[0] === '.') return;\n", " if (process.platform === 'win32') {\n", " // this is a dir\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep"], "after_edit": [" var notHidden = function (f) { return f[0] !== '.'; };\n", " var meteorToolDirs = _.filter(files.readdir(prefix), notHidden);\n", " selftest.expectTrue(meteorToolDirs.length === 2);\n", " _.each(meteorToolDirs, function (f) {\n", " var fPath = files.pathJoin(prefix, f);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 114}, "file": "/**\n * Provide a synchronous Collection API using fibers, backed by\n * MongoDB. This is only for use on the server, and mostly identical\n * to the client API.\n *\n * NOTE: the public API methods must be run within a fiber. If you call\n * these outside of a fiber they will explode!\n */\n\nvar path = Npm.require('path');\nvar MongoDB = Npm.require('mongodb');\nvar Fiber = Npm.require('fibers');\nvar Future = Npm.require(path.join('fibers', 'future'));\n\nMongoInternals = {};\nMongoTest = {};\n\nMongoInternals.NpmModules = {\n mongodb: {\n version: Npm.require('mongodb/package.json').version,\n module: MongoDB\n }\n};\n\n// Older version of what is now available via\n// MongoInternals.NpmModules.mongodb.module. It was never documented, but\n// people do use it.\n// XXX COMPAT WITH 1.0.3.2\nMongoInternals.NpmModule = MongoDB;\n\n// This is used to add or remove EJSON from the beginning of everything nested\n// inside an EJSON custom type. It should only be called on pure JSON!\nvar replaceNames = function (filter, thing) {\n if (typeof thing === \"object\") {\n if (_.isArray(thing)) {\n return _.map(thing, _.bind(replaceNames, null, filter));\n }\n var ret = {};\n _.each(thing, function (value, key) {\n ret[filter(key)] = replaceNames(filter, value);\n });\n return ret;\n }\n return thing;\n};\n\n// Ensure that EJSON.clone keeps a Timestamp as a Timestamp (instead of just\n// doing a structural clone).\n// XXX how ok is this? what if there are multiple copies of MongoDB loaded?\nMongoDB.Timestamp.prototype.clone = function () {\n // Timestamps should be immutable.\n return this;\n};\n\nvar makeMongoLegal = function (name) { return \"EJSON\" + name; };\nvar unmakeMongoLegal = function (name) { return name.substr(5); };\n\nvar replaceMongoAtomWithMeteor = function (document) {\n if (document instanceof MongoDB.Binary) {\n var buffer = document.value(true);\n return new Uint8Array(buffer);\n }\n if (document instanceof MongoDB.ObjectID) {\n return new Mongo.ObjectID(document.toHexString());\n }\n if (document[\"EJSON$type\"] && document[\"EJSON$value\"]\n && _.size(document) === 2) {\n return EJSON.fromJSONValue(replaceNames(unmakeMongoLegal, document));\n }\n if (document instanceof MongoDB.Timestamp) {\n // For now, the Meteor representation of a Mongo timestamp type (not a date!\n // this is a weird internal thing used in the oplog!) is the same as the\n // Mongo representation. We need to do this explicitly or else we would do a\n // structural clone and lose the prototype.\n return document;\n }\n return undefined;\n};\n\nvar replaceMeteorAtomWithMongo = function (document) {\n if (EJSON.isBinary(document)) {\n // This does more copies than we'd like, but is necessary because\n // MongoDB.BSON only looks like it takes a Uint8Array (and doesn't actually\n // serialize it correctly).\n return new MongoDB.Binary(new Buffer(document));\n }\n if (document instanceof Mongo.ObjectID) {\n return new MongoDB.ObjectID(document.toHexString());\n }\n if (document instanceof MongoDB.Timestamp) {\n // For now, the Meteor representation of a Mongo timestamp type (not a date!\n // this is a weird internal thing used in the oplog!) is the same as the\n // Mongo representation. We need to do this explicitly or else we would do a\n // structural clone and lose the prototype.\n return document;\n }\n if (EJSON._isCustomType(document)) {\n return replaceNames(makeMongoLegal, EJSON.toJSONValue(document));\n }\n // It is not ordinarily possible to stick dollar-sign keys into mongo\n // so we don't bother checking for things that need escaping at this time.\n return undefined;\n};\n\nvar replaceTypes = function (document, atomTransformer) {\n if (typeof document !== 'object' || document === null)\n return document;\n\n var replacedTopLevelAtom = atomTransformer(document);\n if (replacedTopLevelAtom !== undefined)\n return replacedTopLevelAtom;\n\n var ret = document;\n _.each(document, function (val, key) {\n var valReplaced = replaceTypes(val, atomTransformer);\n if (val !== valReplaced) {\n // Lazy clone. Shallow copy.\n if (ret === document)\n ret = _.clone(document);\n ret[key] = valReplaced;\n }\n });\n return ret;\n};\n\n\nMongoConnection = function (url, options) {\n var self = this;\n options = options || {};\n self._observeMultiplexers = {};\n self._onFailoverHook = new Hook;\n\n var mongoOptions = {db: {safe: true}, server: {}, replSet: {}};\n\n // Set autoReconnect to true, unless passed on the URL. Why someone\n // would want to set autoReconnect to false, I'm not really sure, but\n // keeping this for backwards compatibility for now.\n if (!(/[\\?&]auto_?[rR]econnect=/.test(url))) {\n mongoOptions.server.auto_reconnect = true;\n }\n\n // Disable the native parser by default, unless specifically enabled\n // in the mongo URL.\n // - The native driver can cause errors which normally would be\n // thrown, caught, and handled into segfaults that take down the\n // whole app.\n // - Binary modules don't yet work when you bundle and move the bundle\n // to a different platform (aka deploy)\n // We should revisit this after binary npm module support lands.\n if (!(/[\\?&]native_?[pP]arser=/.test(url))) {\n mongoOptions.db.native_parser = false;\n }\n\n // XXX maybe we should have a better way of allowing users to configure the\n // underlying Mongo driver\n if (_.has(options, 'poolSize')) {\n // If we just set this for \"server\", replSet will override it. If we just\n // set it for replSet, it will be ignored if we're not using a replSet.\n mongoOptions.server.poolSize = options.poolSize;\n mongoOptions.replSet.poolSize = options.poolSize;\n }\n\n self.db = null;\n // We keep track of the ReplSet's primary, so that we can trigger hooks when\n // it changes. The Node driver's joined callback seems to fire way too\n // often, which is why we need to track it ourselves.\n self._primary = null;\n self._oplogHandle = null;\n self._docFetcher = null;\n\n\n var connectFuture = new Future;\n MongoDB.connect(\n url,\n mongoOptions,\n Meteor.bindEnvironment(\n function (err, db) {\n if (err) {\n throw err;\n }\n\n // First, figure out what the current primary is, if any.\n if (db.serverConfig._state.master)\n self._primary = db.serverConfig._state.master.name;\n db.serverConfig.on(\n 'joined', Meteor.bindEnvironment(function (kind, doc) {\n if (kind === 'primary') {\n if (doc.primary !== self._primary) {\n self._primary = doc.primary;\n self._onFailoverHook.each(function (callback) {\n callback();\n return true;\n });\n }\n } else if (doc.me === self._primary) {\n // The thing we thought was primary is now something other than\n // primary. Forget that we thought it was primary. (This means\n // that if a server stops being primary and then starts being\n // primary again without another server becoming primary in the\n // middle, we'll correctly count it as a failover.)\n self._primary = null;\n }\n }));\n\n // Allow the constructor to return.\n connectFuture['return'](db);\n },\n connectFuture.resolver() // onException\n )\n );\n\n // Wait for the connection to be successful; throws on failure.\n self.db = connectFuture.wait();\n\n if (options.oplogUrl && ! Package['disable-oplog']) {\n self._oplogHandle = new OplogHandle(options.oplogUrl, self.db.databaseName);\n self._docFetcher = new DocFetcher(self);\n }\n};\n\nMongoConnection.prototype.close = function() {\n var self = this;\n\n if (! self.db)\n throw Error(\"close called before Connection created?\");\n\n // XXX probably untested\n var oplogHandle = self._oplogHandle;\n self._oplogHandle = null;\n if (oplogHandle)\n oplogHandle.stop();\n\n // Use Future.wrap so that errors get thrown. This happens to\n // work even outside a fiber since the 'close' method is not\n // actually asynchronous.\n Future.wrap(_.bind(self.db.close, self.db))(true).wait();\n};\n\n// Returns the Mongo Collection object; may yield.\nMongoConnection.prototype.rawCollection = function (collectionName) {\n var self = this;\n\n if (! self.db)\n throw Error(\"rawCollection called before Connection created?\");\n\n var future = new Future;\n self.db.collection(collectionName, future.resolver());\n return future.wait();\n};\n\nMongoConnection.prototype._createCappedCollection = function (\n collectionName, byteSize, maxDocuments) {\n var self = this;\n\n if (! self.db)\n throw Error(\"_createCappedCollection called before Connection created?\");\n\n var future = new Future();\n self.db.createCollection(\n collectionName,\n { capped: true, size: byteSize, max: maxDocuments },\n future.resolver());\n future.wait();\n};\n\n// This should be called synchronously with a write, to create a\n// transaction on the current write fence, if any. After we can read\n// the write, and after observers have been notified (or at least,\n// after the observer notifiers have added themselves to the write\n// fence), you should call 'committed()' on the object returned.\nMongoConnection.prototype._maybeBeginWrite = function () {\n var self = this;\n var fence = DDPServer._CurrentWriteFence.get();\n if (fence)\n return fence.beginWrite();\n else\n return {committed: function () {}};\n};\n\n// Internal interface: adds a callback which is called when the Mongo primary\n// changes. Returns a stop handle.\nMongoConnection.prototype._onFailover = function (callback) {\n return this._onFailoverHook.register(callback);\n};\n\n\n//////////// Public API //////////\n\n// The write methods block until the database has confirmed the write (it may\n// not be replicated or stable on disk, but one server has confirmed it) if no\n// callback is provided. If a callback is provided, then they call the callback\n// when the write is confirmed. They return nothing on success, and raise an\n// exception on failure.\n//\n// After making a write (with insert, update, remove), observers are\n// notified asynchronously. If you want to receive a callback once all\n// of the observer notifications have landed for your write, do the\n// writes inside a write fence (set DDPServer._CurrentWriteFence to a new\n// _WriteFence, and then set a callback on the write fence.)\n//\n// Since our execution environment is single-threaded, this is\n// well-defined -- a write \"has been made\" if it's returned, and an\n// observer \"has been notified\" if its callback has returned.\n\nvar writeCallback = function (write, refresh, callback) {\n return function (err, result) {\n if (! err) {\n // XXX We don't have to run this on error, right?\n refresh();\n }\n write.committed();\n if (callback)\n callback(err, result);\n else if (err)\n throw err;\n };\n};\n\nvar bindEnvironmentForWrite = function (callback) {\n return Meteor.bindEnvironment(callback, \"Mongo write\");\n};\n\nMongoConnection.prototype._insert = function (collection_name, document,\n callback) {\n var self = this;\n\n var sendError = function (e) {\n if (callback)\n return callback(e);\n throw e;\n };\n\n if (collection_name === \"___meteor_failure_test_collection\") {\n var e = new Error(\"Failure test\");\n e.expected = true;\n sendError(e);\n return;\n }\n\n if (!(LocalCollection._isPlainObject(document) &&\n !EJSON._isCustomType(document))) {\n sendError(new Error(\n \"Only plain objects may be inserted into MongoDB\"));\n return;\n }\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n Meteor.refresh({collection: collection_name, id: document._id });\n };\n callback = bindEnvironmentForWrite(writeCallback(write, refresh, callback));\n try {\n var collection = self.rawCollection(collection_name);\n collection.insert(replaceTypes(document, replaceMeteorAtomWithMongo),\n {safe: true}, callback);\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\n// Cause queries that may be affected by the selector to poll in this write\n// fence.\nMongoConnection.prototype._refresh = function (collectionName, selector) {\n var self = this;\n var refreshKey = {collection: collectionName};\n // If we know which documents we're removing, don't poll queries that are\n // specific to other documents. (Note that multiple notifications here should\n // not cause multiple polls, since all our listener is doing is enqueueing a\n // poll.)\n var specificIds = LocalCollection._idsMatchedBySelector(selector);\n if (specificIds) {\n _.each(specificIds, function (id) {\n Meteor.refresh(_.extend({id: id}, refreshKey));\n });\n } else {\n Meteor.refresh(refreshKey);\n }\n};\n\nMongoConnection.prototype._remove = function (collection_name, selector,\n callback) {\n var self = this;\n\n if (collection_name === \"___meteor_failure_test_collection\") {\n var e = new Error(\"Failure test\");\n e.expected = true;\n if (callback)\n return callback(e);\n else\n throw e;\n }\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n self._refresh(collection_name, selector);\n };\n callback = bindEnvironmentForWrite(writeCallback(write, refresh, callback));\n\n try {\n var collection = self.rawCollection(collection_name);\n collection.remove(replaceTypes(selector, replaceMeteorAtomWithMongo),\n {safe: true}, callback);\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\nMongoConnection.prototype._dropCollection = function (collectionName, cb) {\n var self = this;\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n Meteor.refresh({collection: collectionName, id: null,\n dropCollection: true});\n };\n cb = bindEnvironmentForWrite(writeCallback(write, refresh, cb));\n\n try {\n var collection = self.rawCollection(collectionName);\n collection.drop(cb);\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\nMongoConnection.prototype._update = function (collection_name, selector, mod,\n options, callback) {\n var self = this;\n\n if (! callback && options instanceof Function) {\n callback = options;\n options = null;\n }\n\n if (collection_name === \"___meteor_failure_test_collection\") {\n var e = new Error(\"Failure test\");\n e.expected = true;\n if (callback)\n return callback(e);\n else\n throw e;\n }\n\n // explicit safety check. null and undefined can crash the mongo\n // driver. Although the node driver and minimongo do 'support'\n // non-object modifier in that they don't crash, they are not\n // meaningful operations and do not do anything. Defensively throw an\n // error here.\n if (!mod || typeof mod !== 'object')\n throw new Error(\"Invalid modifier. Modifier must be an object.\");\n\n if (!(LocalCollection._isPlainObject(mod) &&\n !EJSON._isCustomType(mod))) {\n throw new Error(\n \"Only plain objects may be used as replacement\" +\n \" documents in MongoDB\");\n return;\n }\n\n if (!options) options = {};\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n self._refresh(collection_name, selector);\n };\n callback = writeCallback(write, refresh, callback);\n try {\n var collection = self.rawCollection(collection_name);\n var mongoOpts = {safe: true};\n // explictly enumerate options that minimongo supports\n if (options.upsert) mongoOpts.upsert = true;\n if (options.multi) mongoOpts.multi = true;\n // Lets you get a more more full result from MongoDB. Use with caution:\n // might not work with C.upsert (as opposed to C.update({upsert:true}) or\n // with simulated upsert.\n if (options.fullResult) mongoOpts.fullResult = true;\n\n var mongoSelector = replaceTypes(selector, replaceMeteorAtomWithMongo);\n var mongoMod = replaceTypes(mod, replaceMeteorAtomWithMongo);\n\n var isModify = isModificationMod(mongoMod);\n var knownId = selector._id || mod._id;\n\n if (options._forbidReplace && ! isModify) {\n var e = new Error(\"Invalid modifier. Replacements are forbidden.\");\n if (callback) {\n return callback(e);\n } else {\n throw e;\n }\n }\n\n if (options.upsert && (! knownId) && options.insertedId) {\n // XXX If we know we're using Mongo 2.6 (and this isn't a replacement)\n // we should be able to just use $setOnInsert instead of this\n // simulated upsert thing. (We can't use $setOnInsert with\n // replacements because there's nowhere to write it, and $setOnInsert\n // can't set _id on Mongo 2.4.)\n //\n // Also, in the future we could do a real upsert for the mongo id\n // generation case, if the the node mongo driver gives us back the id\n // of the upserted doc (which our current version does not).\n //\n // For more context, see\n // https://github.com/meteor/meteor/issues/2278#issuecomment-64252706\n simulateUpsertWithInsertedId(\n collection, mongoSelector, mongoMod,\n isModify, options,\n // This callback does not need to be bindEnvironment'ed because\n // simulateUpsertWithInsertedId() wraps it and then passes it through\n // bindEnvironmentForWrite.\n function (err, result) {\n // If we got here via a upsert() call, then options._returnObject will\n // be set and we should return the whole object. Otherwise, we should\n // just return the number of affected docs to match the mongo API.\n if (result && ! options._returnObject)\n callback(err, result.numberAffected);\n else\n callback(err, result);\n }\n );\n } else {\n collection.update(\n mongoSelector, mongoMod, mongoOpts,\n bindEnvironmentForWrite(function (err, result, extra) {\n if (! err) {\n if (result && options._returnObject) {\n result = { numberAffected: result };\n // If this was an upsert() call, and we ended up\n // inserting a new doc and we know its id, then\n // return that id as well.\n if (options.upsert && knownId &&\n ! extra.updatedExisting)\n result.insertedId = knownId;\n }\n }\n callback(err, result);\n }));\n }\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\nvar isModificationMod = function (mod) {\n var isReplace = false;\n var isModify = false;\n for (var k in mod) {\n if (k.substr(0, 1) === '$') {\n isModify = true;\n } else {\n isReplace = true;\n }\n }\n if (isModify && isReplace) {\n throw new Error(\n \"Update parameter cannot have both modifier and non-modifier fields.\");\n }\n return isModify;\n};\n\nvar NUM_OPTIMISTIC_TRIES = 3;\n\n// exposed for testing\nMongoConnection._isCannotChangeIdError = function (err) {\n // First check for what this error looked like in Mongo 2.4. Either of these\n // checks should work, but just to be safe...\n if (err.code === 13596)\n return true;\n if (err.err.indexOf(\"cannot change _id of a document\") === 0)\n return true;\n\n // Now look for what it looks like in Mongo 2.6. We don't use the error code\n // here, because the error code we observed it producing (16837) appears to be\n // a far more generic error code based on examining the source.\n if (err.err.indexOf(\"The _id field cannot be changed\") === 0)\n return true;\n\n return false;\n};\n\nvar simulateUpsertWithInsertedId = function (collection, selector, mod,\n isModify, options, callback) {\n // STRATEGY: First try doing a plain update. If it affected 0 documents,\n // then without affecting the database, we know we should probably do an\n // insert. We then do a *conditional* insert that will fail in the case\n // of a race condition. This conditional insert is actually an\n // upsert-replace with an _id, which will never successfully update an\n // existing document. If this upsert fails with an error saying it\n // couldn't change an existing _id, then we know an intervening write has\n // caused the query to match something. We go back to step one and repeat.\n // Like all \"optimistic write\" schemes, we rely on the fact that it's\n // unlikely our writes will continue to be interfered with under normal\n // circumstances (though sufficiently heavy contention with writers\n // disagreeing on the existence of an object will cause writes to fail\n // in theory).\n\n var newDoc;\n // Run this code up front so that it fails fast if someone uses\n // a Mongo update operator we don't support.\n if (isModify) {\n // We've already run replaceTypes/replaceMeteorAtomWithMongo on\n // selector and mod. We assume it doesn't matter, as far as\n // the behavior of modifiers is concerned, whether `_modify`\n // is run on EJSON or on mongo-converted EJSON.\n var selectorDoc = LocalCollection._removeDollarOperators(selector);\n LocalCollection._modify(selectorDoc, mod, {isInsert: true});\n newDoc = selectorDoc;\n } else {\n newDoc = mod;\n }\n\n var insertedId = options.insertedId; // must exist\n var mongoOptsForUpdate = {\n safe: true,\n multi: options.multi\n };\n var mongoOptsForInsert = {\n safe: true,\n upsert: true\n };\n\n var tries = NUM_OPTIMISTIC_TRIES;\n\n var doUpdate = function () {\n tries--;\n if (! tries) {\n callback(new Error(\"Upsert failed after \" + NUM_OPTIMISTIC_TRIES + \" tries.\"));\n } else {\n collection.update(selector, mod, mongoOptsForUpdate,\n bindEnvironmentForWrite(function (err, result) {\n if (err)\n callback(err);\n else if (result)\n callback(null, {\n numberAffected: result\n });\n else\n doConditionalInsert();\n }));\n }\n };\n\n var doConditionalInsert = function () {\n var replacementWithId = _.extend(\n replaceTypes({_id: insertedId}, replaceMeteorAtomWithMongo),\n newDoc);\n collection.update(selector, replacementWithId, mongoOptsForInsert,\n bindEnvironmentForWrite(function (err, result) {\n if (err) {\n // figure out if this is a\n // \"cannot change _id of document\" error, and\n // if so, try doUpdate() again, up to 3 times.\n if (MongoConnection._isCannotChangeIdError(err)) {\n doUpdate();\n } else {\n callback(err);\n }\n } else {\n callback(null, {\n numberAffected: result,\n insertedId: insertedId\n });\n }\n }));\n };\n\n doUpdate();\n};\n\n_.each([\"insert\", \"update\", \"remove\", \"dropCollection\"], function (method) {\n MongoConnection.prototype[method] = function (/* arguments */) {\n var self = this;\n return Meteor.wrapAsync(self[\"_\" + method]).apply(self, arguments);\n };\n});\n\n// XXX MongoConnection.upsert() does not return the id of the inserted document\n// unless you set it explicitly in the selector or modifier (as a replacement\n// doc).\nMongoConnection.prototype.upsert = function (collectionName, selector, mod,\n options, callback) {\n var self = this;\n if (typeof options === \"function\" && ! callback) {\n callback = options;\n options = {};\n }\n\n return self.update(collectionName, selector, mod,\n _.extend({}, options, {\n upsert: true,\n _returnObject: true\n }), callback);\n};\n\nMongoConnection.prototype.find = function (collectionName, selector, options) {\n var self = this;\n\n if (arguments.length === 1)\n selector = {};\n\n return new Cursor(\n self, new CursorDescription(collectionName, selector, options));\n};\n\nMongoConnection.prototype.findOne = function (collection_name, selector,\n options) {\n var self = this;\n if (arguments.length === 1)\n selector = {};\n\n options = options || {};\n options.limit = 1;\n return self.find(collection_name, selector, options).fetch()[0];\n};\n\n// We'll actually design an index API later. For now, we just pass through to\n// Mongo's, but make it synchronous.\nMongoConnection.prototype._ensureIndex = function (collectionName, index,\n options) {\n var self = this;\n options = _.extend({safe: true}, options);\n\n // We expect this function to be called at startup, not from within a method,\n // so we don't interact with the write fence.\n var collection = self.rawCollection(collectionName);\n var future = new Future;\n var indexName = collection.ensureIndex(index, options, future.resolver());\n future.wait();\n};\nMongoConnection.prototype._dropIndex = function (collectionName, index) {\n var self = this;\n\n // This function is only used by test code, not within a method, so we don't\n // interact with the write fence.\n var collection = self.rawCollection(collectionName);\n var future = new Future;\n var indexName = collection.dropIndex(index, future.resolver());\n future.wait();\n};\n\n// CURSORS\n\n// There are several classes which relate to cursors:\n//\n// CursorDescription represents the arguments used to construct a cursor:\n// collectionName, selector, and (find) options. Because it is used as a key\n// for cursor de-dup, everything in it should either be JSON-stringifiable or\n// not affect observeChanges output (eg, options.transform functions are not\n// stringifiable but do not affect observeChanges).\n//\n// SynchronousCursor is a wrapper around a MongoDB cursor\n// which includes fully-synchronous versions of forEach, etc.\n//\n// Cursor is the cursor object returned from find(), which implements the\n// documented Mongo.Collection cursor API. It wraps a CursorDescription and a\n// SynchronousCursor (lazily: it doesn't contact Mongo until you call a method\n// like fetch or forEach on it).\n//\n// ObserveHandle is the \"observe handle\" returned from observeChanges. It has a\n// reference to an ObserveMultiplexer.\n//\n// ObserveMultiplexer allows multiple identical ObserveHandles to be driven by a\n// single observe driver.\n//\n// There are two \"observe drivers\" which drive ObserveMultiplexers:\n// - PollingObserveDriver caches the results of a query and reruns it when\n// necessary.\n// - OplogObserveDriver follows the Mongo operation log to directly observe\n// database changes.\n// Both implementations follow the same simple interface: when you create them,\n// they start sending observeChanges callbacks (and a ready() invocation) to\n// their ObserveMultiplexer, and you stop them by calling their stop() method.\n\nCursorDescription = function (collectionName, selector, options) {\n var self = this;\n self.collectionName = collectionName;\n self.selector = Mongo.Collection._rewriteSelector(selector);\n self.options = options || {};\n};\n\nCursor = function (mongo, cursorDescription) {\n var self = this;\n\n self._mongo = mongo;\n self._cursorDescription = cursorDescription;\n self._synchronousCursor = null;\n};\n\n_.each(['forEach', 'map', 'fetch', 'count'], function (method) {\n Cursor.prototype[method] = function () {\n var self = this;\n\n // You can only observe a tailable cursor.\n if (self._cursorDescription.options.tailable)\n throw new Error(\"Cannot call \" + method + \" on a tailable cursor\");\n\n if (!self._synchronousCursor) {\n self._synchronousCursor = self._mongo._createSynchronousCursor(\n self._cursorDescription, {\n // Make sure that the \"self\" argument to forEach/map callbacks is the\n // Cursor, not the SynchronousCursor.\n selfForIteration: self,\n useTransform: true\n });\n }\n\n return self._synchronousCursor[method].apply(\n self._synchronousCursor, arguments);\n };\n});\n\n// Since we don't actually have a \"nextObject\" interface, there's really no\n// reason to have a \"rewind\" interface. All it did was make multiple calls\n// to fetch/map/forEach return nothing the second time.\n// XXX COMPAT WITH 0.8.1\nCursor.prototype.rewind = function () {\n};\n\nCursor.prototype.getTransform = function () {\n return this._cursorDescription.options.transform;\n};\n\n// When you call Meteor.publish() with a function that returns a Cursor, we need\n// to transmute it into the equivalent subscription. This is the function that\n// does that.\n\nCursor.prototype._publishCursor = function (sub) {\n var self = this;\n var collection = self._cursorDescription.collectionName;\n return Mongo.Collection._publishCursor(self, sub, collection);\n};\n\n// Used to guarantee that publish functions return at most one cursor per\n// collection. Private, because we might later have cursors that include\n// documents from multiple collections somehow.\nCursor.prototype._getCollectionName = function () {\n var self = this;\n return self._cursorDescription.collectionName;\n}\n\nCursor.prototype.observe = function (callbacks) {\n var self = this;\n return LocalCollection._observeFromObserveChanges(self, callbacks);\n};\n\nCursor.prototype.observeChanges = function (callbacks) {\n var self = this;\n var ordered = LocalCollection._observeChangesCallbacksAreOrdered(callbacks);\n return self._mongo._observeChanges(\n self._cursorDescription, ordered, callbacks);\n};\n\nMongoConnection.prototype._createSynchronousCursor = function(\n cursorDescription, options) {\n var self = this;\n options = _.pick(options || {}, 'selfForIteration', 'useTransform');\n\n var collection = self.rawCollection(cursorDescription.collectionName);\n var cursorOptions = cursorDescription.options;\n var mongoOptions = {\n sort: cursorOptions.sort,\n limit: cursorOptions.limit,\n skip: cursorOptions.skip\n };\n\n // Do we want a tailable cursor (which only works on capped collections)?\n if (cursorOptions.tailable) {\n // We want a tailable cursor...\n mongoOptions.tailable = true;\n // ... and for the server to wait a bit if any getMore has no data (rather\n // than making us put the relevant sleeps in the client)...\n mongoOptions.awaitdata = true;\n // ... and to keep querying the server indefinitely rather than just 5 times\n // if there's no more data.\n mongoOptions.numberOfRetries = -1;\n // And if this is on the oplog collection and the cursor specifies a 'ts',\n // then set the undocumented oplog replay flag, which does a special scan to\n // find the first document (instead of creating an index on ts). This is a\n // very hard-coded Mongo flag which only works on the oplog collection and\n // only works with the ts field.\n if (cursorDescription.collectionName === OPLOG_COLLECTION &&\n cursorDescription.selector.ts) {\n mongoOptions.oplogReplay = true;\n }\n }\n\n var dbCursor = collection.find(\n replaceTypes(cursorDescription.selector, replaceMeteorAtomWithMongo),\n cursorOptions.fields, mongoOptions);\n\n return new SynchronousCursor(dbCursor, cursorDescription, options);\n};\n\nvar SynchronousCursor = function (dbCursor, cursorDescription, options) {\n var self = this;\n options = _.pick(options || {}, 'selfForIteration', 'useTransform');\n\n self._dbCursor = dbCursor;\n self._cursorDescription = cursorDescription;\n // The \"self\" argument passed to forEach/map callbacks. If we're wrapped\n // inside a user-visible Cursor, we want to provide the outer cursor!\n self._selfForIteration = options.selfForIteration || self;\n if (options.useTransform && cursorDescription.options.transform) {\n self._transform = LocalCollection.wrapTransform(\n cursorDescription.options.transform);\n } else {\n self._transform = null;\n }\n\n // Need to specify that the callback is the first argument to nextObject,\n // since otherwise when we try to call it with no args the driver will\n // interpret \"undefined\" first arg as an options hash and crash.\n self._synchronousNextObject = Future.wrap(\n dbCursor.nextObject.bind(dbCursor), 0);\n self._synchronousCount = Future.wrap(dbCursor.count.bind(dbCursor));\n self._visitedIds = new LocalCollection._IdMap;\n};\n\n_.extend(SynchronousCursor.prototype, {\n _nextObject: function () {\n var self = this;\n\n while (true) {\n var doc = self._synchronousNextObject().wait();\n\n if (!doc) return null;\n doc = replaceTypes(doc, replaceMongoAtomWithMeteor);\n\n if (!self._cursorDescription.options.tailable && _.has(doc, '_id')) {\n // Did Mongo give us duplicate documents in the same cursor? If so,\n // ignore this one. (Do this before the transform, since transform might\n // return some unrelated value.) We don't do this for tailable cursors,\n // because we want to maintain O(1) memory usage. And if there isn't _id\n // for some reason (maybe it's the oplog), then we don't do this either.\n // (Be careful to do this for falsey but existing _id, though.)\n if (self._visitedIds.has(doc._id)) continue;\n self._visitedIds.set(doc._id, true);\n }\n\n if (self._transform)\n doc = self._transform(doc);\n\n return doc;\n }\n },\n\n forEach: function (callback, thisArg) {\n var self = this;\n\n // Get back to the beginning.\n self._rewind();\n\n // We implement the loop ourself instead of using self._dbCursor.each,\n // because \"each\" will call its callback outside of a fiber which makes it\n // much more complex to make this function synchronous.\n var index = 0;\n while (true) {\n var doc = self._nextObject();\n if (!doc) return;\n callback.call(thisArg, doc, index++, self._selfForIteration);\n }\n },\n\n // XXX Allow overlapping callback executions if callback yields.\n map: function (callback, thisArg) {\n var self = this;\n var res = [];\n self.forEach(function (doc, index) {\n res.push(callback.call(thisArg, doc, index, self._selfForIteration));\n });\n return res;\n },\n\n _rewind: function () {\n var self = this;\n\n // known to be synchronous\n self._dbCursor.rewind();\n\n self._visitedIds = new LocalCollection._IdMap;\n },\n\n // Mostly usable for tailable cursors.\n close: function () {\n var self = this;\n\n self._dbCursor.close();\n },\n\n fetch: function () {\n var self = this;\n return self.map(_.identity);\n },\n\n count: function () {\n var self = this;\n return self._synchronousCount().wait();\n },\n\n // This method is NOT wrapped in Cursor.\n getRawObjects: function (ordered) {\n var self = this;\n if (ordered) {\n return self.fetch();\n } else {\n var results = new LocalCollection._IdMap;\n self.forEach(function (doc) {\n results.set(doc._id, doc);\n });\n return results;\n }\n }\n});\n\nMongoConnection.prototype.tail = function (cursorDescription, docCallback) {\n var self = this;\n if (!cursorDescription.options.tailable)\n throw new Error(\"Can only tail a tailable cursor\");\n\n var cursor = self._createSynchronousCursor(cursorDescription);\n\n var stopped = false;\n var lastTS = undefined;\n var loop = function () {\n while (true) {\n if (stopped)\n return;\n try {\n var doc = cursor._nextObject();\n } catch (err) {\n // There's no good way to figure out if this was actually an error\n // from Mongo. Ah well. But either way, we need to retry the cursor\n // (unless the failure was because the observe got stopped).\n doc = null;\n }\n // Since cursor._nextObject can yield, we need to check again to see if\n // we've been stopped before calling the callback.\n if (stopped)\n return;\n if (doc) {\n // If a tailable cursor contains a \"ts\" field, use it to recreate the\n // cursor on error. (\"ts\" is a standard that Mongo uses internally for\n // the oplog, and there's a special flag that lets you do binary search\n // on it instead of needing to use an index.)\n lastTS = doc.ts;\n docCallback(doc);\n } else {\n var newSelector = _.clone(cursorDescription.selector);\n if (lastTS) {\n newSelector.ts = {$gt: lastTS};\n }\n cursor = self._createSynchronousCursor(new CursorDescription(\n cursorDescription.collectionName,\n newSelector,\n cursorDescription.options));\n // Mongo failover takes many seconds. Retry in a bit. (Without this\n // setTimeout, we peg the CPU at 100% and never notice the actual\n // failover.\n Meteor.setTimeout(loop, 100);\n break;\n }\n }\n };\n\n Meteor.defer(loop);\n\n return {\n stop: function () {\n stopped = true;\n cursor.close();\n }\n };\n};\n\nMongoConnection.prototype._observeChanges = function (\n cursorDescription, ordered, callbacks) {\n var self = this;\n\n if (cursorDescription.options.tailable) {\n return self._observeChangesTailable(cursorDescription, ordered, callbacks);\n }\n\n // You may not filter out _id when observing changes, because the id is a core\n // part of the observeChanges API.\n if (cursorDescription.options.fields &&\n (cursorDescription.options.fields._id === 0 ||\n cursorDescription.options.fields._id === false)) {\n throw Error(\"You may not observe a cursor with {fields: {_id: 0}}\");\n }\n\n var observeKey = JSON.stringify(\n _.extend({ordered: ordered}, cursorDescription));\n\n var multiplexer, observeDriver;\n var firstHandle = false;\n\n // Find a matching ObserveMultiplexer, or create a new one. This next block is\n // guaranteed to not yield (and it doesn't call anything that can observe a\n // new query), so no other calls to this function can interleave with it.\n Meteor._noYieldsAllowed(function () {\n if (_.has(self._observeMultiplexers, observeKey)) {\n multiplexer = self._observeMultiplexers[observeKey];\n } else {\n firstHandle = true;\n // Create a new ObserveMultiplexer.\n multiplexer = new ObserveMultiplexer({\n ordered: ordered,\n onStop: function () {\n delete self._observeMultiplexers[observeKey];\n observeDriver.stop();\n }\n });\n self._observeMultiplexers[observeKey] = multiplexer;\n }\n });\n\n var observeHandle = new ObserveHandle(multiplexer, callbacks);\n\n if (firstHandle) {\n var matcher, sorter;\n var canUseOplog = _.all([\n function () {\n // At a bare minimum, using the oplog requires us to have an oplog, to\n // want unordered callbacks, and to not want a callback on the polls\n // that won't happen.\n return self._oplogHandle && !ordered &&\n !callbacks._testOnlyPollCallback;\n }, function () {\n // We need to be able to compile the selector. Fall back to polling for\n // some newfangled $selector that minimongo doesn't support yet.\n try {\n matcher = new Minimongo.Matcher(cursorDescription.selector);\n return true;\n } catch (e) {\n // XXX make all compilation errors MinimongoError or something\n // so that this doesn't ignore unrelated exceptions\n return false;\n }\n }, function () {\n // ... and the selector itself needs to support oplog.\n return OplogObserveDriver.cursorSupported(cursorDescription, matcher);\n }, function () {\n // And we need to be able to compile the sort, if any. eg, can't be\n // {$natural: 1}.\n if (!cursorDescription.options.sort)\n return true;\n try {\n sorter = new Minimongo.Sorter(cursorDescription.options.sort,\n { matcher: matcher });\n return true;\n } catch (e) {\n // XXX make all compilation errors MinimongoError or something\n // so that this doesn't ignore unrelated exceptions\n return false;\n }\n }], function (f) { return f(); }); // invoke each function\n\n var driverClass = canUseOplog ? OplogObserveDriver : PollingObserveDriver;\n observeDriver = new driverClass({\n cursorDescription: cursorDescription,\n mongoHandle: self,\n multiplexer: multiplexer,\n ordered: ordered,\n matcher: matcher, // ignored by polling\n sorter: sorter, // ignored by polling\n _testOnlyPollCallback: callbacks._testOnlyPollCallback\n });\n\n // This field is only set for use in tests.\n multiplexer._observeDriver = observeDriver;\n }\n\n // Blocks until the initial adds have been sent.\n multiplexer.addHandleAndSendInitialAdds(observeHandle);\n\n return observeHandle;\n};\n\n// Listen for the invalidation messages that will trigger us to poll the\n// database for changes. If this selector specifies specific IDs, specify them\n// here, so that updates to different specific IDs don't cause us to poll.\n// listenCallback is the same kind of (notification, complete) callback passed\n// to InvalidationCrossbar.listen.\n\nlistenAll = function (cursorDescription, listenCallback) {\n var listeners = [];\n forEachTrigger(cursorDescription, function (trigger) {\n listeners.push(DDPServer._InvalidationCrossbar.listen(\n trigger, listenCallback));\n });\n\n return {\n stop: function () {\n _.each(listeners, function (listener) {\n listener.stop();\n });\n }\n };\n};\n\nforEachTrigger = function (cursorDescription, triggerCallback) {\n var key = {collection: cursorDescription.collectionName};\n var specificIds = LocalCollection._idsMatchedBySelector(\n cursorDescription.selector);\n if (specificIds) {\n _.each(specificIds, function (id) {\n triggerCallback(_.extend({id: id}, key));\n });\n triggerCallback(_.extend({dropCollection: true, id: null}, key));\n } else {\n triggerCallback(key);\n }\n};\n\n// observeChanges for tailable cursors on capped collections.\n//\n// Some differences from normal cursors:\n// - Will never produce anything other than 'added' or 'addedBefore'. If you\n// do update a document that has already been produced, this will not notice\n// it.\n// - If you disconnect and reconnect from Mongo, it will essentially restart\n// the query, which will lead to duplicate results. This is pretty bad,\n// but if you include a field called 'ts' which is inserted as\n// new MongoInternals.MongoTimestamp(0, 0) (which is initialized to the\n// current Mongo-style timestamp), we'll be able to find the place to\n// restart properly. (This field is specifically understood by Mongo with an\n// optimization which allows it to find the right place to start without\n// an index on ts. It's how the oplog works.)\n// - No callbacks are triggered synchronously with the call (there's no\n// differentiation between \"initial data\" and \"later changes\"; everything\n// that matches the query gets sent asynchronously).\n// - De-duplication is not implemented.\n// - Does not yet interact with the write fence. Probably, this should work by\n// ignoring removes (which don't work on capped collections) and updates\n// (which don't affect tailable cursors), and just keeping track of the ID\n// of the inserted object, and closing the write fence once you get to that\n// ID (or timestamp?). This doesn't work well if the document doesn't match\n// the query, though. On the other hand, the write fence can close\n// immediately if it does not match the query. So if we trust minimongo\n// enough to accurately evaluate the query against the write fence, we\n// should be able to do this... Of course, minimongo doesn't even support\n// Mongo Timestamps yet.\nMongoConnection.prototype._observeChangesTailable = function (\n cursorDescription, ordered, callbacks) {\n var self = this;\n\n // Tailable cursors only ever call added/addedBefore callbacks, so it's an\n // error if you didn't provide them.\n if ((ordered && !callbacks.addedBefore) ||\n (!ordered && !callbacks.added)) {\n throw new Error(\"Can't observe an \" + (ordered ? \"ordered\" : \"unordered\")\n + \" tailable cursor without a \"\n + (ordered ? \"addedBefore\" : \"added\") + \" callback\");\n }\n\n return self.tail(cursorDescription, function (doc) {\n var id = doc._id;\n delete doc._id;\n // The ts is an implementation detail. Hide it.\n delete doc.ts;\n if (ordered) {\n callbacks.addedBefore(id, doc, null);\n } else {\n callbacks.added(id, doc);\n }\n });\n};\n\n// XXX We probably need to find a better way to expose this. Right now\n// it's only used by tests, but in fact you need it in normal\n// operation to interact with capped collections.\nMongoInternals.MongoTimestamp = MongoDB.Timestamp;\n\nMongoInternals.Connection = MongoConnection;\n", "file_path": "packages/mongo/mongo_driver.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00043854338582605124, 0.00017219330766238272, 0.00015823783178348094, 0.00016967541887424886, 2.432183282508049e-05]} {"hunk": {"id": 0, "code_window": ["\n", " // OK, wiped all packages, now let's go and check that everything is removed\n", " // except for the tool we are running right now and the latest tool. i.e. v1\n", " // and v3\n", " _.each(files.readdir(prefix), function (f) {\n", " if (f[0] === '.') return;\n", " if (process.platform === 'win32') {\n", " // this is a dir\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep"], "after_edit": [" var notHidden = function (f) { return f[0] !== '.'; };\n", " var meteorToolDirs = _.filter(files.readdir(prefix), notHidden);\n", " selftest.expectTrue(meteorToolDirs.length === 2);\n", " _.each(meteorToolDirs, function (f) {\n", " var fPath = files.pathJoin(prefix, f);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 114}, "file": "// Use path instead of files.js here because we are explicitly trying to\n// track requires, and files.js is often a culprit of slow requires.\nvar path = require('path');\n\n// seconds since epoch\nvar now = function () {\n return (+ new Date)/1000;\n};\n\nvar currentInvocation;\nvar RequireInvocation = function (name, filename) {\n var self = this;\n self.name = name; // module required\n self.filename = filename; // file doing the requiring, if known\n self.timeStarted = now();\n self.timeFinished = null;\n self.parent = currentInvocation;\n self.children = []; // array of RequireInvocation\n\n self.selfTime = null;\n self.totalTime = null;\n};\n\nRequireInvocation.prototype.isOurCode = function () {\n var self = this;\n\n if (! self.filename)\n return self.name === 'TOP';\n\n if (! self.name.match(/\\//))\n return false; // we always require our stuff via a path\n\n var ourSource = path.resolve(__dirname);\n var required = path.resolve(path.dirname(self.filename), self.name);\n if (ourSource.length > required.length)\n return false;\n return required.substr(0, ourSource.length) === ourSource;\n};\n\nRequireInvocation.prototype.why = function () {\n var self = this;\n var walk = self;\n var last = null;\n\n while (walk && ! walk.isOurCode()) {\n last = walk;\n walk = walk.parent;\n }\n\n if (! walk)\n return \"???\";\n if (last)\n return path.basename(walk.name) + \":\" + path.basename(last.name);\n return path.basename(walk.name);\n};\n\nexports.start = function () {\n var moduleModule = require('module');\n currentInvocation = new RequireInvocation('TOP');\n\n var realLoader = moduleModule._load;\n moduleModule._load = function (/* arguments */) {\n var inv = new RequireInvocation(arguments[0], arguments[1].filename);\n var parent = currentInvocation;\n currentInvocation.children.push(inv);\n currentInvocation = inv;\n\n try {\n return realLoader.apply(this, arguments);\n } finally {\n inv.timeFinished = now();\n currentInvocation = parent;\n }\n };\n};\n\nexports.printReport = function () {\n currentInvocation.timeFinished = now();\n var _ = require('underscore');\n\n var computeTimes = function (inv) {\n inv.totalTime = inv.timeFinished - inv.timeStarted;\n\n var childTime = 0;\n _.each(inv.children, function (child) {\n computeTimes(child);\n childTime += child.totalTime;\n });\n\n if (inv.totalTime !== null)\n inv.selfTime = inv.totalTime - childTime;\n };\n computeTimes(currentInvocation);\n\n var summary = {};\n var summarize = function (inv, depth) {\n var padding = (new Array(depth*2 + 1)).join(' ');\n // console.log(padding + inv.name + \" [\" + inv.selfTime + \"]\");\n if (! (inv.name in summary))\n summary[inv.name] = { name: inv.name, time: 0, ours: inv.isOurCode(),\n via: {} };\n summary[inv.name].time += inv.selfTime;\n if (! inv.isOurCode()) {\n summary[inv.name].via[inv.why()] = true;\n }\n\n _.each(inv.children, function (inv) {\n summarize(inv, depth + 1);\n });\n };\n summarize(currentInvocation, 0);\n\n var times = _.sortBy(_.values(summary), 'time').reverse();\n var ourTotal = 0, otherTotal = 0;\n _.each(times, function (item) {\n var line = (item.time * 1000).toFixed(2) + \" \" + item.name;\n if (! item.ours)\n line += \" [via \" + _.keys(item.via).join(\", \") + \"]\";\n console.log(line);\n if (item.ours)\n ourTotal += item.time;\n else\n otherTotal += item.time;\n });\n\n\n var grandTotal = currentInvocation.totalTime;\n if (grandTotal - ourTotal - otherTotal > 1/1000)\n throw new Error(\"Times don't add up\");\n console.log(\"TOTAL: ours \" + (ourTotal * 1000).toFixed(2) +\n \", other \" + (otherTotal * 1000).toFixed(2) +\n \", grand total \" + (grandTotal * 1000).toFixed(2));\n};\n", "file_path": "tools/profile-require.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.003543520113453269, 0.0004491960571613163, 0.00016626311116851866, 0.00017027606372721493, 0.0008689412497915328]} {"hunk": {"id": 0, "code_window": ["\n", " // OK, wiped all packages, now let's go and check that everything is removed\n", " // except for the tool we are running right now and the latest tool. i.e. v1\n", " // and v3\n", " _.each(files.readdir(prefix), function (f) {\n", " if (f[0] === '.') return;\n", " if (process.platform === 'win32') {\n", " // this is a dir\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep"], "after_edit": [" var notHidden = function (f) { return f[0] !== '.'; };\n", " var meteorToolDirs = _.filter(files.readdir(prefix), notHidden);\n", " selftest.expectTrue(meteorToolDirs.length === 2);\n", " _.each(meteorToolDirs, function (f) {\n", " var fPath = files.pathJoin(prefix, f);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 114}, "file": "var _ = require('underscore');\n\n// schema - Object, representing paths to correct. Ex.:\n// {\n// format: false,\n// arch: false,\n// load: [\n// {\n// node_modulus: true,\n// sourceMap: true,\n// sourceMapRoot: true,\n// path: true\n// }\n// ]\n// }\nvar convertBySchema = function (val, schema) {\n if (schema === true)\n return convert(val);\n else if (schema === false)\n return val;\n\n if (_.isArray(schema)) {\n if (schema.length !== 1) {\n throw new Error(\"Expected an array with one element in schema\");\n }\n\n if (! _.isArray(val)) {\n throw new Error(\"Expected an array in value, got \" + typeof val);\n }\n\n return _.map(val, function (subval) {\n return convertBySchema(subval, schema[0]);\n });\n }\n\n if (! _.isObject(schema))\n throw new Error(\"Unexpected type of schema: \" + typeof(schema));\n\n var ret = _.clone(val);\n _.each(schema, function (subschema, key) {\n if (_.has(ret, key))\n ret[key] = convertBySchema(val[key], subschema);\n });\n\n return ret;\n};\n\nvar convert = function (path) {\n return path.replace(/:/g, '_');\n};\n\nvar ISOPACK_SCHEME = {\n builds: [{\n path: true\n }],\n plugins: [{\n path: true\n }]\n};\n\nvar UNIBUILD_SCHEME = {\n node_modules: true,\n resources: [{\n file: true,\n sourceMap: true,\n servePath: true\n }]\n};\n\nvar JAVASCRIPT_IMAGE_SCHEME = {\n load: [{\n sourceMap: true,\n sourceMapRoot: true,\n path: true,\n node_modules: true\n }]\n};\n\nexports.convertIsopack = function (data) {\n return convertBySchema(data, ISOPACK_SCHEME);\n};\n\nexports.convertUnibuild = function (data) {\n return convertBySchema(data, UNIBUILD_SCHEME);\n};\n\nexports.convertJSImage = function (data) {\n return convertBySchema(data, JAVASCRIPT_IMAGE_SCHEME);\n};\n\nexports.convert = convert;\n\n", "file_path": "tools/colon-converter.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.005752760451287031, 0.0009051371598616242, 0.0001666602329351008, 0.00017122802091762424, 0.0016973038436844945]} {"hunk": {"id": 1, "code_window": [" if (process.platform === 'win32') {\n", " // this is a dir\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n", " } else {\n", " // this is a symlink to a dir and this dir exists\n"], "labels": ["keep", "keep", "replace", "keep", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isDirectory());\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 118}, "file": "var selftest = require('../selftest.js');\nvar Sandbox = selftest.Sandbox;\nvar files = require(\"../files.js\");\nvar utils = require(\"../utils.js\");\nvar archinfo = require(\"../archinfo.js\");\nvar _ = require('underscore');\n\nselftest.define(\"wipe all packages\", function () {\n var s = new Sandbox({\n warehouse: {\n v1: { tool: \"meteor-tool@33.0.1\" },\n v2: { tool: \"meteor-tool@33.0.2\" },\n v3: { tool: \"meteor-tool@33.0.3\" }\n }\n });\n var meteorToolVersion = function (v) {\n return {\n _id: 'VID' + v.replace(/\\./g, ''),\n packageName: 'meteor-tool',\n testName: null,\n version: v,\n publishedBy: null,\n description: 'The Meteor command-line tool',\n git: undefined,\n dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } },\n source: null,\n lastUpdated: null,\n published: null,\n isTest: false,\n debugOnly: false,\n containsPlugins: false\n };\n };\n\n // insert the new tool versions into the catalog\n s.warehouseOfficialCatalog.insertData({\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n });\n\n // help warehouse faking by copying the meteor-tool 3 times and introducing 3\n // fake versions (identical in code to the one we are running)\n var latestMeteorToolVersion =\n files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/');\n latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3];\n\n var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool');\n var copyTool = function (srcVersion, dstVersion) {\n if (process.platform === 'win32') {\n // just copy the files\n files.cp_r(\n files.pathJoin(prefix, srcVersion),\n files.pathJoin(prefix, dstVersion), {\n preserveSymlinks: true\n });\n } else {\n // figure out what the symlink links to and copy the folder *and* the\n // symlink\n var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion));\n var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion);\n\n // copy the hidden folder\n files.cp_r(\n files.pathJoin(prefix, srcFullVersion),\n files.pathJoin(prefix, dstFullVersion), {\n preserveSymlinks: true\n });\n\n // link to it\n files.symlink(\n dstFullVersion,\n files.pathJoin(prefix, dstVersion));\n }\n\n var replaceVersionInFile = function (filename) {\n var filePath = files.pathJoin(prefix, dstVersion, filename);\n files.writeFile(\n filePath,\n files.readFile(filePath, 'utf8')\n .replace(new RegExp(srcVersion, 'g'), dstVersion));\n };\n\n // \"fix\" the isopack.json and unibuild.json files (they contain the versions)\n replaceVersionInFile('isopack.json');\n replaceVersionInFile('unipackage.json');\n };\n\n copyTool(latestMeteorToolVersion, '33.0.3');\n copyTool(latestMeteorToolVersion, '33.0.2');\n copyTool(latestMeteorToolVersion, '33.0.1');\n\n // since the warehouse faking system is weak and under-developed, add more\n // faking, such as making the v3 the latest version\n files.linkToMeteorScript(\n files.pathJoin(s.warehouse, 'packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(s.warehouse, 'meteor'));\n\n\n var run;\n\n run = s.run('--release', 'v1', 'admin', 'wipe-all-packages');\n run.waitSecs(15);\n run.expectExit(0);\n\n // OK, wiped all packages, now let's go and check that everything is removed\n // except for the tool we are running right now and the latest tool. i.e. v1\n // and v3\n _.each(files.readdir(prefix), function (f) {\n if (f[0] === '.') return;\n if (process.platform === 'win32') {\n // this is a dir\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n } else {\n // this is a symlink to a dir and this dir exists\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n }\n });\n\n // Check that all other packages are wiped\n _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n if (p[0] === '.') return;\n if (p === 'meteor-tool') return;\n var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n selftest.expectTrue(contents.length === 0);\n });\n});\n\n", "file_path": "tools/tests/wipe-all-packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.9939395189285278, 0.07426263391971588, 0.0001675943931331858, 0.0006991945556364954, 0.25518348813056946]} {"hunk": {"id": 1, "code_window": [" if (process.platform === 'win32') {\n", " // this is a dir\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n", " } else {\n", " // this is a symlink to a dir and this dir exists\n"], "labels": ["keep", "keep", "replace", "keep", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isDirectory());\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 118}, "file": "@menu-width: 270px;\n@column: 5.55555%;\n\nbody {\n .position(absolute, 0, 0, 0, 0);\n background-color: #315481;\n .background-image( linear-gradient(top, #315481, #918e82 100%) );\n background-repeat: no-repeat;\n background-attachment: fixed;\n}\n\n#container {\n .position(absolute, 0, 0, 0, 0);\n\n @media screen and (min-width: 60em) {\n left: @column;\n right: @column;\n }\n\n @media screen and (min-width: 80em) {\n left: 2*@column;\n right: 2*@column;\n }\n\n // Hide anything offscreen\n overflow: hidden;\n}\n\n#menu {\n .position(absolute, 0, 0, 0, 0, @menu-width);\n}\n\n#content-container {\n .position(absolute, 0, 0, 0, 0);\n .transition(all 200ms ease-out);\n .transform(translate3d(0, 0, 0));\n background: @color-tertiary;\n opacity: 1;\n\n @media screen and (min-width: 40em) {\n left: @menu-width;\n }\n\n .content-scrollable {\n .position(absolute, 0, 0, 0, 0);\n .transform(translate3d(0, 0, 0));\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n }\n\n // Toggle menu on mobile\n .menu-open & {\n .transform(translate3d(@menu-width, 0, 0));\n opacity: .85;\n left: 0;\n\n @media screen and (min-width: 40em) {\n // Show menu on desktop, negate .menu-open\n .transform(translate3d(0, 0, 0)); //reset transform and use position properties instead\n opacity: 1;\n left: @menu-width;\n }\n }\n}\n\n// Transparent screen to prevent interactions on content when menu is open\n.content-overlay {\n .position(absolute, 0, 0, 0, 0);\n cursor: pointer;\n\n .menu-open & {\n .transform(translate3d(@menu-width, 0, 0));\n z-index: 1;\n }\n\n // Hide overlay on desktop\n @media screen and (min-width: 40em) { display: none; }\n}", "file_path": "examples/todos/client/stylesheets/globals/layout.import.less", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00017695136193651706, 0.00017469871090725064, 0.00017178876441903412, 0.0001747365458868444, 1.6827224271764862e-06]} {"hunk": {"id": 1, "code_window": [" if (process.platform === 'win32') {\n", " // this is a dir\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n", " } else {\n", " // this is a symlink to a dir and this dir exists\n"], "labels": ["keep", "keep", "replace", "keep", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isDirectory());\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 118}, "file": "// This implementation of Min/Max-Heap is just a subclass of Max-Heap\n// with a Min-Heap as an encapsulated property.\n//\n// Most of the operations are just proxy methods to call the same method on both\n// heaps.\n//\n// This implementation takes 2*N memory but is fairly simple to write and\n// understand. And the constant factor of a simple Heap is usually smaller\n// compared to other two-way priority queues like Min/Max Heaps\n// (http://www.cs.otago.ac.nz/staffpriv/mike/Papers/MinMaxHeaps/MinMaxHeaps.pdf)\n// and Interval Heaps\n// (http://www.cise.ufl.edu/~sahni/dsaac/enrich/c13/double.htm)\nMinMaxHeap = function (comparator, options) {\n var self = this;\n\n MaxHeap.call(self, comparator, options);\n self._minHeap = new MinHeap(comparator, options);\n};\n\nMeteor._inherits(MinMaxHeap, MaxHeap);\n\n_.extend(MinMaxHeap.prototype, {\n set: function (id, value) {\n var self = this;\n MaxHeap.prototype.set.apply(self, arguments);\n self._minHeap.set(id, value);\n },\n remove: function (id) {\n var self = this;\n MaxHeap.prototype.remove.apply(self, arguments);\n self._minHeap.remove(id);\n },\n clear: function () {\n var self = this;\n MaxHeap.prototype.clear.apply(self, arguments);\n self._minHeap.clear();\n },\n setDefault: function (id, def) {\n var self = this;\n MaxHeap.prototype.setDefault.apply(self, arguments);\n return self._minHeap.setDefault(id, def);\n },\n clone: function () {\n var self = this;\n var clone = new MinMaxHeap(self._comparator, self._heap);\n return clone;\n },\n minElementId: function () {\n var self = this;\n return self._minHeap.minElementId();\n }\n});\n\n", "file_path": "packages/binary-heap/min-max-heap.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00017705971549730748, 0.00017441390082240105, 0.00016774548566900194, 0.0001755667180987075, 3.0886178592481883e-06]} {"hunk": {"id": 1, "code_window": [" if (process.platform === 'win32') {\n", " // this is a dir\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n", " } else {\n", " // this is a symlink to a dir and this dir exists\n"], "labels": ["keep", "keep", "replace", "keep", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isDirectory());\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 118}, "file": ".build*\n", "file_path": "packages/preserve-inputs/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00017769854457583278, 0.00017769854457583278, 0.00017769854457583278, 0.00017769854457583278, 0.0]} {"hunk": {"id": 2, "code_window": [" } else {\n", " // this is a symlink to a dir and this dir exists\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n", " }\n"], "labels": ["keep", "keep", "replace", "replace", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(fPath))));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 121}, "file": "var selftest = require('../selftest.js');\nvar Sandbox = selftest.Sandbox;\nvar files = require(\"../files.js\");\nvar utils = require(\"../utils.js\");\nvar archinfo = require(\"../archinfo.js\");\nvar _ = require('underscore');\n\nselftest.define(\"wipe all packages\", function () {\n var s = new Sandbox({\n warehouse: {\n v1: { tool: \"meteor-tool@33.0.1\" },\n v2: { tool: \"meteor-tool@33.0.2\" },\n v3: { tool: \"meteor-tool@33.0.3\" }\n }\n });\n var meteorToolVersion = function (v) {\n return {\n _id: 'VID' + v.replace(/\\./g, ''),\n packageName: 'meteor-tool',\n testName: null,\n version: v,\n publishedBy: null,\n description: 'The Meteor command-line tool',\n git: undefined,\n dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } },\n source: null,\n lastUpdated: null,\n published: null,\n isTest: false,\n debugOnly: false,\n containsPlugins: false\n };\n };\n\n // insert the new tool versions into the catalog\n s.warehouseOfficialCatalog.insertData({\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n });\n\n // help warehouse faking by copying the meteor-tool 3 times and introducing 3\n // fake versions (identical in code to the one we are running)\n var latestMeteorToolVersion =\n files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/');\n latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3];\n\n var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool');\n var copyTool = function (srcVersion, dstVersion) {\n if (process.platform === 'win32') {\n // just copy the files\n files.cp_r(\n files.pathJoin(prefix, srcVersion),\n files.pathJoin(prefix, dstVersion), {\n preserveSymlinks: true\n });\n } else {\n // figure out what the symlink links to and copy the folder *and* the\n // symlink\n var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion));\n var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion);\n\n // copy the hidden folder\n files.cp_r(\n files.pathJoin(prefix, srcFullVersion),\n files.pathJoin(prefix, dstFullVersion), {\n preserveSymlinks: true\n });\n\n // link to it\n files.symlink(\n dstFullVersion,\n files.pathJoin(prefix, dstVersion));\n }\n\n var replaceVersionInFile = function (filename) {\n var filePath = files.pathJoin(prefix, dstVersion, filename);\n files.writeFile(\n filePath,\n files.readFile(filePath, 'utf8')\n .replace(new RegExp(srcVersion, 'g'), dstVersion));\n };\n\n // \"fix\" the isopack.json and unibuild.json files (they contain the versions)\n replaceVersionInFile('isopack.json');\n replaceVersionInFile('unipackage.json');\n };\n\n copyTool(latestMeteorToolVersion, '33.0.3');\n copyTool(latestMeteorToolVersion, '33.0.2');\n copyTool(latestMeteorToolVersion, '33.0.1');\n\n // since the warehouse faking system is weak and under-developed, add more\n // faking, such as making the v3 the latest version\n files.linkToMeteorScript(\n files.pathJoin(s.warehouse, 'packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(s.warehouse, 'meteor'));\n\n\n var run;\n\n run = s.run('--release', 'v1', 'admin', 'wipe-all-packages');\n run.waitSecs(15);\n run.expectExit(0);\n\n // OK, wiped all packages, now let's go and check that everything is removed\n // except for the tool we are running right now and the latest tool. i.e. v1\n // and v3\n _.each(files.readdir(prefix), function (f) {\n if (f[0] === '.') return;\n if (process.platform === 'win32') {\n // this is a dir\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n } else {\n // this is a symlink to a dir and this dir exists\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n }\n });\n\n // Check that all other packages are wiped\n _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n if (p[0] === '.') return;\n if (p === 'meteor-tool') return;\n var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n selftest.expectTrue(contents.length === 0);\n });\n});\n\n", "file_path": "tools/tests/wipe-all-packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.3262854218482971, 0.026332179084420204, 0.0001663590664975345, 0.0012636248720809817, 0.08333621919155121]} {"hunk": {"id": 2, "code_window": [" } else {\n", " // this is a symlink to a dir and this dir exists\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n", " }\n"], "labels": ["keep", "keep", "replace", "replace", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(fPath))));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 121}, "file": "# This file contains information which helps Meteor properly upgrade your\n# app when you run 'meteor update'. You should check it into version control\n# with your project.\n\nnotices-for-0.9.0\nnotices-for-0.9.1\n0.9.4-platform-file\nnotices-for-facebook-graph-api-2\n", "file_path": "examples/clock/.meteor/.finished-upgraders", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.0001656428212299943, 0.0001656428212299943, 0.0001656428212299943, 0.0001656428212299943, 0.0]} {"hunk": {"id": 2, "code_window": [" } else {\n", " // this is a symlink to a dir and this dir exists\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n", " }\n"], "labels": ["keep", "keep", "replace", "replace", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(fPath))));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 121}, "file": "# accounts-weibo\n\nA login service for Weibo. See the [project page](https://www.meteor.com/accounts) on Meteor Accounts for more details.", "file_path": "packages/accounts-weibo/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.0001660283305682242, 0.0001660283305682242, 0.0001660283305682242, 0.0001660283305682242, 0.0]} {"hunk": {"id": 2, "code_window": [" } else {\n", " // this is a symlink to a dir and this dir exists\n", " selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n", " }\n"], "labels": ["keep", "keep", "replace", "replace", "keep"], "after_edit": [" selftest.expectTrue(files.lstat(fPath).isSymbolicLink());\n", " selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(fPath))));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 121}, "file": "#pragma once\n//-------------------------------------------------------------------------------------------------\n// \n// Copyright (c) 2004, Outercurve Foundation.\n// This software is released under Microsoft Reciprocal License (MS-RL).\n// The license and further copyright text can be found in the file\n// LICENSE.TXT at the root directory of the distribution.\n// \n// \n// \n// Header for string dict helper functions.\n// \n//-------------------------------------------------------------------------------------------------\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define ReleaseDict(sdh) if (sdh) { DictDestroy(sdh); }\n#define ReleaseNullDict(sdh) if (sdh) { DictDestroy(sdh); sdh = NULL; }\n\ntypedef void* STRINGDICT_HANDLE;\ntypedef const void* C_STRINGDICT_HANDLE;\n\nextern const int STRINGDICT_HANDLE_BYTES;\n\nenum DICT_FLAG\n{\n DICT_FLAG_NONE = 0,\n DICT_FLAG_CASEINSENSITIVE = 1\n};\n\nHRESULT DAPI DictCreateWithEmbeddedKey(\n __out_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE* psdHandle,\n __in DWORD dwNumExpectedItems,\n __in_opt void **ppvArray,\n __in size_t cByteOffset,\n __in DICT_FLAG dfFlags\n );\nHRESULT DAPI DictCreateStringList(\n __out_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE* psdHandle,\n __in DWORD dwNumExpectedItems,\n __in DICT_FLAG dfFlags\n );\nHRESULT DAPI DictCreateStringListFromArray(\n __out_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE* psdHandle,\n __in_ecount(cStringArray) const LPCWSTR* rgwzStringArray,\n __in const DWORD cStringArray,\n __in DICT_FLAG dfFlags\n );\nHRESULT DAPI DictCompareStringListToArray(\n __in_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE sdStringList,\n __in_ecount(cStringArray) const LPCWSTR* rgwzStringArray,\n __in const DWORD cStringArray\n );\nHRESULT DAPI DictAddKey(\n __in_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE sdHandle,\n __in_z LPCWSTR szString\n );\nHRESULT DAPI DictAddValue(\n __in_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE sdHandle,\n __in void *pvValue\n );\nHRESULT DAPI DictKeyExists(\n __in_bcount(STRINGDICT_HANDLE_BYTES) C_STRINGDICT_HANDLE sdHandle,\n __in_z LPCWSTR szString\n );\nHRESULT DAPI DictGetValue(\n __in_bcount(STRINGDICT_HANDLE_BYTES) C_STRINGDICT_HANDLE sdHandle,\n __in_z LPCWSTR szString,\n __out void **ppvValue\n );\nvoid DAPI DictDestroy(\n __in_bcount(STRINGDICT_HANDLE_BYTES) STRINGDICT_HANDLE sdHandle\n );\n\n#ifdef __cplusplus\n}\n#endif\n", "file_path": "scripts/windows/installer/WiXSDK/inc/dictutil.h", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00017773665604181588, 0.00017268958617933095, 0.00016566365957260132, 0.00017313091666437685, 4.139316388318548e-06]} {"hunk": {"id": 3, "code_window": [" }\n", " });\n", "\n", " // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", " // check that the version is either the running one, or the latest one\n", " selftest.expectTrue(_.contains(['33.0.1', '33.0.3'], f));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "add", "edit_start_line_idx": 124}, "file": "var selftest = require('../selftest.js');\nvar Sandbox = selftest.Sandbox;\nvar files = require(\"../files.js\");\nvar utils = require(\"../utils.js\");\nvar archinfo = require(\"../archinfo.js\");\nvar _ = require('underscore');\n\nselftest.define(\"wipe all packages\", function () {\n var s = new Sandbox({\n warehouse: {\n v1: { tool: \"meteor-tool@33.0.1\" },\n v2: { tool: \"meteor-tool@33.0.2\" },\n v3: { tool: \"meteor-tool@33.0.3\" }\n }\n });\n var meteorToolVersion = function (v) {\n return {\n _id: 'VID' + v.replace(/\\./g, ''),\n packageName: 'meteor-tool',\n testName: null,\n version: v,\n publishedBy: null,\n description: 'The Meteor command-line tool',\n git: undefined,\n dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } },\n source: null,\n lastUpdated: null,\n published: null,\n isTest: false,\n debugOnly: false,\n containsPlugins: false\n };\n };\n\n // insert the new tool versions into the catalog\n s.warehouseOfficialCatalog.insertData({\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n });\n\n // help warehouse faking by copying the meteor-tool 3 times and introducing 3\n // fake versions (identical in code to the one we are running)\n var latestMeteorToolVersion =\n files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/');\n latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3];\n\n var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool');\n var copyTool = function (srcVersion, dstVersion) {\n if (process.platform === 'win32') {\n // just copy the files\n files.cp_r(\n files.pathJoin(prefix, srcVersion),\n files.pathJoin(prefix, dstVersion), {\n preserveSymlinks: true\n });\n } else {\n // figure out what the symlink links to and copy the folder *and* the\n // symlink\n var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion));\n var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion);\n\n // copy the hidden folder\n files.cp_r(\n files.pathJoin(prefix, srcFullVersion),\n files.pathJoin(prefix, dstFullVersion), {\n preserveSymlinks: true\n });\n\n // link to it\n files.symlink(\n dstFullVersion,\n files.pathJoin(prefix, dstVersion));\n }\n\n var replaceVersionInFile = function (filename) {\n var filePath = files.pathJoin(prefix, dstVersion, filename);\n files.writeFile(\n filePath,\n files.readFile(filePath, 'utf8')\n .replace(new RegExp(srcVersion, 'g'), dstVersion));\n };\n\n // \"fix\" the isopack.json and unibuild.json files (they contain the versions)\n replaceVersionInFile('isopack.json');\n replaceVersionInFile('unipackage.json');\n };\n\n copyTool(latestMeteorToolVersion, '33.0.3');\n copyTool(latestMeteorToolVersion, '33.0.2');\n copyTool(latestMeteorToolVersion, '33.0.1');\n\n // since the warehouse faking system is weak and under-developed, add more\n // faking, such as making the v3 the latest version\n files.linkToMeteorScript(\n files.pathJoin(s.warehouse, 'packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(s.warehouse, 'meteor'));\n\n\n var run;\n\n run = s.run('--release', 'v1', 'admin', 'wipe-all-packages');\n run.waitSecs(15);\n run.expectExit(0);\n\n // OK, wiped all packages, now let's go and check that everything is removed\n // except for the tool we are running right now and the latest tool. i.e. v1\n // and v3\n _.each(files.readdir(prefix), function (f) {\n if (f[0] === '.') return;\n if (process.platform === 'win32') {\n // this is a dir\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n } else {\n // this is a symlink to a dir and this dir exists\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n }\n });\n\n // Check that all other packages are wiped\n _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n if (p[0] === '.') return;\n if (p === 'meteor-tool') return;\n var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n selftest.expectTrue(contents.length === 0);\n });\n});\n\n", "file_path": "tools/tests/wipe-all-packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.9928211569786072, 0.1451805830001831, 0.0001677058171480894, 0.0011345215607434511, 0.3444081246852875]} {"hunk": {"id": 3, "code_window": [" }\n", " });\n", "\n", " // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", " // check that the version is either the running one, or the latest one\n", " selftest.expectTrue(_.contains(['33.0.1', '33.0.3'], f));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "add", "edit_start_line_idx": 124}, "file": "// quick jquery extension to bind text inputs to blur and RET.\n$.fn.onBlurOrEnter = function (callback) {\n this.bind('blur', callback);\n this.bind('keypress', function (evt) {\n if (evt.keyCode === 13 && $(this).val())\n callback.call(this, evt);\n });\n};\n\n// everything else happens after DOM is ready\n$(function () {\n $('body').layout({north__minSize: 50,\n spacing_open: 10,\n north__fxSettings: { direction: \"vertical\" }});\n\n // cache the template function for a single item.\n var item_template = _.template($('#item-template').html());\n\n // this render function could be replaced with a handlebars\n // template. underscore template isn't safe for user-entered data\n // like the item text (XSS).\n function renderItem (obj) {\n // generate template for todo\n var elt = $(item_template(obj));\n\n // set text through jquery for XSS protection\n elt.find('.todo-text').text(obj.text);\n\n // clicking the checkbox toggles done state\n elt.find('.check').click(function () {\n Todos.update(obj._id, {$set: {done: !obj.done}});\n });\n\n // clicking destroy button removes the item\n elt.find('.destroy').click(function () {\n Todos.remove(obj._id);\n });\n\n // wire up tag destruction links\n elt.find('.tag .remove').click(function () {\n var tag = $(this).attr('name');\n $(this).parent().fadeOut(500, function () {\n Todos.update(obj._id, {$pull: {tags: tag}});\n });\n });\n\n // wire up add tag\n elt.find('.addtag').click(function () {\n $(this).hide();\n elt.find('.edittag').show();\n elt.find('.edittag input').focus();\n });\n\n // wire up edit tag\n elt.find('.edittag input').onBlurOrEnter(function () {\n elt.find('.edittag').hide();\n elt.find('.addtag').show();\n if ($(this).val() !== '')\n Todos.update(obj._id, {$addToSet: {tags: $(this).val()}});\n });\n\n // doubleclick on todo text brings up the editor\n elt.find('.todo-text').dblclick(function () {\n elt.addClass('editing');\n\n var input = elt.find('.todo-input');\n input.val(obj.text);\n input.focus();\n input.select();\n\n input.onBlurOrEnter(function () {\n elt.removeClass('editing');\n if ($(this).val() !== '')\n Todos.update(obj._id, {$set: {text: elt.find('.todo-input').val()}});\n });\n });\n\n return elt[0];\n };\n\n // construct new todo from text box\n $('#new-todo').bind('keypress', function (evt) {\n var list_id = Session.get('list_id');\n var tag = Session.get('tag_filter');\n\n // prevent creation of a new todo if nothing is selected\n if (!list_id) return;\n\n var text = $('#new-todo').val();\n\n if (evt.keyCode === 13 && text) {\n var obj = {text: text,\n list_id: list_id,\n done: false,\n timestamp: (new Date()).getTime()};\n if (tag) obj.tags = [tag];\n\n Todos.insert(obj);\n $('#new-todo').val('');\n }\n });\n\n var current_list_stop;\n function setCurrentList (list_id) {\n Session.set('list_id', list_id);\n\n $('#items-view').show();\n\n // kill current findLive render\n if (current_list_stop)\n current_list_stop.stop();\n\n var query = {list_id: list_id};\n if (Session.get('tag_filter'))\n query.tags = Session.get('tag_filter')\n\n // render individual todo list, stash kill function\n current_list_stop =\n Meteor.ui.renderList(Todos, $('#item-list'), {\n selector: query,\n sort: {timestamp: 1},\n render: renderItem,\n events: {}\n });\n };\n\n // render list of lists in the left sidebar.\n Meteor.ui.renderList(Lists, $('#lists'), {\n sort: {name: 1},\n template: $('#list-template'),\n events: {\n 'click': function (evt) {\n window.History.pushState({list_id: this._id},\n \"Todos: \" + this.name,\n \"/\" + this._id);\n },\n 'dblclick': function (evt) {\n var list_elt = $(evt.currentTarget);\n var input = list_elt.find('.list-name-input');\n\n list_elt.addClass('editing');\n\n input.val(this.name);\n input.focus();\n input.select();\n\n var _id = this._id;\n input.onBlurOrEnter(function () {\n list_elt.removeClass('editing');\n if (input.val() !== '')\n Lists.update(_id, {$set: {name: input.val()}});\n });\n }\n }\n });\n\n // construct new todo list from text box\n $('#new-list').bind('keypress', function (evt) {\n var text = $('#new-list').val();\n\n if (evt.keyCode === 13 && text) {\n var list = Lists.insert({name: text});\n $('#new-list').val('');\n window.History.pushState({list_id: list._id},\n \"Todos: \" + list.name,\n \"/\" + list._id);\n }\n });\n\n // tags and filters\n\n // the tag filter bar is easy to generate using a simple\n // renderList() against a minimongo query. since minimongo doesn't\n // support aggregate queries, construct a local collection to serve\n // the same purpose, and drive the renderList() off of it.\n\n var LocalTags = new Mongo.Collection;\n (function () {\n function updateLocalTags() {\n var real = _(Todos.find()).chain().pluck('tags').compact().flatten().uniq().value();\n real.unshift(null); // XXX fake tag\n\n var computed = _(LocalTags.find()).pluck('tag');\n\n _.each(_.difference(real, computed), function (new_tag) {\n LocalTags.insert({tag: new_tag});\n });\n\n _.each(_.difference(computed, real), function (dead_tag) {\n LocalTags.remove({tag: dead_tag});\n });\n };\n\n Todos.findLive({}, {\n added: function (obj, before_idx) { _.defer(updateLocalTags); },\n removed: function (id, at_idx) { _.defer(updateLocalTags); },\n changed: function (obj, at_idx) { _.defer(updateLocalTags); },\n });\n })();\n\n // findLive() against the computed tag table. since we also want a\n // show-all button, arrange for the computed table to always include\n // a null placeholder tag, and for the template to render that as\n // \"Show all\". always begin the user session with a null filter.\n\n Session.set('tag_filter', null);\n\n Meteor.ui.renderList(LocalTags, $('#tag-filter'), {\n sort: {tag: 1},\n template: $('#tag-filter-template'),\n events: {\n 'click': function (evt) {\n if (Session.equals('tag_filter', this.tag))\n Session.set('tag_filter', null);\n else\n Session.set('tag_filter', this.tag);\n\n setCurrentList(Session.get('list_id'));\n }\n }\n });\n\n // load list on statechange (which we drive from several places).\n window.History.Adapter.bind(window, 'statechange', function () {\n var state = window.History.getState();\n var list = Lists.find(state.data.list_id);\n setCurrentList(list._id);\n });\n\n // subscribe to all available todo lists. once the inital load\n // completes, navigate to the list specified by URL, if any.\n Meteor.subscribe('lists', function () {\n var initial_list_id = window.location.pathname.split('/')[1];\n var list;\n\n if (initial_list_id) {\n list = Lists.find(initial_list_id);\n } else {\n var lists = Lists.find({}, {sort: {name: 1}, limit: 1});\n list = lists[0];\n }\n\n if (list) {\n window.History.replaceState({list_id: list._id},\n \"Todos: \" + list.name,\n \"/\" + list._id);\n // replaceState doesn't always trigger statechange on reload. if\n // you last reloaded the same page and the state is the same, it\n // won't fire. so call this here. double calling is not great, but\n // OK.\n setCurrentList(list._id);\n }\n });\n\n // subscribe to all the items in each list. no need for a callback\n // here: todo items are never queried using collection.find().\n Meteor.subscribe('todos');\n});\n", "file_path": "examples/unfinished/todos-underscore/client/client.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00017446062702219933, 0.0001701934525044635, 0.0001642957067815587, 0.00017030283925123513, 2.700097411434399e-06]} {"hunk": {"id": 3, "code_window": [" }\n", " });\n", "\n", " // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", " // check that the version is either the running one, or the latest one\n", " selftest.expectTrue(_.contains(['33.0.1', '33.0.3'], f));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "add", "edit_start_line_idx": 124}, "file": "", "file_path": "docs/client/full-api/packages/webapp.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00016960629727691412, 0.0001653441577218473, 0.0001615835353732109, 0.00016423821216449142, 3.275692279203213e-06]} {"hunk": {"id": 3, "code_window": [" }\n", " });\n", "\n", " // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", " // check that the version is either the running one, or the latest one\n", " selftest.expectTrue(_.contains(['33.0.1', '33.0.3'], f));\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "add", "edit_start_line_idx": 124}, "file": "", "file_path": "examples/localmarket/client/templates/overlay.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00017411580483894795, 0.00017411580483894795, 0.00017411580483894795, 0.00017411580483894795, 0.0]} {"hunk": {"id": 4, "code_window": [" // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n", " if (p[0] === '.') return;\n", " if (p === 'meteor-tool') return;\n", " var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n", " contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n", " selftest.expectTrue(contents.length === 0);\n", " });\n", "});\n", ""], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" contents = _.filter(contents, notHidden);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 131}, "file": "var selftest = require('../selftest.js');\nvar Sandbox = selftest.Sandbox;\nvar files = require(\"../files.js\");\nvar utils = require(\"../utils.js\");\nvar archinfo = require(\"../archinfo.js\");\nvar _ = require('underscore');\n\nselftest.define(\"wipe all packages\", function () {\n var s = new Sandbox({\n warehouse: {\n v1: { tool: \"meteor-tool@33.0.1\" },\n v2: { tool: \"meteor-tool@33.0.2\" },\n v3: { tool: \"meteor-tool@33.0.3\" }\n }\n });\n var meteorToolVersion = function (v) {\n return {\n _id: 'VID' + v.replace(/\\./g, ''),\n packageName: 'meteor-tool',\n testName: null,\n version: v,\n publishedBy: null,\n description: 'The Meteor command-line tool',\n git: undefined,\n dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } },\n source: null,\n lastUpdated: null,\n published: null,\n isTest: false,\n debugOnly: false,\n containsPlugins: false\n };\n };\n\n // insert the new tool versions into the catalog\n s.warehouseOfficialCatalog.insertData({\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n });\n\n // help warehouse faking by copying the meteor-tool 3 times and introducing 3\n // fake versions (identical in code to the one we are running)\n var latestMeteorToolVersion =\n files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/');\n latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3];\n\n var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool');\n var copyTool = function (srcVersion, dstVersion) {\n if (process.platform === 'win32') {\n // just copy the files\n files.cp_r(\n files.pathJoin(prefix, srcVersion),\n files.pathJoin(prefix, dstVersion), {\n preserveSymlinks: true\n });\n } else {\n // figure out what the symlink links to and copy the folder *and* the\n // symlink\n var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion));\n var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion);\n\n // copy the hidden folder\n files.cp_r(\n files.pathJoin(prefix, srcFullVersion),\n files.pathJoin(prefix, dstFullVersion), {\n preserveSymlinks: true\n });\n\n // link to it\n files.symlink(\n dstFullVersion,\n files.pathJoin(prefix, dstVersion));\n }\n\n var replaceVersionInFile = function (filename) {\n var filePath = files.pathJoin(prefix, dstVersion, filename);\n files.writeFile(\n filePath,\n files.readFile(filePath, 'utf8')\n .replace(new RegExp(srcVersion, 'g'), dstVersion));\n };\n\n // \"fix\" the isopack.json and unibuild.json files (they contain the versions)\n replaceVersionInFile('isopack.json');\n replaceVersionInFile('unipackage.json');\n };\n\n copyTool(latestMeteorToolVersion, '33.0.3');\n copyTool(latestMeteorToolVersion, '33.0.2');\n copyTool(latestMeteorToolVersion, '33.0.1');\n\n // since the warehouse faking system is weak and under-developed, add more\n // faking, such as making the v3 the latest version\n files.linkToMeteorScript(\n files.pathJoin(s.warehouse, 'packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(s.warehouse, 'meteor'));\n\n\n var run;\n\n run = s.run('--release', 'v1', 'admin', 'wipe-all-packages');\n run.waitSecs(15);\n run.expectExit(0);\n\n // OK, wiped all packages, now let's go and check that everything is removed\n // except for the tool we are running right now and the latest tool. i.e. v1\n // and v3\n _.each(files.readdir(prefix), function (f) {\n if (f[0] === '.') return;\n if (process.platform === 'win32') {\n // this is a dir\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n } else {\n // this is a symlink to a dir and this dir exists\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n }\n });\n\n // Check that all other packages are wiped\n _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n if (p[0] === '.') return;\n if (p === 'meteor-tool') return;\n var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n selftest.expectTrue(contents.length === 0);\n });\n});\n\n", "file_path": "tools/tests/wipe-all-packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.9983273148536682, 0.14442963898181915, 0.00016679504187777638, 0.0010921244975179434, 0.348265141248703]} {"hunk": {"id": 4, "code_window": [" // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n", " if (p[0] === '.') return;\n", " if (p === 'meteor-tool') return;\n", " var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n", " contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n", " selftest.expectTrue(contents.length === 0);\n", " });\n", "});\n", ""], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" contents = _.filter(contents, notHidden);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 131}, "file": "local\n", "file_path": "tools/tests/old/app-with-private/.meteor/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00016961651272140443, 0.00016961651272140443, 0.00016961651272140443, 0.00016961651272140443, 0.0]} {"hunk": {"id": 4, "code_window": [" // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n", " if (p[0] === '.') return;\n", " if (p === 'meteor-tool') return;\n", " var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n", " contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n", " selftest.expectTrue(contents.length === 0);\n", " });\n", "});\n", ""], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" contents = _.filter(contents, notHidden);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 131}, "file": "# Meteor packages used by this project, one per line.\n#\n# 'meteor add' and 'meteor remove' will edit this file for you,\n# but you can also edit it by hand.\n\nstandard-app-packages\njquery\nunderscore\nshowdown\nspiderable\nappcache\nreload-safetybelt\nsimple:markdown-templating\nsimple:highlight.js\nless\n", "file_path": "docs/.meteor/packages", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00024026025494094938, 0.00020350213162600994, 0.0001667440083110705, 0.00020350213162600994, 3.675812331493944e-05]} {"hunk": {"id": 4, "code_window": [" // Check that all other packages are wiped\n", " _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n", " if (p[0] === '.') return;\n", " if (p === 'meteor-tool') return;\n", " var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n", " contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n", " selftest.expectTrue(contents.length === 0);\n", " });\n", "});\n", ""], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" contents = _.filter(contents, notHidden);\n"], "file_path": "tools/tests/wipe-all-packages.js", "type": "replace", "edit_start_line_idx": 131}, "file": "local\n", "file_path": "tools/tests/apps/standard-app/.meteor/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00016961651272140443, 0.00016961651272140443, 0.00016961651272140443, 0.00016961651272140443, 0.0]} {"hunk": {"id": 5, "code_window": [" var self = this;\n", "\n", " if (self.platform === \"win32\") {\n", " // XXX wipeAllPackages won't work on Windows until we fix that function\n", " isopack.saveToPath(self.packagePath(packageName, isopack.version));\n", " } else {\n", " // Note: wipeAllPackages depends on this filename structure\n", " // On Mac and Linux, we used to use a filename structure that used the\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "tools/tropohouse.js", "type": "replace", "edit_start_line_idx": 327}, "file": "var selftest = require('../selftest.js');\nvar Sandbox = selftest.Sandbox;\nvar files = require(\"../files.js\");\nvar utils = require(\"../utils.js\");\nvar archinfo = require(\"../archinfo.js\");\nvar _ = require('underscore');\n\nselftest.define(\"wipe all packages\", function () {\n var s = new Sandbox({\n warehouse: {\n v1: { tool: \"meteor-tool@33.0.1\" },\n v2: { tool: \"meteor-tool@33.0.2\" },\n v3: { tool: \"meteor-tool@33.0.3\" }\n }\n });\n var meteorToolVersion = function (v) {\n return {\n _id: 'VID' + v.replace(/\\./g, ''),\n packageName: 'meteor-tool',\n testName: null,\n version: v,\n publishedBy: null,\n description: 'The Meteor command-line tool',\n git: undefined,\n dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } },\n source: null,\n lastUpdated: null,\n published: null,\n isTest: false,\n debugOnly: false,\n containsPlugins: false\n };\n };\n\n // insert the new tool versions into the catalog\n s.warehouseOfficialCatalog.insertData({\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n });\n\n // help warehouse faking by copying the meteor-tool 3 times and introducing 3\n // fake versions (identical in code to the one we are running)\n var latestMeteorToolVersion =\n files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/');\n latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3];\n\n var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool');\n var copyTool = function (srcVersion, dstVersion) {\n if (process.platform === 'win32') {\n // just copy the files\n files.cp_r(\n files.pathJoin(prefix, srcVersion),\n files.pathJoin(prefix, dstVersion), {\n preserveSymlinks: true\n });\n } else {\n // figure out what the symlink links to and copy the folder *and* the\n // symlink\n var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion));\n var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion);\n\n // copy the hidden folder\n files.cp_r(\n files.pathJoin(prefix, srcFullVersion),\n files.pathJoin(prefix, dstFullVersion), {\n preserveSymlinks: true\n });\n\n // link to it\n files.symlink(\n dstFullVersion,\n files.pathJoin(prefix, dstVersion));\n }\n\n var replaceVersionInFile = function (filename) {\n var filePath = files.pathJoin(prefix, dstVersion, filename);\n files.writeFile(\n filePath,\n files.readFile(filePath, 'utf8')\n .replace(new RegExp(srcVersion, 'g'), dstVersion));\n };\n\n // \"fix\" the isopack.json and unibuild.json files (they contain the versions)\n replaceVersionInFile('isopack.json');\n replaceVersionInFile('unipackage.json');\n };\n\n copyTool(latestMeteorToolVersion, '33.0.3');\n copyTool(latestMeteorToolVersion, '33.0.2');\n copyTool(latestMeteorToolVersion, '33.0.1');\n\n // since the warehouse faking system is weak and under-developed, add more\n // faking, such as making the v3 the latest version\n files.linkToMeteorScript(\n files.pathJoin(s.warehouse, 'packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(s.warehouse, 'meteor'));\n\n\n var run;\n\n run = s.run('--release', 'v1', 'admin', 'wipe-all-packages');\n run.waitSecs(15);\n run.expectExit(0);\n\n // OK, wiped all packages, now let's go and check that everything is removed\n // except for the tool we are running right now and the latest tool. i.e. v1\n // and v3\n _.each(files.readdir(prefix), function (f) {\n if (f[0] === '.') return;\n if (process.platform === 'win32') {\n // this is a dir\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isDirectory());\n } else {\n // this is a symlink to a dir and this dir exists\n selftest.expectTrue(files.lstat(files.pathJoin(prefix, f)).isSymbolicLink());\n selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(files.pathJoin(prefix, f)))));\n }\n });\n\n // Check that all other packages are wiped\n _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {\n if (p[0] === '.') return;\n if (p === 'meteor-tool') return;\n var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));\n contents = _.filter(contents, function (f) { return f[0] !== '.'; });\n selftest.expectTrue(contents.length === 0);\n });\n});\n\n", "file_path": "tools/tests/wipe-all-packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.0004402086779009551, 0.00020332720305304974, 0.00016621364920865744, 0.00017021014355123043, 8.212235843529925e-05]} {"hunk": {"id": 5, "code_window": [" var self = this;\n", "\n", " if (self.platform === \"win32\") {\n", " // XXX wipeAllPackages won't work on Windows until we fix that function\n", " isopack.saveToPath(self.packagePath(packageName, isopack.version));\n", " } else {\n", " // Note: wipeAllPackages depends on this filename structure\n", " // On Mac and Linux, we used to use a filename structure that used the\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "tools/tropohouse.js", "type": "replace", "edit_start_line_idx": 327}, "file": "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Consolas;}{\\f1\\fnil Consolas;}{\\f2\\fnil\\fcharset0 Calibri;}}\n{\\*\\generator Msftedit 5.41.21.2509;}\\viewkind4\\uc1\\pard\\sa200\\sl276\\slmult1\\b\\f0\\fs40 [Put Your License Agreement Here]\\lang9\\b0\\f1\\fs19\\par\n\\lang1033\\f0 L\\lang9\\f1 orem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultricies ultricies arcu id commodo. Ut dignissim ante nec urna elementum imperdiet. Praesent pretium condimentum orci sit amet laoreet. Fusce condimentum tempor leo, vitae tempor quam interdum et. Nulla ante dui, tincidunt sed porta nec, pulvinar in felis. Pellentesque pellentesque ornare nibh id accumsan. In eu arcu nibh. Aenean ut vulputate nisl. Proin at nibh lacinia urna elementum commodo. Donec semper lorem quis neque fringilla quis facilisis dolor dignissim. Suspendisse a massa in odio viverra vehicula. Curabitur id lectus purus, non bibendum arcu. Cras dictum, turpis eget gravida condimentum, turpis ante varius leo, molestie pulvinar mauris libero ut leo. Morbi libero diam, sollicitudin id interdum sit amet, rhoncus eget turpis.\\par\nVestibulum arcu dui, suscipit vitae suscipit laoreet, posuere eget risus. Sed vitae massa in justo vehicula elementum sed at arcu. Pellentesque arcu ante, accumsan sed lacinia sed, lacinia vel urna. Vivamus at ligula nulla, lobortis ultricies tortor. Vivamus suscipit dolor non velit adipiscing venenatis. Nullam adipiscing accumsan condimentum. Nullam ut lorem neque, et iaculis felis. Donec sed massa diam, et feugiat velit. Pellentesque facilisis mi a odio ultrices facilisis. Nam porta, lorem feugiat aliquet placerat, ipsum risus accumsan sem, euismod bibendum velit dolor sed turpis. Suspendisse tincidunt, lectus congue rhoncus sollicitudin, magna erat porttitor ante, eget sodales ante sem eu augue. Aenean risus risus, mattis vitae pretium at, venenatis dictum est. Vestibulum consectetur euismod magna vel sodales.\\par\nQuisque eu urna lacus. Nunc eget dictum odio. Pellentesque vel dolor leo. Praesent aliquet, erat vel fringilla lobortis, ante nibh dapibus augue, sed semper ligula odio vitae nulla. Nullam dictum gravida lectus nec lacinia. Vivamus fermentum ultricies lobortis. In quis magna massa, ut commodo lectus. Donec nunc velit, gravida id euismod luctus, luctus sed ante. Nunc elementum mollis sapien, ac interdum quam fringilla eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam dui enim, tempus vel aliquam sed, pretium sed nisi. Fusce vitae magna nec nibh aliquam suscipit vel a felis. Etiam gravida, lorem id laoreet gravida, nisl leo hendrerit dolor, quis porta mauris enim vitae justo. Maecenas congue, felis at rhoncus vestibulum, nisl urna pellentesque urna, id iaculis augue metus eget neque. Curabitur pretium risus nec tortor vulputate et rhoncus ipsum gravida.\\par\nMaecenas elementum volutpat arcu, nec ultricies velit faucibus facilisis. Etiam sem lacus, mattis eget gravida ut, rhoncus porta lorem. Vivamus volutpat dui sit amet risus mollis venenatis. Quisque velit velit, condimentum id pharetra sed, varius vitae lectus. Praesent nisi turpis, porttitor nec accumsan a, aliquam sit amet augue. Quisque facilisis enim sed enim pretium tristique. Aliquam commodo varius mi, ut iaculis nunc tempus non. Vivamus velit nunc, dictum a dignissim vitae, commodo id metus. Integer volutpat, neque at ultrices dignissim, felis nulla commodo orci, at auctor nisl quam nec sem. Pellentesque interdum pellentesque nulla, ac fermentum tortor porttitor a. Etiam condimentum aliquet sapien vel adipiscing. Quisque est velit, vulputate a iaculis ut, tempus in nibh. Cras consectetur quam nibh, vel lobortis justo. Aenean a elit leo. Aenean mollis dolor a odio accumsan mollis. Proin blandit neque erat. Integer lectus urna, volutpat quis vulputate et, fermentum et ante. Maecenas vitae ultricies dui.\\par\nMauris accumsan varius luctus. In hac habitasse platea dictumst. Mauris malesuada tempus nibh, porta accumsan tortor tincidunt eu. Proin orci mauris, commodo id malesuada nec, adipiscing ut sapien. Phasellus at dui vel nisi adipiscing auctor quis vel sem. Phasellus fermentum, enim id sodales ullamcorper, magna sapien facilisis urna, ac lobortis nunc augue ut ligula. Quisque vulputate nibh sed velit pharetra dictum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque mi metus, vestibulum vitae dapibus vel, ultrices at tellus. Vivamus iaculis dui a nisl faucibus eget congue velit gravida. Donec vel quam ligula. Nam magna ante, vulputate id pharetra ac, dapibus commodo velit. Cras nisl nulla, congue sit amet laoreet eget, cursus et lorem. Mauris diam tortor, porttitor vitae fringilla id, iaculis sit amet eros. Donec sed enim eget felis fermentum posuere. Pellentesque sodales feugiat dolor, vel molestie est adipiscing non. Morbi tincidunt viverra felis ut hendrerit.\\f2\\fs22\\par\n}\n\u0000", "file_path": "scripts/windows/installer/WiXInstaller/Resources/License.rtf", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.0001654944207984954, 0.0001654944207984954, 0.0001654944207984954, 0.0001654944207984954, 0.0]} {"hunk": {"id": 5, "code_window": [" var self = this;\n", "\n", " if (self.platform === \"win32\") {\n", " // XXX wipeAllPackages won't work on Windows until we fix that function\n", " isopack.saveToPath(self.packagePath(packageName, isopack.version));\n", " } else {\n", " // Note: wipeAllPackages depends on this filename structure\n", " // On Mac and Linux, we used to use a filename structure that used the\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "tools/tropohouse.js", "type": "replace", "edit_start_line_idx": 327}, "file": ".build*\n", "file_path": "packages/html-tools/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.0001732491800794378, 0.0001732491800794378, 0.0001732491800794378, 0.0001732491800794378, 0.0]} {"hunk": {"id": 5, "code_window": [" var self = this;\n", "\n", " if (self.platform === \"win32\") {\n", " // XXX wipeAllPackages won't work on Windows until we fix that function\n", " isopack.saveToPath(self.packagePath(packageName, isopack.version));\n", " } else {\n", " // Note: wipeAllPackages depends on this filename structure\n", " // On Mac and Linux, we used to use a filename structure that used the\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "tools/tropohouse.js", "type": "replace", "edit_start_line_idx": 327}, "file": "32t5gt1m39x2tmc1zkd", "file_path": "tools/tests/apps/package-tests/.meteor/identifier", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d9cc95531ba9495cb9b18f53569a5175d64523e4", "dependency_score": [0.00016583262186031789, 0.00016583262186031789, 0.00016583262186031789, 0.00016583262186031789, 0.0]} {"hunk": {"id": 0, "code_window": ["// Display no toolbar\n", "const char kNoToolbar[] = \"no-toolbar\";\n", "\n", "// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n"], "file_path": "src/common/shell_switches.cc", "type": "add", "edit_start_line_idx": 45}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_browser_client.h\"\n\n#include \"base/command_line.h\"\n#include \"base/file_path.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/browser/browser_url_handler.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_resource_dispatcher_host_delegate.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/nw/src/shell.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"geolocation/shell_access_token_store.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n\n#if defined(OS_ANDROID)\n#include \"base/android/path_utils.h\"\n#include \"base/path_service.h\"\n#include \"base/platform_file.h\"\n#include \"content/shell/android/shell_descriptors.h\"\n#endif\n\nnamespace content {\n\nShellContentBrowserClient::ShellContentBrowserClient()\n : shell_browser_main_parts_(NULL) {\n}\n\nShellContentBrowserClient::~ShellContentBrowserClient() {\n}\n\nBrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);\n return shell_browser_main_parts_;\n}\n\nvoid ShellContentBrowserClient::RenderViewHostCreated(\n RenderViewHost* render_view_host) {\n}\n\nvoid ShellContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line, int child_process_id) {\n // Disable web security\n command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n command_line->AppendSwitch(switches::kDisableWebSecurity);\n\n if (nw::GetManifest() && nw::GetUseNode())\n command_line->AppendSwitch(switches::kmNodejs);\n}\n\nstd::string ShellContentBrowserClient::GetApplicationLocale() {\n return l10n_util::GetApplicationLocale(\"en-US\");\n}\n\nvoid ShellContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new ShellResourceDispatcherHostDelegate());\n ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nstd::string ShellContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n\nMediaObserver* ShellContentBrowserClient::GetMediaObserver() {\n return MediaInternals::GetInstance();\n}\n\nvoid ShellContentBrowserClient::BrowserURLHandlerCreated(\n BrowserURLHandler* handler) {\n}\n\n#if defined(OS_ANDROID)\nvoid ShellContentBrowserClient::GetAdditionalMappedFilesForChildProcess(\n const CommandLine& command_line,\n base::GlobalDescriptors::Mapping* mappings) {\n int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;\n FilePath pak_file;\n DCHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_file));\n pak_file = pak_file.Append(FILE_PATH_LITERAL(\"paks\"));\n pak_file = pak_file.Append(FILE_PATH_LITERAL(\"nw.pak\"));\n\n base::PlatformFile f =\n base::CreatePlatformFile(pak_file, flags, NULL, NULL);\n if (f == base::kInvalidPlatformFileValue) {\n NOTREACHED() << \"Failed to open file when creating renderer process: \"\n << \"nw.pak\";\n }\n mappings->push_back(std::pair(\n kShellPakDescriptor, f));\n}\n#endif\n\nShellBrowserContext* ShellContentBrowserClient::browser_context() {\n return shell_browser_main_parts_->browser_context();\n}\n\nShellBrowserContext*\n ShellContentBrowserClient::off_the_record_browser_context() {\n return shell_browser_main_parts_->off_the_record_browser_context();\n}\n\nAccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {\n return new ShellAccessTokenStore(browser_context()->GetRequestContext());\n}\n\n} // namespace content\n", "file_path": "src/shell_content_browser_client.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017610924260225147, 0.00017017223581206053, 0.00016562749806325883, 0.00016891604172997177, 3.3102553516073385e-06]} {"hunk": {"id": 0, "code_window": ["// Display no toolbar\n", "const char kNoToolbar[] = \"no-toolbar\";\n", "\n", "// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n"], "file_path": "src/common/shell_switches.cc", "type": "add", "edit_start_line_idx": 45}, "file": "// Copyright (c) 2012 Roger Wang \n// Zhao Cheng \n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef NW_VERSION_H\n#define NW_VERSION_H\n\n#define NW_MAJOR_VERSION 0\n#define NW_MINOR_VERSION 2\n#define NW_PATCH_VERSION 6\n#define NW_VERSION_IS_RELEASE 0\n\n#ifndef NW_STRINGIFY\n#define NW_STRINGIFY(n) NW_STRINGIFY_HELPER(n)\n#define NW_STRINGIFY_HELPER(n) #n\n#endif\n\n#if NW_VERSION_IS_RELEASE\n# define NW_VERSION_STRING NW_STRINGIFY(NW_MAJOR_VERSION) \".\" \\\n NW_STRINGIFY(NW_MINOR_VERSION) \".\" \\\n NW_STRINGIFY(NW_PATCH_VERSION)\n#else\n# define NW_VERSION_STRING NW_STRINGIFY(NW_MAJOR_VERSION) \".\" \\\n NW_STRINGIFY(NW_MINOR_VERSION) \".\" \\\n NW_STRINGIFY(NW_PATCH_VERSION) \"-pre\"\n#endif\n\n#define NW_VERSION \"v\" NW_VERSION_STRING\n\n\n#define NW_VERSION_AT_LEAST(major, minor, patch) \\\n (( (major) < NW_MAJOR_VERSION) \\\n || ((major) == NW_MAJOR_VERSION && (minor) < NW_MINOR_VERSION) \\\n || ((major) == NW_MAJOR_VERSION && (minor) == NW_MINOR_VERSION && (patch) <= NW_PATCH_VERSION))\n\n#endif /* NW_VERSION_H */\n", "file_path": "src/nw_version.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0003685752453748137, 0.00020323546777945012, 0.00016340547881554812, 0.0001732881646603346, 7.40614632377401e-05]} {"hunk": {"id": 0, "code_window": ["// Display no toolbar\n", "const char kNoToolbar[] = \"no-toolbar\";\n", "\n", "// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n"], "file_path": "src/common/shell_switches.cc", "type": "add", "edit_start_line_idx": 45}, "file": "// Copyright (c) 2011 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CHROME_COMMON_ZIP_INTERNAL_H_\n#define CHROME_COMMON_ZIP_INTERNAL_H_\n\n#include \n\n#include \"third_party/zlib/contrib/minizip/unzip.h\"\n#include \"third_party/zlib/contrib/minizip/zip.h\"\n\n// Utility functions and constants used internally for the zip file\n// library in the directory. Don't use them outside of the library.\nnamespace zip {\nnamespace internal {\n\n// Opens the given file name in UTF-8 for unzipping, with some setup for\n// Windows.\nunzFile OpenForUnzipping(const std::string& file_name_utf8);\n\n#if defined(OS_POSIX)\n// Opens the file referred to by |zip_fd| for unzipping.\nunzFile OpenFdForUnzipping(int zip_fd);\n#endif\n\n// Opens the given file name in UTF-8 for zipping, with some setup for\n// Windows. |append_flag| will be passed to zipOpen2().\nzipFile OpenForZipping(const std::string& file_name_utf8, int append_flag);\n\nconst int kZipMaxPath = 256;\nconst int kZipBufSize = 8192;\n\n} // namespace internal\n} // namespace zip\n\n#endif // CHROME_COMMON_ZIP_INTERNAL_H_\n", "file_path": "src/common/zip_internal.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0002442144032102078, 0.0001887475955300033, 0.0001654311636229977, 0.00017267241491936147, 3.223183375666849e-05]} {"hunk": {"id": 0, "code_window": ["// Display no toolbar\n", "const char kNoToolbar[] = \"no-toolbar\";\n", "\n", "// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n"], "file_path": "src/common/shell_switches.cc", "type": "add", "edit_start_line_idx": 45}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/menu/menu.h\"\n\n#import \n#include \"content/nw/src/api/menuitem/menuitem.h\"\n\nnamespace api {\n\nusing namespace v8;\n\nMenu::Menu(CreationOption option) {\n menu_ = [[NSMenu alloc]\n initWithTitle:[NSString stringWithUTF8String:option.title.c_str()]];\n [menu_ setAutoenablesItems:NO];\n}\n\nMenu::~Menu() {\n [menu_ release];\n}\n\nvoid Menu::SetTitle(const std::string& title) {\n [menu_ setTitle:[NSString stringWithUTF8String:title.c_str()]];\n}\n\nstd::string Menu::GetTitle() {\n return [[menu_ title] UTF8String];\n}\n\nvoid Menu::Append(MenuItem* menu_item) {\n [menu_ addItem:menu_item->menu_item_];\n}\n\nvoid Menu::Insert(MenuItem* menu_item, int pos) {\n [menu_ insertItem:menu_item->menu_item_ atIndex:pos];\n}\n\nvoid Menu::Remove(MenuItem* menu_item) {\n [menu_ removeItem:menu_item->menu_item_];\n}\n\nvoid Menu::Remove(int pos) {\n [menu_ removeItemAtIndex:pos];\n}\n\n} // namespace api\n", "file_path": "src/api/menu/menu_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017610924260225147, 0.00017172984371427447, 0.00016770567162893713, 0.00017239080625586212, 3.3991746022365987e-06]} {"hunk": {"id": 1, "code_window": ["// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n", "// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n", "const char kmMain[] = \"main\";\n", "const char kmName[] = \"name\";\n", "const char kmWebkit[] = \"webkit\";\n", "const char kmNodejs[] = \"nodejs\";\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["// Set current working directory\n", "const char kWorkingDirectory[] = \"working-directory\";\n"], "file_path": "src/common/shell_switches.cc", "type": "replace", "edit_start_line_idx": 48}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/common/shell_switches.h\"\n\nnamespace switches {\n\n// Check whether all system dependencies for running layout tests are met.\nconst char kCheckLayoutTestSysDeps[] = \"check-layout-test-sys-deps\";\n\n// Tells Content Shell that it's running as a content_browsertest.\nconst char kContentBrowserTest[] = \"browser-test\";\n\n// Makes Content Shell use the given path for its data directory.\nconst char kContentShellDataPath[] = \"data-path\";\n\n// Enable developer tools\nconst char kDeveloper[] = \"developer\";\n\n// Request pages to be dumped as text once they finished loading.\nconst char kDumpRenderTree[] = \"dump-render-tree\";\n\n// Disables the timeout for layout tests.\nconst char kNoTimeout[] = \"no-timeout\";\n\n// Display no toolbar\nconst char kNoToolbar[] = \"no-toolbar\";\n\n// Show version and quit\nconst char kVersion[] = \"version\";\n\n// Open specified url\nconst char kUrl[] = \"url\";\n\nconst char kmMain[] = \"main\";\nconst char kmName[] = \"name\";\nconst char kmWebkit[] = \"webkit\";\nconst char kmNodejs[] = \"nodejs\";\nconst char kmRoot[] = \"root\";\nconst char kmWindow[] = \"window\";\nconst char kmTitle[] = \"title\";\nconst char kmToolbar[] = \"toolbar\";\nconst char kmIcon[] = \"icon\";\nconst char kmWidth[] = \"width\";\nconst char kmHeight[] = \"height\";\nconst char kmX[] = \"x\";\nconst char kmY[] = \"y\";\nconst char kmResizable[] = \"resizable\";\nconst char kmPosition[] = \"position\";\nconst char kmMinWidth[] = \"min_width\";\nconst char kmMinHeight[] = \"min_height\";\nconst char kmMaxWidth[] = \"max_width\";\nconst char kmMaxHeight[] = \"max_height\";\nconst char kmAsDesktop[] = \"as_desktop\";\n\n} // namespace switches\n", "file_path": "src/common/shell_switches.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.9981426000595093, 0.2515798807144165, 0.00017437830683775246, 0.0033469132613390684, 0.43087849020957947]} {"hunk": {"id": 1, "code_window": ["// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n", "// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n", "const char kmMain[] = \"main\";\n", "const char kmName[] = \"name\";\n", "const char kmWebkit[] = \"webkit\";\n", "const char kmNodejs[] = \"nodejs\";\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["// Set current working directory\n", "const char kWorkingDirectory[] = \"working-directory\";\n"], "file_path": "src/common/shell_switches.cc", "type": "replace", "edit_start_line_idx": 48}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_browser_main_parts.h\"\n\n#include \"base/bind.h\"\n#include \"base/command_line.h\"\n#include \"base/message_loop.h\"\n#include \"base/string_number_conversions.h\"\n#include \"base/threading/thread.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/shell.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/common/main_function_params.h\"\n#include \"content/public/common/url_constants.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"grit/net_resources.h\"\n#include \"net/base/net_module.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n\n#if defined(OS_ANDROID)\n#include \"net/base/network_change_notifier.h\"\n#include \"net/android/network_change_notifier_factory.h\"\n#endif\n\nnamespace content {\n\nnamespace {\n\nbase::StringPiece PlatformResourceProvider(int key) {\n if (key == IDR_DIR_HEADER_HTML) {\n base::StringPiece html_data =\n ui::ResourceBundle::GetSharedInstance().GetRawDataResource(\n IDR_DIR_HEADER_HTML, ui::SCALE_FACTOR_NONE);\n return html_data;\n }\n return base::StringPiece();\n}\n\n} // namespace\n\nShellBrowserMainParts::ShellBrowserMainParts(\n const MainFunctionParams& parameters)\n : BrowserMainParts(),\n parameters_(parameters),\n run_message_loop_(true),\n devtools_delegate_(NULL) {\n}\n\nShellBrowserMainParts::~ShellBrowserMainParts() {\n}\n\n#if !defined(OS_MACOSX)\nvoid ShellBrowserMainParts::PreMainMessageLoopStart() {\n}\n#endif\n\nvoid ShellBrowserMainParts::PostMainMessageLoopStart() {\n#if defined(OS_ANDROID)\n MessageLoopForUI::current()->Start();\n#endif\n}\n\nvoid ShellBrowserMainParts::PreEarlyInitialization() {\n#if defined(OS_ANDROID)\n net::NetworkChangeNotifier::SetFactory(\n new net::android::NetworkChangeNotifierFactory());\n#endif\n}\n\nvoid ShellBrowserMainParts::PreMainMessageLoopRun() {\n#if !defined(OS_MACOSX)\n Init();\n#endif\n\n if (parameters_.ui_task) {\n parameters_.ui_task->Run();\n delete parameters_.ui_task;\n run_message_loop_ = false;\n }\n}\n\nbool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) {\n return !run_message_loop_;\n}\n\nvoid ShellBrowserMainParts::PostMainMessageLoopRun() {\n#if defined(USE_AURA)\n Shell::PlatformExit();\n#endif\n if (devtools_delegate_)\n devtools_delegate_->Stop();\n browser_context_.reset();\n off_the_record_browser_context_.reset();\n}\n\nvoid ShellBrowserMainParts::Init() {\n nw::InitPackageForceNoEmpty();\n\n browser_context_.reset(new ShellBrowserContext(false));\n off_the_record_browser_context_.reset(new ShellBrowserContext(true));\n\n Shell::PlatformInitialize();\n net::NetModule::SetResourceProvider(PlatformResourceProvider);\n\n int port = 0;\n// On android the port number isn't used.\n#if !defined(OS_ANDROID)\n // See if the user specified a port on the command line (useful for\n // automation). If not, use an ephemeral port by specifying 0.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) {\n int temp_port;\n std::string port_str =\n command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort);\n if (base::StringToInt(port_str, &temp_port) &&\n temp_port > 0 && temp_port < 65535) {\n port = temp_port;\n } else {\n DLOG(WARNING) << \"Invalid http debugger port number \" << temp_port;\n }\n }\n#endif\n devtools_delegate_ = new ShellDevToolsDelegate(\n port, browser_context_->GetRequestContext());\n\n Shell::CreateNewWindow(browser_context_.get(),\n nw::GetStartupURL(),\n NULL,\n MSG_ROUTING_NONE,\n NULL);\n}\n\n} // namespace\n", "file_path": "src/shell_browser_main_parts.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0002706618106458336, 0.00018350158643443137, 0.0001660943526076153, 0.00017232162645086646, 3.0919723940314725e-05]} {"hunk": {"id": 1, "code_window": ["// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n", "// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n", "const char kmMain[] = \"main\";\n", "const char kmName[] = \"name\";\n", "const char kmWebkit[] = \"webkit\";\n", "const char kmNodejs[] = \"nodejs\";\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["// Set current working directory\n", "const char kWorkingDirectory[] = \"working-directory\";\n"], "file_path": "src/common/shell_switches.cc", "type": "replace", "edit_start_line_idx": 48}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell.h\"\n\n#include \"base/auto_reset.h\"\n#include \"base/command_line.h\"\n#include \"base/message_loop.h\"\n#include \"base/path_service.h\"\n#include \"base/string_number_conversions.h\"\n#include \"base/string_util.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"base/values.h\"\n#include \"content/public/browser/devtools_http_handler.h\"\n#include \"content/public/browser/navigation_entry.h\"\n#include \"content/public/browser/navigation_controller.h\"\n#include \"content/public/browser/notification_details.h\"\n#include \"content/public/browser/notification_source.h\"\n#include \"content/public/browser/notification_types.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/nw/src/browser/file_select_helper.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_javascript_dialog_creator.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/media/media_stream_devices_controller.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"content/nw/src/shell_content_browser_client.h\"\n#include \"ui/gfx/size.h\"\n\nnamespace content {\n\nstd::vector Shell::windows_;\nbase::Callback Shell::shell_created_callback_;\n\nbool Shell::quit_message_loop_ = true;\n\nShell::Shell(WebContents* web_contents, base::DictionaryValue* manifest)\n : window_(NULL),\n url_edit_view_(NULL),\n window_manifest_(manifest),\n is_show_devtools_(false),\n is_toolbar_open_(true),\n max_height_(-1),\n max_width_(-1),\n min_height_(-1),\n min_width_(-1)\n#if defined(OS_WIN) && !defined(USE_AURA)\n , default_edit_wnd_proc_(0)\n#endif\n {\n if (window_manifest_) {\n window_manifest_->GetBoolean(switches::kmToolbar, &is_toolbar_open_);\n window_manifest_->GetBoolean(switches::kDeveloper, &is_show_devtools_);\n window_manifest_->GetInteger(switches::kmMaxHeight, &max_height_);\n window_manifest_->GetInteger(switches::kmMaxWidth, &max_width_);\n window_manifest_->GetInteger(switches::kmMinHeight, &min_height_);\n window_manifest_->GetInteger(switches::kmMinWidth, &min_width_);\n }\n\n registrar_.Add(this, NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,\n Source(web_contents));\n windows_.push_back(this);\n\n if (!shell_created_callback_.is_null()) {\n shell_created_callback_.Run(this);\n shell_created_callback_.Reset();\n }\n}\n\nShell::~Shell() {\n PlatformCleanUp();\n\n for (size_t i = 0; i < windows_.size(); ++i) {\n if (windows_[i] == this) {\n windows_.erase(windows_.begin() + i);\n break;\n }\n }\n\n if (windows_.empty() && quit_message_loop_)\n MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());\n}\n\nShell* Shell::CreateShell(WebContents* web_contents,\n base::DictionaryValue* manifest) {\n int width = 700;\n int height = 450;\n manifest->GetInteger(switches::kmWidth, &width);\n manifest->GetInteger(switches::kmHeight, &height);\n\n Shell* shell = new Shell(web_contents, manifest);\n shell->PlatformCreateWindow(width, height);\n\n shell->web_contents_.reset(web_contents);\n web_contents->SetDelegate(shell);\n\n shell->PlatformSetContents();\n\n shell->PlatformResizeSubViews();\n return shell;\n}\n\nvoid Shell::CloseAllWindows() {\n AutoReset auto_reset(&quit_message_loop_, false);\n std::vector open_windows(windows_);\n for (size_t i = 0; i < open_windows.size(); ++i)\n open_windows[i]->Close();\n MessageLoop::current()->RunAllPending();\n}\n\nvoid Shell::SetShellCreatedCallback(\n base::Callback shell_created_callback) {\n DCHECK(shell_created_callback_.is_null());\n shell_created_callback_ = shell_created_callback;\n}\n\nShell* Shell::FromRenderViewHost(RenderViewHost* rvh) {\n for (size_t i = 0; i < windows_.size(); ++i) {\n if (windows_[i]->web_contents() &&\n windows_[i]->web_contents()->GetRenderViewHost() == rvh) {\n return windows_[i];\n }\n }\n return NULL;\n}\n\nShell* Shell::CreateNewWindow(BrowserContext* browser_context,\n const GURL& url,\n SiteInstance* site_instance,\n int routing_id,\n WebContents* base_web_contents) {\n WebContents* web_contents = WebContents::Create(\n browser_context,\n site_instance,\n routing_id,\n base_web_contents);\n\n // Create with package's manifest\n base::DictionaryValue *manifest = NULL;\n nw::GetManifest()->GetDictionary(switches::kmWindow, &manifest);\n manifest->SetBoolean(switches::kDeveloper,\n CommandLine::ForCurrentProcess()->HasSwitch(switches::kDeveloper));\n\n // Center window by default\n if (!manifest->HasKey(switches::kmPosition))\n manifest->SetString(switches::kmPosition, \"center\");\n\n Shell* shell = CreateShell(web_contents, manifest);\n if (!url.is_empty())\n shell->LoadURL(url);\n return shell;\n}\n\nvoid Shell::LoadURL(const GURL& url) {\n web_contents_->GetController().LoadURL(\n url,\n Referrer(),\n PAGE_TRANSITION_TYPED,\n std::string());\n web_contents_->Focus();\n}\n\nvoid Shell::GoBackOrForward(int offset) {\n web_contents_->GetController().GoToOffset(offset);\n web_contents_->Focus();\n}\n\nvoid Shell::Reload() {\n web_contents_->GetController().Reload(false);\n web_contents_->Focus();\n}\n\nvoid Shell::Stop() {\n web_contents_->Stop();\n web_contents_->Focus();\n}\n\nvoid Shell::UpdateNavigationControls() {\n int current_index = web_contents_->GetController().GetCurrentEntryIndex();\n int max_index = web_contents_->GetController().GetEntryCount() - 1;\n\n PlatformEnableUIControl(BACK_BUTTON, current_index > 0);\n PlatformEnableUIControl(FORWARD_BUTTON, current_index < max_index);\n PlatformEnableUIControl(STOP_BUTTON, web_contents_->IsLoading());\n}\n\nvoid Shell::ShowDevTools() {\n ShellContentBrowserClient* browser_client =\n static_cast(\n GetContentClient()->browser());\n ShellDevToolsDelegate* delegate =\n browser_client->shell_browser_main_parts()->devtools_delegate();\n GURL url = delegate->devtools_http_handler()->GetFrontendURL(\n web_contents()->GetRenderViewHost());\n\n // Use our minimum set manifest\n base::DictionaryValue manifest;\n manifest.SetBoolean(switches::kmToolbar, false);\n manifest.SetBoolean(switches::kDeveloper, true);\n manifest.SetInteger(switches::kmWidth, 600);\n manifest.SetInteger(switches::kmHeight, 500);\n\n Shell* shell = CreateShell(\n WebContents::Create(web_contents()->GetBrowserContext(),\n NULL, MSG_ROUTING_NONE, NULL),\n &manifest);\n shell->LoadURL(url);\n}\n\ngfx::NativeView Shell::GetContentView() {\n if (!web_contents_.get())\n return NULL;\n return web_contents_->GetNativeView();\n}\n\nWebContents* Shell::OpenURLFromTab(WebContents* source,\n const OpenURLParams& params) {\n // The only one we implement for now.\n DCHECK(params.disposition == CURRENT_TAB);\n source->GetController().LoadURL(\n params.url, params.referrer, params.transition, std::string());\n return source;\n}\n\nvoid Shell::LoadingStateChanged(WebContents* source) {\n UpdateNavigationControls();\n PlatformSetIsLoading(source->IsLoading());\n}\n\nvoid Shell::ActivateContents(content::WebContents* contents) {\n LOG(ERROR) << \"activate\";\n}\n\nvoid Shell::DeactivateContents(content::WebContents* contents) {\n LOG(ERROR) << \"deactivate\";\n}\n\nvoid Shell::CloseContents(WebContents* source) {\n Close();\n}\n\nvoid Shell::MoveContents(WebContents* source, const gfx::Rect& pos) {\n Move(pos);\n}\n\nbool Shell::IsPopupOrPanel(const WebContents* source) const {\n // Treat very window as popup so we can use window operations\n return true;\n}\n\nbool Shell::TakeFocus(WebContents* soruce,\n bool reverse) {\n return true;\n}\n\nvoid Shell::LostCapture() {\n}\n\nvoid Shell::WebContentsFocused(WebContents* contents) {\n}\n\nvoid Shell::WebContentsCreated(WebContents* source_contents,\n int64 source_frame_id,\n const GURL& target_url,\n WebContents* new_contents) {\n // Create with package's manifest\n base::DictionaryValue *manifest = NULL;\n nw::GetManifest()->GetDictionary(switches::kmWindow, &manifest);\n manifest->SetBoolean(switches::kDeveloper,\n CommandLine::ForCurrentProcess()->HasSwitch(switches::kDeveloper));\n\n // Get window features\n WebKit::WebWindowFeatures features = new_contents->GetWindowFeatures();\n if (features.widthSet)\n manifest->SetInteger(switches::kmWidth, features.width);\n if (features.heightSet)\n manifest->SetInteger(switches::kmHeight, features.height);\n if (features.xSet)\n manifest->SetInteger(switches::kmX, features.x);\n if (features.ySet)\n manifest->SetInteger(switches::kmY, features.y);\n\n CreateShell(new_contents, manifest);\n}\n\nvoid Shell::RunFileChooser(WebContents* web_contents,\n const content::FileChooserParams& params) {\n FileSelectHelper::RunFileChooser(web_contents, params);\n}\n\nvoid Shell::EnumerateDirectory(WebContents* web_contents,\n int request_id,\n const FilePath& path) {\n FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);\n}\n\nvoid Shell::DidNavigateMainFramePostCommit(WebContents* web_contents) {\n PlatformSetAddressBarURL(web_contents->GetURL());\n}\n\nJavaScriptDialogCreator* Shell::GetJavaScriptDialogCreator() {\n if (!dialog_creator_.get())\n dialog_creator_.reset(new ShellJavaScriptDialogCreator());\n return dialog_creator_.get();\n}\n\nbool Shell::AddMessageToConsole(WebContents* source,\n int32 level,\n const string16& message,\n int32 line_no,\n const string16& source_id) {\n return false;\n}\n\n\nvoid Shell::RequestMediaAccessPermission(\n content::WebContents* web_contents,\n const content::MediaStreamRequest* request,\n const content::MediaResponseCallback& callback) {\n scoped_ptr\n controller(new MediaStreamDevicesController(request,\n callback));\n controller->DismissInfoBarAndTakeActionOnSettings();\n}\n\nvoid Shell::Observe(int type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) {\n std::pair* title =\n Details >(details).ptr();\n\n if (title->first) {\n string16 text = title->first->GetTitle();\n PlatformSetTitle(text);\n }\n }\n}\n\n} // namespace content\n", "file_path": "src/shell.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.7123246192932129, 0.020841671153903008, 0.0001647369790589437, 0.00017289405514020473, 0.11692409217357635]} {"hunk": {"id": 1, "code_window": ["// Show version and quit\n", "const char kVersion[] = \"version\";\n", "\n", "// Open specified url\n", "const char kUrl[] = \"url\";\n", "\n", "const char kmMain[] = \"main\";\n", "const char kmName[] = \"name\";\n", "const char kmWebkit[] = \"webkit\";\n", "const char kmNodejs[] = \"nodejs\";\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["// Set current working directory\n", "const char kWorkingDirectory[] = \"working-directory\";\n"], "file_path": "src/common/shell_switches.cc", "type": "replace", "edit_start_line_idx": 48}, "file": "\n \n \n node-webkit versions\n \n\n node-webkit v
\n node.js v
\n \n\n", "file_path": "src/resources/nw_version.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017337048484478146, 0.00016978391795419157, 0.00016619733651168644, 0.00016978391795419157, 3.586574166547507e-06]} {"hunk": {"id": 2, "code_window": ["extern const char kDeveloper[];\n", "extern const char kDumpRenderTree[];\n", "extern const char kNoTimeout[];\n", "extern const char kNoToolbar[];\n", "extern const char kVersion[];\n", "extern const char kUrl[];\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "src/common/shell_switches.h", "type": "replace", "edit_start_line_idx": 18}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n// Defines all the \"content_shell\" command-line switches.\n\n#ifndef CONTENT_NW_SRC_SHELL_SWITCHES_H_\n#define CONTENT_NW_SRC_SHELL_SWITCHES_H_\n\nnamespace switches {\n\nextern const char kCheckLayoutTestSysDeps[];\nextern const char kContentBrowserTest[];\nextern const char kContentShellDataPath[];\nextern const char kDeveloper[];\nextern const char kDumpRenderTree[];\nextern const char kNoTimeout[];\nextern const char kNoToolbar[];\nextern const char kVersion[];\nextern const char kUrl[];\n\n// Manifest settings\nextern const char kmMain[];\nextern const char kmName[];\nextern const char kmWebkit[];\nextern const char kmNodejs[];\nextern const char kmRoot[];\nextern const char kmWindow[];\nextern const char kmTitle[];\nextern const char kmToolbar[];\nextern const char kmIcon[];\nextern const char kmWidth[];\nextern const char kmHeight[];\nextern const char kmX[];\nextern const char kmY[];\nextern const char kmResizable[];\nextern const char kmPosition[];\nextern const char kmMinWidth[];\nextern const char kmMinHeight[];\nextern const char kmMaxWidth[];\nextern const char kmMaxHeight[];\nextern const char kmAsDesktop[];\n\n} // namespace switches\n\n#endif // CONTENT_NW_SRC_SHELL_SWITCHES_H_\n", "file_path": "src/common/shell_switches.h", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.9980276226997375, 0.19996467232704163, 0.00016918990877456963, 0.00024237397883553058, 0.3990316689014435]} {"hunk": {"id": 2, "code_window": ["extern const char kDeveloper[];\n", "extern const char kDumpRenderTree[];\n", "extern const char kNoTimeout[];\n", "extern const char kNoToolbar[];\n", "extern const char kVersion[];\n", "extern const char kUrl[];\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "src/common/shell_switches.h", "type": "replace", "edit_start_line_idx": 18}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_SHELL_BROWSER_MAIN_H_\n#define CONTENT_SHELL_SHELL_BROWSER_MAIN_H_\n\nnamespace content {\nstruct MainFunctionParams;\n}\n\nint ShellBrowserMain(const content::MainFunctionParams& parameters);\n\n#endif // CONTENT_SHELL_SHELL_BROWSER_MAIN_H_\n", "file_path": "src/shell_browser_main.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00016890476399566978, 0.00016845838399603963, 0.00016801200399640948, 0.00016845838399603963, 4.463799996301532e-07]} {"hunk": {"id": 2, "code_window": ["extern const char kDeveloper[];\n", "extern const char kDumpRenderTree[];\n", "extern const char kNoTimeout[];\n", "extern const char kNoToolbar[];\n", "extern const char kVersion[];\n", "extern const char kUrl[];\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "src/common/shell_switches.h", "type": "replace", "edit_start_line_idx": 18}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/shell_login_dialog.h\"\n\n#include \n\n#include \"base/logging.h\"\n#include \"base/string16.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"content/public/browser/browser_thread.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/public/browser/resource_request_info.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n#include \"ui/base/gtk/gtk_hig_constants.h\"\n\nnamespace content {\n\nvoid ShellLoginDialog::PlatformCreateDialog(const string16& message) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n int render_process_id;\n int render_view_id;\n if (!ResourceRequestInfo::ForRequest(request_)->GetAssociatedRenderView(\n &render_process_id, &render_view_id)) {\n NOTREACHED();\n }\n\n WebContents* web_contents = NULL;\n RenderViewHost* render_view_host =\n RenderViewHost::FromID(render_process_id, render_view_id);\n if (render_view_host)\n web_contents = WebContents::FromRenderViewHost(render_view_host);\n DCHECK(web_contents);\n\n gfx::NativeWindow parent_window =\n web_contents->GetView()->GetTopLevelNativeWindow();\n\n root_ = gtk_message_dialog_new(parent_window,\n GTK_DIALOG_MODAL,\n GTK_MESSAGE_INFO,\n GTK_BUTTONS_OK_CANCEL,\n \"Please log in.\");\n\n GtkWidget* content_area = gtk_dialog_get_content_area(GTK_DIALOG(root_));\n GtkWidget* label = gtk_label_new(UTF16ToUTF8(message).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);\n gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0);\n\n username_entry_ = gtk_entry_new();\n gtk_entry_set_activates_default(GTK_ENTRY(username_entry_), TRUE);\n\n password_entry_ = gtk_entry_new();\n gtk_entry_set_activates_default(GTK_ENTRY(password_entry_), TRUE);\n gtk_entry_set_visibility(GTK_ENTRY(password_entry_), FALSE);\n\n GtkWidget* table = gtk_table_new(2, 2, FALSE);\n gtk_table_set_col_spacing(GTK_TABLE(table), 0, ui::kLabelSpacing);\n gtk_table_set_row_spacings(GTK_TABLE(table), ui::kControlSpacing);\n\n GtkWidget* username_label = gtk_label_new(\"Username:\");\n gtk_misc_set_alignment(GTK_MISC(username_label), 0, 0.5);\n\n gtk_table_attach(GTK_TABLE(table), username_label, 0, 1, 0, 1, GTK_FILL,\n GTK_FILL, 0, 0);\n gtk_table_attach_defaults(GTK_TABLE(table), username_entry_, 1, 2, 0, 1);\n\n GtkWidget* password_label = gtk_label_new(\"Password:\");\n gtk_misc_set_alignment(GTK_MISC(password_label), 0, 0.5);\n\n gtk_table_attach(GTK_TABLE(table), password_label, 0, 1, 1, 2, GTK_FILL,\n GTK_FILL, 0, 0);\n gtk_table_attach_defaults(GTK_TABLE(table), password_entry_, 1, 2, 1, 2);\n\n gtk_box_pack_start(GTK_BOX(content_area), table, FALSE, FALSE, 0);\n\n g_signal_connect(root_, \"response\", G_CALLBACK(OnResponseThunk), this);\n gtk_widget_grab_focus(username_entry_);\n gtk_widget_show_all(GTK_WIDGET(root_));\n}\n\nvoid ShellLoginDialog::PlatformCleanUp() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n}\n\nvoid ShellLoginDialog::PlatformRequestCancelled() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n}\n\nvoid ShellLoginDialog::OnResponse(GtkWidget* sender, int response_id) {\n switch (response_id) {\n case GTK_RESPONSE_OK:\n UserAcceptedAuth(\n UTF8ToUTF16(gtk_entry_get_text(GTK_ENTRY(username_entry_))),\n UTF8ToUTF16(gtk_entry_get_text(GTK_ENTRY(password_entry_))));\n break;\n case GTK_RESPONSE_CANCEL:\n case GTK_RESPONSE_DELETE_EVENT:\n UserCancelledAuth();\n break;\n default:\n NOTREACHED();\n }\n\n gtk_widget_destroy(root_);\n}\n\n} // namespace content\n", "file_path": "src/browser/shell_login_dialog_gtk.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017752325220499188, 0.00017306781955994666, 0.00016686982417013496, 0.0001727834460325539, 3.053085947612999e-06]} {"hunk": {"id": 2, "code_window": ["extern const char kDeveloper[];\n", "extern const char kDumpRenderTree[];\n", "extern const char kNoTimeout[];\n", "extern const char kNoToolbar[];\n", "extern const char kVersion[];\n", "extern const char kUrl[];\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "src/common/shell_switches.h", "type": "replace", "edit_start_line_idx": 18}, "file": "\n\n\n\n\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleDisplayName\n\t${EXECUTABLE_NAME}\n\tCFBundleExecutable\n\t${EXECUTABLE_NAME}\n\tCFBundleIdentifier\n\tcom.intel.nw.helper\n\tCFBundleInfoDictionaryVersion\n\t6.0\n\tCFBundleName\n\t${PRODUCT_NAME}\n\tCFBundlePackageType\n\tAPPL\n\tCFBundleSignature\n\t????\n\tLSFileQuarantineEnabled\n\t\n\tLSMinimumSystemVersion\n\t${MACOSX_DEPLOYMENT_TARGET}.0\n\tLSUIElement\n\t1\n\tNSSupportsAutomaticGraphicsSwitching\n\t\n\n\n", "file_path": "src/mac/helper-Info.plist", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001759649021551013, 0.00017109177133534104, 0.00016822264296934009, 0.00017008975555654615, 2.9945961159683065e-06]} {"hunk": {"id": 3, "code_window": ["extern const char kUrl[];\n", "\n", "// Manifest settings\n", "extern const char kmMain[];\n", "extern const char kmName[];\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["extern const char kVersion[];\n", "extern const char kWorkingDirectory[];\n"], "file_path": "src/common/shell_switches.h", "type": "add", "edit_start_line_idx": 20}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/common/shell_switches.h\"\n\nnamespace switches {\n\n// Check whether all system dependencies for running layout tests are met.\nconst char kCheckLayoutTestSysDeps[] = \"check-layout-test-sys-deps\";\n\n// Tells Content Shell that it's running as a content_browsertest.\nconst char kContentBrowserTest[] = \"browser-test\";\n\n// Makes Content Shell use the given path for its data directory.\nconst char kContentShellDataPath[] = \"data-path\";\n\n// Enable developer tools\nconst char kDeveloper[] = \"developer\";\n\n// Request pages to be dumped as text once they finished loading.\nconst char kDumpRenderTree[] = \"dump-render-tree\";\n\n// Disables the timeout for layout tests.\nconst char kNoTimeout[] = \"no-timeout\";\n\n// Display no toolbar\nconst char kNoToolbar[] = \"no-toolbar\";\n\n// Show version and quit\nconst char kVersion[] = \"version\";\n\n// Open specified url\nconst char kUrl[] = \"url\";\n\nconst char kmMain[] = \"main\";\nconst char kmName[] = \"name\";\nconst char kmWebkit[] = \"webkit\";\nconst char kmNodejs[] = \"nodejs\";\nconst char kmRoot[] = \"root\";\nconst char kmWindow[] = \"window\";\nconst char kmTitle[] = \"title\";\nconst char kmToolbar[] = \"toolbar\";\nconst char kmIcon[] = \"icon\";\nconst char kmWidth[] = \"width\";\nconst char kmHeight[] = \"height\";\nconst char kmX[] = \"x\";\nconst char kmY[] = \"y\";\nconst char kmResizable[] = \"resizable\";\nconst char kmPosition[] = \"position\";\nconst char kmMinWidth[] = \"min_width\";\nconst char kmMinHeight[] = \"min_height\";\nconst char kmMaxWidth[] = \"max_width\";\nconst char kmMaxHeight[] = \"max_height\";\nconst char kmAsDesktop[] = \"as_desktop\";\n\n} // namespace switches\n", "file_path": "src/common/shell_switches.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.988832950592041, 0.12549971044063568, 0.00017520446272101253, 0.0003631538129411638, 0.3263355493545532]} {"hunk": {"id": 3, "code_window": ["extern const char kUrl[];\n", "\n", "// Manifest settings\n", "extern const char kmMain[];\n", "extern const char kmName[];\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["extern const char kVersion[];\n", "extern const char kWorkingDirectory[];\n"], "file_path": "src/common/shell_switches.h", "type": "add", "edit_start_line_idx": 20}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_PATHS_MAC_H_\n#define CONTENT_SHELL_PATHS_MAC_H_\n\n#include \"base/file_path.h\"\n\n// Sets up base::mac::FrameworkBundle.\nvoid OverrideFrameworkBundlePath();\n\n// Sets up the CHILD_PROCESS_EXE path to properly point to the helper app.\nvoid OverrideChildProcessPath();\n\n// Gets the path to the content shell's pak file.\nFilePath GetResourcesPakFilePath();\n\n#endif // CONTENT_SHELL_PATHS_MAC_H_\n", "file_path": "src/paths_mac.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017555698286741972, 0.00017105865117628127, 0.00016656031948514283, 0.00017105865117628127, 4.498331691138446e-06]} {"hunk": {"id": 3, "code_window": ["extern const char kUrl[];\n", "\n", "// Manifest settings\n", "extern const char kmMain[];\n", "extern const char kmName[];\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["extern const char kVersion[];\n", "extern const char kWorkingDirectory[];\n"], "file_path": "src/common/shell_switches.h", "type": "add", "edit_start_line_idx": 20}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/tray/tray.h\"\n\n#include \"content/nw/src/api/menu/menu.h\"\n\n#import \n\nnamespace api {\n\nTray::Tray(CreationOption option) {\n NSStatusBar *status_bar = [NSStatusBar systemStatusBar];\n status_item_ = [status_bar statusItemWithLength:NSVariableStatusItemLength];\n [status_item_ retain];\n [status_item_ setHighlightMode:YES];\n\n if (!option.icon.empty())\n SetIcon(option.icon);\n if (!option.title.empty())\n SetTitle(option.title);\n if (!option.tooltip.empty())\n SetTooltip(option.tooltip);\n}\n\nTray::~Tray() {\n [status_item_ release];\n}\n\nvoid Tray::SetTitle(const std::string& title) {\n [status_item_ setTitle:\n [NSString stringWithUTF8String:title.c_str()]];\n}\n\nstd::string Tray::GetTitle() {\n return [[status_item_ title] UTF8String];\n}\n\nvoid Tray::SetIcon(const std::string& path) {\n NSString* icon_path = [NSString stringWithUTF8String:path.c_str()];\n NSImage* icon = [[NSImage alloc] initWithContentsOfFile:icon_path];\n [status_item_ setImage:icon];\n}\n\nvoid Tray::SetTooltip(const std::string& tooltip) {\n [status_item_ setToolTip:\n [NSString stringWithUTF8String:tooltip.c_str()]];\n}\n\nstd::string Tray::GetTooltip() {\n NSString* tooltip = [status_item_ toolTip];\n return tooltip == nil ? \"\" : [tooltip UTF8String];\n}\n\nvoid Tray::SetMenu(Menu* menu) {\n [status_item_ setMenu:menu->menu_];\n}\n\nvoid Tray::Remove() {\n [[NSStatusBar systemStatusBar] removeStatusItem:status_item_];\n}\n\n} // namespace api\n\n", "file_path": "src/api/tray/tray_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001790143141988665, 0.0001745812623994425, 0.00016954680904746056, 0.00017520446272101253, 2.836315388776711e-06]} {"hunk": {"id": 3, "code_window": ["extern const char kUrl[];\n", "\n", "// Manifest settings\n", "extern const char kmMain[];\n", "extern const char kmName[];\n"], "labels": ["add", "keep", "keep", "keep", "keep"], "after_edit": ["extern const char kVersion[];\n", "extern const char kWorkingDirectory[];\n"], "file_path": "src/common/shell_switches.h", "type": "add", "edit_start_line_idx": 20}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_browser_main.h\"\n\n#include \"base/command_line.h\"\n#include \"base/compiler_specific.h\"\n#include \"base/logging.h\"\n#include \"base/memory/scoped_ptr.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/shell.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_content_browser_client.h\"\n#include \"content/public/browser/browser_main_runner.h\"\n\n// Main routine for running as the Browser process.\nint ShellBrowserMain(const content::MainFunctionParams& parameters) {\n scoped_ptr main_runner_(\n content::BrowserMainRunner::Create());\n\n int exit_code = main_runner_->Initialize(parameters);\n\n if (exit_code >= 0)\n return exit_code;\n\n exit_code = main_runner_->Run();\n\n main_runner_->Shutdown();\n\n return exit_code;\n}\n", "file_path": "src/shell_browser_main.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0002523738658055663, 0.00018725272093433887, 0.00016488564142491668, 0.0001760190207278356, 2.9460044970619492e-05]} {"hunk": {"id": 4, "code_window": ["// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", "\n", "#include \"content/nw/src/renderer/shell_content_renderer_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/logging.h\"\n", "#include \"base/utf_string_conversions.h\"\n", "#include \"content/nw/src/api/dispatcher.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_path.h\"\n", "#include \"base/file_util.h\"\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 23}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n// Defines all the \"content_shell\" command-line switches.\n\n#ifndef CONTENT_NW_SRC_SHELL_SWITCHES_H_\n#define CONTENT_NW_SRC_SHELL_SWITCHES_H_\n\nnamespace switches {\n\nextern const char kCheckLayoutTestSysDeps[];\nextern const char kContentBrowserTest[];\nextern const char kContentShellDataPath[];\nextern const char kDeveloper[];\nextern const char kDumpRenderTree[];\nextern const char kNoTimeout[];\nextern const char kNoToolbar[];\nextern const char kVersion[];\nextern const char kUrl[];\n\n// Manifest settings\nextern const char kmMain[];\nextern const char kmName[];\nextern const char kmWebkit[];\nextern const char kmNodejs[];\nextern const char kmRoot[];\nextern const char kmWindow[];\nextern const char kmTitle[];\nextern const char kmToolbar[];\nextern const char kmIcon[];\nextern const char kmWidth[];\nextern const char kmHeight[];\nextern const char kmX[];\nextern const char kmY[];\nextern const char kmResizable[];\nextern const char kmPosition[];\nextern const char kmMinWidth[];\nextern const char kmMinHeight[];\nextern const char kmMaxWidth[];\nextern const char kmMaxHeight[];\nextern const char kmAsDesktop[];\n\n} // namespace switches\n\n#endif // CONTENT_NW_SRC_SHELL_SWITCHES_H_\n", "file_path": "src/common/shell_switches.h", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0005452478071674705, 0.0002650842652656138, 0.00017095115617848933, 0.0001782050239853561, 0.0001437245518900454]} {"hunk": {"id": 4, "code_window": ["// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", "\n", "#include \"content/nw/src/renderer/shell_content_renderer_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/logging.h\"\n", "#include \"base/utf_string_conversions.h\"\n", "#include \"content/nw/src/api/dispatcher.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_path.h\"\n", "#include \"base/file_util.h\"\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 23}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_RENDERER_PRERENDERER_PRERENDERER_CLIENT_H_\n#define CONTENT_NW_SRC_RENDERER_PRERENDERER_PRERENDERER_CLIENT_H_\n\n#include \"base/compiler_specific.h\"\n#include \"content/public/renderer/render_view_observer.h\"\n#include \"third_party/WebKit/Source/WebKit/chromium/public/WebPrerendererClient.h\"\n\nnamespace prerender {\n\nclass PrerendererClient : public content::RenderViewObserver,\n public WebKit::WebPrerendererClient {\n public:\n explicit PrerendererClient(content::RenderView* render_view);\n\n private:\n virtual ~PrerendererClient();\n\n // Implements WebKit::WebPrerendererClient\n virtual void willAddPrerender(WebKit::WebPrerender* prerender) OVERRIDE;\n};\n\n} // namespace prerender\n\n#endif // CONTENT_NW_SRC_RENDERER_PRERENDERER_PRERENDERER_CLIENT_H_\n\n", "file_path": "src/renderer/prerenderer/prerenderer_client.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0303734689950943, 0.008091849274933338, 0.00016125969705171883, 0.00017297366866841912, 0.011722820810973644]} {"hunk": {"id": 4, "code_window": ["// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", "\n", "#include \"content/nw/src/renderer/shell_content_renderer_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/logging.h\"\n", "#include \"base/utf_string_conversions.h\"\n", "#include \"content/nw/src/api/dispatcher.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_path.h\"\n", "#include \"base/file_util.h\"\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 23}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/shell_javascript_dialog_creator.h\"\n\n#include \"base/command_line.h\"\n#include \"base/logging.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n#include \"content/nw/src/browser/shell_javascript_dialog.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"net/base/net_util.h\"\n\nnamespace content {\n\nShellJavaScriptDialogCreator::ShellJavaScriptDialogCreator() {\n}\n\nShellJavaScriptDialogCreator::~ShellJavaScriptDialogCreator() {\n}\n\nvoid ShellJavaScriptDialogCreator::RunJavaScriptDialog(\n WebContents* web_contents,\n const GURL& origin_url,\n const std::string& accept_lang,\n JavaScriptMessageType javascript_message_type,\n const string16& message_text,\n const string16& default_prompt_text,\n const DialogClosedCallback& callback,\n bool* did_suppress_message) {\n if (!dialog_request_callback_.is_null()) {\n dialog_request_callback_.Run();\n callback.Run(true, string16());\n dialog_request_callback_.Reset();\n return;\n }\n\n#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)\n *did_suppress_message = false;\n\n if (dialog_.get()) {\n // One dialog at a time, please.\n *did_suppress_message = true;\n return;\n }\n\n string16 new_message_text = net::FormatUrl(origin_url, accept_lang) +\n ASCIIToUTF16(\"\\n\\n\") +\n message_text;\n gfx::NativeWindow parent_window =\n web_contents->GetView()->GetTopLevelNativeWindow();\n\n dialog_.reset(new ShellJavaScriptDialog(this,\n parent_window,\n javascript_message_type,\n new_message_text,\n default_prompt_text,\n callback));\n#else\n // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if\n *did_suppress_message = true;\n return;\n#endif\n}\n\nvoid ShellJavaScriptDialogCreator::RunBeforeUnloadDialog(\n WebContents* web_contents,\n const string16& message_text,\n bool is_reload,\n const DialogClosedCallback& callback) {\n if (!dialog_request_callback_.is_null()) {\n dialog_request_callback_.Run();\n callback.Run(true, string16());\n dialog_request_callback_.Reset();\n return;\n }\n\n#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)\n if (dialog_.get()) {\n // Seriously!?\n callback.Run(true, string16());\n return;\n }\n\n string16 new_message_text =\n message_text +\n ASCIIToUTF16(\"\\n\\nIs it OK to leave/reload this page?\");\n\n gfx::NativeWindow parent_window =\n web_contents->GetView()->GetTopLevelNativeWindow();\n\n dialog_.reset(new ShellJavaScriptDialog(this,\n parent_window,\n JAVASCRIPT_MESSAGE_TYPE_CONFIRM,\n new_message_text,\n string16(), // default_prompt_text\n callback));\n#else\n // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if\n callback.Run(true, string16());\n return;\n#endif\n}\n\nvoid ShellJavaScriptDialogCreator::ResetJavaScriptState(\n WebContents* web_contents) {\n#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)\n if (dialog_.get()) {\n dialog_->Cancel();\n dialog_.reset();\n }\n#else\n // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if\n#endif\n}\n\nvoid ShellJavaScriptDialogCreator::DialogClosed(ShellJavaScriptDialog* dialog) {\n#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)\n DCHECK_EQ(dialog, dialog_.get());\n dialog_.reset();\n#else\n // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if\n#endif\n}\n\n} // namespace content\n", "file_path": "src/browser/shell_javascript_dialog_creator.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0011683071497827768, 0.0003211634757462889, 0.00016125969705171883, 0.00017297366866841912, 0.0002822621609084308]} {"hunk": {"id": 4, "code_window": ["// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", "\n", "#include \"content/nw/src/renderer/shell_content_renderer_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/logging.h\"\n", "#include \"base/utf_string_conversions.h\"\n", "#include \"content/nw/src/api/dispatcher.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_path.h\"\n", "#include \"base/file_util.h\"\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 23}, "file": "\n\n \n\n\n\n\n\n", "file_path": "tests/menu/index.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001785201602615416, 0.0001757772552082315, 0.00016552470333408564, 0.00017764449876267463, 3.5556811326387106e-06]} {"hunk": {"id": 5, "code_window": ["\n", "ShellContentRendererClient::~ShellContentRendererClient() {\n", "}\n", "\n", "void ShellContentRendererClient::RenderThreadStarted() {\n", " // Initialize node after render thread is started\n", " v8::V8::Initialize();\n", " v8::HandleScope scope;\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" // Change working directory\n", " CommandLine* command_line = CommandLine::ForCurrentProcess();\n", " if (command_line->HasSwitch(switches::kWorkingDirectory)) {\n", " file_util::SetCurrentDirectory(\n", " command_line->GetSwitchValuePath(switches::kWorkingDirectory));\n", " }\n", "\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 47}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n// Defines all the \"content_shell\" command-line switches.\n\n#ifndef CONTENT_NW_SRC_SHELL_SWITCHES_H_\n#define CONTENT_NW_SRC_SHELL_SWITCHES_H_\n\nnamespace switches {\n\nextern const char kCheckLayoutTestSysDeps[];\nextern const char kContentBrowserTest[];\nextern const char kContentShellDataPath[];\nextern const char kDeveloper[];\nextern const char kDumpRenderTree[];\nextern const char kNoTimeout[];\nextern const char kNoToolbar[];\nextern const char kVersion[];\nextern const char kUrl[];\n\n// Manifest settings\nextern const char kmMain[];\nextern const char kmName[];\nextern const char kmWebkit[];\nextern const char kmNodejs[];\nextern const char kmRoot[];\nextern const char kmWindow[];\nextern const char kmTitle[];\nextern const char kmToolbar[];\nextern const char kmIcon[];\nextern const char kmWidth[];\nextern const char kmHeight[];\nextern const char kmX[];\nextern const char kmY[];\nextern const char kmResizable[];\nextern const char kmPosition[];\nextern const char kmMinWidth[];\nextern const char kmMinHeight[];\nextern const char kmMaxWidth[];\nextern const char kmMaxHeight[];\nextern const char kmAsDesktop[];\n\n} // namespace switches\n\n#endif // CONTENT_NW_SRC_SHELL_SWITCHES_H_\n", "file_path": "src/common/shell_switches.h", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00019938396872021258, 0.00017682972247712314, 0.00016843900084495544, 0.00017267558723688126, 1.144593352364609e-05]} {"hunk": {"id": 5, "code_window": ["\n", "ShellContentRendererClient::~ShellContentRendererClient() {\n", "}\n", "\n", "void ShellContentRendererClient::RenderThreadStarted() {\n", " // Initialize node after render thread is started\n", " v8::V8::Initialize();\n", " v8::HandleScope scope;\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" // Change working directory\n", " CommandLine* command_line = CommandLine::ForCurrentProcess();\n", " if (command_line->HasSwitch(switches::kWorkingDirectory)) {\n", " file_util::SetCurrentDirectory(\n", " command_line->GetSwitchValuePath(switches::kWorkingDirectory));\n", " }\n", "\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 47}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/menu/menu.h\"\n\nnamespace api {\n\nusing namespace v8;\n\nMenu::Menu(CreationOptions options) {\n}\n\nMenu::~Menu() {\n}\n\n} // namespace api\n", "file_path": "src/api/menu/menu_win.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0017202908638864756, 0.0005612641689367592, 0.0001738336286507547, 0.00017546610615681857, 0.0006691653397865593]} {"hunk": {"id": 5, "code_window": ["\n", "ShellContentRendererClient::~ShellContentRendererClient() {\n", "}\n", "\n", "void ShellContentRendererClient::RenderThreadStarted() {\n", " // Initialize node after render thread is started\n", " v8::V8::Initialize();\n", " v8::HandleScope scope;\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" // Change working directory\n", " CommandLine* command_line = CommandLine::ForCurrentProcess();\n", " if (command_line->HasSwitch(switches::kWorkingDirectory)) {\n", " file_util::SetCurrentDirectory(\n", " command_line->GetSwitchValuePath(switches::kWorkingDirectory));\n", " }\n", "\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 47}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/shell_javascript_dialog.h\"\n\n#import \n\n#import \"base/memory/scoped_nsobject.h\"\n#include \"base/sys_string_conversions.h\"\n#include \"content/nw/src/browser/shell_javascript_dialog_creator.h\"\n\n// Helper object that receives the notification that the dialog/sheet is\n// going away. Is responsible for cleaning itself up.\n@interface ShellJavaScriptDialogHelper : NSObject {\n @private\n scoped_nsobject alert_;\n NSTextField* textField_; // WEAK; owned by alert_\n\n // Copies of the fields in ShellJavaScriptDialog because they're private.\n content::ShellJavaScriptDialogCreator* creator_;\n content::JavaScriptDialogCreator::DialogClosedCallback callback_;\n}\n\n- (id)initHelperWithCreator:(content::ShellJavaScriptDialogCreator*)creator\n andCallback:(content::JavaScriptDialogCreator::DialogClosedCallback)callback;\n- (NSAlert*)alert;\n- (NSTextField*)textField;\n- (void)alertDidEnd:(NSAlert*)alert\n returnCode:(int)returnCode\n contextInfo:(void*)contextInfo;\n- (void)cancel;\n\n@end\n\n@implementation ShellJavaScriptDialogHelper\n\n- (id)initHelperWithCreator:(content::ShellJavaScriptDialogCreator*)creator\n andCallback:(content::JavaScriptDialogCreator::DialogClosedCallback)callback {\n if (self = [super init]) {\n creator_ = creator;\n callback_ = callback;\n }\n\n return self;\n}\n\n- (NSAlert*)alert {\n alert_.reset([[NSAlert alloc] init]);\n return alert_;\n}\n\n- (NSTextField*)textField {\n textField_ = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 22)];\n [[textField_ cell] setLineBreakMode:NSLineBreakByTruncatingTail];\n [alert_ setAccessoryView:textField_];\n [textField_ release];\n\n return textField_;\n}\n\n- (void)alertDidEnd:(NSAlert*)alert\n returnCode:(int)returnCode\n contextInfo:(void*)contextInfo {\n if (returnCode == NSRunStoppedResponse)\n return;\n\n bool success = returnCode == NSAlertFirstButtonReturn;\n string16 input;\n if (textField_)\n input = base::SysNSStringToUTF16([textField_ stringValue]);\n\n content::ShellJavaScriptDialog* native_dialog =\n reinterpret_cast(contextInfo);\n callback_.Run(success, input);\n creator_->DialogClosed(native_dialog);\n}\n\n- (void)cancel {\n [NSApp endSheet:[alert_ window]];\n alert_.reset();\n}\n\n@end\n\nnamespace content {\n\nShellJavaScriptDialog::ShellJavaScriptDialog(\n ShellJavaScriptDialogCreator* creator,\n gfx::NativeWindow parent_window,\n JavaScriptMessageType message_type,\n const string16& message_text,\n const string16& default_prompt_text,\n const JavaScriptDialogCreator::DialogClosedCallback& callback)\n : creator_(creator),\n callback_(callback) {\n bool text_field = message_type == JAVASCRIPT_MESSAGE_TYPE_PROMPT;\n bool one_button = message_type == JAVASCRIPT_MESSAGE_TYPE_ALERT;\n\n helper_ =\n [[ShellJavaScriptDialogHelper alloc] initHelperWithCreator:creator\n andCallback:callback];\n\n // Show the modal dialog.\n NSAlert* alert = [helper_ alert];\n NSTextField* field = nil;\n if (text_field) {\n field = [helper_ textField];\n [field setStringValue:base::SysUTF16ToNSString(default_prompt_text)];\n }\n [alert setDelegate:helper_];\n [alert setInformativeText:base::SysUTF16ToNSString(message_text)];\n [alert setMessageText:@\"Javascript alert\"];\n [alert addButtonWithTitle:@\"OK\"];\n if (!one_button) {\n NSButton* other = [alert addButtonWithTitle:@\"Cancel\"];\n [other setKeyEquivalent:@\"\\e\"];\n }\n\n [alert\n beginSheetModalForWindow:nil // nil here makes it app-modal\n modalDelegate:helper_\n didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)\n contextInfo:this];\n\n if ([alert accessoryView])\n [[alert window] makeFirstResponder:[alert accessoryView]];\n}\n\nShellJavaScriptDialog::~ShellJavaScriptDialog() {\n [helper_ release];\n}\n\nvoid ShellJavaScriptDialog::Cancel() {\n [helper_ cancel];\n}\n\n} // namespace content\n", "file_path": "src/browser/shell_javascript_dialog_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.002417774172499776, 0.0003803152940236032, 0.00016748496273066849, 0.00017440569354221225, 0.0005471268086694181]} {"hunk": {"id": 5, "code_window": ["\n", "ShellContentRendererClient::~ShellContentRendererClient() {\n", "}\n", "\n", "void ShellContentRendererClient::RenderThreadStarted() {\n", " // Initialize node after render thread is started\n", " v8::V8::Initialize();\n", " v8::HandleScope scope;\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" // Change working directory\n", " CommandLine* command_line = CommandLine::ForCurrentProcess();\n", " if (command_line->HasSwitch(switches::kWorkingDirectory)) {\n", " file_util::SetCurrentDirectory(\n", " command_line->GetSwitchValuePath(switches::kWorkingDirectory));\n", " }\n", "\n"], "file_path": "src/renderer/shell_content_renderer_client.cc", "type": "add", "edit_start_line_idx": 47}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_MEDIA_MEDIA_INTERNALS_H_\n#define CONTENT_NW_SRC_MEDIA_MEDIA_INTERNALS_H_\n\n#include \"base/memory/ref_counted.h\"\n#include \"base/memory/singleton.h\"\n#include \"base/observer_list.h\"\n#include \"base/values.h\"\n#include \"content/public/browser/media_observer.h\"\n\n// This class stores information about currently active media.\n// It's constructed on the UI thread but all of its methods are called on the IO\n// thread.\nclass MediaInternals : public content::MediaObserver {\n public:\n virtual ~MediaInternals();\n\n static MediaInternals* GetInstance();\n\n // Overridden from content::MediaObserver:\n virtual void OnDeleteAudioStream(void* host, int stream_id) OVERRIDE;\n virtual void OnSetAudioStreamPlaying(void* host,\n int stream_id,\n bool playing) OVERRIDE;\n virtual void OnSetAudioStreamStatus(void* host,\n int stream_id,\n const std::string& status) OVERRIDE;\n virtual void OnSetAudioStreamVolume(void* host,\n int stream_id,\n double volume) OVERRIDE;\n virtual void OnMediaEvent(int render_process_id,\n const media::MediaLogEvent& event) OVERRIDE;\n virtual void OnCaptureDevicesOpened(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) OVERRIDE;\n virtual void OnCaptureDevicesClosed(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) OVERRIDE;\n\n private:\n friend struct DefaultSingletonTraits;\n\n MediaInternals();\n\n DISALLOW_COPY_AND_ASSIGN(MediaInternals);\n};\n\n#endif // CONTENT_NW_SRC_MEDIA_MEDIA_INTERNALS_H_\n", "file_path": "src/media/media_internals.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017674698028713465, 0.00017107951862271875, 0.00016736700490582734, 0.0001701285073067993, 3.105803898506565e-06]} {"hunk": {"id": 6, "code_window": ["\n", "#include \"content/nw/src/shell_content_browser_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/file_path.h\"\n", "#include \"content/public/common/content_switches.h\"\n", "#include \"content/public/browser/browser_url_handler.h\"\n", "#include \"content/public/browser/resource_dispatcher_host.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_util.h\"\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/common/shell_switches.h\"\n\nnamespace switches {\n\n// Check whether all system dependencies for running layout tests are met.\nconst char kCheckLayoutTestSysDeps[] = \"check-layout-test-sys-deps\";\n\n// Tells Content Shell that it's running as a content_browsertest.\nconst char kContentBrowserTest[] = \"browser-test\";\n\n// Makes Content Shell use the given path for its data directory.\nconst char kContentShellDataPath[] = \"data-path\";\n\n// Enable developer tools\nconst char kDeveloper[] = \"developer\";\n\n// Request pages to be dumped as text once they finished loading.\nconst char kDumpRenderTree[] = \"dump-render-tree\";\n\n// Disables the timeout for layout tests.\nconst char kNoTimeout[] = \"no-timeout\";\n\n// Display no toolbar\nconst char kNoToolbar[] = \"no-toolbar\";\n\n// Show version and quit\nconst char kVersion[] = \"version\";\n\n// Open specified url\nconst char kUrl[] = \"url\";\n\nconst char kmMain[] = \"main\";\nconst char kmName[] = \"name\";\nconst char kmWebkit[] = \"webkit\";\nconst char kmNodejs[] = \"nodejs\";\nconst char kmRoot[] = \"root\";\nconst char kmWindow[] = \"window\";\nconst char kmTitle[] = \"title\";\nconst char kmToolbar[] = \"toolbar\";\nconst char kmIcon[] = \"icon\";\nconst char kmWidth[] = \"width\";\nconst char kmHeight[] = \"height\";\nconst char kmX[] = \"x\";\nconst char kmY[] = \"y\";\nconst char kmResizable[] = \"resizable\";\nconst char kmPosition[] = \"position\";\nconst char kmMinWidth[] = \"min_width\";\nconst char kmMinHeight[] = \"min_height\";\nconst char kmMaxWidth[] = \"max_width\";\nconst char kmMaxHeight[] = \"max_height\";\nconst char kmAsDesktop[] = \"as_desktop\";\n\n} // namespace switches\n", "file_path": "src/common/shell_switches.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00801808200776577, 0.0012251005973666906, 0.00016594049520790577, 0.00017415874754078686, 0.0025708952452987432]} {"hunk": {"id": 6, "code_window": ["\n", "#include \"content/nw/src/shell_content_browser_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/file_path.h\"\n", "#include \"content/public/common/content_switches.h\"\n", "#include \"content/public/browser/browser_url_handler.h\"\n", "#include \"content/public/browser/resource_dispatcher_host.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_util.h\"\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/v8_utils.h\"\n\nusing namespace v8;\n\nnamespace api {\n\nHandle CallMethod(Handle recv,\n const char* method,\n int argc,\n Handle argv[]) {\n Handle object = recv->ToObject();\n Handle func = Handle::Cast(\n object->Get(String::New(method)));\n return func->Call(object, argc, argv);\n}\n\n} // api\n\n", "file_path": "src/api/v8_utils.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0004064655804540962, 0.00023170423810370266, 0.00016988096467684954, 0.00017523521091789007, 0.00010092384763993323]} {"hunk": {"id": 6, "code_window": ["\n", "#include \"content/nw/src/shell_content_browser_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/file_path.h\"\n", "#include \"content/public/common/content_switches.h\"\n", "#include \"content/public/browser/browser_url_handler.h\"\n", "#include \"content/public/browser/resource_dispatcher_host.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_util.h\"\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/menu/menu.h\"\n\n#import \n#include \"content/nw/src/api/menuitem/menuitem.h\"\n\nnamespace api {\n\nusing namespace v8;\n\nMenu::Menu(CreationOption option) {\n menu_ = [[NSMenu alloc]\n initWithTitle:[NSString stringWithUTF8String:option.title.c_str()]];\n [menu_ setAutoenablesItems:NO];\n}\n\nMenu::~Menu() {\n [menu_ release];\n}\n\nvoid Menu::SetTitle(const std::string& title) {\n [menu_ setTitle:[NSString stringWithUTF8String:title.c_str()]];\n}\n\nstd::string Menu::GetTitle() {\n return [[menu_ title] UTF8String];\n}\n\nvoid Menu::Append(MenuItem* menu_item) {\n [menu_ addItem:menu_item->menu_item_];\n}\n\nvoid Menu::Insert(MenuItem* menu_item, int pos) {\n [menu_ insertItem:menu_item->menu_item_ atIndex:pos];\n}\n\nvoid Menu::Remove(MenuItem* menu_item) {\n [menu_ removeItem:menu_item->menu_item_];\n}\n\nvoid Menu::Remove(int pos) {\n [menu_ removeItemAtIndex:pos];\n}\n\n} // namespace api\n", "file_path": "src/api/menu/menu_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00020893767941743135, 0.00017643703904468566, 0.0001642814459046349, 0.00017312004638370126, 1.3697342183149885e-05]} {"hunk": {"id": 6, "code_window": ["\n", "#include \"content/nw/src/shell_content_browser_client.h\"\n", "\n", "#include \"base/command_line.h\"\n", "#include \"base/file_path.h\"\n", "#include \"content/public/common/content_switches.h\"\n", "#include \"content/public/browser/browser_url_handler.h\"\n", "#include \"content/public/browser/resource_dispatcher_host.h\"\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["#include \"base/file_util.h\"\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CHROME_BROWSER_PLATFORM_UTIL_H_\n#define CHROME_BROWSER_PLATFORM_UTIL_H_\n\n#include \n\n#include \"base/string16.h\"\n#include \"ui/gfx/native_widget_types.h\"\n\nclass FilePath;\nclass GURL;\n\nnamespace platform_util {\n\n// Show the given file in a file manager. If possible, select the file.\n// Must be called from the UI thread.\nvoid ShowItemInFolder(const FilePath& full_path);\n\n// Open the given file in the desktop's default manner.\n// Must be called from the UI thread.\nvoid OpenItem(const FilePath& full_path);\n\n// Open the given external protocol URL in the desktop's default manner.\n// (For example, mailto: URLs in the default mail user agent.)\nvoid OpenExternal(const GURL& url);\n\n// Get the top level window for the native view. This can return NULL.\ngfx::NativeWindow GetTopLevel(gfx::NativeView view);\n\n// Get the direct parent of |view|, may return NULL.\ngfx::NativeView GetParent(gfx::NativeView view);\n\n// Returns true if |window| is the foreground top level window.\nbool IsWindowActive(gfx::NativeWindow window);\n\n// Activate the window, bringing it to the foreground top level.\nvoid ActivateWindow(gfx::NativeWindow window);\n\n// Returns true if the view is visible. The exact definition of this is\n// platform-specific, but it is generally not \"visible to the user\", rather\n// whether the view has the visible attribute set.\nbool IsVisible(gfx::NativeView view);\n\n#if defined(OS_MACOSX)\n// On 10.7+, back and forward swipe gestures can be triggered using a scroll\n// gesture, if enabled in System Preferences. This function returns true if\n// the feature is supported and enabled, and false otherwise.\nbool IsSwipeTrackingFromScrollEventsEnabled();\n#endif\n\n} // platform_util\n\n#endif // CHROME_BROWSER_PLATFORM_UTIL_H_\n", "file_path": "src/browser/platform_util.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001890127023216337, 0.00017540475528221577, 0.00016295052773784846, 0.00017542639398016036, 9.999268513638526e-06]} {"hunk": {"id": 7, "code_window": [" // Disable web security\n", " command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n", " command_line->AppendSwitch(switches::kDisableWebSecurity);\n", "\n", " if (nw::GetManifest() && nw::GetUseNode())\n", " command_line->AppendSwitch(switches::kmNodejs);\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" if (nw::GetManifest() && nw::GetUseNode()) {\n", " // Whether to disable node\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 71}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/common/shell_switches.h\"\n\nnamespace switches {\n\n// Check whether all system dependencies for running layout tests are met.\nconst char kCheckLayoutTestSysDeps[] = \"check-layout-test-sys-deps\";\n\n// Tells Content Shell that it's running as a content_browsertest.\nconst char kContentBrowserTest[] = \"browser-test\";\n\n// Makes Content Shell use the given path for its data directory.\nconst char kContentShellDataPath[] = \"data-path\";\n\n// Enable developer tools\nconst char kDeveloper[] = \"developer\";\n\n// Request pages to be dumped as text once they finished loading.\nconst char kDumpRenderTree[] = \"dump-render-tree\";\n\n// Disables the timeout for layout tests.\nconst char kNoTimeout[] = \"no-timeout\";\n\n// Display no toolbar\nconst char kNoToolbar[] = \"no-toolbar\";\n\n// Show version and quit\nconst char kVersion[] = \"version\";\n\n// Open specified url\nconst char kUrl[] = \"url\";\n\nconst char kmMain[] = \"main\";\nconst char kmName[] = \"name\";\nconst char kmWebkit[] = \"webkit\";\nconst char kmNodejs[] = \"nodejs\";\nconst char kmRoot[] = \"root\";\nconst char kmWindow[] = \"window\";\nconst char kmTitle[] = \"title\";\nconst char kmToolbar[] = \"toolbar\";\nconst char kmIcon[] = \"icon\";\nconst char kmWidth[] = \"width\";\nconst char kmHeight[] = \"height\";\nconst char kmX[] = \"x\";\nconst char kmY[] = \"y\";\nconst char kmResizable[] = \"resizable\";\nconst char kmPosition[] = \"position\";\nconst char kmMinWidth[] = \"min_width\";\nconst char kmMinHeight[] = \"min_height\";\nconst char kmMaxWidth[] = \"max_width\";\nconst char kmMaxHeight[] = \"max_height\";\nconst char kmAsDesktop[] = \"as_desktop\";\n\n} // namespace switches\n", "file_path": "src/common/shell_switches.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.003938150126487017, 0.0007591347675770521, 0.0001650869962759316, 0.0001757228164933622, 0.0012364735594019294]} {"hunk": {"id": 7, "code_window": [" // Disable web security\n", " command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n", " command_line->AppendSwitch(switches::kDisableWebSecurity);\n", "\n", " if (nw::GetManifest() && nw::GetUseNode())\n", " command_line->AppendSwitch(switches::kmNodejs);\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" if (nw::GetManifest() && nw::GetUseNode()) {\n", " // Whether to disable node\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 71}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_PATHS_MAC_H_\n#define CONTENT_SHELL_PATHS_MAC_H_\n\n#include \"base/file_path.h\"\n\n// Sets up base::mac::FrameworkBundle.\nvoid OverrideFrameworkBundlePath();\n\n// Sets up the CHILD_PROCESS_EXE path to properly point to the helper app.\nvoid OverrideChildProcessPath();\n\n// Gets the path to the content shell's pak file.\nFilePath GetResourcesPakFilePath();\n\n#endif // CONTENT_SHELL_PATHS_MAC_H_\n", "file_path": "src/paths_mac.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001742408494465053, 0.00017072592163458467, 0.00016721099382266402, 0.00017072592163458467, 3.514927811920643e-06]} {"hunk": {"id": 7, "code_window": [" // Disable web security\n", " command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n", " command_line->AppendSwitch(switches::kDisableWebSecurity);\n", "\n", " if (nw::GetManifest() && nw::GetUseNode())\n", " command_line->AppendSwitch(switches::kmNodejs);\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" if (nw::GetManifest() && nw::GetUseNode()) {\n", " // Whether to disable node\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 71}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/v8_utils.h\"\n\nusing namespace v8;\n\nnamespace api {\n\nHandle CallMethod(Handle recv,\n const char* method,\n int argc,\n Handle argv[]) {\n Handle object = recv->ToObject();\n Handle func = Handle::Cast(\n object->Get(String::New(method)));\n return func->Call(object, argc, argv);\n}\n\n} // api\n\n", "file_path": "src/api/v8_utils.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001823161874199286, 0.00017804875096771866, 0.0001746447233017534, 0.00017761706840246916, 2.8064148409612244e-06]} {"hunk": {"id": 7, "code_window": [" // Disable web security\n", " command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n", " command_line->AppendSwitch(switches::kDisableWebSecurity);\n", "\n", " if (nw::GetManifest() && nw::GetUseNode())\n", " command_line->AppendSwitch(switches::kmNodejs);\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" if (nw::GetManifest() && nw::GetUseNode()) {\n", " // Whether to disable node\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 71}, "file": "\n\n \n 1060\n 11D50b\n 851\n 1138.32\n 568.00\n \n com.apple.InterfaceBuilder.CocoaPlugin\n 851\n \n \n YES\n \n \n \n YES\n com.apple.InterfaceBuilder.CocoaPlugin\n \n \n YES\n \n YES\n \n \n YES\n \n \n \n YES\n \n NSObject\n \n \n FirstResponder\n \n \n NSApplication\n \n \n \n 268\n \n YES\n \n \n 268\n {{99, 20}, {156, 22}}\n \n _NS:3407\n 2\n YES\n \n 343014976\n 272630848\n \n \n LucidaGrande\n 13\n 1040\n \n _NS:3407\n \n YES\n \n 6\n System\n textBackgroundColor\n \n 3\n MQA\n \n \n \n 6\n System\n textColor\n \n 3\n MAA\n \n \n \n YES\n NSAllRomanInputSourcesLocaleIdentifier\n \n \n \n \n \n 268\n {{99, 52}, {156, 22}}\n \n _NS:817\n 1\n YES\n \n -1804468671\n 272630784\n \n \n _NS:817\n \n YES\n \n \n \n \n \n \n 268\n {{17, 22}, {77, 17}}\n \n _NS:4068\n YES\n \n 68288064\n 71304192\n Password:\n \n _NS:4068\n \n \n 6\n System\n controlColor\n \n 3\n MC42NjY2NjY2NjY3AA\n \n \n \n 6\n System\n controlTextColor\n \n \n \n \n \n \n 268\n {{17, 54}, {77, 17}}\n \n _NS:4068\n YES\n \n 68288064\n 71304192\n Username:\n \n _NS:4068\n \n \n \n \n \n \n {275, 94}\n \n NSView\n \n \n \n \n YES\n \n \n \n YES\n \n 0\n \n \n \n \n \n -2\n \n \n File's Owner\n \n \n -1\n \n \n First Responder\n \n \n -3\n \n \n Application\n \n \n 1\n \n \n YES\n \n \n \n \n \n \n \n \n 2\n \n \n YES\n \n \n \n \n \n 3\n \n \n \n \n 4\n \n \n YES\n \n \n \n \n \n 5\n \n \n \n \n 6\n \n \n YES\n \n \n \n \n \n 7\n \n \n \n \n 8\n \n \n YES\n \n \n \n \n \n 9\n \n \n \n \n \n \n YES\n \n YES\n -1.IBPluginDependency\n -2.IBPluginDependency\n -3.IBPluginDependency\n 1.IBEditorWindowLastContentRect\n 1.IBPluginDependency\n 1.WindowOrigin\n 1.editorWindowContentRectSynchronizationRect\n 2.IBPluginDependency\n 2.IBViewBoundsToFrameTransform\n 3.IBPluginDependency\n 4.IBPluginDependency\n 4.IBViewBoundsToFrameTransform\n 5.IBPluginDependency\n 6.IBPluginDependency\n 6.IBViewBoundsToFrameTransform\n 7.IBPluginDependency\n 8.IBPluginDependency\n 8.IBViewBoundsToFrameTransform\n 9.IBPluginDependency\n \n \n YES\n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n {{969, 1048}, {275, 94}}\n com.apple.InterfaceBuilder.CocoaPlugin\n {628, 654}\n {{357, 416}, {480, 272}}\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABBiAAAwpAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABBiAAAwiAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABCxgAAwpAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABCxgAAwiAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n \n \n \n YES\n \n \n YES\n \n \n \n \n YES\n \n \n YES\n \n \n \n 9\n \n \n 0\n IBCocoaFramework\n \n com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3\n \n \n YES\n \n 3\n \n\n", "file_path": "src/mac/English.lproj/HttpAuth.xib", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.00017743271018844098, 0.00017185957403853536, 0.00016546538972761482, 0.00017193969688378274, 2.6922839424514677e-06]} {"hunk": {"id": 8, "code_window": [" command_line->AppendSwitch(switches::kmNodejs);\n", "}\n", "\n", "std::string ShellContentBrowserClient::GetApplicationLocale() {\n"], "labels": ["add", "keep", "keep", "keep"], "after_edit": ["\n", " // Set cwd\n", " FilePath cwd;\n", " file_util::GetCurrentDirectory(&cwd);\n", " command_line->AppendSwitchPath(switches::kWorkingDirectory, cwd);\n", " }\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 73}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_browser_client.h\"\n\n#include \"base/command_line.h\"\n#include \"base/file_path.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/browser/browser_url_handler.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_resource_dispatcher_host_delegate.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/nw/src/shell.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"geolocation/shell_access_token_store.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n\n#if defined(OS_ANDROID)\n#include \"base/android/path_utils.h\"\n#include \"base/path_service.h\"\n#include \"base/platform_file.h\"\n#include \"content/shell/android/shell_descriptors.h\"\n#endif\n\nnamespace content {\n\nShellContentBrowserClient::ShellContentBrowserClient()\n : shell_browser_main_parts_(NULL) {\n}\n\nShellContentBrowserClient::~ShellContentBrowserClient() {\n}\n\nBrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);\n return shell_browser_main_parts_;\n}\n\nvoid ShellContentBrowserClient::RenderViewHostCreated(\n RenderViewHost* render_view_host) {\n}\n\nvoid ShellContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line, int child_process_id) {\n // Disable web security\n command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n command_line->AppendSwitch(switches::kDisableWebSecurity);\n\n if (nw::GetManifest() && nw::GetUseNode())\n command_line->AppendSwitch(switches::kmNodejs);\n}\n\nstd::string ShellContentBrowserClient::GetApplicationLocale() {\n return l10n_util::GetApplicationLocale(\"en-US\");\n}\n\nvoid ShellContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new ShellResourceDispatcherHostDelegate());\n ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nstd::string ShellContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n\nMediaObserver* ShellContentBrowserClient::GetMediaObserver() {\n return MediaInternals::GetInstance();\n}\n\nvoid ShellContentBrowserClient::BrowserURLHandlerCreated(\n BrowserURLHandler* handler) {\n}\n\n#if defined(OS_ANDROID)\nvoid ShellContentBrowserClient::GetAdditionalMappedFilesForChildProcess(\n const CommandLine& command_line,\n base::GlobalDescriptors::Mapping* mappings) {\n int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;\n FilePath pak_file;\n DCHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_file));\n pak_file = pak_file.Append(FILE_PATH_LITERAL(\"paks\"));\n pak_file = pak_file.Append(FILE_PATH_LITERAL(\"nw.pak\"));\n\n base::PlatformFile f =\n base::CreatePlatformFile(pak_file, flags, NULL, NULL);\n if (f == base::kInvalidPlatformFileValue) {\n NOTREACHED() << \"Failed to open file when creating renderer process: \"\n << \"nw.pak\";\n }\n mappings->push_back(std::pair(\n kShellPakDescriptor, f));\n}\n#endif\n\nShellBrowserContext* ShellContentBrowserClient::browser_context() {\n return shell_browser_main_parts_->browser_context();\n}\n\nShellBrowserContext*\n ShellContentBrowserClient::off_the_record_browser_context() {\n return shell_browser_main_parts_->off_the_record_browser_context();\n}\n\nAccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {\n return new ShellAccessTokenStore(browser_context()->GetRequestContext());\n}\n\n} // namespace content\n", "file_path": "src/shell_content_browser_client.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.9987010955810547, 0.49944308400154114, 0.00016851580585353076, 0.5082817077636719, 0.4922875165939331]} {"hunk": {"id": 8, "code_window": [" command_line->AppendSwitch(switches::kmNodejs);\n", "}\n", "\n", "std::string ShellContentBrowserClient::GetApplicationLocale() {\n"], "labels": ["add", "keep", "keep", "keep"], "after_edit": ["\n", " // Set cwd\n", " FilePath cwd;\n", " file_util::GetCurrentDirectory(&cwd);\n", " command_line->AppendSwitchPath(switches::kWorkingDirectory, cwd);\n", " }\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 73}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n#define CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n\n#include \n\n#include \"base/compiler_specific.h\"\n#include \"base/memory/scoped_ptr.h\"\n#include \"content/public/browser/content_browser_client.h\"\n\nnamespace content {\n\nclass ShellBrowserContext;\nclass ShellBrowserMainParts;\nclass ShellResourceDispatcherHostDelegate;\n\nclass ShellContentBrowserClient : public ContentBrowserClient {\n public:\n ShellContentBrowserClient();\n virtual ~ShellContentBrowserClient();\n\n // ContentBrowserClient overrides.\n virtual BrowserMainParts* CreateBrowserMainParts(\n const MainFunctionParams& parameters) OVERRIDE;\n virtual void RenderViewHostCreated(\n RenderViewHost* render_view_host) OVERRIDE;\n virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,\n int child_process_id) OVERRIDE;\n virtual std::string GetApplicationLocale() OVERRIDE;\n virtual void ResourceDispatcherHostCreated() OVERRIDE;\n virtual AccessTokenStore* CreateAccessTokenStore() OVERRIDE;\n virtual std::string GetDefaultDownloadName() OVERRIDE;\n virtual MediaObserver* GetMediaObserver() OVERRIDE;\n virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) OVERRIDE;\n\n#if defined(OS_ANDROID)\n virtual void GetAdditionalMappedFilesForChildProcess(\n const CommandLine& command_line,\n base::GlobalDescriptors::Mapping* mappings) OVERRIDE;\n#endif\n\n ShellBrowserContext* browser_context();\n ShellBrowserContext* off_the_record_browser_context();\n ShellResourceDispatcherHostDelegate* resource_dispatcher_host_delegate() {\n return resource_dispatcher_host_delegate_.get();\n }\n ShellBrowserMainParts* shell_browser_main_parts() {\n return shell_browser_main_parts_;\n }\n\n private:\n scoped_ptr\n resource_dispatcher_host_delegate_;\n\n ShellBrowserMainParts* shell_browser_main_parts_;\n};\n\n} // namespace content\n\n#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n", "file_path": "src/shell_content_browser_client.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.9820531606674194, 0.277913898229599, 0.00016767240595072508, 0.002246206160634756, 0.435720831155777]} {"hunk": {"id": 8, "code_window": [" command_line->AppendSwitch(switches::kmNodejs);\n", "}\n", "\n", "std::string ShellContentBrowserClient::GetApplicationLocale() {\n"], "labels": ["add", "keep", "keep", "keep"], "after_edit": ["\n", " // Set cwd\n", " FilePath cwd;\n", " file_util::GetCurrentDirectory(&cwd);\n", " command_line->AppendSwitchPath(switches::kWorkingDirectory, cwd);\n", " }\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 73}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"zip_reader.h\"\n\n#include \"base/file_util.h\"\n#include \"base/logging.h\"\n#include \"base/string_util.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"net/base/file_stream.h\"\n#include \"third_party/zlib/contrib/minizip/unzip.h\"\n#if defined(OS_WIN)\n#include \"third_party/zlib/contrib/minizip/iowin32.h\"\n#endif\n#include \"zip_internal.h\"\n\nnamespace zip {\n\n// TODO(satorux): The implementation assumes that file names in zip files\n// are encoded in UTF-8. This is true for zip files created by Zip()\n// function in zip.h, but not true for user-supplied random zip files.\nZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip,\n const unz_file_info& raw_file_info)\n : file_path_(FilePath::FromUTF8Unsafe(file_name_in_zip)),\n is_directory_(false) {\n original_size_ = raw_file_info.uncompressed_size;\n\n // Directory entries in zip files end with \"/\".\n is_directory_ = EndsWith(file_name_in_zip, \"/\", false);\n\n // Check the file name here for directory traversal issues. In the name of\n // simplicity and security, we might reject a valid file name such as \"a..b\".\n is_unsafe_ = file_name_in_zip.find(\"..\") != std::string::npos;\n\n // We also consider that the file name is unsafe, if it's invalid UTF-8.\n string16 file_name_utf16;\n if (!UTF8ToUTF16(file_name_in_zip.data(), file_name_in_zip.size(),\n &file_name_utf16)) {\n is_unsafe_ = true;\n }\n\n // We also consider that the file name is unsafe, if it's absolute.\n // On Windows, IsAbsolute() returns false for paths starting with \"/\".\n if (file_path_.IsAbsolute() || StartsWithASCII(file_name_in_zip, \"/\", false))\n is_unsafe_ = true;\n\n // Construct the last modified time. The timezone info is not present in\n // zip files, so we construct the time as local time.\n base::Time::Exploded exploded_time = {}; // Zero-clear.\n exploded_time.year = raw_file_info.tmu_date.tm_year;\n // The month in zip file is 0-based, whereas ours is 1-based.\n exploded_time.month = raw_file_info.tmu_date.tm_mon + 1;\n exploded_time.day_of_month = raw_file_info.tmu_date.tm_mday;\n exploded_time.hour = raw_file_info.tmu_date.tm_hour;\n exploded_time.minute = raw_file_info.tmu_date.tm_min;\n exploded_time.second = raw_file_info.tmu_date.tm_sec;\n exploded_time.millisecond = 0;\n if (exploded_time.HasValidValues()) {\n last_modified_ = base::Time::FromLocalExploded(exploded_time);\n } else {\n // Use Unix time epoch if the time stamp data is invalid.\n last_modified_ = base::Time::UnixEpoch();\n }\n}\n\nZipReader::ZipReader() {\n Reset();\n}\n\nZipReader::~ZipReader() {\n Close();\n}\n\nbool ZipReader::Open(const FilePath& zip_file_path) {\n DCHECK(!zip_file_);\n\n // Use of \"Unsafe\" function does not look good, but there is no way to do\n // this safely on Linux. See file_util.h for details.\n zip_file_ = internal::OpenForUnzipping(zip_file_path.AsUTF8Unsafe());\n if (!zip_file_) {\n return false;\n }\n\n return OpenInternal();\n}\n\n#if defined(OS_POSIX)\nbool ZipReader::OpenFromFd(const int zip_fd) {\n DCHECK(!zip_file_);\n\n zip_file_ = internal::OpenFdForUnzipping(zip_fd);\n if (!zip_file_) {\n return false;\n }\n\n return OpenInternal();\n}\n#endif\n\nvoid ZipReader::Close() {\n if (zip_file_) {\n unzClose(zip_file_);\n }\n Reset();\n}\n\nbool ZipReader::HasMore() {\n return !reached_end_;\n}\n\nbool ZipReader::AdvanceToNextEntry() {\n DCHECK(zip_file_);\n\n // Should not go further if we already reached the end.\n if (reached_end_)\n return false;\n\n unz_file_pos position = {};\n if (unzGetFilePos(zip_file_, &position) != UNZ_OK)\n return false;\n const int current_entry_index = position.num_of_file;\n // If we are currently at the last entry, then the next position is the\n // end of the zip file, so mark that we reached the end.\n if (current_entry_index + 1 == num_entries_) {\n reached_end_ = true;\n } else {\n DCHECK_LT(current_entry_index + 1, num_entries_);\n if (unzGoToNextFile(zip_file_) != UNZ_OK) {\n return false;\n }\n }\n current_entry_info_.reset();\n return true;\n}\n\nbool ZipReader::OpenCurrentEntryInZip() {\n DCHECK(zip_file_);\n\n unz_file_info raw_file_info = {};\n char raw_file_name_in_zip[internal::kZipMaxPath] = {};\n const int result = unzGetCurrentFileInfo(zip_file_,\n &raw_file_info,\n raw_file_name_in_zip,\n sizeof(raw_file_name_in_zip) - 1,\n NULL, // extraField.\n 0, // extraFieldBufferSize.\n NULL, // szComment.\n 0); // commentBufferSize.\n if (result != UNZ_OK)\n return false;\n if (raw_file_name_in_zip[0] == '\\0')\n return false;\n current_entry_info_.reset(\n new EntryInfo(raw_file_name_in_zip, raw_file_info));\n return true;\n}\n\nbool ZipReader::LocateAndOpenEntry(const FilePath& path_in_zip) {\n DCHECK(zip_file_);\n\n current_entry_info_.reset();\n reached_end_ = false;\n const int kDefaultCaseSensivityOfOS = 0;\n const int result = unzLocateFile(zip_file_,\n path_in_zip.AsUTF8Unsafe().c_str(),\n kDefaultCaseSensivityOfOS);\n if (result != UNZ_OK)\n return false;\n\n // Then Open the entry.\n return OpenCurrentEntryInZip();\n}\n\nbool ZipReader::ExtractCurrentEntryToFilePath(\n const FilePath& output_file_path) {\n DCHECK(zip_file_);\n\n // If this is a directory, just create it and return.\n if (current_entry_info()->is_directory())\n return file_util::CreateDirectory(output_file_path);\n\n const int open_result = unzOpenCurrentFile(zip_file_);\n if (open_result != UNZ_OK)\n return false;\n\n // We can't rely on parent directory entries being specified in the\n // zip, so we make sure they are created.\n FilePath output_dir_path = output_file_path.DirName();\n if (!file_util::CreateDirectory(output_dir_path))\n return false;\n\n net::FileStream stream(NULL);\n const int flags = (base::PLATFORM_FILE_CREATE_ALWAYS |\n base::PLATFORM_FILE_WRITE);\n if (stream.OpenSync(output_file_path, flags) != 0)\n return false;\n\n bool success = true; // This becomes false when something bad happens.\n while (true) {\n char buf[internal::kZipBufSize];\n const int num_bytes_read = unzReadCurrentFile(zip_file_, buf,\n internal::kZipBufSize);\n if (num_bytes_read == 0) {\n // Reached the end of the file.\n break;\n } else if (num_bytes_read < 0) {\n // If num_bytes_read < 0, then it's a specific UNZ_* error code.\n success = false;\n break;\n } else if (num_bytes_read > 0) {\n // Some data is read. Write it to the output file.\n if (num_bytes_read != stream.WriteSync(buf, num_bytes_read)) {\n success = false;\n break;\n }\n }\n }\n\n stream.CloseSync();\n unzCloseCurrentFile(zip_file_);\n return success;\n}\n\nbool ZipReader::ExtractCurrentEntryIntoDirectory(\n const FilePath& output_directory_path) {\n DCHECK(current_entry_info_.get());\n\n FilePath output_file_path = output_directory_path.Append(\n current_entry_info()->file_path());\n return ExtractCurrentEntryToFilePath(output_file_path);\n}\n\n#if defined(OS_POSIX)\nbool ZipReader::ExtractCurrentEntryToFd(const int fd) {\n DCHECK(zip_file_);\n\n // If this is a directory, there's nothing to extract to the file descriptor,\n // so return false.\n if (current_entry_info()->is_directory())\n return false;\n\n const int open_result = unzOpenCurrentFile(zip_file_);\n if (open_result != UNZ_OK)\n return false;\n\n bool success = true; // This becomes false when something bad happens.\n while (true) {\n char buf[internal::kZipBufSize];\n const int num_bytes_read = unzReadCurrentFile(zip_file_, buf,\n internal::kZipBufSize);\n if (num_bytes_read == 0) {\n // Reached the end of the file.\n break;\n } else if (num_bytes_read < 0) {\n // If num_bytes_read < 0, then it's a specific UNZ_* error code.\n success = false;\n break;\n } else if (num_bytes_read > 0) {\n // Some data is read. Write it to the output file descriptor.\n if (num_bytes_read !=\n file_util::WriteFileDescriptor(fd, buf, num_bytes_read)) {\n success = false;\n break;\n }\n }\n }\n\n unzCloseCurrentFile(zip_file_);\n return success;\n}\n#endif // defined(OS_POSIX)\n\nbool ZipReader::OpenInternal() {\n DCHECK(zip_file_);\n\n unz_global_info zip_info = {}; // Zero-clear.\n if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) {\n return false;\n }\n num_entries_ = zip_info.number_entry;\n if (num_entries_ < 0)\n return false;\n\n // We are already at the end if the zip file is empty.\n reached_end_ = (num_entries_ == 0);\n return true;\n}\n\nvoid ZipReader::Reset() {\n zip_file_ = NULL;\n num_entries_ = 0;\n reached_end_ = false;\n current_entry_info_.reset();\n}\n\n} // namespace zip\n", "file_path": "src/common/zip_reader.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.0001923052332131192, 0.00017142538854386657, 0.00016646934091113508, 0.00017120670236181468, 4.548540346149821e-06]} {"hunk": {"id": 8, "code_window": [" command_line->AppendSwitch(switches::kmNodejs);\n", "}\n", "\n", "std::string ShellContentBrowserClient::GetApplicationLocale() {\n"], "labels": ["add", "keep", "keep", "keep"], "after_edit": ["\n", " // Set cwd\n", " FilePath cwd;\n", " file_util::GetCurrentDirectory(&cwd);\n", " command_line->AppendSwitchPath(switches::kWorkingDirectory, cwd);\n", " }\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 73}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"content/shell/geolocation/shell_access_token_store.h\"\n\n#include \"base/bind.h\"\n#include \"base/message_loop.h\"\n#include \"base/utf_string_conversions.h\"\n\nShellAccessTokenStore::ShellAccessTokenStore(\n net::URLRequestContextGetter* request_context)\n : request_context_(request_context) {\n}\n\nShellAccessTokenStore::~ShellAccessTokenStore() {\n}\n\nvoid ShellAccessTokenStore::LoadAccessTokens(\n const LoadAccessTokensCallbackType& callback) {\n MessageLoop::current()->PostTask(\n FROM_HERE,\n base::Bind(&ShellAccessTokenStore::DidLoadAccessTokens,\n request_context_, callback));\n}\n\nvoid ShellAccessTokenStore::DidLoadAccessTokens(\n net::URLRequestContextGetter* request_context,\n const LoadAccessTokensCallbackType& callback) {\n // Since content_shell is a test executable, rather than an end user program,\n // we provide a dummy access_token set to avoid hitting the server.\n AccessTokenSet access_token_set;\n access_token_set[GURL()] = ASCIIToUTF16(\"chromium_content_shell\");\n callback.Run(access_token_set, request_context);\n}\n\nvoid ShellAccessTokenStore::SaveAccessToken(\n const GURL& server_url, const string16& access_token) {\n}\n", "file_path": "src/geolocation/shell_access_token_store.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/74e4029e44d11d60e1d6a0ce285ae5ee401ebf51", "dependency_score": [0.005763125140219927, 0.0016555775655433536, 0.00017386993567924947, 0.00034265758586116135, 0.002375474665313959]} {"hunk": {"id": 0, "code_window": ["\n", "* Node has been updated to version\n", " [8.16.0](https://nodejs.org/en/blog/release/v8.16.0/).\n", "\n", "* The `meteor-babel` npm package has been updated to version 7.4.12.\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": ["* The `meteor-babel` npm package has been updated to version 7.4.13.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 13}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"@babel/code-frame\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz\",\n \"integrity\": \"sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==\"\n },\n \"@babel/core\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz\",\n \"integrity\": \"sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==\",\n \"dependencies\": {\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n }\n }\n },\n \"@babel/generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/generator/-/generator-7.4.4.tgz\",\n \"integrity\": \"sha512-53UOLK6TVNqKxf7RUh8NE851EHRxOOeVXKbK2bivdb+iziMyk03Sr4eaE9OELCbyZAAafAKPDwF2TPUES5QbxQ==\"\n },\n \"@babel/helper-annotate-as-pure\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.0.0.tgz\",\n \"integrity\": \"sha512-3UYcJUj9kvSLbLbUIfQTqzcy5VX7GRZ/CCDrnOaZorFFM01aXp1+GJwuFGV4NDDoAS+mOUyHcO6UD/RfqOks3Q==\"\n },\n \"@babel/helper-builder-binary-assignment-operator-visitor\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.1.0.tgz\",\n \"integrity\": \"sha512-qNSR4jrmJ8M1VMM9tibvyRAHXQs2PmaksQF7c1CGJNipfe3D8p+wgNwgso/P2A2r2mdgBWAXljNWR0QRZAMW8w==\"\n },\n \"@babel/helper-builder-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-react-jsx/-/helper-builder-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-MjA9KgwCuPEkQd9ncSXvSyJ5y+j2sICHyrI0M3L+6fnS4wMSNDc1ARXsbTfbb2cXHn17VisSnU/sHFTCxVxSMw==\"\n },\n \"@babel/helper-call-delegate\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.4.tgz\",\n \"integrity\": \"sha512-l79boDFJ8S1c5hvQvG+rc+wHw6IuH7YldmRKsYtpbawsxURu/paVy57FZMomGK22/JckepaikOkY0MoAmdyOlQ==\"\n },\n \"@babel/helper-create-class-features-plugin\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.4.4.tgz\",\n \"integrity\": \"sha512-UbBHIa2qeAGgyiNR9RszVF7bUHEdgS4JAUNT8SiqrAN6YJVxlOxeLr5pBzb5kan302dejJ9nla4RyKcR1XT6XA==\"\n },\n \"@babel/helper-define-map\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.4.4.tgz\",\n \"integrity\": \"sha512-IX3Ln8gLhZpSuqHJSnTNBWGDE9kdkTEWl21A/K7PQ00tseBwbqCHTvNLHSBd9M0R5rER4h5Rsvj9vw0R5SieBg==\"\n },\n \"@babel/helper-explode-assignable-expression\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.1.0.tgz\",\n \"integrity\": \"sha512-NRQpfHrJ1msCHtKjbzs9YcMmJZOg6mQMmGRB+hbamEdG5PNpaSm95275VD92DvJKuyl0s2sFiDmMZ+EnnvufqA==\"\n },\n \"@babel/helper-function-name\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz\",\n \"integrity\": \"sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==\"\n },\n \"@babel/helper-get-function-arity\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz\",\n \"integrity\": \"sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==\"\n },\n \"@babel/helper-hoist-variables\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.4.4.tgz\",\n \"integrity\": \"sha512-VYk2/H/BnYbZDDg39hr3t2kKyifAm1W6zHRfhx8jGjIHpQEBv9dry7oQ2f3+J703TLu69nYdxsovl0XYfcnK4w==\"\n },\n \"@babel/helper-member-expression-to-functions\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.0.0.tgz\",\n \"integrity\": \"sha512-avo+lm/QmZlv27Zsi0xEor2fKcqWG56D5ae9dzklpIaY7cQMK5N8VSpaNVPPagiqmy7LrEjK1IWdGMOqPu5csg==\"\n },\n \"@babel/helper-module-imports\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz\",\n \"integrity\": \"sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==\"\n },\n \"@babel/helper-module-transforms\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.4.4.tgz\",\n \"integrity\": \"sha512-3Z1yp8TVQf+B4ynN7WoHPKS8EkdTbgAEy0nU0rs/1Kw4pDgmvYH3rz3aI11KgxKCba2cn7N+tqzV1mY2HMN96w==\"\n },\n \"@babel/helper-optimise-call-expression\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.0.0.tgz\",\n \"integrity\": \"sha512-u8nd9NQePYNQV8iPWu/pLLYBqZBa4ZaY1YWRFMuxrid94wKI1QNt67NEZ7GAe5Kc/0LLScbim05xZFWkAdrj9g==\"\n },\n \"@babel/helper-plugin-utils\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz\",\n \"integrity\": \"sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==\"\n },\n \"@babel/helper-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-Y5nuB/kESmR3tKjU8Nkn1wMGEx1tjJX076HBMeL3XLQCu6vA/YRzuTW0bbb+qRnXvQGn+d6Rx953yffl8vEy7Q==\"\n },\n \"@babel/helper-remap-async-to-generator\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.1.0.tgz\",\n \"integrity\": \"sha512-3fOK0L+Fdlg8S5al8u/hWE6vhufGSn0bN09xm2LXMy//REAF8kDCrYoOBKYmA8m5Nom+sV9LyLCwrFynA8/slg==\"\n },\n \"@babel/helper-replace-supers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.4.4.tgz\",\n \"integrity\": \"sha512-04xGEnd+s01nY1l15EuMS1rfKktNF+1CkKmHoErDppjAAZL+IUBZpzT748x262HF7fibaQPhbvWUl5HeSt1EXg==\"\n },\n \"@babel/helper-simple-access\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz\",\n \"integrity\": \"sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==\"\n },\n \"@babel/helper-split-export-declaration\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz\",\n \"integrity\": \"sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==\"\n },\n \"@babel/helper-wrap-function\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.2.0.tgz\",\n \"integrity\": \"sha512-o9fP1BZLLSrYlxYEYyl2aS+Flun5gtjTIG8iln+XuEzQTs0PLagAGSXUcqruJwD5fM48jzIEggCKpIfWTcR7pQ==\"\n },\n \"@babel/helpers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helpers/-/helpers-7.4.4.tgz\",\n \"integrity\": \"sha512-igczbR/0SeuPR8RFfC7tGrbdTbFL3QTvH6D+Z6zNxnTe//GyqmtHmDkzrqDmyZ3eSwPqB/LhyKoU5DXsp+Vp2A==\"\n },\n \"@babel/highlight\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz\",\n \"integrity\": \"sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==\"\n },\n \"@babel/parser\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/parser/-/parser-7.4.5.tgz\",\n \"integrity\": \"sha512-9mUqkL1FF5T7f0WDFfAoDdiMVPWsdD1gZYzSnaXsxUCUqzuch/8of9G3VUSNiZmMBoRxT3neyVsqeiL/ZPcjew==\"\n },\n \"@babel/plugin-proposal-async-generator-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-+Dfo/SCQqrwx48ptLVGLdE39YtWRuKc/Y9I5Fy0P1DDBB9lsAHpjcEJQt+4IifuSOSTLBKJObJqMvaO1pIE8LQ==\"\n },\n \"@babel/plugin-proposal-class-properties\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.4.4.tgz\",\n \"integrity\": \"sha512-WjKTI8g8d5w1Bc9zgwSz2nfrsNQsXcCf9J9cdCvrJV6RF56yztwm4TmJC0MgJ9tvwO9gUA/mcYe89bLdGfiXFg==\"\n },\n \"@babel/plugin-proposal-object-rest-spread\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.4.4.tgz\",\n \"integrity\": \"sha512-dMBG6cSPBbHeEBdFXeQ2QLc5gUpg4Vkaz8octD4aoW/ISO+jBOcsuxYL7bsb5WSu8RLP6boxrBIALEHgoHtO9g==\"\n },\n \"@babel/plugin-syntax-async-generators\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.2.0.tgz\",\n \"integrity\": \"sha512-1ZrIRBv2t0GSlcwVoQ6VgSLpLgiN/FVQUzt9znxo7v2Ov4jJrs8RY8tv0wvDmFN3qIdMKWrmMMW6yZ0G19MfGg==\"\n },\n \"@babel/plugin-syntax-dynamic-import\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.2.0.tgz\",\n \"integrity\": \"sha512-mVxuJ0YroI/h/tbFTPGZR8cv6ai+STMKNBq0f8hFxsxWjl94qqhsb+wXbpNMDPU3cfR1TIsVFzU3nXyZMqyK4w==\"\n },\n \"@babel/plugin-syntax-flow\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.2.0.tgz\",\n \"integrity\": \"sha512-r6YMuZDWLtLlu0kqIim5o/3TNRAlWb073HwT3e2nKf9I8IIvOggPrnILYPsrrKilmn/mYEMCf/Z07w3yQJF6dg==\"\n },\n \"@babel/plugin-syntax-jsx\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.2.0.tgz\",\n \"integrity\": \"sha512-VyN4QANJkRW6lDBmENzRszvZf3/4AXaj9YR7GwrWeeN9tEBPuXbmDYVU9bYBN0D70zCWVwUy0HWq2553VCb6Hw==\"\n },\n \"@babel/plugin-syntax-object-rest-spread\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz\",\n \"integrity\": \"sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==\"\n },\n \"@babel/plugin-syntax-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-dGwbSMA1YhVS8+31CnPR7LB4pcbrzcV99wQzby4uAfrkZPYZlQ7ImwdpzLqi6Z6IL02b8IAL379CaMwo0x5Lag==\"\n },\n \"@babel/plugin-transform-arrow-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ER77Cax1+8/8jCB9fo4Ud161OZzWN5qawi4GusDuRLcDbDG+bIGYY20zb2dfAFdTRGzrfq2xZPvF0R64EHnimg==\"\n },\n \"@babel/plugin-transform-async-to-generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.4.4.tgz\",\n \"integrity\": \"sha512-YiqW2Li8TXmzgbXw+STsSqPBPFnGviiaSp6CYOq55X8GQ2SGVLrXB6pNid8HkqkZAzOH6knbai3snhP7v0fNwA==\"\n },\n \"@babel/plugin-transform-block-scoped-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ntQPR6q1/NKuphly49+QiQiTN0O63uOwjdD6dhIjSWBI5xlrbUFh720TIpzBhpnrLfv2tNH/BXvLIab1+BAI0w==\"\n },\n \"@babel/plugin-transform-block-scoping\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.4.4.tgz\",\n \"integrity\": \"sha512-jkTUyWZcTrwxu5DD4rWz6rDB5Cjdmgz6z7M7RLXOJyCUkFBawssDGcGh8M/0FTSB87avyJI1HsTwUXp9nKA1PA==\"\n },\n \"@babel/plugin-transform-classes\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.4.4.tgz\",\n \"integrity\": \"sha512-/e44eFLImEGIpL9qPxSRat13I5QNRgBLu2hOQJCF7VLy/otSM/sypV1+XaIw5+502RX/+6YaSAPmldk+nhHDPw==\"\n },\n \"@babel/plugin-transform-computed-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-kP/drqTxY6Xt3NNpKiMomfgkNn4o7+vKxK2DDKcBG9sHj51vHqMBGy8wbDS/J4lMxnqs153/T3+DmCEAkC5cpA==\"\n },\n \"@babel/plugin-transform-destructuring\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.4.4.tgz\",\n \"integrity\": \"sha512-/aOx+nW0w8eHiEHm+BTERB2oJn5D127iye/SUQl7NjHy0lf+j7h4MKMMSOwdazGq9OxgiNADncE+SRJkCxjZpQ==\"\n },\n \"@babel/plugin-transform-exponentiation-operator\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.2.0.tgz\",\n \"integrity\": \"sha512-umh4hR6N7mu4Elq9GG8TOu9M0bakvlsREEC+ialrQN6ABS4oDQ69qJv1VtR3uxlKMCQMCvzk7vr17RHKcjx68A==\"\n },\n \"@babel/plugin-transform-flow-strip-types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.4.4.tgz\",\n \"integrity\": \"sha512-WyVedfeEIILYEaWGAUWzVNyqG4sfsNooMhXWsu/YzOvVGcsnPb5PguysjJqI3t3qiaYj0BR8T2f5njdjTGe44Q==\"\n },\n \"@babel/plugin-transform-for-of\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.4.4.tgz\",\n \"integrity\": \"sha512-9T/5Dlr14Z9TIEXLXkt8T1DU7F24cbhwhMNUziN3hB1AXoZcdzPcTiKGRn/6iOymDqtTKWnr/BtRKN9JwbKtdQ==\"\n },\n \"@babel/plugin-transform-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-2ThDhm4lI4oV7fVQ6pNNK+sx+c/GM5/SaML0w/r4ZB7sAneD/piDJtwdKlNckXeyGK7wlwg2E2w33C/Hh+VFCg==\"\n },\n \"@babel/plugin-transform-modules-commonjs\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.4.4.tgz\",\n \"integrity\": \"sha512-4sfBOJt58sEo9a2BQXnZq+Q3ZTSAUXyK3E30o36BOGnJ+tvJ6YSxF0PG6kERvbeISgProodWuI9UVG3/FMY6iw==\"\n },\n \"@babel/plugin-transform-object-super\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.2.0.tgz\",\n \"integrity\": \"sha512-VMyhPYZISFZAqAPVkiYb7dUe2AsVi2/wCT5+wZdsNO31FojQJa9ns40hzZ6U9f50Jlq4w6qwzdBB2uwqZ00ebg==\"\n },\n \"@babel/plugin-transform-parameters\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.4.4.tgz\",\n \"integrity\": \"sha512-oMh5DUO1V63nZcu/ZVLQFqiihBGo4OpxJxR1otF50GMeCLiRx5nUdtokd+u9SuVJrvvuIh9OosRFPP4pIPnwmw==\"\n },\n \"@babel/plugin-transform-property-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-9q7Dbk4RhgcLp8ebduOpCbtjh7C0itoLYHXd9ueASKAG/is5PQtMR5VJGka9NKqGhYEGn5ITahd4h9QeBMylWQ==\"\n },\n \"@babel/plugin-transform-react-display-name\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.2.0.tgz\",\n \"integrity\": \"sha512-Htf/tPa5haZvRMiNSQSFifK12gtr/8vwfr+A9y69uF0QcU77AVu4K7MiHEkTxF7lQoHOL0F9ErqgfNEAKgXj7A==\"\n },\n \"@babel/plugin-transform-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-a/+aRb7R06WcKvQLOu4/TpjKOdvVEKRLWFpKcNuHhiREPgGRB4TQJxq07+EZLS8LFVYpfq1a5lDUnuMdcCpBKg==\"\n },\n \"@babel/plugin-transform-react-jsx-self\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.2.0.tgz\",\n \"integrity\": \"sha512-v6S5L/myicZEy+jr6ielB0OR8h+EH/1QFx/YJ7c7Ua+7lqsjj/vW6fD5FR9hB/6y7mGbfT4vAURn3xqBxsUcdg==\"\n },\n \"@babel/plugin-transform-react-jsx-source\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.2.0.tgz\",\n \"integrity\": \"sha512-A32OkKTp4i5U6aE88GwwcuV4HAprUgHcTq0sSafLxjr6AW0QahrCRCjxogkbbcdtpbXkuTOlgpjophCxb6sh5g==\"\n },\n \"@babel/plugin-transform-regenerator\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.5.tgz\",\n \"integrity\": \"sha512-gBKRh5qAaCWntnd09S8QC7r3auLCqq5DI6O0DlfoyDjslSBVqBibrMdsqO+Uhmx3+BlOmE/Kw1HFxmGbv0N9dA==\"\n },\n \"@babel/plugin-transform-runtime\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.4.4.tgz\",\n \"integrity\": \"sha512-aMVojEjPszvau3NRg+TIH14ynZLvPewH4xhlCW1w6A3rkxTS1m4uwzRclYR9oS+rl/dr+kT+pzbfHuAWP/lc7Q==\"\n },\n \"@babel/plugin-transform-shorthand-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-QP4eUM83ha9zmYtpbnyjTLAGKQritA5XW/iG9cjtuOI8s1RuL/3V6a3DeSHfKutJQ+ayUfeZJPcnCYEQzaPQqg==\"\n },\n \"@babel/plugin-transform-spread\": {\n \"version\": \"7.2.2\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.2.2.tgz\",\n \"integrity\": \"sha512-KWfky/58vubwtS0hLqEnrWJjsMGaOeSBn90Ezn5Jeg9Z8KKHmELbP1yGylMlm5N6TPKeY9A2+UaSYLdxahg01w==\"\n },\n \"@babel/plugin-transform-sticky-regex\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.2.0.tgz\",\n \"integrity\": \"sha512-KKYCoGaRAf+ckH8gEL3JHUaFVyNHKe3ASNsZ+AlktgHevvxGigoIttrEJb8iKN03Q7Eazlv1s6cx2B2cQ3Jabw==\"\n },\n \"@babel/plugin-transform-template-literals\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.4.4.tgz\",\n \"integrity\": \"sha512-mQrEC4TWkhLN0z8ygIvEL9ZEToPhG5K7KDW3pzGqOfIGZ28Jb0POUkeWcoz8HnHvhFy6dwAT1j8OzqN8s804+g==\"\n },\n \"@babel/plugin-transform-typeof-symbol\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.2.0.tgz\",\n \"integrity\": \"sha512-2LNhETWYxiYysBtrBTqL8+La0jIoQQnIScUJc74OYvUGRmkskNY4EzLCnjHBzdmb38wqtTaixpo1NctEcvMDZw==\"\n },\n \"@babel/plugin-transform-typescript\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.4.5.tgz\",\n \"integrity\": \"sha512-RPB/YeGr4ZrFKNwfuQRlMf2lxoCUaU01MTw39/OFE/RiL8HDjtn68BwEPft1P7JN4akyEmjGWAMNldOV7o9V2g==\"\n },\n \"@babel/plugin-transform-unicode-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-il+/XdNw01i93+M9J9u4T7/e/Ue/vWfNZE4IRUQjplu2Mqb/AFTDimkw2tdEdSH50wuQXZAbXSql0UphQke+vA==\"\n },\n \"@babel/preset-react\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.0.0.tgz\",\n \"integrity\": \"sha512-oayxyPS4Zj+hF6Et11BwuBkmpgT/zMxyuZgFrMeZID6Hdh3dGlk4sHCAhdBCpuCKW2ppBfl2uCCetlrUIJRY3w==\"\n },\n \"@babel/preset-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-mzMVuIP4lqtn4du2ynEfdO0+RYcslwrZiJHXu4MGaC1ctJiW2fyaeDrtjJGs7R/KebZ1sgowcIoWf4uRpEfKEg==\"\n },\n \"@babel/runtime\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/runtime/-/runtime-7.4.5.tgz\",\n \"integrity\": \"sha512-TuI4qpWZP6lGOGIuGWtp9sPluqYICmbk8T/1vpSysqJxRPkudh/ofFWyqdcMsDf2s7KvDL4/YHgKyvcS3g9CJQ==\"\n },\n \"@babel/template\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/template/-/template-7.4.4.tgz\",\n \"integrity\": \"sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw==\"\n },\n \"@babel/traverse\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/traverse/-/traverse-7.4.5.tgz\",\n \"integrity\": \"sha512-Vc+qjynwkjRmIFGxy0KYoPj4FdVDxLej89kMHFsWScq999uX+pwcX4v9mWRjW0KcAYTPAuVQl2LKP1wEVLsp+A==\"\n },\n \"@babel/types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/types/-/types-7.4.4.tgz\",\n \"integrity\": \"sha512-dOllgYdnEFOebhkKCjzSVFqw/PmmB8pH6RGOWkY4GsboQNd47b1fBThBSwlHAq9alF9vc1M3+6oqR47R50L0tQ==\"\n },\n \"acorn\": {\n \"version\": \"6.1.1\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz\",\n \"integrity\": \"sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==\"\n },\n \"acorn-dynamic-import\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz\",\n \"integrity\": \"sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==\"\n },\n \"ansi-styles\": {\n \"version\": \"3.2.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz\",\n \"integrity\": \"sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==\"\n },\n \"babel-helper-evaluate-path\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-evaluate-path/-/babel-helper-evaluate-path-0.5.0.tgz\",\n \"integrity\": \"sha512-mUh0UhS607bGh5wUMAQfOpt2JX2ThXMtppHRdRU1kL7ZLRWIXxoV2UIV1r2cAeeNeU1M5SB5/RSUgUxrK8yOkA==\"\n },\n \"babel-helper-flip-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-flip-expressions/-/babel-helper-flip-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-NpZzahKKwYvCUlS19AoizrPB0/0=\"\n },\n \"babel-helper-is-nodes-equiv\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-nodes-equiv/-/babel-helper-is-nodes-equiv-0.0.1.tgz\",\n \"integrity\": \"sha1-NOmzALFHnd2Y7HfqC76TQt/jloQ=\"\n },\n \"babel-helper-is-void-0\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-void-0/-/babel-helper-is-void-0-0.4.3.tgz\",\n \"integrity\": \"sha1-fZwBtFYee5Xb2g9u7kj1tg5nMT4=\"\n },\n \"babel-helper-mark-eval-scopes\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-mark-eval-scopes/-/babel-helper-mark-eval-scopes-0.4.3.tgz\",\n \"integrity\": \"sha1-0kSjvvmESHJgP/tG4izorN9VFWI=\"\n },\n \"babel-helper-remove-or-void\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-remove-or-void/-/babel-helper-remove-or-void-0.4.3.tgz\",\n \"integrity\": \"sha1-pPA7QAd6D/6I5F0HAQ3uJB/1rmA=\"\n },\n \"babel-helper-to-multiple-sequence-expressions\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-to-multiple-sequence-expressions/-/babel-helper-to-multiple-sequence-expressions-0.5.0.tgz\",\n \"integrity\": \"sha512-m2CvfDW4+1qfDdsrtf4dwOslQC3yhbgyBFptncp4wvtdrDHqueW7slsYv4gArie056phvQFhT2nRcGS4bnm6mA==\"\n },\n \"babel-plugin-minify-builtins\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-builtins/-/babel-plugin-minify-builtins-0.5.0.tgz\",\n \"integrity\": \"sha512-wpqbN7Ov5hsNwGdzuzvFcjgRlzbIeVv1gMIlICbPj0xkexnfoIDe7q+AZHMkQmAE/F9R5jkrB6TLfTegImlXag==\"\n },\n \"babel-plugin-minify-constant-folding\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-constant-folding/-/babel-plugin-minify-constant-folding-0.5.0.tgz\",\n \"integrity\": \"sha512-Vj97CTn/lE9hR1D+jKUeHfNy+m1baNiJ1wJvoGyOBUx7F7kJqDZxr9nCHjO/Ad+irbR3HzR6jABpSSA29QsrXQ==\"\n },\n \"babel-plugin-minify-dead-code-elimination\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-dead-code-elimination/-/babel-plugin-minify-dead-code-elimination-0.5.0.tgz\",\n \"integrity\": \"sha512-XQteBGXlgEoAKc/BhO6oafUdT4LBa7ARi55mxoyhLHNuA+RlzRmeMAfc31pb/UqU01wBzRc36YqHQzopnkd/6Q==\"\n },\n \"babel-plugin-minify-flip-comparisons\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-flip-comparisons/-/babel-plugin-minify-flip-comparisons-0.4.3.tgz\",\n \"integrity\": \"sha1-AMqHDLjxO0XAOLPB68DyJyk8llo=\"\n },\n \"babel-plugin-minify-guarded-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-guarded-expressions/-/babel-plugin-minify-guarded-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-zHCbRFP9IbHzAod0RMifiEJ845c=\"\n },\n \"babel-plugin-minify-infinity\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-infinity/-/babel-plugin-minify-infinity-0.4.3.tgz\",\n \"integrity\": \"sha1-37h2obCKBldjhO8/kuZTumB7Oco=\"\n },\n \"babel-plugin-minify-mangle-names\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-mangle-names/-/babel-plugin-minify-mangle-names-0.5.0.tgz\",\n \"integrity\": \"sha512-3jdNv6hCAw6fsX1p2wBGPfWuK69sfOjfd3zjUXkbq8McbohWy23tpXfy5RnToYWggvqzuMOwlId1PhyHOfgnGw==\"\n },\n \"babel-plugin-minify-numeric-literals\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-numeric-literals/-/babel-plugin-minify-numeric-literals-0.4.3.tgz\",\n \"integrity\": \"sha1-jk/VYcefeAEob/YOjF/Z3u6TwLw=\"\n },\n \"babel-plugin-minify-replace\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-replace/-/babel-plugin-minify-replace-0.5.0.tgz\",\n \"integrity\": \"sha512-aXZiaqWDNUbyNNNpWs/8NyST+oU7QTpK7J9zFEFSA0eOmtUNMU3fczlTTTlnCxHmq/jYNFEmkkSG3DDBtW3Y4Q==\"\n },\n \"babel-plugin-minify-simplify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-simplify/-/babel-plugin-minify-simplify-0.5.0.tgz\",\n \"integrity\": \"sha512-TM01J/YcKZ8XIQd1Z3nF2AdWHoDsarjtZ5fWPDksYZNsoOjQ2UO2EWm824Ym6sp127m44gPlLFiO5KFxU8pA5Q==\"\n },\n \"babel-plugin-minify-type-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-type-constructors/-/babel-plugin-minify-type-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-G8bxW4f3qxCF1CszC3F2V6IVZQA=\"\n },\n \"babel-plugin-transform-inline-consecutive-adds\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-inline-consecutive-adds/-/babel-plugin-transform-inline-consecutive-adds-0.4.3.tgz\",\n \"integrity\": \"sha1-Mj1Ho+pjqDp6w8gRro5pQfrysNE=\"\n },\n \"babel-plugin-transform-member-expression-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-member-expression-literals/-/babel-plugin-transform-member-expression-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-NwOcmgwzE6OUlfqsL/OmtbnQOL8=\"\n },\n \"babel-plugin-transform-merge-sibling-variables\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-merge-sibling-variables/-/babel-plugin-transform-merge-sibling-variables-6.9.4.tgz\",\n \"integrity\": \"sha1-hbQi/DN3tEnJ0c3kQIcgNTJAHa4=\"\n },\n \"babel-plugin-transform-minify-booleans\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-minify-booleans/-/babel-plugin-transform-minify-booleans-6.9.4.tgz\",\n \"integrity\": \"sha1-rLs+VqNVXdI5KOS1gtKFFi3SsZg=\"\n },\n \"babel-plugin-transform-property-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-property-literals/-/babel-plugin-transform-property-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-mMHSHiVXNlc/k+zlRFn2ziSYXTk=\"\n },\n \"babel-plugin-transform-regexp-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-regexp-constructors/-/babel-plugin-transform-regexp-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-WLd3W2OvzzMyj66aX4j71PsLSWU=\"\n },\n \"babel-plugin-transform-remove-console\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-console/-/babel-plugin-transform-remove-console-6.9.4.tgz\",\n \"integrity\": \"sha1-uYA2DAZzhOJLNXpYjYB9PINSd4A=\"\n },\n \"babel-plugin-transform-remove-debugger\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-debugger/-/babel-plugin-transform-remove-debugger-6.9.4.tgz\",\n \"integrity\": \"sha1-QrcnYxyXl44estGZp67IShgznvI=\"\n },\n \"babel-plugin-transform-remove-undefined\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-undefined/-/babel-plugin-transform-remove-undefined-0.5.0.tgz\",\n \"integrity\": \"sha512-+M7fJYFaEE/M9CXa0/IRkDbiV3wRELzA1kKQFCJ4ifhrzLKn/9VCCgj9OFmYWwBd8IB48YdgPkHYtbYq+4vtHQ==\"\n },\n \"babel-plugin-transform-simplify-comparison-operators\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-simplify-comparison-operators/-/babel-plugin-transform-simplify-comparison-operators-6.9.4.tgz\",\n \"integrity\": \"sha1-9ir+CWyrDh9ootdT/fKDiIRxzrk=\"\n },\n \"babel-plugin-transform-undefined-to-void\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-undefined-to-void/-/babel-plugin-transform-undefined-to-void-6.9.4.tgz\",\n \"integrity\": \"sha1-viQcqBQEAwZ4t0hxcyK4nQyP4oA=\"\n },\n \"babel-preset-meteor\": {\n \"version\": \"7.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-meteor/-/babel-preset-meteor-7.4.3.tgz\",\n \"integrity\": \"sha512-0nxAvTPAQMMIRM64KcQN3sLgQQSjM41vFZY4lqpAc1vZ9SA3UeYbmMaZ6tqONveiQ09IwTukkVIiAeQd5/mw1Q==\"\n },\n \"babel-preset-minify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-minify/-/babel-preset-minify-0.5.0.tgz\",\n \"integrity\": \"sha512-xj1s9Mon+RFubH569vrGCayA9Fm2GMsCgDRm1Jb8SgctOB7KFcrVc2o8K3YHUyMz+SWP8aea75BoS8YfsXXuiA==\"\n },\n \"chalk\": {\n \"version\": \"2.4.2\",\n \"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz\",\n \"integrity\": \"sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==\"\n },\n \"color-convert\": {\n \"version\": \"1.9.3\",\n \"resolved\": \"https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz\",\n \"integrity\": \"sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==\"\n },\n \"color-name\": {\n \"version\": \"1.1.3\",\n \"resolved\": \"https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz\",\n \"integrity\": \"sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=\"\n },\n \"convert-source-map\": {\n \"version\": \"1.6.0\",\n \"resolved\": \"https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz\",\n \"integrity\": \"sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==\"\n },\n \"debug\": {\n \"version\": \"4.1.1\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-4.1.1.tgz\",\n \"integrity\": \"sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==\"\n },\n \"escape-string-regexp\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz\",\n \"integrity\": \"sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=\"\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"globals\": {\n \"version\": \"11.12.0\",\n \"resolved\": \"https://registry.npmjs.org/globals/-/globals-11.12.0.tgz\",\n \"integrity\": \"sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==\"\n },\n \"has-flag\": {\n \"version\": \"3.0.0\",\n \"resolved\": \"https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz\",\n \"integrity\": \"sha1-tdRU3CGZriJWmfNGfloH87lVuv0=\"\n },\n \"js-tokens\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz\",\n \"integrity\": \"sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==\"\n },\n \"jsesc\": {\n \"version\": \"2.5.2\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz\",\n \"integrity\": \"sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==\"\n },\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n },\n \"lodash\": {\n \"version\": \"4.17.11\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz\",\n \"integrity\": \"sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==\"\n },\n \"lodash.isplainobject\": {\n \"version\": \"4.0.6\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz\",\n \"integrity\": \"sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=\"\n },\n \"lodash.some\": {\n \"version\": \"4.6.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n },\n \"meteor-babel\": {\n \"version\": \"7.4.12\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n },\n \"meteor-babel-helpers\": {\n \"version\": \"0.0.3\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel-helpers/-/meteor-babel-helpers-0.0.3.tgz\",\n \"integrity\": \"sha1-8uXZ+HlvvS6JAQI9dpnlsgLqn7A=\"\n },\n \"minimist\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz\",\n \"integrity\": \"sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=\"\n },\n \"ms\": {\n \"version\": \"2.1.2\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-2.1.2.tgz\",\n \"integrity\": \"sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==\"\n },\n \"path-parse\": {\n \"version\": \"1.0.6\",\n \"resolved\": \"https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz\",\n \"integrity\": \"sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==\"\n },\n \"private\": {\n \"version\": \"0.1.8\",\n \"resolved\": \"https://registry.npmjs.org/private/-/private-0.1.8.tgz\",\n \"integrity\": \"sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==\"\n },\n \"regenerate\": {\n \"version\": \"1.4.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz\",\n \"integrity\": \"sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==\"\n },\n \"regenerate-unicode-properties\": {\n \"version\": \"8.1.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz\",\n \"integrity\": \"sha512-LGZzkgtLY79GeXLm8Dp0BVLdQlWICzBnJz/ipWUgo59qBaZ+BHtq51P2q1uVZlppMuUAT37SDk39qUbjTWB7bA==\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.13.2\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.2.tgz\",\n \"integrity\": \"sha512-S/TQAZJO+D3m9xeN1WTI8dLKBBiRgXBlTJvbWjCThHWZj9EvHK70Ff50/tYj2J/fvBY6JtFVwRuazHN2E7M9BA==\"\n },\n \"regenerator-transform\": {\n \"version\": \"0.14.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.14.0.tgz\",\n \"integrity\": \"sha512-rtOelq4Cawlbmq9xuMR5gdFmv7ku/sFoB7sRiywx7aq53bc52b4j6zvH7Te1Vt/X2YveDKnCGUbioieU7FEL3w==\"\n },\n \"regexpu-core\": {\n \"version\": \"4.5.4\",\n \"resolved\": \"https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.5.4.tgz\",\n \"integrity\": \"sha512-BtizvGtFQKGPUcTy56o3nk1bGRp4SZOTYrDtGNlqCQufptV5IkkLN6Emw+yunAJjzf+C9FQFtvq7IoA3+oMYHQ==\"\n },\n \"regjsgen\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.0.tgz\",\n \"integrity\": \"sha512-RnIrLhrXCX5ow/E5/Mh2O4e/oa1/jW0eaBKTSy3LaCj+M3Bqvm97GWDp2yUtzIs4LEn65zR2yiYGFqb2ApnzDA==\"\n },\n \"regjsparser\": {\n \"version\": \"0.6.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.0.tgz\",\n \"integrity\": \"sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ==\",\n \"dependencies\": {\n \"jsesc\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz\",\n \"integrity\": \"sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=\"\n }\n }\n },\n \"reify\": {\n \"version\": \"0.20.4\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n },\n \"resolve\": {\n \"version\": \"1.11.0\",\n \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n },\n \"safe-buffer\": {\n \"version\": \"5.1.2\",\n \"resolved\": \"https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz\",\n \"integrity\": \"sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==\"\n },\n \"semver\": {\n \"version\": \"5.7.0\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.7.0.tgz\",\n \"integrity\": \"sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==\"\n },\n \"source-map\": {\n \"version\": \"0.5.7\",\n \"resolved\": \"https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz\",\n \"integrity\": \"sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=\"\n },\n \"supports-color\": {\n \"version\": \"5.5.0\",\n \"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz\",\n \"integrity\": \"sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==\"\n },\n \"to-fast-properties\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz\",\n \"integrity\": \"sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=\"\n },\n \"trim-right\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz\",\n \"integrity\": \"sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=\"\n },\n \"unicode-canonical-property-names-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ==\"\n },\n \"unicode-match-property-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg==\"\n },\n \"unicode-match-property-value-ecmascript\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz\",\n \"integrity\": \"sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g==\"\n },\n \"unicode-property-aliases-ecmascript\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz\",\n \"integrity\": \"sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw==\"\n }\n }\n}\n", "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00026854811585508287, 0.00016961769142653793, 0.00016353688261006027, 0.00016695511294528842, 1.2917221283714753e-05]} {"hunk": {"id": 0, "code_window": ["\n", "* Node has been updated to version\n", " [8.16.0](https://nodejs.org/en/blog/release/v8.16.0/).\n", "\n", "* The `meteor-babel` npm package has been updated to version 7.4.12.\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": ["* The `meteor-babel` npm package has been updated to version 7.4.13.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 13}, "file": "//\n// When an oauth request is made, Meteor receives oauth credentials\n// in one browser tab, and temporarily persists them while that\n// tab is closed, then retrieves them in the browser tab that\n// initiated the credential request.\n//\n// _pendingCredentials is the storage mechanism used to share the\n// credential between the 2 tabs\n//\n\n\n// Collection containing pending credentials of oauth credential requests\n// Has key, credential, and createdAt fields.\nOAuth._pendingCredentials = new Mongo.Collection(\n \"meteor_oauth_pendingCredentials\", {\n _preventAutopublish: true\n });\n\nOAuth._pendingCredentials._ensureIndex('key', {unique: 1});\nOAuth._pendingCredentials._ensureIndex('credentialSecret');\nOAuth._pendingCredentials._ensureIndex('createdAt');\n\n\n\n// Periodically clear old entries that were never retrieved\nconst _cleanStaleResults = () => {\n // Remove credentials older than 1 minute\n const timeCutoff = new Date();\n timeCutoff.setMinutes(timeCutoff.getMinutes() - 1);\n OAuth._pendingCredentials.remove({ createdAt: { $lt: timeCutoff } });\n};\nconst _cleanupHandle = Meteor.setInterval(_cleanStaleResults, 60 * 1000);\n\n\n// Stores the key and credential in the _pendingCredentials collection.\n// Will throw an exception if `key` is not a string.\n//\n// @param key {string}\n// @param credential {Object} The credential to store\n// @param credentialSecret {string} A secret that must be presented in\n// addition to the `key` to retrieve the credential\n//\nOAuth._storePendingCredential = (key, credential, credentialSecret = null) => {\n check(key, String);\n check(credentialSecret, Match.Maybe(String));\n\n if (credential instanceof Error) {\n credential = storableError(credential);\n } else {\n credential = OAuth.sealSecret(credential);\n }\n\n // We do an upsert here instead of an insert in case the user happens\n // to somehow send the same `state` parameter twice during an OAuth\n // login; we don't want a duplicate key error.\n OAuth._pendingCredentials.upsert({\n key,\n }, {\n key,\n credential,\n credentialSecret,\n createdAt: new Date()\n });\n};\n\n\n// Retrieves and removes a credential from the _pendingCredentials collection\n//\n// @param key {string}\n// @param credentialSecret {string}\n//\nOAuth._retrievePendingCredential = (key, credentialSecret = null) => {\n check(key, String);\n\n const pendingCredential = OAuth._pendingCredentials.findOne({\n key,\n credentialSecret,\n });\n\n if (pendingCredential) {\n OAuth._pendingCredentials.remove({ _id: pendingCredential._id });\n if (pendingCredential.credential.error)\n return recreateError(pendingCredential.credential.error);\n else\n return OAuth.openSecret(pendingCredential.credential);\n } else {\n return undefined;\n }\n};\n\n\n// Convert an Error into an object that can be stored in mongo\n// Note: A Meteor.Error is reconstructed as a Meteor.Error\n// All other error classes are reconstructed as a plain Error.\n// TODO: Can we do this more simply with EJSON?\nconst storableError = error => {\n const plainObject = {};\n Object.getOwnPropertyNames(error).forEach(\n key => plainObject[key] = error[key]\n );\n\n // Keep track of whether it's a Meteor.Error\n if(error instanceof Meteor.Error) {\n plainObject['meteorError'] = true;\n }\n\n return { error: plainObject };\n};\n\n// Create an error from the error format stored in mongo\nconst recreateError = errorDoc => {\n let error;\n\n if (errorDoc.meteorError) {\n error = new Meteor.Error();\n delete errorDoc.meteorError;\n } else {\n error = new Error();\n }\n\n Object.getOwnPropertyNames(errorDoc).forEach(key =>\n error[key] = errorDoc[key]\n );\n\n return error;\n};\n", "file_path": "packages/oauth/pending_credentials.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001911693689180538, 0.00017139186093118042, 0.00016369883087463677, 0.00016852334374561906, 7.422347607644042e-06]} {"hunk": {"id": 0, "code_window": ["\n", "* Node has been updated to version\n", " [8.16.0](https://nodejs.org/en/blog/release/v8.16.0/).\n", "\n", "* The `meteor-babel` npm package has been updated to version 7.4.12.\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": ["* The `meteor-babel` npm package has been updated to version 7.4.13.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 13}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"lolex\": {\n \"version\": \"2.3.1\",\n \"resolved\": \"https://registry.npmjs.org/lolex/-/lolex-2.3.1.tgz\",\n \"integrity\": \"sha512-mQuW55GhduF3ppo+ZRUTz1PRjEh1hS5BbqU7d8D0ez2OKxHDod7StPPeAVKisZR5aLkHZjdGWSL42LSONUJsZw==\"\n }\n }\n}\n", "file_path": "packages/ddp-client/.npm/package/npm-shrinkwrap.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001703447342151776, 0.00016811357636470348, 0.00016588241851422936, 0.00016811357636470348, 2.231157850474119e-06]} {"hunk": {"id": 0, "code_window": ["\n", "* Node has been updated to version\n", " [8.16.0](https://nodejs.org/en/blog/release/v8.16.0/).\n", "\n", "* The `meteor-babel` npm package has been updated to version 7.4.12.\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": ["* The `meteor-babel` npm package has been updated to version 7.4.13.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 13}, "file": "var assert = require(\"assert\");\nvar files = require('../fs/files.js');\nvar _ = require(\"underscore\");\n\n// This class encapsulates a structured specification of files and\n// directories that should be stripped from the node_modules directories\n// of Meteor packages during `meteor build`, as requested by calling\n// `Npm.discard` in package.js files.\nfunction NpmDiscards() {\n assert.ok(this instanceof NpmDiscards);\n this.discards = {};\n}\n\nvar NDp = NpmDiscards.prototype;\n\n// Update the current specification of discarded files with additional\n// patterns that should be discarded. See the comment in package-source.js\n// about `Npm.strip` for an explanation of what should be passed for the\n// `discards` parameter.\nNDp.merge = function(discards) {\n merge(this.discards, discards);\n};\n\nfunction merge(into, from) {\n _.each(from, function(fromValue, packageName) {\n var intoValue = _.has(into, packageName) && into[packageName];\n if (_.isString(fromValue) ||\n _.isRegExp(fromValue)) {\n if (intoValue) {\n intoValue.push(fromValue);\n } else {\n into[packageName] = [fromValue];\n }\n } else if (_.isArray(fromValue)) {\n if (intoValue) {\n intoValue.push.apply(intoValue, fromValue);\n } else {\n // Make a defensive copy of any arrays passed to `Npm.strip`.\n into[packageName] = fromValue.slice(0);\n }\n }\n });\n}\n\nNDp.shouldDiscard = function shouldDiscard(candidatePath, isDirectory) {\n if (typeof isDirectory === \"undefined\") {\n isDirectory = files.lstat(candidatePath).isDirectory();\n }\n\n for (var currentPath = candidatePath, parentPath;\n (parentPath = files.pathDirname(currentPath)) !== currentPath;\n currentPath = parentPath) {\n if (files.pathBasename(parentPath) === \"node_modules\") {\n var packageName = files.pathBasename(currentPath);\n\n if (_.has(this.discards, packageName)) {\n var relPath = files.pathRelative(currentPath, candidatePath);\n\n if (isDirectory) {\n relPath = files.pathJoin(relPath, files.pathSep);\n }\n\n return this.discards[packageName].some(function(pattern) {\n return matches(pattern, relPath);\n });\n }\n\n // Stop at the first ancestor node_modules directory we find.\n break;\n }\n }\n\n return false;\n};\n\n// TODO Improve this. For example we don't currently support wildcard\n// string patterns (just use a RegExp if you need that flexibility).\nfunction matches(pattern, relPath) {\n if (_.isRegExp(pattern)) {\n return relPath.match(pattern);\n }\n\n assert.ok(_.isString(pattern));\n\n if (pattern.charAt(0) === files.pathSep) {\n return relPath.indexOf(pattern.slice(1)) === 0;\n }\n\n return relPath.indexOf(pattern) !== -1;\n}\n\nmodule.exports = NpmDiscards;\n", "file_path": "tools/isobuild/npm-discards.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0003262848767917603, 0.00018385831208433956, 0.00016597576905041933, 0.00016806458006612957, 4.750003063236363e-05]} {"hunk": {"id": 1, "code_window": ["\n", "* The `reify` npm package has been updated to version 0.20.4.\n", "\n", "* The `core-js` npm package used by `ecmascript-runtime-client` and\n", " `ecmascript-runtime-server` has been updated to version 3.1.4.\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.20.5.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 15}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"acorn\": {\n \"version\": \"6.1.1\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz\",\n \"integrity\": \"sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==\"\n },\n \"acorn-dynamic-import\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz\",\n \"integrity\": \"sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==\"\n },\n \"reify\": {\n \"version\": \"0.20.4\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n },\n \"semver\": {\n \"version\": \"5.7.0\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.7.0.tgz\",\n \"integrity\": \"sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==\"\n }\n }\n}\n", "file_path": "packages/modules/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00018103999900631607, 0.00017111963825300336, 0.00016612064791843295, 0.0001661982823861763, 7.01482213116833e-06]} {"hunk": {"id": 1, "code_window": ["\n", "* The `reify` npm package has been updated to version 0.20.4.\n", "\n", "* The `core-js` npm package used by `ecmascript-runtime-client` and\n", " `ecmascript-runtime-server` has been updated to version 3.1.4.\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.20.5.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 15}, "file": "export const name = module.id;\n", "file_path": "tools/tests/apps/dynamic-import/packages/colon-name/dynamic.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001677896361798048, 0.0001677896361798048, 0.0001677896361798048, 0.0001677896361798048, 0.0]} {"hunk": {"id": 1, "code_window": ["\n", "* The `reify` npm package has been updated to version 0.20.4.\n", "\n", "* The `core-js` npm package used by `ecmascript-runtime-client` and\n", " `ecmascript-runtime-server` has been updated to version 3.1.4.\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.20.5.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 15}, "file": "Package.describe({\n summary: 'CSS minifier',\n version: '1.4.2'\n});\n\nNpm.depends({\n postcss: '7.0.14',\n cssnano: '4.1.9'\n});\n\nPackage.onUse(function (api) {\n api.use('ecmascript');\n api.mainModule('minifier.js', 'server');\n api.export('CssTools');\n});\n\nPackage.onTest(function (api) {\n api.use('ecmascript');\n api.use('tinytest');\n api.addFiles([\n 'minifier-tests.js',\n 'urlrewriting-tests.js'\n ], 'server');\n});\n", "file_path": "packages/minifier-css/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00019732402870431542, 0.00017634721007198095, 0.00016441136540379375, 0.000167306192452088, 1.4879867194395047e-05]} {"hunk": {"id": 1, "code_window": ["\n", "* The `reify` npm package has been updated to version 0.20.4.\n", "\n", "* The `core-js` npm package used by `ecmascript-runtime-client` and\n", " `ecmascript-runtime-server` has been updated to version 3.1.4.\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": ["* The `reify` npm package has been updated to version 0.20.5.\n"], "file_path": "History.md", "type": "replace", "edit_start_line_idx": 15}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"bluebird\": {\n \"version\": \"2.11.0\",\n \"resolved\": \"https://registry.npmjs.org/bluebird/-/bluebird-2.11.0.tgz\",\n \"integrity\": \"sha1-U0uQM8AiyVecVro7Plpcqvu2UOE=\"\n },\n \"combined-stream2\": {\n \"version\": \"1.1.2\",\n \"resolved\": \"https://registry.npmjs.org/combined-stream2/-/combined-stream2-1.1.2.tgz\",\n \"integrity\": \"sha1-9uFLegFWZvjHsKH6xQYkAWSsNXA=\"\n },\n \"debug\": {\n \"version\": \"2.6.9\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-2.6.9.tgz\",\n \"integrity\": \"sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==\"\n },\n \"ms\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-2.0.0.tgz\",\n \"integrity\": \"sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=\"\n },\n \"stream-length\": {\n \"version\": \"1.0.2\",\n \"resolved\": \"https://registry.npmjs.org/stream-length/-/stream-length-1.0.2.tgz\",\n \"integrity\": \"sha1-gnfzy+5JpNqrz9tOL0qbXp8snwA=\"\n }\n }\n}\n", "file_path": "packages/boilerplate-generator/.npm/package/npm-shrinkwrap.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00016930917627178133, 0.00016684544971212745, 0.00016578819486312568, 0.00016614218475297093, 1.4344419696499244e-06]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n", " \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n", " },\n", " \"meteor-babel\": {\n", " \"version\": \"7.4.12\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n", " \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n", " },\n", " \"meteor-babel-helpers\": {\n", " \"version\": \"0.0.3\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"7.4.13\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.13.tgz\",\n", " \"integrity\": \"sha512-NAOh0UOzFd1rs3HmyerYlIWo6LyExqXwgn/hom1ZYCyd0ytL1Pm9dH7AZiM1gOiV50tjBWdMxx08fM5B5ScZDA==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 606}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"@babel/code-frame\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz\",\n \"integrity\": \"sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==\"\n },\n \"@babel/core\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz\",\n \"integrity\": \"sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==\",\n \"dependencies\": {\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n }\n }\n },\n \"@babel/generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/generator/-/generator-7.4.4.tgz\",\n \"integrity\": \"sha512-53UOLK6TVNqKxf7RUh8NE851EHRxOOeVXKbK2bivdb+iziMyk03Sr4eaE9OELCbyZAAafAKPDwF2TPUES5QbxQ==\"\n },\n \"@babel/helper-annotate-as-pure\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.0.0.tgz\",\n \"integrity\": \"sha512-3UYcJUj9kvSLbLbUIfQTqzcy5VX7GRZ/CCDrnOaZorFFM01aXp1+GJwuFGV4NDDoAS+mOUyHcO6UD/RfqOks3Q==\"\n },\n \"@babel/helper-builder-binary-assignment-operator-visitor\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.1.0.tgz\",\n \"integrity\": \"sha512-qNSR4jrmJ8M1VMM9tibvyRAHXQs2PmaksQF7c1CGJNipfe3D8p+wgNwgso/P2A2r2mdgBWAXljNWR0QRZAMW8w==\"\n },\n \"@babel/helper-builder-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-react-jsx/-/helper-builder-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-MjA9KgwCuPEkQd9ncSXvSyJ5y+j2sICHyrI0M3L+6fnS4wMSNDc1ARXsbTfbb2cXHn17VisSnU/sHFTCxVxSMw==\"\n },\n \"@babel/helper-call-delegate\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.4.tgz\",\n \"integrity\": \"sha512-l79boDFJ8S1c5hvQvG+rc+wHw6IuH7YldmRKsYtpbawsxURu/paVy57FZMomGK22/JckepaikOkY0MoAmdyOlQ==\"\n },\n \"@babel/helper-create-class-features-plugin\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.4.4.tgz\",\n \"integrity\": \"sha512-UbBHIa2qeAGgyiNR9RszVF7bUHEdgS4JAUNT8SiqrAN6YJVxlOxeLr5pBzb5kan302dejJ9nla4RyKcR1XT6XA==\"\n },\n \"@babel/helper-define-map\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.4.4.tgz\",\n \"integrity\": \"sha512-IX3Ln8gLhZpSuqHJSnTNBWGDE9kdkTEWl21A/K7PQ00tseBwbqCHTvNLHSBd9M0R5rER4h5Rsvj9vw0R5SieBg==\"\n },\n \"@babel/helper-explode-assignable-expression\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.1.0.tgz\",\n \"integrity\": \"sha512-NRQpfHrJ1msCHtKjbzs9YcMmJZOg6mQMmGRB+hbamEdG5PNpaSm95275VD92DvJKuyl0s2sFiDmMZ+EnnvufqA==\"\n },\n \"@babel/helper-function-name\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz\",\n \"integrity\": \"sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==\"\n },\n \"@babel/helper-get-function-arity\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz\",\n \"integrity\": \"sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==\"\n },\n \"@babel/helper-hoist-variables\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.4.4.tgz\",\n \"integrity\": \"sha512-VYk2/H/BnYbZDDg39hr3t2kKyifAm1W6zHRfhx8jGjIHpQEBv9dry7oQ2f3+J703TLu69nYdxsovl0XYfcnK4w==\"\n },\n \"@babel/helper-member-expression-to-functions\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.0.0.tgz\",\n \"integrity\": \"sha512-avo+lm/QmZlv27Zsi0xEor2fKcqWG56D5ae9dzklpIaY7cQMK5N8VSpaNVPPagiqmy7LrEjK1IWdGMOqPu5csg==\"\n },\n \"@babel/helper-module-imports\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz\",\n \"integrity\": \"sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==\"\n },\n \"@babel/helper-module-transforms\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.4.4.tgz\",\n \"integrity\": \"sha512-3Z1yp8TVQf+B4ynN7WoHPKS8EkdTbgAEy0nU0rs/1Kw4pDgmvYH3rz3aI11KgxKCba2cn7N+tqzV1mY2HMN96w==\"\n },\n \"@babel/helper-optimise-call-expression\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.0.0.tgz\",\n \"integrity\": \"sha512-u8nd9NQePYNQV8iPWu/pLLYBqZBa4ZaY1YWRFMuxrid94wKI1QNt67NEZ7GAe5Kc/0LLScbim05xZFWkAdrj9g==\"\n },\n \"@babel/helper-plugin-utils\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz\",\n \"integrity\": \"sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==\"\n },\n \"@babel/helper-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-Y5nuB/kESmR3tKjU8Nkn1wMGEx1tjJX076HBMeL3XLQCu6vA/YRzuTW0bbb+qRnXvQGn+d6Rx953yffl8vEy7Q==\"\n },\n \"@babel/helper-remap-async-to-generator\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.1.0.tgz\",\n \"integrity\": \"sha512-3fOK0L+Fdlg8S5al8u/hWE6vhufGSn0bN09xm2LXMy//REAF8kDCrYoOBKYmA8m5Nom+sV9LyLCwrFynA8/slg==\"\n },\n \"@babel/helper-replace-supers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.4.4.tgz\",\n \"integrity\": \"sha512-04xGEnd+s01nY1l15EuMS1rfKktNF+1CkKmHoErDppjAAZL+IUBZpzT748x262HF7fibaQPhbvWUl5HeSt1EXg==\"\n },\n \"@babel/helper-simple-access\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz\",\n \"integrity\": \"sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==\"\n },\n \"@babel/helper-split-export-declaration\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz\",\n \"integrity\": \"sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==\"\n },\n \"@babel/helper-wrap-function\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.2.0.tgz\",\n \"integrity\": \"sha512-o9fP1BZLLSrYlxYEYyl2aS+Flun5gtjTIG8iln+XuEzQTs0PLagAGSXUcqruJwD5fM48jzIEggCKpIfWTcR7pQ==\"\n },\n \"@babel/helpers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helpers/-/helpers-7.4.4.tgz\",\n \"integrity\": \"sha512-igczbR/0SeuPR8RFfC7tGrbdTbFL3QTvH6D+Z6zNxnTe//GyqmtHmDkzrqDmyZ3eSwPqB/LhyKoU5DXsp+Vp2A==\"\n },\n \"@babel/highlight\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz\",\n \"integrity\": \"sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==\"\n },\n \"@babel/parser\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/parser/-/parser-7.4.5.tgz\",\n \"integrity\": \"sha512-9mUqkL1FF5T7f0WDFfAoDdiMVPWsdD1gZYzSnaXsxUCUqzuch/8of9G3VUSNiZmMBoRxT3neyVsqeiL/ZPcjew==\"\n },\n \"@babel/plugin-proposal-async-generator-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-+Dfo/SCQqrwx48ptLVGLdE39YtWRuKc/Y9I5Fy0P1DDBB9lsAHpjcEJQt+4IifuSOSTLBKJObJqMvaO1pIE8LQ==\"\n },\n \"@babel/plugin-proposal-class-properties\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.4.4.tgz\",\n \"integrity\": \"sha512-WjKTI8g8d5w1Bc9zgwSz2nfrsNQsXcCf9J9cdCvrJV6RF56yztwm4TmJC0MgJ9tvwO9gUA/mcYe89bLdGfiXFg==\"\n },\n \"@babel/plugin-proposal-object-rest-spread\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.4.4.tgz\",\n \"integrity\": \"sha512-dMBG6cSPBbHeEBdFXeQ2QLc5gUpg4Vkaz8octD4aoW/ISO+jBOcsuxYL7bsb5WSu8RLP6boxrBIALEHgoHtO9g==\"\n },\n \"@babel/plugin-syntax-async-generators\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.2.0.tgz\",\n \"integrity\": \"sha512-1ZrIRBv2t0GSlcwVoQ6VgSLpLgiN/FVQUzt9znxo7v2Ov4jJrs8RY8tv0wvDmFN3qIdMKWrmMMW6yZ0G19MfGg==\"\n },\n \"@babel/plugin-syntax-dynamic-import\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.2.0.tgz\",\n \"integrity\": \"sha512-mVxuJ0YroI/h/tbFTPGZR8cv6ai+STMKNBq0f8hFxsxWjl94qqhsb+wXbpNMDPU3cfR1TIsVFzU3nXyZMqyK4w==\"\n },\n \"@babel/plugin-syntax-flow\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.2.0.tgz\",\n \"integrity\": \"sha512-r6YMuZDWLtLlu0kqIim5o/3TNRAlWb073HwT3e2nKf9I8IIvOggPrnILYPsrrKilmn/mYEMCf/Z07w3yQJF6dg==\"\n },\n \"@babel/plugin-syntax-jsx\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.2.0.tgz\",\n \"integrity\": \"sha512-VyN4QANJkRW6lDBmENzRszvZf3/4AXaj9YR7GwrWeeN9tEBPuXbmDYVU9bYBN0D70zCWVwUy0HWq2553VCb6Hw==\"\n },\n \"@babel/plugin-syntax-object-rest-spread\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz\",\n \"integrity\": \"sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==\"\n },\n \"@babel/plugin-syntax-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-dGwbSMA1YhVS8+31CnPR7LB4pcbrzcV99wQzby4uAfrkZPYZlQ7ImwdpzLqi6Z6IL02b8IAL379CaMwo0x5Lag==\"\n },\n \"@babel/plugin-transform-arrow-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ER77Cax1+8/8jCB9fo4Ud161OZzWN5qawi4GusDuRLcDbDG+bIGYY20zb2dfAFdTRGzrfq2xZPvF0R64EHnimg==\"\n },\n \"@babel/plugin-transform-async-to-generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.4.4.tgz\",\n \"integrity\": \"sha512-YiqW2Li8TXmzgbXw+STsSqPBPFnGviiaSp6CYOq55X8GQ2SGVLrXB6pNid8HkqkZAzOH6knbai3snhP7v0fNwA==\"\n },\n \"@babel/plugin-transform-block-scoped-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ntQPR6q1/NKuphly49+QiQiTN0O63uOwjdD6dhIjSWBI5xlrbUFh720TIpzBhpnrLfv2tNH/BXvLIab1+BAI0w==\"\n },\n \"@babel/plugin-transform-block-scoping\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.4.4.tgz\",\n \"integrity\": \"sha512-jkTUyWZcTrwxu5DD4rWz6rDB5Cjdmgz6z7M7RLXOJyCUkFBawssDGcGh8M/0FTSB87avyJI1HsTwUXp9nKA1PA==\"\n },\n \"@babel/plugin-transform-classes\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.4.4.tgz\",\n \"integrity\": \"sha512-/e44eFLImEGIpL9qPxSRat13I5QNRgBLu2hOQJCF7VLy/otSM/sypV1+XaIw5+502RX/+6YaSAPmldk+nhHDPw==\"\n },\n \"@babel/plugin-transform-computed-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-kP/drqTxY6Xt3NNpKiMomfgkNn4o7+vKxK2DDKcBG9sHj51vHqMBGy8wbDS/J4lMxnqs153/T3+DmCEAkC5cpA==\"\n },\n \"@babel/plugin-transform-destructuring\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.4.4.tgz\",\n \"integrity\": \"sha512-/aOx+nW0w8eHiEHm+BTERB2oJn5D127iye/SUQl7NjHy0lf+j7h4MKMMSOwdazGq9OxgiNADncE+SRJkCxjZpQ==\"\n },\n \"@babel/plugin-transform-exponentiation-operator\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.2.0.tgz\",\n \"integrity\": \"sha512-umh4hR6N7mu4Elq9GG8TOu9M0bakvlsREEC+ialrQN6ABS4oDQ69qJv1VtR3uxlKMCQMCvzk7vr17RHKcjx68A==\"\n },\n \"@babel/plugin-transform-flow-strip-types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.4.4.tgz\",\n \"integrity\": \"sha512-WyVedfeEIILYEaWGAUWzVNyqG4sfsNooMhXWsu/YzOvVGcsnPb5PguysjJqI3t3qiaYj0BR8T2f5njdjTGe44Q==\"\n },\n \"@babel/plugin-transform-for-of\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.4.4.tgz\",\n \"integrity\": \"sha512-9T/5Dlr14Z9TIEXLXkt8T1DU7F24cbhwhMNUziN3hB1AXoZcdzPcTiKGRn/6iOymDqtTKWnr/BtRKN9JwbKtdQ==\"\n },\n \"@babel/plugin-transform-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-2ThDhm4lI4oV7fVQ6pNNK+sx+c/GM5/SaML0w/r4ZB7sAneD/piDJtwdKlNckXeyGK7wlwg2E2w33C/Hh+VFCg==\"\n },\n \"@babel/plugin-transform-modules-commonjs\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.4.4.tgz\",\n \"integrity\": \"sha512-4sfBOJt58sEo9a2BQXnZq+Q3ZTSAUXyK3E30o36BOGnJ+tvJ6YSxF0PG6kERvbeISgProodWuI9UVG3/FMY6iw==\"\n },\n \"@babel/plugin-transform-object-super\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.2.0.tgz\",\n \"integrity\": \"sha512-VMyhPYZISFZAqAPVkiYb7dUe2AsVi2/wCT5+wZdsNO31FojQJa9ns40hzZ6U9f50Jlq4w6qwzdBB2uwqZ00ebg==\"\n },\n \"@babel/plugin-transform-parameters\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.4.4.tgz\",\n \"integrity\": \"sha512-oMh5DUO1V63nZcu/ZVLQFqiihBGo4OpxJxR1otF50GMeCLiRx5nUdtokd+u9SuVJrvvuIh9OosRFPP4pIPnwmw==\"\n },\n \"@babel/plugin-transform-property-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-9q7Dbk4RhgcLp8ebduOpCbtjh7C0itoLYHXd9ueASKAG/is5PQtMR5VJGka9NKqGhYEGn5ITahd4h9QeBMylWQ==\"\n },\n \"@babel/plugin-transform-react-display-name\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.2.0.tgz\",\n \"integrity\": \"sha512-Htf/tPa5haZvRMiNSQSFifK12gtr/8vwfr+A9y69uF0QcU77AVu4K7MiHEkTxF7lQoHOL0F9ErqgfNEAKgXj7A==\"\n },\n \"@babel/plugin-transform-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-a/+aRb7R06WcKvQLOu4/TpjKOdvVEKRLWFpKcNuHhiREPgGRB4TQJxq07+EZLS8LFVYpfq1a5lDUnuMdcCpBKg==\"\n },\n \"@babel/plugin-transform-react-jsx-self\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.2.0.tgz\",\n \"integrity\": \"sha512-v6S5L/myicZEy+jr6ielB0OR8h+EH/1QFx/YJ7c7Ua+7lqsjj/vW6fD5FR9hB/6y7mGbfT4vAURn3xqBxsUcdg==\"\n },\n \"@babel/plugin-transform-react-jsx-source\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.2.0.tgz\",\n \"integrity\": \"sha512-A32OkKTp4i5U6aE88GwwcuV4HAprUgHcTq0sSafLxjr6AW0QahrCRCjxogkbbcdtpbXkuTOlgpjophCxb6sh5g==\"\n },\n \"@babel/plugin-transform-regenerator\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.5.tgz\",\n \"integrity\": \"sha512-gBKRh5qAaCWntnd09S8QC7r3auLCqq5DI6O0DlfoyDjslSBVqBibrMdsqO+Uhmx3+BlOmE/Kw1HFxmGbv0N9dA==\"\n },\n \"@babel/plugin-transform-runtime\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.4.4.tgz\",\n \"integrity\": \"sha512-aMVojEjPszvau3NRg+TIH14ynZLvPewH4xhlCW1w6A3rkxTS1m4uwzRclYR9oS+rl/dr+kT+pzbfHuAWP/lc7Q==\"\n },\n \"@babel/plugin-transform-shorthand-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-QP4eUM83ha9zmYtpbnyjTLAGKQritA5XW/iG9cjtuOI8s1RuL/3V6a3DeSHfKutJQ+ayUfeZJPcnCYEQzaPQqg==\"\n },\n \"@babel/plugin-transform-spread\": {\n \"version\": \"7.2.2\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.2.2.tgz\",\n \"integrity\": \"sha512-KWfky/58vubwtS0hLqEnrWJjsMGaOeSBn90Ezn5Jeg9Z8KKHmELbP1yGylMlm5N6TPKeY9A2+UaSYLdxahg01w==\"\n },\n \"@babel/plugin-transform-sticky-regex\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.2.0.tgz\",\n \"integrity\": \"sha512-KKYCoGaRAf+ckH8gEL3JHUaFVyNHKe3ASNsZ+AlktgHevvxGigoIttrEJb8iKN03Q7Eazlv1s6cx2B2cQ3Jabw==\"\n },\n \"@babel/plugin-transform-template-literals\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.4.4.tgz\",\n \"integrity\": \"sha512-mQrEC4TWkhLN0z8ygIvEL9ZEToPhG5K7KDW3pzGqOfIGZ28Jb0POUkeWcoz8HnHvhFy6dwAT1j8OzqN8s804+g==\"\n },\n \"@babel/plugin-transform-typeof-symbol\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.2.0.tgz\",\n \"integrity\": \"sha512-2LNhETWYxiYysBtrBTqL8+La0jIoQQnIScUJc74OYvUGRmkskNY4EzLCnjHBzdmb38wqtTaixpo1NctEcvMDZw==\"\n },\n \"@babel/plugin-transform-typescript\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.4.5.tgz\",\n \"integrity\": \"sha512-RPB/YeGr4ZrFKNwfuQRlMf2lxoCUaU01MTw39/OFE/RiL8HDjtn68BwEPft1P7JN4akyEmjGWAMNldOV7o9V2g==\"\n },\n \"@babel/plugin-transform-unicode-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-il+/XdNw01i93+M9J9u4T7/e/Ue/vWfNZE4IRUQjplu2Mqb/AFTDimkw2tdEdSH50wuQXZAbXSql0UphQke+vA==\"\n },\n \"@babel/preset-react\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.0.0.tgz\",\n \"integrity\": \"sha512-oayxyPS4Zj+hF6Et11BwuBkmpgT/zMxyuZgFrMeZID6Hdh3dGlk4sHCAhdBCpuCKW2ppBfl2uCCetlrUIJRY3w==\"\n },\n \"@babel/preset-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-mzMVuIP4lqtn4du2ynEfdO0+RYcslwrZiJHXu4MGaC1ctJiW2fyaeDrtjJGs7R/KebZ1sgowcIoWf4uRpEfKEg==\"\n },\n \"@babel/runtime\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/runtime/-/runtime-7.4.5.tgz\",\n \"integrity\": \"sha512-TuI4qpWZP6lGOGIuGWtp9sPluqYICmbk8T/1vpSysqJxRPkudh/ofFWyqdcMsDf2s7KvDL4/YHgKyvcS3g9CJQ==\"\n },\n \"@babel/template\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/template/-/template-7.4.4.tgz\",\n \"integrity\": \"sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw==\"\n },\n \"@babel/traverse\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/traverse/-/traverse-7.4.5.tgz\",\n \"integrity\": \"sha512-Vc+qjynwkjRmIFGxy0KYoPj4FdVDxLej89kMHFsWScq999uX+pwcX4v9mWRjW0KcAYTPAuVQl2LKP1wEVLsp+A==\"\n },\n \"@babel/types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/types/-/types-7.4.4.tgz\",\n \"integrity\": \"sha512-dOllgYdnEFOebhkKCjzSVFqw/PmmB8pH6RGOWkY4GsboQNd47b1fBThBSwlHAq9alF9vc1M3+6oqR47R50L0tQ==\"\n },\n \"acorn\": {\n \"version\": \"6.1.1\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz\",\n \"integrity\": \"sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==\"\n },\n \"acorn-dynamic-import\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz\",\n \"integrity\": \"sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==\"\n },\n \"ansi-styles\": {\n \"version\": \"3.2.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz\",\n \"integrity\": \"sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==\"\n },\n \"babel-helper-evaluate-path\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-evaluate-path/-/babel-helper-evaluate-path-0.5.0.tgz\",\n \"integrity\": \"sha512-mUh0UhS607bGh5wUMAQfOpt2JX2ThXMtppHRdRU1kL7ZLRWIXxoV2UIV1r2cAeeNeU1M5SB5/RSUgUxrK8yOkA==\"\n },\n \"babel-helper-flip-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-flip-expressions/-/babel-helper-flip-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-NpZzahKKwYvCUlS19AoizrPB0/0=\"\n },\n \"babel-helper-is-nodes-equiv\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-nodes-equiv/-/babel-helper-is-nodes-equiv-0.0.1.tgz\",\n \"integrity\": \"sha1-NOmzALFHnd2Y7HfqC76TQt/jloQ=\"\n },\n \"babel-helper-is-void-0\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-void-0/-/babel-helper-is-void-0-0.4.3.tgz\",\n \"integrity\": \"sha1-fZwBtFYee5Xb2g9u7kj1tg5nMT4=\"\n },\n \"babel-helper-mark-eval-scopes\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-mark-eval-scopes/-/babel-helper-mark-eval-scopes-0.4.3.tgz\",\n \"integrity\": \"sha1-0kSjvvmESHJgP/tG4izorN9VFWI=\"\n },\n \"babel-helper-remove-or-void\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-remove-or-void/-/babel-helper-remove-or-void-0.4.3.tgz\",\n \"integrity\": \"sha1-pPA7QAd6D/6I5F0HAQ3uJB/1rmA=\"\n },\n \"babel-helper-to-multiple-sequence-expressions\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-to-multiple-sequence-expressions/-/babel-helper-to-multiple-sequence-expressions-0.5.0.tgz\",\n \"integrity\": \"sha512-m2CvfDW4+1qfDdsrtf4dwOslQC3yhbgyBFptncp4wvtdrDHqueW7slsYv4gArie056phvQFhT2nRcGS4bnm6mA==\"\n },\n \"babel-plugin-minify-builtins\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-builtins/-/babel-plugin-minify-builtins-0.5.0.tgz\",\n \"integrity\": \"sha512-wpqbN7Ov5hsNwGdzuzvFcjgRlzbIeVv1gMIlICbPj0xkexnfoIDe7q+AZHMkQmAE/F9R5jkrB6TLfTegImlXag==\"\n },\n \"babel-plugin-minify-constant-folding\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-constant-folding/-/babel-plugin-minify-constant-folding-0.5.0.tgz\",\n \"integrity\": \"sha512-Vj97CTn/lE9hR1D+jKUeHfNy+m1baNiJ1wJvoGyOBUx7F7kJqDZxr9nCHjO/Ad+irbR3HzR6jABpSSA29QsrXQ==\"\n },\n \"babel-plugin-minify-dead-code-elimination\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-dead-code-elimination/-/babel-plugin-minify-dead-code-elimination-0.5.0.tgz\",\n \"integrity\": \"sha512-XQteBGXlgEoAKc/BhO6oafUdT4LBa7ARi55mxoyhLHNuA+RlzRmeMAfc31pb/UqU01wBzRc36YqHQzopnkd/6Q==\"\n },\n \"babel-plugin-minify-flip-comparisons\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-flip-comparisons/-/babel-plugin-minify-flip-comparisons-0.4.3.tgz\",\n \"integrity\": \"sha1-AMqHDLjxO0XAOLPB68DyJyk8llo=\"\n },\n \"babel-plugin-minify-guarded-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-guarded-expressions/-/babel-plugin-minify-guarded-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-zHCbRFP9IbHzAod0RMifiEJ845c=\"\n },\n \"babel-plugin-minify-infinity\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-infinity/-/babel-plugin-minify-infinity-0.4.3.tgz\",\n \"integrity\": \"sha1-37h2obCKBldjhO8/kuZTumB7Oco=\"\n },\n \"babel-plugin-minify-mangle-names\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-mangle-names/-/babel-plugin-minify-mangle-names-0.5.0.tgz\",\n \"integrity\": \"sha512-3jdNv6hCAw6fsX1p2wBGPfWuK69sfOjfd3zjUXkbq8McbohWy23tpXfy5RnToYWggvqzuMOwlId1PhyHOfgnGw==\"\n },\n \"babel-plugin-minify-numeric-literals\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-numeric-literals/-/babel-plugin-minify-numeric-literals-0.4.3.tgz\",\n \"integrity\": \"sha1-jk/VYcefeAEob/YOjF/Z3u6TwLw=\"\n },\n \"babel-plugin-minify-replace\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-replace/-/babel-plugin-minify-replace-0.5.0.tgz\",\n \"integrity\": \"sha512-aXZiaqWDNUbyNNNpWs/8NyST+oU7QTpK7J9zFEFSA0eOmtUNMU3fczlTTTlnCxHmq/jYNFEmkkSG3DDBtW3Y4Q==\"\n },\n \"babel-plugin-minify-simplify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-simplify/-/babel-plugin-minify-simplify-0.5.0.tgz\",\n \"integrity\": \"sha512-TM01J/YcKZ8XIQd1Z3nF2AdWHoDsarjtZ5fWPDksYZNsoOjQ2UO2EWm824Ym6sp127m44gPlLFiO5KFxU8pA5Q==\"\n },\n \"babel-plugin-minify-type-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-type-constructors/-/babel-plugin-minify-type-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-G8bxW4f3qxCF1CszC3F2V6IVZQA=\"\n },\n \"babel-plugin-transform-inline-consecutive-adds\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-inline-consecutive-adds/-/babel-plugin-transform-inline-consecutive-adds-0.4.3.tgz\",\n \"integrity\": \"sha1-Mj1Ho+pjqDp6w8gRro5pQfrysNE=\"\n },\n \"babel-plugin-transform-member-expression-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-member-expression-literals/-/babel-plugin-transform-member-expression-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-NwOcmgwzE6OUlfqsL/OmtbnQOL8=\"\n },\n \"babel-plugin-transform-merge-sibling-variables\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-merge-sibling-variables/-/babel-plugin-transform-merge-sibling-variables-6.9.4.tgz\",\n \"integrity\": \"sha1-hbQi/DN3tEnJ0c3kQIcgNTJAHa4=\"\n },\n \"babel-plugin-transform-minify-booleans\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-minify-booleans/-/babel-plugin-transform-minify-booleans-6.9.4.tgz\",\n \"integrity\": \"sha1-rLs+VqNVXdI5KOS1gtKFFi3SsZg=\"\n },\n \"babel-plugin-transform-property-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-property-literals/-/babel-plugin-transform-property-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-mMHSHiVXNlc/k+zlRFn2ziSYXTk=\"\n },\n \"babel-plugin-transform-regexp-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-regexp-constructors/-/babel-plugin-transform-regexp-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-WLd3W2OvzzMyj66aX4j71PsLSWU=\"\n },\n \"babel-plugin-transform-remove-console\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-console/-/babel-plugin-transform-remove-console-6.9.4.tgz\",\n \"integrity\": \"sha1-uYA2DAZzhOJLNXpYjYB9PINSd4A=\"\n },\n \"babel-plugin-transform-remove-debugger\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-debugger/-/babel-plugin-transform-remove-debugger-6.9.4.tgz\",\n \"integrity\": \"sha1-QrcnYxyXl44estGZp67IShgznvI=\"\n },\n \"babel-plugin-transform-remove-undefined\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-undefined/-/babel-plugin-transform-remove-undefined-0.5.0.tgz\",\n \"integrity\": \"sha512-+M7fJYFaEE/M9CXa0/IRkDbiV3wRELzA1kKQFCJ4ifhrzLKn/9VCCgj9OFmYWwBd8IB48YdgPkHYtbYq+4vtHQ==\"\n },\n \"babel-plugin-transform-simplify-comparison-operators\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-simplify-comparison-operators/-/babel-plugin-transform-simplify-comparison-operators-6.9.4.tgz\",\n \"integrity\": \"sha1-9ir+CWyrDh9ootdT/fKDiIRxzrk=\"\n },\n \"babel-plugin-transform-undefined-to-void\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-undefined-to-void/-/babel-plugin-transform-undefined-to-void-6.9.4.tgz\",\n \"integrity\": \"sha1-viQcqBQEAwZ4t0hxcyK4nQyP4oA=\"\n },\n \"babel-preset-meteor\": {\n \"version\": \"7.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-meteor/-/babel-preset-meteor-7.4.3.tgz\",\n \"integrity\": \"sha512-0nxAvTPAQMMIRM64KcQN3sLgQQSjM41vFZY4lqpAc1vZ9SA3UeYbmMaZ6tqONveiQ09IwTukkVIiAeQd5/mw1Q==\"\n },\n \"babel-preset-minify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-minify/-/babel-preset-minify-0.5.0.tgz\",\n \"integrity\": \"sha512-xj1s9Mon+RFubH569vrGCayA9Fm2GMsCgDRm1Jb8SgctOB7KFcrVc2o8K3YHUyMz+SWP8aea75BoS8YfsXXuiA==\"\n },\n \"chalk\": {\n \"version\": \"2.4.2\",\n \"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz\",\n \"integrity\": \"sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==\"\n },\n \"color-convert\": {\n \"version\": \"1.9.3\",\n \"resolved\": \"https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz\",\n \"integrity\": \"sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==\"\n },\n \"color-name\": {\n \"version\": \"1.1.3\",\n \"resolved\": \"https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz\",\n \"integrity\": \"sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=\"\n },\n \"convert-source-map\": {\n \"version\": \"1.6.0\",\n \"resolved\": \"https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz\",\n \"integrity\": \"sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==\"\n },\n \"debug\": {\n \"version\": \"4.1.1\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-4.1.1.tgz\",\n \"integrity\": \"sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==\"\n },\n \"escape-string-regexp\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz\",\n \"integrity\": \"sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=\"\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"globals\": {\n \"version\": \"11.12.0\",\n \"resolved\": \"https://registry.npmjs.org/globals/-/globals-11.12.0.tgz\",\n \"integrity\": \"sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==\"\n },\n \"has-flag\": {\n \"version\": \"3.0.0\",\n \"resolved\": \"https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz\",\n \"integrity\": \"sha1-tdRU3CGZriJWmfNGfloH87lVuv0=\"\n },\n \"js-tokens\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz\",\n \"integrity\": \"sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==\"\n },\n \"jsesc\": {\n \"version\": \"2.5.2\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz\",\n \"integrity\": \"sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==\"\n },\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n },\n \"lodash\": {\n \"version\": \"4.17.11\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz\",\n \"integrity\": \"sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==\"\n },\n \"lodash.isplainobject\": {\n \"version\": \"4.0.6\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz\",\n \"integrity\": \"sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=\"\n },\n \"lodash.some\": {\n \"version\": \"4.6.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n },\n \"meteor-babel\": {\n \"version\": \"7.4.12\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n },\n \"meteor-babel-helpers\": {\n \"version\": \"0.0.3\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel-helpers/-/meteor-babel-helpers-0.0.3.tgz\",\n \"integrity\": \"sha1-8uXZ+HlvvS6JAQI9dpnlsgLqn7A=\"\n },\n \"minimist\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz\",\n \"integrity\": \"sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=\"\n },\n \"ms\": {\n \"version\": \"2.1.2\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-2.1.2.tgz\",\n \"integrity\": \"sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==\"\n },\n \"path-parse\": {\n \"version\": \"1.0.6\",\n \"resolved\": \"https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz\",\n \"integrity\": \"sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==\"\n },\n \"private\": {\n \"version\": \"0.1.8\",\n \"resolved\": \"https://registry.npmjs.org/private/-/private-0.1.8.tgz\",\n \"integrity\": \"sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==\"\n },\n \"regenerate\": {\n \"version\": \"1.4.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz\",\n \"integrity\": \"sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==\"\n },\n \"regenerate-unicode-properties\": {\n \"version\": \"8.1.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz\",\n \"integrity\": \"sha512-LGZzkgtLY79GeXLm8Dp0BVLdQlWICzBnJz/ipWUgo59qBaZ+BHtq51P2q1uVZlppMuUAT37SDk39qUbjTWB7bA==\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.13.2\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.2.tgz\",\n \"integrity\": \"sha512-S/TQAZJO+D3m9xeN1WTI8dLKBBiRgXBlTJvbWjCThHWZj9EvHK70Ff50/tYj2J/fvBY6JtFVwRuazHN2E7M9BA==\"\n },\n \"regenerator-transform\": {\n \"version\": \"0.14.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.14.0.tgz\",\n \"integrity\": \"sha512-rtOelq4Cawlbmq9xuMR5gdFmv7ku/sFoB7sRiywx7aq53bc52b4j6zvH7Te1Vt/X2YveDKnCGUbioieU7FEL3w==\"\n },\n \"regexpu-core\": {\n \"version\": \"4.5.4\",\n \"resolved\": \"https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.5.4.tgz\",\n \"integrity\": \"sha512-BtizvGtFQKGPUcTy56o3nk1bGRp4SZOTYrDtGNlqCQufptV5IkkLN6Emw+yunAJjzf+C9FQFtvq7IoA3+oMYHQ==\"\n },\n \"regjsgen\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.0.tgz\",\n \"integrity\": \"sha512-RnIrLhrXCX5ow/E5/Mh2O4e/oa1/jW0eaBKTSy3LaCj+M3Bqvm97GWDp2yUtzIs4LEn65zR2yiYGFqb2ApnzDA==\"\n },\n \"regjsparser\": {\n \"version\": \"0.6.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.0.tgz\",\n \"integrity\": \"sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ==\",\n \"dependencies\": {\n \"jsesc\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz\",\n \"integrity\": \"sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=\"\n }\n }\n },\n \"reify\": {\n \"version\": \"0.20.4\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n },\n \"resolve\": {\n \"version\": \"1.11.0\",\n \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n },\n \"safe-buffer\": {\n \"version\": \"5.1.2\",\n \"resolved\": \"https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz\",\n \"integrity\": \"sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==\"\n },\n \"semver\": {\n \"version\": \"5.7.0\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.7.0.tgz\",\n \"integrity\": \"sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==\"\n },\n \"source-map\": {\n \"version\": \"0.5.7\",\n \"resolved\": \"https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz\",\n \"integrity\": \"sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=\"\n },\n \"supports-color\": {\n \"version\": \"5.5.0\",\n \"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz\",\n \"integrity\": \"sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==\"\n },\n \"to-fast-properties\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz\",\n \"integrity\": \"sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=\"\n },\n \"trim-right\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz\",\n \"integrity\": \"sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=\"\n },\n \"unicode-canonical-property-names-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ==\"\n },\n \"unicode-match-property-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg==\"\n },\n \"unicode-match-property-value-ecmascript\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz\",\n \"integrity\": \"sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g==\"\n },\n \"unicode-property-aliases-ecmascript\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz\",\n \"integrity\": \"sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw==\"\n }\n }\n}\n", "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.9964569211006165, 0.016221487894654274, 0.00023509164748247713, 0.0012808169703930616, 0.114784374833107]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n", " \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n", " },\n", " \"meteor-babel\": {\n", " \"version\": \"7.4.12\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n", " \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n", " },\n", " \"meteor-babel-helpers\": {\n", " \"version\": \"0.0.3\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"7.4.13\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.13.tgz\",\n", " \"integrity\": \"sha512-NAOh0UOzFd1rs3HmyerYlIWo6LyExqXwgn/hom1ZYCyd0ytL1Pm9dH7AZiM1gOiV50tjBWdMxx08fM5B5ScZDA==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 606}, "file": "const selftest = require(\"../tool-testing/selftest.js\");\nconst Sandbox = selftest.Sandbox;\n\nselftest.define(\".meteorignore\", function () {\n const s = new Sandbox();\n\n s.createApp(\"myapp\", \"meteor-ignore\");\n s.cd(\"myapp\");\n\n let run = s.run();\n run.waitSecs(30);\n run.match(\"/a.js\");\n run.match(\"/b.js\");\n run.match(\"/lib/e.js\");\n run.match(\"/lib/f.js\");\n run.match(\"/main.js\");\n run.match(\"/server/c.js\");\n run.match(\"/server/d.js\");\n run.match(\"App running at\");\n\n s.write(\"server/.meteorignore\", \"c.*\");\n run.waitSecs(10);\n run.match(\"/a.js\");\n run.match(\"/b.js\");\n run.match(\"/lib/e.js\");\n run.match(\"/lib/f.js\");\n run.match(\"/main.js\");\n run.match(\"/server/d.js\");\n run.match(\"restarted\");\n\n s.write(\".meteorignore\", \"server/d.js\");\n run.waitSecs(10);\n run.match(\"/a.js\");\n run.match(\"/b.js\");\n run.match(\"/lib/e.js\");\n run.match(\"/lib/f.js\");\n run.match(\"/main.js\");\n run.match(\"restarted\");\n\n s.write(\"lib/.meteorignore\", \"*.js\\n!e.*\");\n run.waitSecs(10);\n run.match(\"/a.js\");\n run.match(\"/b.js\");\n run.match(\"/lib/e.js\");\n run.match(\"/main.js\");\n run.match(\"restarted\");\n\n s.write(\".meteorignore\", \"lib/**\");\n run.waitSecs(10);\n run.match(\"/a.js\");\n run.match(\"/b.js\");\n run.match(\"/main.js\");\n run.match(\"/server/d.js\");\n run.match(\"restarted\");\n\n s.write(\".meteorignore\", \"/*.js\\nlib\");\n run.waitSecs(10);\n run.match(\"/server/d.js\");\n run.match(\"restarted\");\n\n s.unlink(\".meteorignore\");\n s.unlink(\"lib/.meteorignore\");\n s.unlink(\"server/.meteorignore\");\n run.waitSecs(10);\n run.match(\"/a.js\");\n run.match(\"/b.js\");\n run.match(\"/lib/e.js\");\n run.match(\"/lib/f.js\");\n run.match(\"/main.js\");\n run.match(\"/server/c.js\");\n run.match(\"/server/d.js\");\n run.match(\"restarted\");\n\n run.stop();\n});\n", "file_path": "tools/tests/meteor-ignore.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00016991466691251844, 0.00016729626804590225, 0.00016486317326780409, 0.0001671152131166309, 1.6893478687052266e-06]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n", " \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n", " },\n", " \"meteor-babel\": {\n", " \"version\": \"7.4.12\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n", " \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n", " },\n", " \"meteor-babel-helpers\": {\n", " \"version\": \"0.0.3\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"7.4.13\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.13.tgz\",\n", " \"integrity\": \"sha512-NAOh0UOzFd1rs3HmyerYlIWo6LyExqXwgn/hom1ZYCyd0ytL1Pm9dH7AZiM1gOiV50tjBWdMxx08fM5B5ScZDA==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 606}, "file": "This package exists to test dynamic imports from packages that are\nprefixed by a username, and thus have a colon between the username and the\npackage name.\n", "file_path": "tools/tests/apps/dynamic-import/packages/colon-name/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00016266053717117757, 0.00016266053717117757, 0.00016266053717117757, 0.00016266053717117757, 0.0]} {"hunk": {"id": 2, "code_window": [" \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n", " \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n", " },\n", " \"meteor-babel\": {\n", " \"version\": \"7.4.12\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n", " \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n", " },\n", " \"meteor-babel-helpers\": {\n", " \"version\": \"0.0.3\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"7.4.13\",\n", " \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.13.tgz\",\n", " \"integrity\": \"sha512-NAOh0UOzFd1rs3HmyerYlIWo6LyExqXwgn/hom1ZYCyd0ytL1Pm9dH7AZiM1gOiV50tjBWdMxx08fM5B5ScZDA==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 606}, "file": "none\n", "file_path": "tools/tests/apps/npmtest/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00016461953055113554, 0.00016461953055113554, 0.00016461953055113554, 0.00016461953055113554, 0.0]} {"hunk": {"id": 3, "code_window": [" }\n", " }\n", " },\n", " \"reify\": {\n", " \"version\": \"0.20.4\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n", " \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n", " },\n", " \"resolve\": {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep"], "after_edit": [" \"version\": \"0.20.5\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.5.tgz\",\n", " \"integrity\": \"sha512-Pk4eu8KcVdIzZHT5Uviax2hUDcGp7lS6/VZuWEtPhy0hkXMSegi/uZKKEMV6PcpjpCBVgwyw7KgCHaUy5uJkeQ==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 678}, "file": "Package.describe({\n name: \"babel-compiler\",\n summary: \"Parser/transpiler for ECMAScript 2015+ syntax\",\n // Tracks the npm version below. Use wrap numbers to increment\n // without incrementing the npm version. Hmm-- Apparently this\n // isn't possible because you can't publish a non-recommended\n // release with package versions that don't have a pre-release\n // identifier at the end (eg, -dev)\n version: '7.4.0'\n});\n\nNpm.depends({\n 'meteor-babel': '7.4.12',\n 'json5': '2.1.0'\n});\n\nPackage.onUse(function (api) {\n api.use('ecmascript-runtime', 'server');\n api.use('modern-browsers');\n\n api.addFiles([\n 'babel.js',\n 'babel-compiler.js',\n 'versions.js',\n ], 'server');\n\n api.export('Babel', 'server');\n api.export('BabelCompiler', 'server');\n});\n", "file_path": "packages/babel-compiler/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001731377124087885, 0.00016854533168952912, 0.00016268939361907542, 0.00016980890359263867, 4.358080332167447e-06]} {"hunk": {"id": 3, "code_window": [" }\n", " }\n", " },\n", " \"reify\": {\n", " \"version\": \"0.20.4\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n", " \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n", " },\n", " \"resolve\": {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep"], "after_edit": [" \"version\": \"0.20.5\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.5.tgz\",\n", " \"integrity\": \"sha512-Pk4eu8KcVdIzZHT5Uviax2hUDcGp7lS6/VZuWEtPhy0hkXMSegi/uZKKEMV6PcpjpCBVgwyw7KgCHaUy5uJkeQ==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 678}, "file": "# ddp-server\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/ddp-server) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/ddp-server)\n***\n\n", "file_path": "packages/ddp-server/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00016651648911647499, 0.00016651648911647499, 0.00016651648911647499, 0.00016651648911647499, 0.0]} {"hunk": {"id": 3, "code_window": [" }\n", " }\n", " },\n", " \"reify\": {\n", " \"version\": \"0.20.4\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n", " \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n", " },\n", " \"resolve\": {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep"], "after_edit": [" \"version\": \"0.20.5\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.5.tgz\",\n", " \"integrity\": \"sha512-Pk4eu8KcVdIzZHT5Uviax2hUDcGp7lS6/VZuWEtPhy0hkXMSegi/uZKKEMV6PcpjpCBVgwyw7KgCHaUy5uJkeQ==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 678}, "file": "Package.describe({\n summary: \"Run tests interactively in the browser\",\n version: '1.2.0',\n documentation: null\n});\n\nPackage.onUse(function (api) {\n api.use('ecmascript');\n // XXX this should go away, and there should be a clean interface\n // that tinytest and the driver both implement?\n api.use('tinytest');\n api.use('bootstrap@1.0.1');\n api.use('underscore');\n\n api.use('session');\n api.use('reload');\n api.use('jquery@1.11.1');\n\n api.use(['webapp', 'blaze@2.1.8', 'templating@1.2.13', 'spacebars@1.0.12',\n 'ddp', 'tracker'], 'client');\n\n api.addFiles('diff_match_patch_uncompressed.js', 'client');\n\n api.addFiles([\n 'driver.html',\n 'driver.js',\n 'driver.css'\n ], \"client\");\n\n api.use(\"random\", \"server\");\n api.mainModule(\"server.js\", \"server\");\n\n api.export('runTests');\n});\n", "file_path": "packages/test-in-browser/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00017197232227772474, 0.00016939484339673072, 0.00016594049520790577, 0.00016983326349873096, 2.3080465325620025e-06]} {"hunk": {"id": 3, "code_window": [" }\n", " }\n", " },\n", " \"reify\": {\n", " \"version\": \"0.20.4\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n", " \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n", " },\n", " \"resolve\": {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep"], "after_edit": [" \"version\": \"0.20.5\",\n", " \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.5.tgz\",\n", " \"integrity\": \"sha512-Pk4eu8KcVdIzZHT5Uviax2hUDcGp7lS6/VZuWEtPhy0hkXMSegi/uZKKEMV6PcpjpCBVgwyw7KgCHaUy5uJkeQ==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 678}, "file": "0.7.0.1\n", "file_path": "examples/other/client-info/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00016405664791818708, 0.00016405664791818708, 0.00016405664791818708, 0.00016405664791818708, 0.0]} {"hunk": {"id": 4, "code_window": [" },\n", " \"resolve\": {\n", " \"version\": \"1.11.0\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n", " \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n", " },\n", " \"safe-buffer\": {\n", " \"version\": \"5.1.2\",\n"], "labels": ["keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"1.11.1\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.1.tgz\",\n", " \"integrity\": \"sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 683}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"@babel/code-frame\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz\",\n \"integrity\": \"sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==\"\n },\n \"@babel/core\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz\",\n \"integrity\": \"sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==\",\n \"dependencies\": {\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n }\n }\n },\n \"@babel/generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/generator/-/generator-7.4.4.tgz\",\n \"integrity\": \"sha512-53UOLK6TVNqKxf7RUh8NE851EHRxOOeVXKbK2bivdb+iziMyk03Sr4eaE9OELCbyZAAafAKPDwF2TPUES5QbxQ==\"\n },\n \"@babel/helper-annotate-as-pure\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.0.0.tgz\",\n \"integrity\": \"sha512-3UYcJUj9kvSLbLbUIfQTqzcy5VX7GRZ/CCDrnOaZorFFM01aXp1+GJwuFGV4NDDoAS+mOUyHcO6UD/RfqOks3Q==\"\n },\n \"@babel/helper-builder-binary-assignment-operator-visitor\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.1.0.tgz\",\n \"integrity\": \"sha512-qNSR4jrmJ8M1VMM9tibvyRAHXQs2PmaksQF7c1CGJNipfe3D8p+wgNwgso/P2A2r2mdgBWAXljNWR0QRZAMW8w==\"\n },\n \"@babel/helper-builder-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-react-jsx/-/helper-builder-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-MjA9KgwCuPEkQd9ncSXvSyJ5y+j2sICHyrI0M3L+6fnS4wMSNDc1ARXsbTfbb2cXHn17VisSnU/sHFTCxVxSMw==\"\n },\n \"@babel/helper-call-delegate\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.4.tgz\",\n \"integrity\": \"sha512-l79boDFJ8S1c5hvQvG+rc+wHw6IuH7YldmRKsYtpbawsxURu/paVy57FZMomGK22/JckepaikOkY0MoAmdyOlQ==\"\n },\n \"@babel/helper-create-class-features-plugin\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.4.4.tgz\",\n \"integrity\": \"sha512-UbBHIa2qeAGgyiNR9RszVF7bUHEdgS4JAUNT8SiqrAN6YJVxlOxeLr5pBzb5kan302dejJ9nla4RyKcR1XT6XA==\"\n },\n \"@babel/helper-define-map\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.4.4.tgz\",\n \"integrity\": \"sha512-IX3Ln8gLhZpSuqHJSnTNBWGDE9kdkTEWl21A/K7PQ00tseBwbqCHTvNLHSBd9M0R5rER4h5Rsvj9vw0R5SieBg==\"\n },\n \"@babel/helper-explode-assignable-expression\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.1.0.tgz\",\n \"integrity\": \"sha512-NRQpfHrJ1msCHtKjbzs9YcMmJZOg6mQMmGRB+hbamEdG5PNpaSm95275VD92DvJKuyl0s2sFiDmMZ+EnnvufqA==\"\n },\n \"@babel/helper-function-name\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz\",\n \"integrity\": \"sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==\"\n },\n \"@babel/helper-get-function-arity\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz\",\n \"integrity\": \"sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==\"\n },\n \"@babel/helper-hoist-variables\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.4.4.tgz\",\n \"integrity\": \"sha512-VYk2/H/BnYbZDDg39hr3t2kKyifAm1W6zHRfhx8jGjIHpQEBv9dry7oQ2f3+J703TLu69nYdxsovl0XYfcnK4w==\"\n },\n \"@babel/helper-member-expression-to-functions\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.0.0.tgz\",\n \"integrity\": \"sha512-avo+lm/QmZlv27Zsi0xEor2fKcqWG56D5ae9dzklpIaY7cQMK5N8VSpaNVPPagiqmy7LrEjK1IWdGMOqPu5csg==\"\n },\n \"@babel/helper-module-imports\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz\",\n \"integrity\": \"sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==\"\n },\n \"@babel/helper-module-transforms\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.4.4.tgz\",\n \"integrity\": \"sha512-3Z1yp8TVQf+B4ynN7WoHPKS8EkdTbgAEy0nU0rs/1Kw4pDgmvYH3rz3aI11KgxKCba2cn7N+tqzV1mY2HMN96w==\"\n },\n \"@babel/helper-optimise-call-expression\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.0.0.tgz\",\n \"integrity\": \"sha512-u8nd9NQePYNQV8iPWu/pLLYBqZBa4ZaY1YWRFMuxrid94wKI1QNt67NEZ7GAe5Kc/0LLScbim05xZFWkAdrj9g==\"\n },\n \"@babel/helper-plugin-utils\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz\",\n \"integrity\": \"sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==\"\n },\n \"@babel/helper-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-Y5nuB/kESmR3tKjU8Nkn1wMGEx1tjJX076HBMeL3XLQCu6vA/YRzuTW0bbb+qRnXvQGn+d6Rx953yffl8vEy7Q==\"\n },\n \"@babel/helper-remap-async-to-generator\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.1.0.tgz\",\n \"integrity\": \"sha512-3fOK0L+Fdlg8S5al8u/hWE6vhufGSn0bN09xm2LXMy//REAF8kDCrYoOBKYmA8m5Nom+sV9LyLCwrFynA8/slg==\"\n },\n \"@babel/helper-replace-supers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.4.4.tgz\",\n \"integrity\": \"sha512-04xGEnd+s01nY1l15EuMS1rfKktNF+1CkKmHoErDppjAAZL+IUBZpzT748x262HF7fibaQPhbvWUl5HeSt1EXg==\"\n },\n \"@babel/helper-simple-access\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz\",\n \"integrity\": \"sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==\"\n },\n \"@babel/helper-split-export-declaration\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz\",\n \"integrity\": \"sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==\"\n },\n \"@babel/helper-wrap-function\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.2.0.tgz\",\n \"integrity\": \"sha512-o9fP1BZLLSrYlxYEYyl2aS+Flun5gtjTIG8iln+XuEzQTs0PLagAGSXUcqruJwD5fM48jzIEggCKpIfWTcR7pQ==\"\n },\n \"@babel/helpers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helpers/-/helpers-7.4.4.tgz\",\n \"integrity\": \"sha512-igczbR/0SeuPR8RFfC7tGrbdTbFL3QTvH6D+Z6zNxnTe//GyqmtHmDkzrqDmyZ3eSwPqB/LhyKoU5DXsp+Vp2A==\"\n },\n \"@babel/highlight\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz\",\n \"integrity\": \"sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==\"\n },\n \"@babel/parser\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/parser/-/parser-7.4.5.tgz\",\n \"integrity\": \"sha512-9mUqkL1FF5T7f0WDFfAoDdiMVPWsdD1gZYzSnaXsxUCUqzuch/8of9G3VUSNiZmMBoRxT3neyVsqeiL/ZPcjew==\"\n },\n \"@babel/plugin-proposal-async-generator-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-+Dfo/SCQqrwx48ptLVGLdE39YtWRuKc/Y9I5Fy0P1DDBB9lsAHpjcEJQt+4IifuSOSTLBKJObJqMvaO1pIE8LQ==\"\n },\n \"@babel/plugin-proposal-class-properties\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.4.4.tgz\",\n \"integrity\": \"sha512-WjKTI8g8d5w1Bc9zgwSz2nfrsNQsXcCf9J9cdCvrJV6RF56yztwm4TmJC0MgJ9tvwO9gUA/mcYe89bLdGfiXFg==\"\n },\n \"@babel/plugin-proposal-object-rest-spread\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.4.4.tgz\",\n \"integrity\": \"sha512-dMBG6cSPBbHeEBdFXeQ2QLc5gUpg4Vkaz8octD4aoW/ISO+jBOcsuxYL7bsb5WSu8RLP6boxrBIALEHgoHtO9g==\"\n },\n \"@babel/plugin-syntax-async-generators\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.2.0.tgz\",\n \"integrity\": \"sha512-1ZrIRBv2t0GSlcwVoQ6VgSLpLgiN/FVQUzt9znxo7v2Ov4jJrs8RY8tv0wvDmFN3qIdMKWrmMMW6yZ0G19MfGg==\"\n },\n \"@babel/plugin-syntax-dynamic-import\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.2.0.tgz\",\n \"integrity\": \"sha512-mVxuJ0YroI/h/tbFTPGZR8cv6ai+STMKNBq0f8hFxsxWjl94qqhsb+wXbpNMDPU3cfR1TIsVFzU3nXyZMqyK4w==\"\n },\n \"@babel/plugin-syntax-flow\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.2.0.tgz\",\n \"integrity\": \"sha512-r6YMuZDWLtLlu0kqIim5o/3TNRAlWb073HwT3e2nKf9I8IIvOggPrnILYPsrrKilmn/mYEMCf/Z07w3yQJF6dg==\"\n },\n \"@babel/plugin-syntax-jsx\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.2.0.tgz\",\n \"integrity\": \"sha512-VyN4QANJkRW6lDBmENzRszvZf3/4AXaj9YR7GwrWeeN9tEBPuXbmDYVU9bYBN0D70zCWVwUy0HWq2553VCb6Hw==\"\n },\n \"@babel/plugin-syntax-object-rest-spread\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz\",\n \"integrity\": \"sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==\"\n },\n \"@babel/plugin-syntax-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-dGwbSMA1YhVS8+31CnPR7LB4pcbrzcV99wQzby4uAfrkZPYZlQ7ImwdpzLqi6Z6IL02b8IAL379CaMwo0x5Lag==\"\n },\n \"@babel/plugin-transform-arrow-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ER77Cax1+8/8jCB9fo4Ud161OZzWN5qawi4GusDuRLcDbDG+bIGYY20zb2dfAFdTRGzrfq2xZPvF0R64EHnimg==\"\n },\n \"@babel/plugin-transform-async-to-generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.4.4.tgz\",\n \"integrity\": \"sha512-YiqW2Li8TXmzgbXw+STsSqPBPFnGviiaSp6CYOq55X8GQ2SGVLrXB6pNid8HkqkZAzOH6knbai3snhP7v0fNwA==\"\n },\n \"@babel/plugin-transform-block-scoped-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ntQPR6q1/NKuphly49+QiQiTN0O63uOwjdD6dhIjSWBI5xlrbUFh720TIpzBhpnrLfv2tNH/BXvLIab1+BAI0w==\"\n },\n \"@babel/plugin-transform-block-scoping\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.4.4.tgz\",\n \"integrity\": \"sha512-jkTUyWZcTrwxu5DD4rWz6rDB5Cjdmgz6z7M7RLXOJyCUkFBawssDGcGh8M/0FTSB87avyJI1HsTwUXp9nKA1PA==\"\n },\n \"@babel/plugin-transform-classes\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.4.4.tgz\",\n \"integrity\": \"sha512-/e44eFLImEGIpL9qPxSRat13I5QNRgBLu2hOQJCF7VLy/otSM/sypV1+XaIw5+502RX/+6YaSAPmldk+nhHDPw==\"\n },\n \"@babel/plugin-transform-computed-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-kP/drqTxY6Xt3NNpKiMomfgkNn4o7+vKxK2DDKcBG9sHj51vHqMBGy8wbDS/J4lMxnqs153/T3+DmCEAkC5cpA==\"\n },\n \"@babel/plugin-transform-destructuring\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.4.4.tgz\",\n \"integrity\": \"sha512-/aOx+nW0w8eHiEHm+BTERB2oJn5D127iye/SUQl7NjHy0lf+j7h4MKMMSOwdazGq9OxgiNADncE+SRJkCxjZpQ==\"\n },\n \"@babel/plugin-transform-exponentiation-operator\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.2.0.tgz\",\n \"integrity\": \"sha512-umh4hR6N7mu4Elq9GG8TOu9M0bakvlsREEC+ialrQN6ABS4oDQ69qJv1VtR3uxlKMCQMCvzk7vr17RHKcjx68A==\"\n },\n \"@babel/plugin-transform-flow-strip-types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.4.4.tgz\",\n \"integrity\": \"sha512-WyVedfeEIILYEaWGAUWzVNyqG4sfsNooMhXWsu/YzOvVGcsnPb5PguysjJqI3t3qiaYj0BR8T2f5njdjTGe44Q==\"\n },\n \"@babel/plugin-transform-for-of\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.4.4.tgz\",\n \"integrity\": \"sha512-9T/5Dlr14Z9TIEXLXkt8T1DU7F24cbhwhMNUziN3hB1AXoZcdzPcTiKGRn/6iOymDqtTKWnr/BtRKN9JwbKtdQ==\"\n },\n \"@babel/plugin-transform-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-2ThDhm4lI4oV7fVQ6pNNK+sx+c/GM5/SaML0w/r4ZB7sAneD/piDJtwdKlNckXeyGK7wlwg2E2w33C/Hh+VFCg==\"\n },\n \"@babel/plugin-transform-modules-commonjs\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.4.4.tgz\",\n \"integrity\": \"sha512-4sfBOJt58sEo9a2BQXnZq+Q3ZTSAUXyK3E30o36BOGnJ+tvJ6YSxF0PG6kERvbeISgProodWuI9UVG3/FMY6iw==\"\n },\n \"@babel/plugin-transform-object-super\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.2.0.tgz\",\n \"integrity\": \"sha512-VMyhPYZISFZAqAPVkiYb7dUe2AsVi2/wCT5+wZdsNO31FojQJa9ns40hzZ6U9f50Jlq4w6qwzdBB2uwqZ00ebg==\"\n },\n \"@babel/plugin-transform-parameters\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.4.4.tgz\",\n \"integrity\": \"sha512-oMh5DUO1V63nZcu/ZVLQFqiihBGo4OpxJxR1otF50GMeCLiRx5nUdtokd+u9SuVJrvvuIh9OosRFPP4pIPnwmw==\"\n },\n \"@babel/plugin-transform-property-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-9q7Dbk4RhgcLp8ebduOpCbtjh7C0itoLYHXd9ueASKAG/is5PQtMR5VJGka9NKqGhYEGn5ITahd4h9QeBMylWQ==\"\n },\n \"@babel/plugin-transform-react-display-name\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.2.0.tgz\",\n \"integrity\": \"sha512-Htf/tPa5haZvRMiNSQSFifK12gtr/8vwfr+A9y69uF0QcU77AVu4K7MiHEkTxF7lQoHOL0F9ErqgfNEAKgXj7A==\"\n },\n \"@babel/plugin-transform-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-a/+aRb7R06WcKvQLOu4/TpjKOdvVEKRLWFpKcNuHhiREPgGRB4TQJxq07+EZLS8LFVYpfq1a5lDUnuMdcCpBKg==\"\n },\n \"@babel/plugin-transform-react-jsx-self\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.2.0.tgz\",\n \"integrity\": \"sha512-v6S5L/myicZEy+jr6ielB0OR8h+EH/1QFx/YJ7c7Ua+7lqsjj/vW6fD5FR9hB/6y7mGbfT4vAURn3xqBxsUcdg==\"\n },\n \"@babel/plugin-transform-react-jsx-source\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.2.0.tgz\",\n \"integrity\": \"sha512-A32OkKTp4i5U6aE88GwwcuV4HAprUgHcTq0sSafLxjr6AW0QahrCRCjxogkbbcdtpbXkuTOlgpjophCxb6sh5g==\"\n },\n \"@babel/plugin-transform-regenerator\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.5.tgz\",\n \"integrity\": \"sha512-gBKRh5qAaCWntnd09S8QC7r3auLCqq5DI6O0DlfoyDjslSBVqBibrMdsqO+Uhmx3+BlOmE/Kw1HFxmGbv0N9dA==\"\n },\n \"@babel/plugin-transform-runtime\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.4.4.tgz\",\n \"integrity\": \"sha512-aMVojEjPszvau3NRg+TIH14ynZLvPewH4xhlCW1w6A3rkxTS1m4uwzRclYR9oS+rl/dr+kT+pzbfHuAWP/lc7Q==\"\n },\n \"@babel/plugin-transform-shorthand-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-QP4eUM83ha9zmYtpbnyjTLAGKQritA5XW/iG9cjtuOI8s1RuL/3V6a3DeSHfKutJQ+ayUfeZJPcnCYEQzaPQqg==\"\n },\n \"@babel/plugin-transform-spread\": {\n \"version\": \"7.2.2\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.2.2.tgz\",\n \"integrity\": \"sha512-KWfky/58vubwtS0hLqEnrWJjsMGaOeSBn90Ezn5Jeg9Z8KKHmELbP1yGylMlm5N6TPKeY9A2+UaSYLdxahg01w==\"\n },\n \"@babel/plugin-transform-sticky-regex\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.2.0.tgz\",\n \"integrity\": \"sha512-KKYCoGaRAf+ckH8gEL3JHUaFVyNHKe3ASNsZ+AlktgHevvxGigoIttrEJb8iKN03Q7Eazlv1s6cx2B2cQ3Jabw==\"\n },\n \"@babel/plugin-transform-template-literals\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.4.4.tgz\",\n \"integrity\": \"sha512-mQrEC4TWkhLN0z8ygIvEL9ZEToPhG5K7KDW3pzGqOfIGZ28Jb0POUkeWcoz8HnHvhFy6dwAT1j8OzqN8s804+g==\"\n },\n \"@babel/plugin-transform-typeof-symbol\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.2.0.tgz\",\n \"integrity\": \"sha512-2LNhETWYxiYysBtrBTqL8+La0jIoQQnIScUJc74OYvUGRmkskNY4EzLCnjHBzdmb38wqtTaixpo1NctEcvMDZw==\"\n },\n \"@babel/plugin-transform-typescript\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.4.5.tgz\",\n \"integrity\": \"sha512-RPB/YeGr4ZrFKNwfuQRlMf2lxoCUaU01MTw39/OFE/RiL8HDjtn68BwEPft1P7JN4akyEmjGWAMNldOV7o9V2g==\"\n },\n \"@babel/plugin-transform-unicode-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-il+/XdNw01i93+M9J9u4T7/e/Ue/vWfNZE4IRUQjplu2Mqb/AFTDimkw2tdEdSH50wuQXZAbXSql0UphQke+vA==\"\n },\n \"@babel/preset-react\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.0.0.tgz\",\n \"integrity\": \"sha512-oayxyPS4Zj+hF6Et11BwuBkmpgT/zMxyuZgFrMeZID6Hdh3dGlk4sHCAhdBCpuCKW2ppBfl2uCCetlrUIJRY3w==\"\n },\n \"@babel/preset-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-mzMVuIP4lqtn4du2ynEfdO0+RYcslwrZiJHXu4MGaC1ctJiW2fyaeDrtjJGs7R/KebZ1sgowcIoWf4uRpEfKEg==\"\n },\n \"@babel/runtime\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/runtime/-/runtime-7.4.5.tgz\",\n \"integrity\": \"sha512-TuI4qpWZP6lGOGIuGWtp9sPluqYICmbk8T/1vpSysqJxRPkudh/ofFWyqdcMsDf2s7KvDL4/YHgKyvcS3g9CJQ==\"\n },\n \"@babel/template\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/template/-/template-7.4.4.tgz\",\n \"integrity\": \"sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw==\"\n },\n \"@babel/traverse\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/traverse/-/traverse-7.4.5.tgz\",\n \"integrity\": \"sha512-Vc+qjynwkjRmIFGxy0KYoPj4FdVDxLej89kMHFsWScq999uX+pwcX4v9mWRjW0KcAYTPAuVQl2LKP1wEVLsp+A==\"\n },\n \"@babel/types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/types/-/types-7.4.4.tgz\",\n \"integrity\": \"sha512-dOllgYdnEFOebhkKCjzSVFqw/PmmB8pH6RGOWkY4GsboQNd47b1fBThBSwlHAq9alF9vc1M3+6oqR47R50L0tQ==\"\n },\n \"acorn\": {\n \"version\": \"6.1.1\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz\",\n \"integrity\": \"sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==\"\n },\n \"acorn-dynamic-import\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz\",\n \"integrity\": \"sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==\"\n },\n \"ansi-styles\": {\n \"version\": \"3.2.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz\",\n \"integrity\": \"sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==\"\n },\n \"babel-helper-evaluate-path\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-evaluate-path/-/babel-helper-evaluate-path-0.5.0.tgz\",\n \"integrity\": \"sha512-mUh0UhS607bGh5wUMAQfOpt2JX2ThXMtppHRdRU1kL7ZLRWIXxoV2UIV1r2cAeeNeU1M5SB5/RSUgUxrK8yOkA==\"\n },\n \"babel-helper-flip-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-flip-expressions/-/babel-helper-flip-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-NpZzahKKwYvCUlS19AoizrPB0/0=\"\n },\n \"babel-helper-is-nodes-equiv\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-nodes-equiv/-/babel-helper-is-nodes-equiv-0.0.1.tgz\",\n \"integrity\": \"sha1-NOmzALFHnd2Y7HfqC76TQt/jloQ=\"\n },\n \"babel-helper-is-void-0\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-void-0/-/babel-helper-is-void-0-0.4.3.tgz\",\n \"integrity\": \"sha1-fZwBtFYee5Xb2g9u7kj1tg5nMT4=\"\n },\n \"babel-helper-mark-eval-scopes\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-mark-eval-scopes/-/babel-helper-mark-eval-scopes-0.4.3.tgz\",\n \"integrity\": \"sha1-0kSjvvmESHJgP/tG4izorN9VFWI=\"\n },\n \"babel-helper-remove-or-void\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-remove-or-void/-/babel-helper-remove-or-void-0.4.3.tgz\",\n \"integrity\": \"sha1-pPA7QAd6D/6I5F0HAQ3uJB/1rmA=\"\n },\n \"babel-helper-to-multiple-sequence-expressions\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-to-multiple-sequence-expressions/-/babel-helper-to-multiple-sequence-expressions-0.5.0.tgz\",\n \"integrity\": \"sha512-m2CvfDW4+1qfDdsrtf4dwOslQC3yhbgyBFptncp4wvtdrDHqueW7slsYv4gArie056phvQFhT2nRcGS4bnm6mA==\"\n },\n \"babel-plugin-minify-builtins\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-builtins/-/babel-plugin-minify-builtins-0.5.0.tgz\",\n \"integrity\": \"sha512-wpqbN7Ov5hsNwGdzuzvFcjgRlzbIeVv1gMIlICbPj0xkexnfoIDe7q+AZHMkQmAE/F9R5jkrB6TLfTegImlXag==\"\n },\n \"babel-plugin-minify-constant-folding\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-constant-folding/-/babel-plugin-minify-constant-folding-0.5.0.tgz\",\n \"integrity\": \"sha512-Vj97CTn/lE9hR1D+jKUeHfNy+m1baNiJ1wJvoGyOBUx7F7kJqDZxr9nCHjO/Ad+irbR3HzR6jABpSSA29QsrXQ==\"\n },\n \"babel-plugin-minify-dead-code-elimination\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-dead-code-elimination/-/babel-plugin-minify-dead-code-elimination-0.5.0.tgz\",\n \"integrity\": \"sha512-XQteBGXlgEoAKc/BhO6oafUdT4LBa7ARi55mxoyhLHNuA+RlzRmeMAfc31pb/UqU01wBzRc36YqHQzopnkd/6Q==\"\n },\n \"babel-plugin-minify-flip-comparisons\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-flip-comparisons/-/babel-plugin-minify-flip-comparisons-0.4.3.tgz\",\n \"integrity\": \"sha1-AMqHDLjxO0XAOLPB68DyJyk8llo=\"\n },\n \"babel-plugin-minify-guarded-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-guarded-expressions/-/babel-plugin-minify-guarded-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-zHCbRFP9IbHzAod0RMifiEJ845c=\"\n },\n \"babel-plugin-minify-infinity\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-infinity/-/babel-plugin-minify-infinity-0.4.3.tgz\",\n \"integrity\": \"sha1-37h2obCKBldjhO8/kuZTumB7Oco=\"\n },\n \"babel-plugin-minify-mangle-names\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-mangle-names/-/babel-plugin-minify-mangle-names-0.5.0.tgz\",\n \"integrity\": \"sha512-3jdNv6hCAw6fsX1p2wBGPfWuK69sfOjfd3zjUXkbq8McbohWy23tpXfy5RnToYWggvqzuMOwlId1PhyHOfgnGw==\"\n },\n \"babel-plugin-minify-numeric-literals\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-numeric-literals/-/babel-plugin-minify-numeric-literals-0.4.3.tgz\",\n \"integrity\": \"sha1-jk/VYcefeAEob/YOjF/Z3u6TwLw=\"\n },\n \"babel-plugin-minify-replace\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-replace/-/babel-plugin-minify-replace-0.5.0.tgz\",\n \"integrity\": \"sha512-aXZiaqWDNUbyNNNpWs/8NyST+oU7QTpK7J9zFEFSA0eOmtUNMU3fczlTTTlnCxHmq/jYNFEmkkSG3DDBtW3Y4Q==\"\n },\n \"babel-plugin-minify-simplify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-simplify/-/babel-plugin-minify-simplify-0.5.0.tgz\",\n \"integrity\": \"sha512-TM01J/YcKZ8XIQd1Z3nF2AdWHoDsarjtZ5fWPDksYZNsoOjQ2UO2EWm824Ym6sp127m44gPlLFiO5KFxU8pA5Q==\"\n },\n \"babel-plugin-minify-type-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-type-constructors/-/babel-plugin-minify-type-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-G8bxW4f3qxCF1CszC3F2V6IVZQA=\"\n },\n \"babel-plugin-transform-inline-consecutive-adds\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-inline-consecutive-adds/-/babel-plugin-transform-inline-consecutive-adds-0.4.3.tgz\",\n \"integrity\": \"sha1-Mj1Ho+pjqDp6w8gRro5pQfrysNE=\"\n },\n \"babel-plugin-transform-member-expression-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-member-expression-literals/-/babel-plugin-transform-member-expression-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-NwOcmgwzE6OUlfqsL/OmtbnQOL8=\"\n },\n \"babel-plugin-transform-merge-sibling-variables\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-merge-sibling-variables/-/babel-plugin-transform-merge-sibling-variables-6.9.4.tgz\",\n \"integrity\": \"sha1-hbQi/DN3tEnJ0c3kQIcgNTJAHa4=\"\n },\n \"babel-plugin-transform-minify-booleans\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-minify-booleans/-/babel-plugin-transform-minify-booleans-6.9.4.tgz\",\n \"integrity\": \"sha1-rLs+VqNVXdI5KOS1gtKFFi3SsZg=\"\n },\n \"babel-plugin-transform-property-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-property-literals/-/babel-plugin-transform-property-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-mMHSHiVXNlc/k+zlRFn2ziSYXTk=\"\n },\n \"babel-plugin-transform-regexp-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-regexp-constructors/-/babel-plugin-transform-regexp-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-WLd3W2OvzzMyj66aX4j71PsLSWU=\"\n },\n \"babel-plugin-transform-remove-console\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-console/-/babel-plugin-transform-remove-console-6.9.4.tgz\",\n \"integrity\": \"sha1-uYA2DAZzhOJLNXpYjYB9PINSd4A=\"\n },\n \"babel-plugin-transform-remove-debugger\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-debugger/-/babel-plugin-transform-remove-debugger-6.9.4.tgz\",\n \"integrity\": \"sha1-QrcnYxyXl44estGZp67IShgznvI=\"\n },\n \"babel-plugin-transform-remove-undefined\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-undefined/-/babel-plugin-transform-remove-undefined-0.5.0.tgz\",\n \"integrity\": \"sha512-+M7fJYFaEE/M9CXa0/IRkDbiV3wRELzA1kKQFCJ4ifhrzLKn/9VCCgj9OFmYWwBd8IB48YdgPkHYtbYq+4vtHQ==\"\n },\n \"babel-plugin-transform-simplify-comparison-operators\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-simplify-comparison-operators/-/babel-plugin-transform-simplify-comparison-operators-6.9.4.tgz\",\n \"integrity\": \"sha1-9ir+CWyrDh9ootdT/fKDiIRxzrk=\"\n },\n \"babel-plugin-transform-undefined-to-void\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-undefined-to-void/-/babel-plugin-transform-undefined-to-void-6.9.4.tgz\",\n \"integrity\": \"sha1-viQcqBQEAwZ4t0hxcyK4nQyP4oA=\"\n },\n \"babel-preset-meteor\": {\n \"version\": \"7.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-meteor/-/babel-preset-meteor-7.4.3.tgz\",\n \"integrity\": \"sha512-0nxAvTPAQMMIRM64KcQN3sLgQQSjM41vFZY4lqpAc1vZ9SA3UeYbmMaZ6tqONveiQ09IwTukkVIiAeQd5/mw1Q==\"\n },\n \"babel-preset-minify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-minify/-/babel-preset-minify-0.5.0.tgz\",\n \"integrity\": \"sha512-xj1s9Mon+RFubH569vrGCayA9Fm2GMsCgDRm1Jb8SgctOB7KFcrVc2o8K3YHUyMz+SWP8aea75BoS8YfsXXuiA==\"\n },\n \"chalk\": {\n \"version\": \"2.4.2\",\n \"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz\",\n \"integrity\": \"sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==\"\n },\n \"color-convert\": {\n \"version\": \"1.9.3\",\n \"resolved\": \"https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz\",\n \"integrity\": \"sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==\"\n },\n \"color-name\": {\n \"version\": \"1.1.3\",\n \"resolved\": \"https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz\",\n \"integrity\": \"sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=\"\n },\n \"convert-source-map\": {\n \"version\": \"1.6.0\",\n \"resolved\": \"https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz\",\n \"integrity\": \"sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==\"\n },\n \"debug\": {\n \"version\": \"4.1.1\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-4.1.1.tgz\",\n \"integrity\": \"sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==\"\n },\n \"escape-string-regexp\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz\",\n \"integrity\": \"sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=\"\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"globals\": {\n \"version\": \"11.12.0\",\n \"resolved\": \"https://registry.npmjs.org/globals/-/globals-11.12.0.tgz\",\n \"integrity\": \"sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==\"\n },\n \"has-flag\": {\n \"version\": \"3.0.0\",\n \"resolved\": \"https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz\",\n \"integrity\": \"sha1-tdRU3CGZriJWmfNGfloH87lVuv0=\"\n },\n \"js-tokens\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz\",\n \"integrity\": \"sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==\"\n },\n \"jsesc\": {\n \"version\": \"2.5.2\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz\",\n \"integrity\": \"sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==\"\n },\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n },\n \"lodash\": {\n \"version\": \"4.17.11\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz\",\n \"integrity\": \"sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==\"\n },\n \"lodash.isplainobject\": {\n \"version\": \"4.0.6\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz\",\n \"integrity\": \"sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=\"\n },\n \"lodash.some\": {\n \"version\": \"4.6.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n },\n \"meteor-babel\": {\n \"version\": \"7.4.12\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n },\n \"meteor-babel-helpers\": {\n \"version\": \"0.0.3\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel-helpers/-/meteor-babel-helpers-0.0.3.tgz\",\n \"integrity\": \"sha1-8uXZ+HlvvS6JAQI9dpnlsgLqn7A=\"\n },\n \"minimist\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz\",\n \"integrity\": \"sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=\"\n },\n \"ms\": {\n \"version\": \"2.1.2\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-2.1.2.tgz\",\n \"integrity\": \"sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==\"\n },\n \"path-parse\": {\n \"version\": \"1.0.6\",\n \"resolved\": \"https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz\",\n \"integrity\": \"sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==\"\n },\n \"private\": {\n \"version\": \"0.1.8\",\n \"resolved\": \"https://registry.npmjs.org/private/-/private-0.1.8.tgz\",\n \"integrity\": \"sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==\"\n },\n \"regenerate\": {\n \"version\": \"1.4.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz\",\n \"integrity\": \"sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==\"\n },\n \"regenerate-unicode-properties\": {\n \"version\": \"8.1.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz\",\n \"integrity\": \"sha512-LGZzkgtLY79GeXLm8Dp0BVLdQlWICzBnJz/ipWUgo59qBaZ+BHtq51P2q1uVZlppMuUAT37SDk39qUbjTWB7bA==\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.13.2\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.2.tgz\",\n \"integrity\": \"sha512-S/TQAZJO+D3m9xeN1WTI8dLKBBiRgXBlTJvbWjCThHWZj9EvHK70Ff50/tYj2J/fvBY6JtFVwRuazHN2E7M9BA==\"\n },\n \"regenerator-transform\": {\n \"version\": \"0.14.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.14.0.tgz\",\n \"integrity\": \"sha512-rtOelq4Cawlbmq9xuMR5gdFmv7ku/sFoB7sRiywx7aq53bc52b4j6zvH7Te1Vt/X2YveDKnCGUbioieU7FEL3w==\"\n },\n \"regexpu-core\": {\n \"version\": \"4.5.4\",\n \"resolved\": \"https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.5.4.tgz\",\n \"integrity\": \"sha512-BtizvGtFQKGPUcTy56o3nk1bGRp4SZOTYrDtGNlqCQufptV5IkkLN6Emw+yunAJjzf+C9FQFtvq7IoA3+oMYHQ==\"\n },\n \"regjsgen\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.0.tgz\",\n \"integrity\": \"sha512-RnIrLhrXCX5ow/E5/Mh2O4e/oa1/jW0eaBKTSy3LaCj+M3Bqvm97GWDp2yUtzIs4LEn65zR2yiYGFqb2ApnzDA==\"\n },\n \"regjsparser\": {\n \"version\": \"0.6.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.0.tgz\",\n \"integrity\": \"sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ==\",\n \"dependencies\": {\n \"jsesc\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz\",\n \"integrity\": \"sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=\"\n }\n }\n },\n \"reify\": {\n \"version\": \"0.20.4\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n },\n \"resolve\": {\n \"version\": \"1.11.0\",\n \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n },\n \"safe-buffer\": {\n \"version\": \"5.1.2\",\n \"resolved\": \"https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz\",\n \"integrity\": \"sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==\"\n },\n \"semver\": {\n \"version\": \"5.7.0\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.7.0.tgz\",\n \"integrity\": \"sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==\"\n },\n \"source-map\": {\n \"version\": \"0.5.7\",\n \"resolved\": \"https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz\",\n \"integrity\": \"sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=\"\n },\n \"supports-color\": {\n \"version\": \"5.5.0\",\n \"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz\",\n \"integrity\": \"sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==\"\n },\n \"to-fast-properties\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz\",\n \"integrity\": \"sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=\"\n },\n \"trim-right\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz\",\n \"integrity\": \"sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=\"\n },\n \"unicode-canonical-property-names-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ==\"\n },\n \"unicode-match-property-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg==\"\n },\n \"unicode-match-property-value-ecmascript\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz\",\n \"integrity\": \"sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g==\"\n },\n \"unicode-property-aliases-ecmascript\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz\",\n \"integrity\": \"sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw==\"\n }\n }\n}\n", "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.9925273656845093, 0.02240130305290222, 0.0003320267132949084, 0.006848030723631382, 0.11383988708257675]} {"hunk": {"id": 4, "code_window": [" },\n", " \"resolve\": {\n", " \"version\": \"1.11.0\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n", " \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n", " },\n", " \"safe-buffer\": {\n", " \"version\": \"5.1.2\",\n"], "labels": ["keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"1.11.1\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.1.tgz\",\n", " \"integrity\": \"sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 683}, "file": "import { pathJoin, getDevBundle } from '../fs/files.js';\nimport { installNpmModule, moduleDoesResolve } from '../isobuild/meteor-npm.js';\n\nexport function ensureDependencies(deps) {\n // Check if each of the requested dependencies resolves, if not\n // mark them for installation.\n const needToInstall = Object.create(null);\n Object.keys(deps).forEach(dep => {\n if (!moduleDoesResolve(dep)) {\n const versionToInstall = deps[dep];\n needToInstall[dep] = versionToInstall;\n }\n });\n\n const devBundleLib = pathJoin(getDevBundle(), 'lib');\n\n // Install each of the requested modules.\n Object.keys(needToInstall)\n .forEach(dep => installNpmModule(dep, needToInstall[dep], devBundleLib));\n}\n", "file_path": "tools/cli/dev-bundle-helpers.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001672329963184893, 0.0001661708374740556, 0.00016516857431270182, 0.00016611098544672132, 8.438591976300813e-07]} {"hunk": {"id": 4, "code_window": [" },\n", " \"resolve\": {\n", " \"version\": \"1.11.0\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n", " \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n", " },\n", " \"safe-buffer\": {\n", " \"version\": \"5.1.2\",\n"], "labels": ["keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"1.11.1\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.1.tgz\",\n", " \"integrity\": \"sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 683}, "file": "Package.describe({\n summary: \"Reactive dictionary\",\n version: '1.3.0'\n});\n\nPackage.onUse(function (api) {\n api.use(['tracker', 'ejson', 'ecmascript']);\n // If we are loading mongo-livedata, let you store ObjectIDs in it.\n api.use(['mongo', 'reload'], { weak: true });\n api.mainModule('migration.js');\n api.export('ReactiveDict');\n});\n\nPackage.onTest(function (api) {\n api.use('tinytest');\n api.use('reactive-dict');\n api.use('tracker');\n api.use('reload');\n api.addFiles('reactive-dict-tests.js');\n});\n", "file_path": "packages/reactive-dict/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00017286388901993632, 0.00017059198580682278, 0.0001672329963184893, 0.00017167904297821224, 2.4239120648417156e-06]} {"hunk": {"id": 4, "code_window": [" },\n", " \"resolve\": {\n", " \"version\": \"1.11.0\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n", " \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n", " },\n", " \"safe-buffer\": {\n", " \"version\": \"5.1.2\",\n"], "labels": ["keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" \"version\": \"1.11.1\",\n", " \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.1.tgz\",\n", " \"integrity\": \"sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==\"\n"], "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "type": "replace", "edit_start_line_idx": 683}, "file": "var assert = require(\"assert\");\nvar files = require('../fs/files.js');\nvar _ = require(\"underscore\");\n\n// This class encapsulates a structured specification of files and\n// directories that should be stripped from the node_modules directories\n// of Meteor packages during `meteor build`, as requested by calling\n// `Npm.discard` in package.js files.\nfunction NpmDiscards() {\n assert.ok(this instanceof NpmDiscards);\n this.discards = {};\n}\n\nvar NDp = NpmDiscards.prototype;\n\n// Update the current specification of discarded files with additional\n// patterns that should be discarded. See the comment in package-source.js\n// about `Npm.strip` for an explanation of what should be passed for the\n// `discards` parameter.\nNDp.merge = function(discards) {\n merge(this.discards, discards);\n};\n\nfunction merge(into, from) {\n _.each(from, function(fromValue, packageName) {\n var intoValue = _.has(into, packageName) && into[packageName];\n if (_.isString(fromValue) ||\n _.isRegExp(fromValue)) {\n if (intoValue) {\n intoValue.push(fromValue);\n } else {\n into[packageName] = [fromValue];\n }\n } else if (_.isArray(fromValue)) {\n if (intoValue) {\n intoValue.push.apply(intoValue, fromValue);\n } else {\n // Make a defensive copy of any arrays passed to `Npm.strip`.\n into[packageName] = fromValue.slice(0);\n }\n }\n });\n}\n\nNDp.shouldDiscard = function shouldDiscard(candidatePath, isDirectory) {\n if (typeof isDirectory === \"undefined\") {\n isDirectory = files.lstat(candidatePath).isDirectory();\n }\n\n for (var currentPath = candidatePath, parentPath;\n (parentPath = files.pathDirname(currentPath)) !== currentPath;\n currentPath = parentPath) {\n if (files.pathBasename(parentPath) === \"node_modules\") {\n var packageName = files.pathBasename(currentPath);\n\n if (_.has(this.discards, packageName)) {\n var relPath = files.pathRelative(currentPath, candidatePath);\n\n if (isDirectory) {\n relPath = files.pathJoin(relPath, files.pathSep);\n }\n\n return this.discards[packageName].some(function(pattern) {\n return matches(pattern, relPath);\n });\n }\n\n // Stop at the first ancestor node_modules directory we find.\n break;\n }\n }\n\n return false;\n};\n\n// TODO Improve this. For example we don't currently support wildcard\n// string patterns (just use a RegExp if you need that flexibility).\nfunction matches(pattern, relPath) {\n if (_.isRegExp(pattern)) {\n return relPath.match(pattern);\n }\n\n assert.ok(_.isString(pattern));\n\n if (pattern.charAt(0) === files.pathSep) {\n return relPath.indexOf(pattern.slice(1)) === 0;\n }\n\n return relPath.indexOf(pattern) !== -1;\n}\n\nmodule.exports = NpmDiscards;\n", "file_path": "tools/isobuild/npm-discards.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0008496062364429235, 0.00023711472749710083, 0.00016403115296270698, 0.0001689325727056712, 0.00020422421221155673]} {"hunk": {"id": 7, "code_window": ["});\n", "\n", "Npm.depends({\n", " reify: \"0.20.4\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n", " api.mainModule(\"client.js\", \"client\");\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "// This file contains a package.json for the dependencies of the command-line\n// tool.\n\n// We put this in a JS file so that it can contain comments. It is processed\n// into a package.json file by generate-dev-bundle.sh.\n\nvar packageJson = {\n name: \"meteor-dev-bundle-tool\",\n private: true,\n dependencies: {\n // Explicit dependency because we are replacing it with a bundled version\n // and we want to make sure there are no dependencies on a higher version\n npm: \"6.9.0\",\n pacote: \"https://github.com/meteor/pacote/tarball/c5043daa1b768594e01d76275e3854fc19f038f9\",\n \"node-gyp\": \"3.7.0\",\n \"node-pre-gyp\": \"0.10.3\",\n \"meteor-babel\": \"7.4.12\",\n // Keep the versions of these packages consistent with the versions\n // found in dev-bundle-server-package.js.\n \"meteor-promise\": \"0.8.7\",\n reify: \"0.20.4\",\n fibers: \"3.1.1\",\n // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n \"@babel/runtime\": \"7.4.4\",\n // For backwards compatibility with isopackets that still depend on\n // babel-runtime rather than @babel/runtime.\n \"babel-runtime\": \"7.0.0-beta.3\",\n // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n // in the package too) because we should consider using lodash instead\n // (and there are backwards-incompatible changes either way).\n underscore: \"1.5.2\",\n \"source-map-support\": \"https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e\",\n semver: \"5.4.1\",\n request: \"2.88.0\",\n uuid: \"3.3.2\",\n fstream: \"https://github.com/meteor/fstream/tarball/cf4ea6c175355cec7bee38311e170d08c4078a5d\",\n tar: \"2.2.1\",\n kexec: \"3.0.0\",\n \"source-map\": \"0.5.7\",\n chalk: \"0.5.1\",\n sqlite3: \"3.1.8\",\n netroute: \"1.0.2\",\n \"http-proxy\": \"1.16.2\",\n \"is-reachable\": \"3.1.0\",\n \"wordwrap\": \"0.0.2\",\n \"moment\": \"2.20.1\",\n \"rimraf\": \"2.6.2\",\n \"glob\": \"7.1.2\",\n ignore: \"3.3.7\",\n // XXX: When we update this, see if it fixes this Github issue:\n // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the\n // workaround from the tool.\n \"commonmark\": \"0.15.0\",\n escope: \"3.6.0\",\n split2: \"2.2.0\",\n multipipe: \"2.0.1\",\n pathwatcher: \"8.0.2\",\n // The @wry/context package version must be compatible with the\n // version constraint imposed by optimism/package.json.\n optimism: \"0.9.5\",\n \"@wry/context\": \"0.4.0\",\n 'lru-cache': '4.1.3'\n }\n};\n\nif (process.platform === 'win32') {\n // Remove dependencies that do not work on Windows\n delete packageJson.dependencies.netroute;\n delete packageJson.dependencies.kexec;\n}\n\nprocess.stdout.write(JSON.stringify(packageJson, null, 2) + '\\n');\n", "file_path": "scripts/dev-bundle-tool-package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00029243482276797295, 0.00018489192007109523, 0.0001653198414715007, 0.00017040170496329665, 4.077761332155205e-05]} {"hunk": {"id": 7, "code_window": ["});\n", "\n", "Npm.depends({\n", " reify: \"0.20.4\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n", " api.mainModule(\"client.js\", \"client\");\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "This directory and the files immediately inside it are automatically generated\nwhen you change this package's NPM dependencies. Commit the files in this\ndirectory (npm-shrinkwrap.json, .gitignore, and this README) to source control\nso that others run the same versions of sub-dependencies.\n\nYou should NOT check in the node_modules directory that Meteor automatically\ncreates; if you are using git, the .gitignore file tells git to ignore it.\n", "file_path": "packages/boilerplate-generator-tests/.npm/package/README", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001653814542805776, 0.0001653814542805776, 0.0001653814542805776, 0.0001653814542805776, 0.0]} {"hunk": {"id": 7, "code_window": ["});\n", "\n", "Npm.depends({\n", " reify: \"0.20.4\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n", " api.mainModule(\"client.js\", \"client\");\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "node_modules\n", "file_path": "packages/minifier-css/.npm/package/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001732103555696085, 0.0001732103555696085, 0.0001732103555696085, 0.0001732103555696085, 0.0]} {"hunk": {"id": 7, "code_window": ["});\n", "\n", "Npm.depends({\n", " reify: \"0.20.4\"\n", "});\n", "\n", "Package.onUse(function(api) {\n", " api.use(\"modules-runtime\");\n", " api.mainModule(\"client.js\", \"client\");\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\"\n"], "file_path": "packages/modules/package.js", "type": "replace", "edit_start_line_idx": 8}, "file": "# observe-sequence\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/observe-sequence) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/observe-sequence)\n***\n\nThis is an internal Meteor package.", "file_path": "packages/observe-sequence/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001714019599603489, 0.0001714019599603489, 0.0001714019599603489, 0.0001714019599603489, 0.0]} {"hunk": {"id": 8, "code_window": [" npm: \"6.9.0\",\n", " pacote: \"https://github.com/meteor/pacote/tarball/c5043daa1b768594e01d76275e3854fc19f038f9\",\n", " \"node-gyp\": \"3.7.0\",\n", " \"node-pre-gyp\": \"0.10.3\",\n", " \"meteor-babel\": \"7.4.12\",\n", " // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"7.4.13\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 16}, "file": "// This file contains a package.json for the dependencies of the command-line\n// tool.\n\n// We put this in a JS file so that it can contain comments. It is processed\n// into a package.json file by generate-dev-bundle.sh.\n\nvar packageJson = {\n name: \"meteor-dev-bundle-tool\",\n private: true,\n dependencies: {\n // Explicit dependency because we are replacing it with a bundled version\n // and we want to make sure there are no dependencies on a higher version\n npm: \"6.9.0\",\n pacote: \"https://github.com/meteor/pacote/tarball/c5043daa1b768594e01d76275e3854fc19f038f9\",\n \"node-gyp\": \"3.7.0\",\n \"node-pre-gyp\": \"0.10.3\",\n \"meteor-babel\": \"7.4.12\",\n // Keep the versions of these packages consistent with the versions\n // found in dev-bundle-server-package.js.\n \"meteor-promise\": \"0.8.7\",\n reify: \"0.20.4\",\n fibers: \"3.1.1\",\n // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n \"@babel/runtime\": \"7.4.4\",\n // For backwards compatibility with isopackets that still depend on\n // babel-runtime rather than @babel/runtime.\n \"babel-runtime\": \"7.0.0-beta.3\",\n // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n // in the package too) because we should consider using lodash instead\n // (and there are backwards-incompatible changes either way).\n underscore: \"1.5.2\",\n \"source-map-support\": \"https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e\",\n semver: \"5.4.1\",\n request: \"2.88.0\",\n uuid: \"3.3.2\",\n fstream: \"https://github.com/meteor/fstream/tarball/cf4ea6c175355cec7bee38311e170d08c4078a5d\",\n tar: \"2.2.1\",\n kexec: \"3.0.0\",\n \"source-map\": \"0.5.7\",\n chalk: \"0.5.1\",\n sqlite3: \"3.1.8\",\n netroute: \"1.0.2\",\n \"http-proxy\": \"1.16.2\",\n \"is-reachable\": \"3.1.0\",\n \"wordwrap\": \"0.0.2\",\n \"moment\": \"2.20.1\",\n \"rimraf\": \"2.6.2\",\n \"glob\": \"7.1.2\",\n ignore: \"3.3.7\",\n // XXX: When we update this, see if it fixes this Github issue:\n // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the\n // workaround from the tool.\n \"commonmark\": \"0.15.0\",\n escope: \"3.6.0\",\n split2: \"2.2.0\",\n multipipe: \"2.0.1\",\n pathwatcher: \"8.0.2\",\n // The @wry/context package version must be compatible with the\n // version constraint imposed by optimism/package.json.\n optimism: \"0.9.5\",\n \"@wry/context\": \"0.4.0\",\n 'lru-cache': '4.1.3'\n }\n};\n\nif (process.platform === 'win32') {\n // Remove dependencies that do not work on Windows\n delete packageJson.dependencies.netroute;\n delete packageJson.dependencies.kexec;\n}\n\nprocess.stdout.write(JSON.stringify(packageJson, null, 2) + '\\n');\n", "file_path": "scripts/dev-bundle-tool-package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.9660478830337524, 0.12097398191690445, 0.00016376299026887864, 0.00017431200831197202, 0.31940793991088867]} {"hunk": {"id": 8, "code_window": [" npm: \"6.9.0\",\n", " pacote: \"https://github.com/meteor/pacote/tarball/c5043daa1b768594e01d76275e3854fc19f038f9\",\n", " \"node-gyp\": \"3.7.0\",\n", " \"node-pre-gyp\": \"0.10.3\",\n", " \"meteor-babel\": \"7.4.12\",\n", " // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"7.4.13\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 16}, "file": "// Constructor of Heap\n// - comparator - Function - given two items returns a number\n// - options:\n// - initData - Array - Optional - the initial data in a format:\n// Object:\n// - id - String - unique id of the item\n// - value - Any - the data value\n// each value is retained\n// - IdMap - Constructor - Optional - custom IdMap class to store id->index\n// mappings internally. Standard IdMap is used by default.\nexport class MaxHeap { \n constructor(comparator, options = {}) {\n if (typeof comparator !== 'function') {\n throw new Error('Passed comparator is invalid, should be a comparison function');\n }\n\n // a C-style comparator that is given two values and returns a number,\n // negative if the first value is less than the second, positive if the second\n // value is greater than the first and zero if they are equal.\n this._comparator = comparator;\n\n if (! options.IdMap) {\n options.IdMap = IdMap;\n }\n\n // _heapIdx maps an id to an index in the Heap array the corresponding value\n // is located on.\n this._heapIdx = new options.IdMap;\n\n // The Heap data-structure implemented as a 0-based contiguous array where\n // every item on index idx is a node in a complete binary tree. Every node can\n // have children on indexes idx*2+1 and idx*2+2, except for the leaves. Every\n // node has a parent on index (idx-1)/2;\n this._heap = [];\n\n // If the initial array is passed, we can build the heap in linear time\n // complexity (O(N)) compared to linearithmic time complexity (O(nlogn)) if\n // we push elements one by one.\n if (Array.isArray(options.initData)) {\n this._initFromData(options.initData);\n }\n }\n\n // Builds a new heap in-place in linear time based on passed data\n _initFromData(data) {\n this._heap = data.map(({ id, value }) => ({ id, value }));\n\n data.forEach(({ id }, i) => this._heapIdx.set(id, i));\n\n if (! data.length) {\n return;\n }\n\n // start from the first non-leaf - the parent of the last leaf\n for (let i = parentIdx(data.length - 1); i >= 0; i--) {\n this._downHeap(i);\n }\n }\n\n _downHeap(idx) {\n while (leftChildIdx(idx) < this.size()) {\n const left = leftChildIdx(idx);\n const right = rightChildIdx(idx);\n let largest = idx;\n\n if (left < this.size()) {\n largest = this._maxIndex(largest, left);\n }\n\n if (right < this.size()) {\n largest = this._maxIndex(largest, right);\n }\n\n if (largest === idx) {\n break;\n }\n\n this._swap(largest, idx);\n idx = largest;\n }\n }\n\n _upHeap(idx) {\n while (idx > 0) {\n const parent = parentIdx(idx);\n if (this._maxIndex(parent, idx) === idx) {\n this._swap(parent, idx)\n idx = parent;\n } else {\n break;\n }\n }\n }\n\n _maxIndex(idxA, idxB) {\n const valueA = this._get(idxA);\n const valueB = this._get(idxB);\n return this._comparator(valueA, valueB) >= 0 ? idxA : idxB;\n }\n\n // Internal: gets raw data object placed on idxth place in heap\n _get(idx) {\n return this._heap[idx].value;\n }\n\n _swap(idxA, idxB) {\n const recA = this._heap[idxA];\n const recB = this._heap[idxB];\n\n this._heapIdx.set(recA.id, idxB);\n this._heapIdx.set(recB.id, idxA);\n\n this._heap[idxA] = recB;\n this._heap[idxB] = recA;\n }\n\n get(id) {\n return this.has(id) ?\n this._get(this._heapIdx.get(id)) :\n null;\n }\n\n set(id, value) {\n if (this.has(id)) {\n if (this.get(id) === value) {\n return;\n }\n\n const idx = this._heapIdx.get(id);\n this._heap[idx].value = value;\n\n // Fix the new value's position\n // Either bubble new value up if it is greater than its parent\n this._upHeap(idx);\n // or bubble it down if it is smaller than one of its children\n this._downHeap(idx);\n } else {\n this._heapIdx.set(id, this._heap.length);\n this._heap.push({ id, value });\n this._upHeap(this._heap.length - 1);\n }\n }\n\n remove(id) {\n if (this.has(id)) {\n const last = this._heap.length - 1;\n const idx = this._heapIdx.get(id);\n\n if (idx !== last) {\n this._swap(idx, last);\n this._heap.pop();\n this._heapIdx.remove(id);\n\n // Fix the swapped value's position\n this._upHeap(idx);\n this._downHeap(idx);\n } else {\n this._heap.pop();\n this._heapIdx.remove(id);\n }\n }\n }\n\n has(id) {\n return this._heapIdx.has(id);\n }\n\n empty() {\n return !this.size();\n }\n\n clear() {\n this._heap = [];\n this._heapIdx.clear();\n }\n\n // iterate over values in no particular order\n forEach(iterator) {\n this._heap.forEach(obj => iterator(obj.value, obj.id));\n }\n\n size() {\n return this._heap.length;\n }\n\n setDefault(id, def) {\n if (this.has(id)) {\n return this.get(id);\n }\n\n this.set(id, def);\n return def;\n }\n\n clone() {\n const clone = new MaxHeap(this._comparator, this._heap);\n return clone;\n }\n\n maxElementId() {\n return this.size() ? this._heap[0].id : null;\n }\n\n _selfCheck() {\n for (let i = 1; i < this._heap.length; i++) {\n if (this._maxIndex(parentIdx(i), i) !== parentIdx(i)) {\n throw new Error(`An item with id ${this._heap[i].id}` +\n \" has a parent younger than it: \" +\n this._heap[parentIdx(i)].id);\n }\n }\n }\n}\n\nconst leftChildIdx = i => i * 2 + 1;\nconst rightChildIdx = i => i * 2 + 2;\nconst parentIdx = i => (i - 1) >> 1;\n", "file_path": "packages/binary-heap/max-heap.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00024014434893615544, 0.0001718690909910947, 0.00016271002823486924, 0.00016871468687895685, 1.5227531548589468e-05]} {"hunk": {"id": 8, "code_window": [" npm: \"6.9.0\",\n", " pacote: \"https://github.com/meteor/pacote/tarball/c5043daa1b768594e01d76275e3854fc19f038f9\",\n", " \"node-gyp\": \"3.7.0\",\n", " \"node-pre-gyp\": \"0.10.3\",\n", " \"meteor-babel\": \"7.4.12\",\n", " // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"7.4.13\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 16}, "file": "Package.describe({\n name: 'coffeescript',\n summary: 'JavaScript dialect with fewer braces and semicolons',\n // This package version should track the version of the `coffeescript-compiler`\n // package, because people will likely only have this one added to their apps;\n // so bumping the version of this package will be how they get newer versions\n // of `coffeescript-compiler`. If you change this, make sure to also update\n // ../coffeescript-compiler/package.js to match.\n version: '2.3.2_1'\n});\n\nPackage.registerBuildPlugin({\n name: 'compile-coffeescript',\n use: ['caching-compiler@1.1.12', 'ecmascript@0.11.1', 'coffeescript-compiler@2.3.2_1'],\n sources: ['compile-coffeescript.js'],\n npmDependencies: {\n // A breaking change was introduced in @babel/runtime@7.0.0-beta.56\n // with the removal of the @babel/runtime/helpers/builtin directory.\n // Since the compile-coffeescript plugin is bundled and published with\n // a specific version of babel-compiler and babel-runtime, it also\n // needs to have a reliable version of the @babel/runtime npm package,\n // rather than delegating to the one installed in the application's\n // node_modules directory, so the coffeescript package can work in\n // Meteor 1.7.1 apps as well as 1.7.0.x and earlier.\n '@babel/runtime': '7.1.2'\n }\n});\n\nPackage.onUse(function (api) {\n api.use('isobuild:compiler-plugin@1.0.0');\n\n // Because the CoffeeScript plugin now calls\n // BabelCompiler.prototype.processOneFileForTarget for any ES2015+\n // JavaScript or JavaScript enclosed by backticks, it must provide the\n // same runtime environment that the 'ecmascript' package provides.\n // The following api.imply calls should match those in ../../ecmascript/package.js,\n // except that coffeescript does not api.imply('modules').\n api.imply('ecmascript-runtime@0.7.0');\n api.imply('babel-runtime@1.2.4');\n api.imply('promise@0.11.1');\n api.imply('dynamic-import@0.4.1');\n});\n\nPackage.onTest(function (api) {\n api.use(['coffeescript', 'tinytest', 'modern-browsers']);\n api.use(['coffeescript-test-helper', 'ecmascript'], ['client', 'server']); // Need ecmascript to compile tests/es2015_module.js\n api.addFiles('tests/bare_test_setup.coffee', ['client'], {bare: true});\n api.addFiles('tests/bare_tests.js', ['client']);\n api.addFiles([\n 'tests/coffeescript_test_setup.js',\n 'tests/coffeescript_tests.coffee',\n 'tests/coffeescript_strict_tests.coffee',\n 'tests/coffeescript_module.coffee',\n 'tests/es2015_module.js',\n 'tests/litcoffeescript_tests.litcoffee',\n 'tests/litcoffeescript_tests.coffee.md',\n 'tests/coffeescript_tests.js'\n ], ['client', 'server']);\n api.addFiles('tests/modern_browsers.coffee', ['server']);\n});\n", "file_path": "packages/non-core/coffeescript/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0003148744290228933, 0.00018856347014661878, 0.0001630266779102385, 0.00016743817832320929, 5.167225390323438e-05]} {"hunk": {"id": 8, "code_window": [" npm: \"6.9.0\",\n", " pacote: \"https://github.com/meteor/pacote/tarball/c5043daa1b768594e01d76275e3854fc19f038f9\",\n", " \"node-gyp\": \"3.7.0\",\n", " \"node-pre-gyp\": \"0.10.3\",\n", " \"meteor-babel\": \"7.4.12\",\n", " // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"7.4.13\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 16}, "file": "Plugin.registerCompiler({\n extensions: ['myext']\n}, function () {\n return { processFilesForTarget: function () {} };\n});\n", "file_path": "tools/tests/apps/duplicate-compiler-extensions/packages/another-local-plugin/plugin.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00017013824253808707, 0.00017013824253808707, 0.00017013824253808707, 0.00017013824253808707, 0.0]} {"hunk": {"id": 9, "code_window": [" // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n", " reify: \"0.20.4\",\n", " fibers: \"3.1.1\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.4.4\",\n", " // For backwards compatibility with isopackets that still depend on\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 20}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"@babel/code-frame\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz\",\n \"integrity\": \"sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==\"\n },\n \"@babel/core\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz\",\n \"integrity\": \"sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==\",\n \"dependencies\": {\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n }\n }\n },\n \"@babel/generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/generator/-/generator-7.4.4.tgz\",\n \"integrity\": \"sha512-53UOLK6TVNqKxf7RUh8NE851EHRxOOeVXKbK2bivdb+iziMyk03Sr4eaE9OELCbyZAAafAKPDwF2TPUES5QbxQ==\"\n },\n \"@babel/helper-annotate-as-pure\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.0.0.tgz\",\n \"integrity\": \"sha512-3UYcJUj9kvSLbLbUIfQTqzcy5VX7GRZ/CCDrnOaZorFFM01aXp1+GJwuFGV4NDDoAS+mOUyHcO6UD/RfqOks3Q==\"\n },\n \"@babel/helper-builder-binary-assignment-operator-visitor\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.1.0.tgz\",\n \"integrity\": \"sha512-qNSR4jrmJ8M1VMM9tibvyRAHXQs2PmaksQF7c1CGJNipfe3D8p+wgNwgso/P2A2r2mdgBWAXljNWR0QRZAMW8w==\"\n },\n \"@babel/helper-builder-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-builder-react-jsx/-/helper-builder-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-MjA9KgwCuPEkQd9ncSXvSyJ5y+j2sICHyrI0M3L+6fnS4wMSNDc1ARXsbTfbb2cXHn17VisSnU/sHFTCxVxSMw==\"\n },\n \"@babel/helper-call-delegate\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.4.tgz\",\n \"integrity\": \"sha512-l79boDFJ8S1c5hvQvG+rc+wHw6IuH7YldmRKsYtpbawsxURu/paVy57FZMomGK22/JckepaikOkY0MoAmdyOlQ==\"\n },\n \"@babel/helper-create-class-features-plugin\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.4.4.tgz\",\n \"integrity\": \"sha512-UbBHIa2qeAGgyiNR9RszVF7bUHEdgS4JAUNT8SiqrAN6YJVxlOxeLr5pBzb5kan302dejJ9nla4RyKcR1XT6XA==\"\n },\n \"@babel/helper-define-map\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.4.4.tgz\",\n \"integrity\": \"sha512-IX3Ln8gLhZpSuqHJSnTNBWGDE9kdkTEWl21A/K7PQ00tseBwbqCHTvNLHSBd9M0R5rER4h5Rsvj9vw0R5SieBg==\"\n },\n \"@babel/helper-explode-assignable-expression\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.1.0.tgz\",\n \"integrity\": \"sha512-NRQpfHrJ1msCHtKjbzs9YcMmJZOg6mQMmGRB+hbamEdG5PNpaSm95275VD92DvJKuyl0s2sFiDmMZ+EnnvufqA==\"\n },\n \"@babel/helper-function-name\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz\",\n \"integrity\": \"sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==\"\n },\n \"@babel/helper-get-function-arity\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz\",\n \"integrity\": \"sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==\"\n },\n \"@babel/helper-hoist-variables\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.4.4.tgz\",\n \"integrity\": \"sha512-VYk2/H/BnYbZDDg39hr3t2kKyifAm1W6zHRfhx8jGjIHpQEBv9dry7oQ2f3+J703TLu69nYdxsovl0XYfcnK4w==\"\n },\n \"@babel/helper-member-expression-to-functions\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.0.0.tgz\",\n \"integrity\": \"sha512-avo+lm/QmZlv27Zsi0xEor2fKcqWG56D5ae9dzklpIaY7cQMK5N8VSpaNVPPagiqmy7LrEjK1IWdGMOqPu5csg==\"\n },\n \"@babel/helper-module-imports\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz\",\n \"integrity\": \"sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==\"\n },\n \"@babel/helper-module-transforms\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.4.4.tgz\",\n \"integrity\": \"sha512-3Z1yp8TVQf+B4ynN7WoHPKS8EkdTbgAEy0nU0rs/1Kw4pDgmvYH3rz3aI11KgxKCba2cn7N+tqzV1mY2HMN96w==\"\n },\n \"@babel/helper-optimise-call-expression\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.0.0.tgz\",\n \"integrity\": \"sha512-u8nd9NQePYNQV8iPWu/pLLYBqZBa4ZaY1YWRFMuxrid94wKI1QNt67NEZ7GAe5Kc/0LLScbim05xZFWkAdrj9g==\"\n },\n \"@babel/helper-plugin-utils\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz\",\n \"integrity\": \"sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==\"\n },\n \"@babel/helper-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-Y5nuB/kESmR3tKjU8Nkn1wMGEx1tjJX076HBMeL3XLQCu6vA/YRzuTW0bbb+qRnXvQGn+d6Rx953yffl8vEy7Q==\"\n },\n \"@babel/helper-remap-async-to-generator\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.1.0.tgz\",\n \"integrity\": \"sha512-3fOK0L+Fdlg8S5al8u/hWE6vhufGSn0bN09xm2LXMy//REAF8kDCrYoOBKYmA8m5Nom+sV9LyLCwrFynA8/slg==\"\n },\n \"@babel/helper-replace-supers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.4.4.tgz\",\n \"integrity\": \"sha512-04xGEnd+s01nY1l15EuMS1rfKktNF+1CkKmHoErDppjAAZL+IUBZpzT748x262HF7fibaQPhbvWUl5HeSt1EXg==\"\n },\n \"@babel/helper-simple-access\": {\n \"version\": \"7.1.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz\",\n \"integrity\": \"sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==\"\n },\n \"@babel/helper-split-export-declaration\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz\",\n \"integrity\": \"sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==\"\n },\n \"@babel/helper-wrap-function\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.2.0.tgz\",\n \"integrity\": \"sha512-o9fP1BZLLSrYlxYEYyl2aS+Flun5gtjTIG8iln+XuEzQTs0PLagAGSXUcqruJwD5fM48jzIEggCKpIfWTcR7pQ==\"\n },\n \"@babel/helpers\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/helpers/-/helpers-7.4.4.tgz\",\n \"integrity\": \"sha512-igczbR/0SeuPR8RFfC7tGrbdTbFL3QTvH6D+Z6zNxnTe//GyqmtHmDkzrqDmyZ3eSwPqB/LhyKoU5DXsp+Vp2A==\"\n },\n \"@babel/highlight\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz\",\n \"integrity\": \"sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==\"\n },\n \"@babel/parser\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/parser/-/parser-7.4.5.tgz\",\n \"integrity\": \"sha512-9mUqkL1FF5T7f0WDFfAoDdiMVPWsdD1gZYzSnaXsxUCUqzuch/8of9G3VUSNiZmMBoRxT3neyVsqeiL/ZPcjew==\"\n },\n \"@babel/plugin-proposal-async-generator-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-+Dfo/SCQqrwx48ptLVGLdE39YtWRuKc/Y9I5Fy0P1DDBB9lsAHpjcEJQt+4IifuSOSTLBKJObJqMvaO1pIE8LQ==\"\n },\n \"@babel/plugin-proposal-class-properties\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.4.4.tgz\",\n \"integrity\": \"sha512-WjKTI8g8d5w1Bc9zgwSz2nfrsNQsXcCf9J9cdCvrJV6RF56yztwm4TmJC0MgJ9tvwO9gUA/mcYe89bLdGfiXFg==\"\n },\n \"@babel/plugin-proposal-object-rest-spread\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.4.4.tgz\",\n \"integrity\": \"sha512-dMBG6cSPBbHeEBdFXeQ2QLc5gUpg4Vkaz8octD4aoW/ISO+jBOcsuxYL7bsb5WSu8RLP6boxrBIALEHgoHtO9g==\"\n },\n \"@babel/plugin-syntax-async-generators\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.2.0.tgz\",\n \"integrity\": \"sha512-1ZrIRBv2t0GSlcwVoQ6VgSLpLgiN/FVQUzt9znxo7v2Ov4jJrs8RY8tv0wvDmFN3qIdMKWrmMMW6yZ0G19MfGg==\"\n },\n \"@babel/plugin-syntax-dynamic-import\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.2.0.tgz\",\n \"integrity\": \"sha512-mVxuJ0YroI/h/tbFTPGZR8cv6ai+STMKNBq0f8hFxsxWjl94qqhsb+wXbpNMDPU3cfR1TIsVFzU3nXyZMqyK4w==\"\n },\n \"@babel/plugin-syntax-flow\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.2.0.tgz\",\n \"integrity\": \"sha512-r6YMuZDWLtLlu0kqIim5o/3TNRAlWb073HwT3e2nKf9I8IIvOggPrnILYPsrrKilmn/mYEMCf/Z07w3yQJF6dg==\"\n },\n \"@babel/plugin-syntax-jsx\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.2.0.tgz\",\n \"integrity\": \"sha512-VyN4QANJkRW6lDBmENzRszvZf3/4AXaj9YR7GwrWeeN9tEBPuXbmDYVU9bYBN0D70zCWVwUy0HWq2553VCb6Hw==\"\n },\n \"@babel/plugin-syntax-object-rest-spread\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz\",\n \"integrity\": \"sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==\"\n },\n \"@babel/plugin-syntax-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-dGwbSMA1YhVS8+31CnPR7LB4pcbrzcV99wQzby4uAfrkZPYZlQ7ImwdpzLqi6Z6IL02b8IAL379CaMwo0x5Lag==\"\n },\n \"@babel/plugin-transform-arrow-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ER77Cax1+8/8jCB9fo4Ud161OZzWN5qawi4GusDuRLcDbDG+bIGYY20zb2dfAFdTRGzrfq2xZPvF0R64EHnimg==\"\n },\n \"@babel/plugin-transform-async-to-generator\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.4.4.tgz\",\n \"integrity\": \"sha512-YiqW2Li8TXmzgbXw+STsSqPBPFnGviiaSp6CYOq55X8GQ2SGVLrXB6pNid8HkqkZAzOH6knbai3snhP7v0fNwA==\"\n },\n \"@babel/plugin-transform-block-scoped-functions\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.2.0.tgz\",\n \"integrity\": \"sha512-ntQPR6q1/NKuphly49+QiQiTN0O63uOwjdD6dhIjSWBI5xlrbUFh720TIpzBhpnrLfv2tNH/BXvLIab1+BAI0w==\"\n },\n \"@babel/plugin-transform-block-scoping\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.4.4.tgz\",\n \"integrity\": \"sha512-jkTUyWZcTrwxu5DD4rWz6rDB5Cjdmgz6z7M7RLXOJyCUkFBawssDGcGh8M/0FTSB87avyJI1HsTwUXp9nKA1PA==\"\n },\n \"@babel/plugin-transform-classes\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.4.4.tgz\",\n \"integrity\": \"sha512-/e44eFLImEGIpL9qPxSRat13I5QNRgBLu2hOQJCF7VLy/otSM/sypV1+XaIw5+502RX/+6YaSAPmldk+nhHDPw==\"\n },\n \"@babel/plugin-transform-computed-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-kP/drqTxY6Xt3NNpKiMomfgkNn4o7+vKxK2DDKcBG9sHj51vHqMBGy8wbDS/J4lMxnqs153/T3+DmCEAkC5cpA==\"\n },\n \"@babel/plugin-transform-destructuring\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.4.4.tgz\",\n \"integrity\": \"sha512-/aOx+nW0w8eHiEHm+BTERB2oJn5D127iye/SUQl7NjHy0lf+j7h4MKMMSOwdazGq9OxgiNADncE+SRJkCxjZpQ==\"\n },\n \"@babel/plugin-transform-exponentiation-operator\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.2.0.tgz\",\n \"integrity\": \"sha512-umh4hR6N7mu4Elq9GG8TOu9M0bakvlsREEC+ialrQN6ABS4oDQ69qJv1VtR3uxlKMCQMCvzk7vr17RHKcjx68A==\"\n },\n \"@babel/plugin-transform-flow-strip-types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.4.4.tgz\",\n \"integrity\": \"sha512-WyVedfeEIILYEaWGAUWzVNyqG4sfsNooMhXWsu/YzOvVGcsnPb5PguysjJqI3t3qiaYj0BR8T2f5njdjTGe44Q==\"\n },\n \"@babel/plugin-transform-for-of\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.4.4.tgz\",\n \"integrity\": \"sha512-9T/5Dlr14Z9TIEXLXkt8T1DU7F24cbhwhMNUziN3hB1AXoZcdzPcTiKGRn/6iOymDqtTKWnr/BtRKN9JwbKtdQ==\"\n },\n \"@babel/plugin-transform-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-2ThDhm4lI4oV7fVQ6pNNK+sx+c/GM5/SaML0w/r4ZB7sAneD/piDJtwdKlNckXeyGK7wlwg2E2w33C/Hh+VFCg==\"\n },\n \"@babel/plugin-transform-modules-commonjs\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.4.4.tgz\",\n \"integrity\": \"sha512-4sfBOJt58sEo9a2BQXnZq+Q3ZTSAUXyK3E30o36BOGnJ+tvJ6YSxF0PG6kERvbeISgProodWuI9UVG3/FMY6iw==\"\n },\n \"@babel/plugin-transform-object-super\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.2.0.tgz\",\n \"integrity\": \"sha512-VMyhPYZISFZAqAPVkiYb7dUe2AsVi2/wCT5+wZdsNO31FojQJa9ns40hzZ6U9f50Jlq4w6qwzdBB2uwqZ00ebg==\"\n },\n \"@babel/plugin-transform-parameters\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.4.4.tgz\",\n \"integrity\": \"sha512-oMh5DUO1V63nZcu/ZVLQFqiihBGo4OpxJxR1otF50GMeCLiRx5nUdtokd+u9SuVJrvvuIh9OosRFPP4pIPnwmw==\"\n },\n \"@babel/plugin-transform-property-literals\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.2.0.tgz\",\n \"integrity\": \"sha512-9q7Dbk4RhgcLp8ebduOpCbtjh7C0itoLYHXd9ueASKAG/is5PQtMR5VJGka9NKqGhYEGn5ITahd4h9QeBMylWQ==\"\n },\n \"@babel/plugin-transform-react-display-name\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.2.0.tgz\",\n \"integrity\": \"sha512-Htf/tPa5haZvRMiNSQSFifK12gtr/8vwfr+A9y69uF0QcU77AVu4K7MiHEkTxF7lQoHOL0F9ErqgfNEAKgXj7A==\"\n },\n \"@babel/plugin-transform-react-jsx\": {\n \"version\": \"7.3.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.3.0.tgz\",\n \"integrity\": \"sha512-a/+aRb7R06WcKvQLOu4/TpjKOdvVEKRLWFpKcNuHhiREPgGRB4TQJxq07+EZLS8LFVYpfq1a5lDUnuMdcCpBKg==\"\n },\n \"@babel/plugin-transform-react-jsx-self\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.2.0.tgz\",\n \"integrity\": \"sha512-v6S5L/myicZEy+jr6ielB0OR8h+EH/1QFx/YJ7c7Ua+7lqsjj/vW6fD5FR9hB/6y7mGbfT4vAURn3xqBxsUcdg==\"\n },\n \"@babel/plugin-transform-react-jsx-source\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.2.0.tgz\",\n \"integrity\": \"sha512-A32OkKTp4i5U6aE88GwwcuV4HAprUgHcTq0sSafLxjr6AW0QahrCRCjxogkbbcdtpbXkuTOlgpjophCxb6sh5g==\"\n },\n \"@babel/plugin-transform-regenerator\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.5.tgz\",\n \"integrity\": \"sha512-gBKRh5qAaCWntnd09S8QC7r3auLCqq5DI6O0DlfoyDjslSBVqBibrMdsqO+Uhmx3+BlOmE/Kw1HFxmGbv0N9dA==\"\n },\n \"@babel/plugin-transform-runtime\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.4.4.tgz\",\n \"integrity\": \"sha512-aMVojEjPszvau3NRg+TIH14ynZLvPewH4xhlCW1w6A3rkxTS1m4uwzRclYR9oS+rl/dr+kT+pzbfHuAWP/lc7Q==\"\n },\n \"@babel/plugin-transform-shorthand-properties\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.2.0.tgz\",\n \"integrity\": \"sha512-QP4eUM83ha9zmYtpbnyjTLAGKQritA5XW/iG9cjtuOI8s1RuL/3V6a3DeSHfKutJQ+ayUfeZJPcnCYEQzaPQqg==\"\n },\n \"@babel/plugin-transform-spread\": {\n \"version\": \"7.2.2\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.2.2.tgz\",\n \"integrity\": \"sha512-KWfky/58vubwtS0hLqEnrWJjsMGaOeSBn90Ezn5Jeg9Z8KKHmELbP1yGylMlm5N6TPKeY9A2+UaSYLdxahg01w==\"\n },\n \"@babel/plugin-transform-sticky-regex\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.2.0.tgz\",\n \"integrity\": \"sha512-KKYCoGaRAf+ckH8gEL3JHUaFVyNHKe3ASNsZ+AlktgHevvxGigoIttrEJb8iKN03Q7Eazlv1s6cx2B2cQ3Jabw==\"\n },\n \"@babel/plugin-transform-template-literals\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.4.4.tgz\",\n \"integrity\": \"sha512-mQrEC4TWkhLN0z8ygIvEL9ZEToPhG5K7KDW3pzGqOfIGZ28Jb0POUkeWcoz8HnHvhFy6dwAT1j8OzqN8s804+g==\"\n },\n \"@babel/plugin-transform-typeof-symbol\": {\n \"version\": \"7.2.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.2.0.tgz\",\n \"integrity\": \"sha512-2LNhETWYxiYysBtrBTqL8+La0jIoQQnIScUJc74OYvUGRmkskNY4EzLCnjHBzdmb38wqtTaixpo1NctEcvMDZw==\"\n },\n \"@babel/plugin-transform-typescript\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.4.5.tgz\",\n \"integrity\": \"sha512-RPB/YeGr4ZrFKNwfuQRlMf2lxoCUaU01MTw39/OFE/RiL8HDjtn68BwEPft1P7JN4akyEmjGWAMNldOV7o9V2g==\"\n },\n \"@babel/plugin-transform-unicode-regex\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.4.4.tgz\",\n \"integrity\": \"sha512-il+/XdNw01i93+M9J9u4T7/e/Ue/vWfNZE4IRUQjplu2Mqb/AFTDimkw2tdEdSH50wuQXZAbXSql0UphQke+vA==\"\n },\n \"@babel/preset-react\": {\n \"version\": \"7.0.0\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.0.0.tgz\",\n \"integrity\": \"sha512-oayxyPS4Zj+hF6Et11BwuBkmpgT/zMxyuZgFrMeZID6Hdh3dGlk4sHCAhdBCpuCKW2ppBfl2uCCetlrUIJRY3w==\"\n },\n \"@babel/preset-typescript\": {\n \"version\": \"7.3.3\",\n \"resolved\": \"https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.3.3.tgz\",\n \"integrity\": \"sha512-mzMVuIP4lqtn4du2ynEfdO0+RYcslwrZiJHXu4MGaC1ctJiW2fyaeDrtjJGs7R/KebZ1sgowcIoWf4uRpEfKEg==\"\n },\n \"@babel/runtime\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/runtime/-/runtime-7.4.5.tgz\",\n \"integrity\": \"sha512-TuI4qpWZP6lGOGIuGWtp9sPluqYICmbk8T/1vpSysqJxRPkudh/ofFWyqdcMsDf2s7KvDL4/YHgKyvcS3g9CJQ==\"\n },\n \"@babel/template\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/template/-/template-7.4.4.tgz\",\n \"integrity\": \"sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw==\"\n },\n \"@babel/traverse\": {\n \"version\": \"7.4.5\",\n \"resolved\": \"https://registry.npmjs.org/@babel/traverse/-/traverse-7.4.5.tgz\",\n \"integrity\": \"sha512-Vc+qjynwkjRmIFGxy0KYoPj4FdVDxLej89kMHFsWScq999uX+pwcX4v9mWRjW0KcAYTPAuVQl2LKP1wEVLsp+A==\"\n },\n \"@babel/types\": {\n \"version\": \"7.4.4\",\n \"resolved\": \"https://registry.npmjs.org/@babel/types/-/types-7.4.4.tgz\",\n \"integrity\": \"sha512-dOllgYdnEFOebhkKCjzSVFqw/PmmB8pH6RGOWkY4GsboQNd47b1fBThBSwlHAq9alF9vc1M3+6oqR47R50L0tQ==\"\n },\n \"acorn\": {\n \"version\": \"6.1.1\",\n \"resolved\": \"https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz\",\n \"integrity\": \"sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==\"\n },\n \"acorn-dynamic-import\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz\",\n \"integrity\": \"sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==\"\n },\n \"ansi-styles\": {\n \"version\": \"3.2.1\",\n \"resolved\": \"https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz\",\n \"integrity\": \"sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==\"\n },\n \"babel-helper-evaluate-path\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-evaluate-path/-/babel-helper-evaluate-path-0.5.0.tgz\",\n \"integrity\": \"sha512-mUh0UhS607bGh5wUMAQfOpt2JX2ThXMtppHRdRU1kL7ZLRWIXxoV2UIV1r2cAeeNeU1M5SB5/RSUgUxrK8yOkA==\"\n },\n \"babel-helper-flip-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-flip-expressions/-/babel-helper-flip-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-NpZzahKKwYvCUlS19AoizrPB0/0=\"\n },\n \"babel-helper-is-nodes-equiv\": {\n \"version\": \"0.0.1\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-nodes-equiv/-/babel-helper-is-nodes-equiv-0.0.1.tgz\",\n \"integrity\": \"sha1-NOmzALFHnd2Y7HfqC76TQt/jloQ=\"\n },\n \"babel-helper-is-void-0\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-is-void-0/-/babel-helper-is-void-0-0.4.3.tgz\",\n \"integrity\": \"sha1-fZwBtFYee5Xb2g9u7kj1tg5nMT4=\"\n },\n \"babel-helper-mark-eval-scopes\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-mark-eval-scopes/-/babel-helper-mark-eval-scopes-0.4.3.tgz\",\n \"integrity\": \"sha1-0kSjvvmESHJgP/tG4izorN9VFWI=\"\n },\n \"babel-helper-remove-or-void\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-remove-or-void/-/babel-helper-remove-or-void-0.4.3.tgz\",\n \"integrity\": \"sha1-pPA7QAd6D/6I5F0HAQ3uJB/1rmA=\"\n },\n \"babel-helper-to-multiple-sequence-expressions\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-helper-to-multiple-sequence-expressions/-/babel-helper-to-multiple-sequence-expressions-0.5.0.tgz\",\n \"integrity\": \"sha512-m2CvfDW4+1qfDdsrtf4dwOslQC3yhbgyBFptncp4wvtdrDHqueW7slsYv4gArie056phvQFhT2nRcGS4bnm6mA==\"\n },\n \"babel-plugin-minify-builtins\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-builtins/-/babel-plugin-minify-builtins-0.5.0.tgz\",\n \"integrity\": \"sha512-wpqbN7Ov5hsNwGdzuzvFcjgRlzbIeVv1gMIlICbPj0xkexnfoIDe7q+AZHMkQmAE/F9R5jkrB6TLfTegImlXag==\"\n },\n \"babel-plugin-minify-constant-folding\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-constant-folding/-/babel-plugin-minify-constant-folding-0.5.0.tgz\",\n \"integrity\": \"sha512-Vj97CTn/lE9hR1D+jKUeHfNy+m1baNiJ1wJvoGyOBUx7F7kJqDZxr9nCHjO/Ad+irbR3HzR6jABpSSA29QsrXQ==\"\n },\n \"babel-plugin-minify-dead-code-elimination\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-dead-code-elimination/-/babel-plugin-minify-dead-code-elimination-0.5.0.tgz\",\n \"integrity\": \"sha512-XQteBGXlgEoAKc/BhO6oafUdT4LBa7ARi55mxoyhLHNuA+RlzRmeMAfc31pb/UqU01wBzRc36YqHQzopnkd/6Q==\"\n },\n \"babel-plugin-minify-flip-comparisons\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-flip-comparisons/-/babel-plugin-minify-flip-comparisons-0.4.3.tgz\",\n \"integrity\": \"sha1-AMqHDLjxO0XAOLPB68DyJyk8llo=\"\n },\n \"babel-plugin-minify-guarded-expressions\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-guarded-expressions/-/babel-plugin-minify-guarded-expressions-0.4.3.tgz\",\n \"integrity\": \"sha1-zHCbRFP9IbHzAod0RMifiEJ845c=\"\n },\n \"babel-plugin-minify-infinity\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-infinity/-/babel-plugin-minify-infinity-0.4.3.tgz\",\n \"integrity\": \"sha1-37h2obCKBldjhO8/kuZTumB7Oco=\"\n },\n \"babel-plugin-minify-mangle-names\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-mangle-names/-/babel-plugin-minify-mangle-names-0.5.0.tgz\",\n \"integrity\": \"sha512-3jdNv6hCAw6fsX1p2wBGPfWuK69sfOjfd3zjUXkbq8McbohWy23tpXfy5RnToYWggvqzuMOwlId1PhyHOfgnGw==\"\n },\n \"babel-plugin-minify-numeric-literals\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-numeric-literals/-/babel-plugin-minify-numeric-literals-0.4.3.tgz\",\n \"integrity\": \"sha1-jk/VYcefeAEob/YOjF/Z3u6TwLw=\"\n },\n \"babel-plugin-minify-replace\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-replace/-/babel-plugin-minify-replace-0.5.0.tgz\",\n \"integrity\": \"sha512-aXZiaqWDNUbyNNNpWs/8NyST+oU7QTpK7J9zFEFSA0eOmtUNMU3fczlTTTlnCxHmq/jYNFEmkkSG3DDBtW3Y4Q==\"\n },\n \"babel-plugin-minify-simplify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-simplify/-/babel-plugin-minify-simplify-0.5.0.tgz\",\n \"integrity\": \"sha512-TM01J/YcKZ8XIQd1Z3nF2AdWHoDsarjtZ5fWPDksYZNsoOjQ2UO2EWm824Ym6sp127m44gPlLFiO5KFxU8pA5Q==\"\n },\n \"babel-plugin-minify-type-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-minify-type-constructors/-/babel-plugin-minify-type-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-G8bxW4f3qxCF1CszC3F2V6IVZQA=\"\n },\n \"babel-plugin-transform-inline-consecutive-adds\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-inline-consecutive-adds/-/babel-plugin-transform-inline-consecutive-adds-0.4.3.tgz\",\n \"integrity\": \"sha1-Mj1Ho+pjqDp6w8gRro5pQfrysNE=\"\n },\n \"babel-plugin-transform-member-expression-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-member-expression-literals/-/babel-plugin-transform-member-expression-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-NwOcmgwzE6OUlfqsL/OmtbnQOL8=\"\n },\n \"babel-plugin-transform-merge-sibling-variables\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-merge-sibling-variables/-/babel-plugin-transform-merge-sibling-variables-6.9.4.tgz\",\n \"integrity\": \"sha1-hbQi/DN3tEnJ0c3kQIcgNTJAHa4=\"\n },\n \"babel-plugin-transform-minify-booleans\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-minify-booleans/-/babel-plugin-transform-minify-booleans-6.9.4.tgz\",\n \"integrity\": \"sha1-rLs+VqNVXdI5KOS1gtKFFi3SsZg=\"\n },\n \"babel-plugin-transform-property-literals\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-property-literals/-/babel-plugin-transform-property-literals-6.9.4.tgz\",\n \"integrity\": \"sha1-mMHSHiVXNlc/k+zlRFn2ziSYXTk=\"\n },\n \"babel-plugin-transform-regexp-constructors\": {\n \"version\": \"0.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-regexp-constructors/-/babel-plugin-transform-regexp-constructors-0.4.3.tgz\",\n \"integrity\": \"sha1-WLd3W2OvzzMyj66aX4j71PsLSWU=\"\n },\n \"babel-plugin-transform-remove-console\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-console/-/babel-plugin-transform-remove-console-6.9.4.tgz\",\n \"integrity\": \"sha1-uYA2DAZzhOJLNXpYjYB9PINSd4A=\"\n },\n \"babel-plugin-transform-remove-debugger\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-debugger/-/babel-plugin-transform-remove-debugger-6.9.4.tgz\",\n \"integrity\": \"sha1-QrcnYxyXl44estGZp67IShgznvI=\"\n },\n \"babel-plugin-transform-remove-undefined\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-remove-undefined/-/babel-plugin-transform-remove-undefined-0.5.0.tgz\",\n \"integrity\": \"sha512-+M7fJYFaEE/M9CXa0/IRkDbiV3wRELzA1kKQFCJ4ifhrzLKn/9VCCgj9OFmYWwBd8IB48YdgPkHYtbYq+4vtHQ==\"\n },\n \"babel-plugin-transform-simplify-comparison-operators\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-simplify-comparison-operators/-/babel-plugin-transform-simplify-comparison-operators-6.9.4.tgz\",\n \"integrity\": \"sha1-9ir+CWyrDh9ootdT/fKDiIRxzrk=\"\n },\n \"babel-plugin-transform-undefined-to-void\": {\n \"version\": \"6.9.4\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-undefined-to-void/-/babel-plugin-transform-undefined-to-void-6.9.4.tgz\",\n \"integrity\": \"sha1-viQcqBQEAwZ4t0hxcyK4nQyP4oA=\"\n },\n \"babel-preset-meteor\": {\n \"version\": \"7.4.3\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-meteor/-/babel-preset-meteor-7.4.3.tgz\",\n \"integrity\": \"sha512-0nxAvTPAQMMIRM64KcQN3sLgQQSjM41vFZY4lqpAc1vZ9SA3UeYbmMaZ6tqONveiQ09IwTukkVIiAeQd5/mw1Q==\"\n },\n \"babel-preset-minify\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-preset-minify/-/babel-preset-minify-0.5.0.tgz\",\n \"integrity\": \"sha512-xj1s9Mon+RFubH569vrGCayA9Fm2GMsCgDRm1Jb8SgctOB7KFcrVc2o8K3YHUyMz+SWP8aea75BoS8YfsXXuiA==\"\n },\n \"chalk\": {\n \"version\": \"2.4.2\",\n \"resolved\": \"https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz\",\n \"integrity\": \"sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==\"\n },\n \"color-convert\": {\n \"version\": \"1.9.3\",\n \"resolved\": \"https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz\",\n \"integrity\": \"sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==\"\n },\n \"color-name\": {\n \"version\": \"1.1.3\",\n \"resolved\": \"https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz\",\n \"integrity\": \"sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=\"\n },\n \"convert-source-map\": {\n \"version\": \"1.6.0\",\n \"resolved\": \"https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz\",\n \"integrity\": \"sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==\"\n },\n \"debug\": {\n \"version\": \"4.1.1\",\n \"resolved\": \"https://registry.npmjs.org/debug/-/debug-4.1.1.tgz\",\n \"integrity\": \"sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==\"\n },\n \"escape-string-regexp\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz\",\n \"integrity\": \"sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=\"\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"globals\": {\n \"version\": \"11.12.0\",\n \"resolved\": \"https://registry.npmjs.org/globals/-/globals-11.12.0.tgz\",\n \"integrity\": \"sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==\"\n },\n \"has-flag\": {\n \"version\": \"3.0.0\",\n \"resolved\": \"https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz\",\n \"integrity\": \"sha1-tdRU3CGZriJWmfNGfloH87lVuv0=\"\n },\n \"js-tokens\": {\n \"version\": \"4.0.0\",\n \"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz\",\n \"integrity\": \"sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==\"\n },\n \"jsesc\": {\n \"version\": \"2.5.2\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz\",\n \"integrity\": \"sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==\"\n },\n \"json5\": {\n \"version\": \"2.1.0\",\n \"resolved\": \"https://registry.npmjs.org/json5/-/json5-2.1.0.tgz\",\n \"integrity\": \"sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==\"\n },\n \"lodash\": {\n \"version\": \"4.17.11\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz\",\n \"integrity\": \"sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==\"\n },\n \"lodash.isplainobject\": {\n \"version\": \"4.0.6\",\n \"resolved\": \"https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz\",\n \"integrity\": \"sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=\"\n },\n \"lodash.some\": {\n \"version\": \"4.6.0\",\n \"resolved\": \"https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz\",\n \"integrity\": \"sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=\"\n },\n \"meteor-babel\": {\n \"version\": \"7.4.12\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel/-/meteor-babel-7.4.12.tgz\",\n \"integrity\": \"sha512-G405OBkupPl7fOQYhzfTBFrk4FCJ801fwYH9CLN0uerfiwx1mm8tufXB98gjXlxg6EgaQ2TKH0+XwWwLkCVrgQ==\"\n },\n \"meteor-babel-helpers\": {\n \"version\": \"0.0.3\",\n \"resolved\": \"https://registry.npmjs.org/meteor-babel-helpers/-/meteor-babel-helpers-0.0.3.tgz\",\n \"integrity\": \"sha1-8uXZ+HlvvS6JAQI9dpnlsgLqn7A=\"\n },\n \"minimist\": {\n \"version\": \"1.2.0\",\n \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz\",\n \"integrity\": \"sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=\"\n },\n \"ms\": {\n \"version\": \"2.1.2\",\n \"resolved\": \"https://registry.npmjs.org/ms/-/ms-2.1.2.tgz\",\n \"integrity\": \"sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==\"\n },\n \"path-parse\": {\n \"version\": \"1.0.6\",\n \"resolved\": \"https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz\",\n \"integrity\": \"sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==\"\n },\n \"private\": {\n \"version\": \"0.1.8\",\n \"resolved\": \"https://registry.npmjs.org/private/-/private-0.1.8.tgz\",\n \"integrity\": \"sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==\"\n },\n \"regenerate\": {\n \"version\": \"1.4.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz\",\n \"integrity\": \"sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==\"\n },\n \"regenerate-unicode-properties\": {\n \"version\": \"8.1.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz\",\n \"integrity\": \"sha512-LGZzkgtLY79GeXLm8Dp0BVLdQlWICzBnJz/ipWUgo59qBaZ+BHtq51P2q1uVZlppMuUAT37SDk39qUbjTWB7bA==\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.13.2\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.2.tgz\",\n \"integrity\": \"sha512-S/TQAZJO+D3m9xeN1WTI8dLKBBiRgXBlTJvbWjCThHWZj9EvHK70Ff50/tYj2J/fvBY6JtFVwRuazHN2E7M9BA==\"\n },\n \"regenerator-transform\": {\n \"version\": \"0.14.0\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.14.0.tgz\",\n \"integrity\": \"sha512-rtOelq4Cawlbmq9xuMR5gdFmv7ku/sFoB7sRiywx7aq53bc52b4j6zvH7Te1Vt/X2YveDKnCGUbioieU7FEL3w==\"\n },\n \"regexpu-core\": {\n \"version\": \"4.5.4\",\n \"resolved\": \"https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.5.4.tgz\",\n \"integrity\": \"sha512-BtizvGtFQKGPUcTy56o3nk1bGRp4SZOTYrDtGNlqCQufptV5IkkLN6Emw+yunAJjzf+C9FQFtvq7IoA3+oMYHQ==\"\n },\n \"regjsgen\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.0.tgz\",\n \"integrity\": \"sha512-RnIrLhrXCX5ow/E5/Mh2O4e/oa1/jW0eaBKTSy3LaCj+M3Bqvm97GWDp2yUtzIs4LEn65zR2yiYGFqb2ApnzDA==\"\n },\n \"regjsparser\": {\n \"version\": \"0.6.0\",\n \"resolved\": \"https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.0.tgz\",\n \"integrity\": \"sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ==\",\n \"dependencies\": {\n \"jsesc\": {\n \"version\": \"0.5.0\",\n \"resolved\": \"https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz\",\n \"integrity\": \"sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=\"\n }\n }\n },\n \"reify\": {\n \"version\": \"0.20.4\",\n \"resolved\": \"https://registry.npmjs.org/reify/-/reify-0.20.4.tgz\",\n \"integrity\": \"sha512-uE8mYe+JsW9C7Cuaweo9bMRSx3+nNHUSFkJkT1kLogJnhtSENqqmm9D4J9EqTKsApqLSczl7vYKG6Kn4/3Kcqw==\"\n },\n \"resolve\": {\n \"version\": \"1.11.0\",\n \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz\",\n \"integrity\": \"sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==\"\n },\n \"safe-buffer\": {\n \"version\": \"5.1.2\",\n \"resolved\": \"https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz\",\n \"integrity\": \"sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==\"\n },\n \"semver\": {\n \"version\": \"5.7.0\",\n \"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.7.0.tgz\",\n \"integrity\": \"sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==\"\n },\n \"source-map\": {\n \"version\": \"0.5.7\",\n \"resolved\": \"https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz\",\n \"integrity\": \"sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=\"\n },\n \"supports-color\": {\n \"version\": \"5.5.0\",\n \"resolved\": \"https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz\",\n \"integrity\": \"sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==\"\n },\n \"to-fast-properties\": {\n \"version\": \"2.0.0\",\n \"resolved\": \"https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz\",\n \"integrity\": \"sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=\"\n },\n \"trim-right\": {\n \"version\": \"1.0.1\",\n \"resolved\": \"https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz\",\n \"integrity\": \"sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=\"\n },\n \"unicode-canonical-property-names-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ==\"\n },\n \"unicode-match-property-ecmascript\": {\n \"version\": \"1.0.4\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz\",\n \"integrity\": \"sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg==\"\n },\n \"unicode-match-property-value-ecmascript\": {\n \"version\": \"1.1.0\",\n \"resolved\": \"https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz\",\n \"integrity\": \"sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g==\"\n },\n \"unicode-property-aliases-ecmascript\": {\n \"version\": \"1.0.5\",\n \"resolved\": \"https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz\",\n \"integrity\": \"sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw==\"\n }\n }\n}\n", "file_path": "packages/babel-compiler/.npm/package/npm-shrinkwrap.json", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.000236689651501365, 0.00017436579219065607, 0.00016357992717530578, 0.00016955917817540467, 1.4453772564593237e-05]} {"hunk": {"id": 9, "code_window": [" // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n", " reify: \"0.20.4\",\n", " fibers: \"3.1.1\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.4.4\",\n", " // For backwards compatibility with isopackets that still depend on\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 20}, "file": ".build*\n", "file_path": "packages/facebook-oauth/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00017078366363421082, 0.00017078366363421082, 0.00017078366363421082, 0.00017078366363421082, 0.0]} {"hunk": {"id": 9, "code_window": [" // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n", " reify: \"0.20.4\",\n", " fibers: \"3.1.1\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.4.4\",\n", " // For backwards compatibility with isopackets that still depend on\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 20}, "file": "var Future = Npm.require('fibers/future');\n\nvar PHASE = {\n QUERYING: \"QUERYING\",\n FETCHING: \"FETCHING\",\n STEADY: \"STEADY\"\n};\n\n// Exception thrown by _needToPollQuery which unrolls the stack up to the\n// enclosing call to finishIfNeedToPollQuery.\nvar SwitchedToQuery = function () {};\nvar finishIfNeedToPollQuery = function (f) {\n return function () {\n try {\n f.apply(this, arguments);\n } catch (e) {\n if (!(e instanceof SwitchedToQuery))\n throw e;\n }\n };\n};\n\nvar currentId = 0;\n\n// OplogObserveDriver is an alternative to PollingObserveDriver which follows\n// the Mongo operation log instead of just re-polling the query. It obeys the\n// same simple interface: constructing it starts sending observeChanges\n// callbacks (and a ready() invocation) to the ObserveMultiplexer, and you stop\n// it by calling the stop() method.\nOplogObserveDriver = function (options) {\n var self = this;\n self._usesOplog = true; // tests look at this\n\n self._id = currentId;\n currentId++;\n\n self._cursorDescription = options.cursorDescription;\n self._mongoHandle = options.mongoHandle;\n self._multiplexer = options.multiplexer;\n\n if (options.ordered) {\n throw Error(\"OplogObserveDriver only supports unordered observeChanges\");\n }\n\n var sorter = options.sorter;\n // We don't support $near and other geo-queries so it's OK to initialize the\n // comparator only once in the constructor.\n var comparator = sorter && sorter.getComparator();\n\n if (options.cursorDescription.options.limit) {\n // There are several properties ordered driver implements:\n // - _limit is a positive number\n // - _comparator is a function-comparator by which the query is ordered\n // - _unpublishedBuffer is non-null Min/Max Heap,\n // the empty buffer in STEADY phase implies that the\n // everything that matches the queries selector fits\n // into published set.\n // - _published - Min Heap (also implements IdMap methods)\n\n var heapOptions = { IdMap: LocalCollection._IdMap };\n self._limit = self._cursorDescription.options.limit;\n self._comparator = comparator;\n self._sorter = sorter;\n self._unpublishedBuffer = new MinMaxHeap(comparator, heapOptions);\n // We need something that can find Max value in addition to IdMap interface\n self._published = new MaxHeap(comparator, heapOptions);\n } else {\n self._limit = 0;\n self._comparator = null;\n self._sorter = null;\n self._unpublishedBuffer = null;\n self._published = new LocalCollection._IdMap;\n }\n\n // Indicates if it is safe to insert a new document at the end of the buffer\n // for this query. i.e. it is known that there are no documents matching the\n // selector those are not in published or buffer.\n self._safeAppendToBuffer = false;\n\n self._stopped = false;\n self._stopHandles = [];\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-oplog\", 1);\n\n self._registerPhaseChange(PHASE.QUERYING);\n\n self._matcher = options.matcher;\n var projection = self._cursorDescription.options.fields || {};\n self._projectionFn = LocalCollection._compileProjection(projection);\n // Projection function, result of combining important fields for selector and\n // existing fields projection\n self._sharedProjection = self._matcher.combineIntoProjection(projection);\n if (sorter)\n self._sharedProjection = sorter.combineIntoProjection(self._sharedProjection);\n self._sharedProjectionFn = LocalCollection._compileProjection(\n self._sharedProjection);\n\n self._needToFetch = new LocalCollection._IdMap;\n self._currentlyFetching = null;\n self._fetchGeneration = 0;\n\n self._requeryWhenDoneThisQuery = false;\n self._writesToCommitWhenWeReachSteady = [];\n\n // If the oplog handle tells us that it skipped some entries (because it got\n // behind, say), re-poll.\n self._stopHandles.push(self._mongoHandle._oplogHandle.onSkippedEntries(\n finishIfNeedToPollQuery(function () {\n self._needToPollQuery();\n })\n ));\n\n forEachTrigger(self._cursorDescription, function (trigger) {\n self._stopHandles.push(self._mongoHandle._oplogHandle.onOplogEntry(\n trigger, function (notification) {\n Meteor._noYieldsAllowed(finishIfNeedToPollQuery(function () {\n var op = notification.op;\n if (notification.dropCollection || notification.dropDatabase) {\n // Note: this call is not allowed to block on anything (especially\n // on waiting for oplog entries to catch up) because that will block\n // onOplogEntry!\n self._needToPollQuery();\n } else {\n // All other operators should be handled depending on phase\n if (self._phase === PHASE.QUERYING) {\n self._handleOplogEntryQuerying(op);\n } else {\n self._handleOplogEntrySteadyOrFetching(op);\n }\n }\n }));\n }\n ));\n });\n\n // XXX ordering w.r.t. everything else?\n self._stopHandles.push(listenAll(\n self._cursorDescription, function (notification) {\n // If we're not in a pre-fire write fence, we don't have to do anything.\n var fence = DDPServer._CurrentWriteFence.get();\n if (!fence || fence.fired)\n return;\n\n if (fence._oplogObserveDrivers) {\n fence._oplogObserveDrivers[self._id] = self;\n return;\n }\n\n fence._oplogObserveDrivers = {};\n fence._oplogObserveDrivers[self._id] = self;\n\n fence.onBeforeFire(function () {\n var drivers = fence._oplogObserveDrivers;\n delete fence._oplogObserveDrivers;\n\n // This fence cannot fire until we've caught up to \"this point\" in the\n // oplog, and all observers made it back to the steady state.\n self._mongoHandle._oplogHandle.waitUntilCaughtUp();\n\n _.each(drivers, function (driver) {\n if (driver._stopped)\n return;\n\n var write = fence.beginWrite();\n if (driver._phase === PHASE.STEADY) {\n // Make sure that all of the callbacks have made it through the\n // multiplexer and been delivered to ObserveHandles before committing\n // writes.\n driver._multiplexer.onFlush(function () {\n write.committed();\n });\n } else {\n driver._writesToCommitWhenWeReachSteady.push(write);\n }\n });\n });\n }\n ));\n\n // When Mongo fails over, we need to repoll the query, in case we processed an\n // oplog entry that got rolled back.\n self._stopHandles.push(self._mongoHandle._onFailover(finishIfNeedToPollQuery(\n function () {\n self._needToPollQuery();\n })));\n\n // Give _observeChanges a chance to add the new ObserveHandle to our\n // multiplexer, so that the added calls get streamed.\n Meteor.defer(finishIfNeedToPollQuery(function () {\n self._runInitialQuery();\n }));\n};\n\n_.extend(OplogObserveDriver.prototype, {\n _addPublished: function (id, doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var fields = _.clone(doc);\n delete fields._id;\n self._published.set(id, self._sharedProjectionFn(doc));\n self._multiplexer.added(id, self._projectionFn(fields));\n\n // After adding this document, the published set might be overflowed\n // (exceeding capacity specified by limit). If so, push the maximum\n // element to the buffer, we might want to save it in memory to reduce the\n // amount of Mongo lookups in the future.\n if (self._limit && self._published.size() > self._limit) {\n // XXX in theory the size of published is no more than limit+1\n if (self._published.size() !== self._limit + 1) {\n throw new Error(\"After adding to published, \" +\n (self._published.size() - self._limit) +\n \" documents are overflowing the set\");\n }\n\n var overflowingDocId = self._published.maxElementId();\n var overflowingDoc = self._published.get(overflowingDocId);\n\n if (EJSON.equals(overflowingDocId, id)) {\n throw new Error(\"The document just added is overflowing the published set\");\n }\n\n self._published.remove(overflowingDocId);\n self._multiplexer.removed(overflowingDocId);\n self._addBuffered(overflowingDocId, overflowingDoc);\n }\n });\n },\n _removePublished: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._published.remove(id);\n self._multiplexer.removed(id);\n if (! self._limit || self._published.size() === self._limit)\n return;\n\n if (self._published.size() > self._limit)\n throw Error(\"self._published got too big\");\n\n // OK, we are publishing less than the limit. Maybe we should look in the\n // buffer to find the next element past what we were publishing before.\n\n if (!self._unpublishedBuffer.empty()) {\n // There's something in the buffer; move the first thing in it to\n // _published.\n var newDocId = self._unpublishedBuffer.minElementId();\n var newDoc = self._unpublishedBuffer.get(newDocId);\n self._removeBuffered(newDocId);\n self._addPublished(newDocId, newDoc);\n return;\n }\n\n // There's nothing in the buffer. This could mean one of a few things.\n\n // (a) We could be in the middle of re-running the query (specifically, we\n // could be in _publishNewResults). In that case, _unpublishedBuffer is\n // empty because we clear it at the beginning of _publishNewResults. In\n // this case, our caller already knows the entire answer to the query and\n // we don't need to do anything fancy here. Just return.\n if (self._phase === PHASE.QUERYING)\n return;\n\n // (b) We're pretty confident that the union of _published and\n // _unpublishedBuffer contain all documents that match selector. Because\n // _unpublishedBuffer is empty, that means we're confident that _published\n // contains all documents that match selector. So we have nothing to do.\n if (self._safeAppendToBuffer)\n return;\n\n // (c) Maybe there are other documents out there that should be in our\n // buffer. But in that case, when we emptied _unpublishedBuffer in\n // _removeBuffered, we should have called _needToPollQuery, which will\n // either put something in _unpublishedBuffer or set _safeAppendToBuffer\n // (or both), and it will put us in QUERYING for that whole time. So in\n // fact, we shouldn't be able to get here.\n\n throw new Error(\"Buffer inexplicably empty\");\n });\n },\n _changePublished: function (id, oldDoc, newDoc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._published.set(id, self._sharedProjectionFn(newDoc));\n var projectedNew = self._projectionFn(newDoc);\n var projectedOld = self._projectionFn(oldDoc);\n var changed = DiffSequence.makeChangedFields(\n projectedNew, projectedOld);\n if (!_.isEmpty(changed))\n self._multiplexer.changed(id, changed);\n });\n },\n _addBuffered: function (id, doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._unpublishedBuffer.set(id, self._sharedProjectionFn(doc));\n\n // If something is overflowing the buffer, we just remove it from cache\n if (self._unpublishedBuffer.size() > self._limit) {\n var maxBufferedId = self._unpublishedBuffer.maxElementId();\n\n self._unpublishedBuffer.remove(maxBufferedId);\n\n // Since something matching is removed from cache (both published set and\n // buffer), set flag to false\n self._safeAppendToBuffer = false;\n }\n });\n },\n // Is called either to remove the doc completely from matching set or to move\n // it to the published set later.\n _removeBuffered: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._unpublishedBuffer.remove(id);\n // To keep the contract \"buffer is never empty in STEADY phase unless the\n // everything matching fits into published\" true, we poll everything as\n // soon as we see the buffer becoming empty.\n if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer)\n self._needToPollQuery();\n });\n },\n // Called when a document has joined the \"Matching\" results set.\n // Takes responsibility of keeping _unpublishedBuffer in sync with _published\n // and the effect of limit enforced.\n _addMatching: function (doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var id = doc._id;\n if (self._published.has(id))\n throw Error(\"tried to add something already published \" + id);\n if (self._limit && self._unpublishedBuffer.has(id))\n throw Error(\"tried to add something already existed in buffer \" + id);\n\n var limit = self._limit;\n var comparator = self._comparator;\n var maxPublished = (limit && self._published.size() > 0) ?\n self._published.get(self._published.maxElementId()) : null;\n var maxBuffered = (limit && self._unpublishedBuffer.size() > 0)\n ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId())\n : null;\n // The query is unlimited or didn't publish enough documents yet or the\n // new document would fit into published set pushing the maximum element\n // out, then we need to publish the doc.\n var toPublish = ! limit || self._published.size() < limit ||\n comparator(doc, maxPublished) < 0;\n\n // Otherwise we might need to buffer it (only in case of limited query).\n // Buffering is allowed if the buffer is not filled up yet and all\n // matching docs are either in the published set or in the buffer.\n var canAppendToBuffer = !toPublish && self._safeAppendToBuffer &&\n self._unpublishedBuffer.size() < limit;\n\n // Or if it is small enough to be safely inserted to the middle or the\n // beginning of the buffer.\n var canInsertIntoBuffer = !toPublish && maxBuffered &&\n comparator(doc, maxBuffered) <= 0;\n\n var toBuffer = canAppendToBuffer || canInsertIntoBuffer;\n\n if (toPublish) {\n self._addPublished(id, doc);\n } else if (toBuffer) {\n self._addBuffered(id, doc);\n } else {\n // dropping it and not saving to the cache\n self._safeAppendToBuffer = false;\n }\n });\n },\n // Called when a document leaves the \"Matching\" results set.\n // Takes responsibility of keeping _unpublishedBuffer in sync with _published\n // and the effect of limit enforced.\n _removeMatching: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (! self._published.has(id) && ! self._limit)\n throw Error(\"tried to remove something matching but not cached \" + id);\n\n if (self._published.has(id)) {\n self._removePublished(id);\n } else if (self._unpublishedBuffer.has(id)) {\n self._removeBuffered(id);\n }\n });\n },\n _handleDoc: function (id, newDoc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var matchesNow = newDoc && self._matcher.documentMatches(newDoc).result;\n\n var publishedBefore = self._published.has(id);\n var bufferedBefore = self._limit && self._unpublishedBuffer.has(id);\n var cachedBefore = publishedBefore || bufferedBefore;\n\n if (matchesNow && !cachedBefore) {\n self._addMatching(newDoc);\n } else if (cachedBefore && !matchesNow) {\n self._removeMatching(id);\n } else if (cachedBefore && matchesNow) {\n var oldDoc = self._published.get(id);\n var comparator = self._comparator;\n var minBuffered = self._limit && self._unpublishedBuffer.size() &&\n self._unpublishedBuffer.get(self._unpublishedBuffer.minElementId());\n var maxBuffered;\n\n if (publishedBefore) {\n // Unlimited case where the document stays in published once it\n // matches or the case when we don't have enough matching docs to\n // publish or the changed but matching doc will stay in published\n // anyways.\n //\n // XXX: We rely on the emptiness of buffer. Be sure to maintain the\n // fact that buffer can't be empty if there are matching documents not\n // published. Notably, we don't want to schedule repoll and continue\n // relying on this property.\n var staysInPublished = ! self._limit ||\n self._unpublishedBuffer.size() === 0 ||\n comparator(newDoc, minBuffered) <= 0;\n\n if (staysInPublished) {\n self._changePublished(id, oldDoc, newDoc);\n } else {\n // after the change doc doesn't stay in the published, remove it\n self._removePublished(id);\n // but it can move into buffered now, check it\n maxBuffered = self._unpublishedBuffer.get(\n self._unpublishedBuffer.maxElementId());\n\n var toBuffer = self._safeAppendToBuffer ||\n (maxBuffered && comparator(newDoc, maxBuffered) <= 0);\n\n if (toBuffer) {\n self._addBuffered(id, newDoc);\n } else {\n // Throw away from both published set and buffer\n self._safeAppendToBuffer = false;\n }\n }\n } else if (bufferedBefore) {\n oldDoc = self._unpublishedBuffer.get(id);\n // remove the old version manually instead of using _removeBuffered so\n // we don't trigger the querying immediately. if we end this block\n // with the buffer empty, we will need to trigger the query poll\n // manually too.\n self._unpublishedBuffer.remove(id);\n\n var maxPublished = self._published.get(\n self._published.maxElementId());\n maxBuffered = self._unpublishedBuffer.size() &&\n self._unpublishedBuffer.get(\n self._unpublishedBuffer.maxElementId());\n\n // the buffered doc was updated, it could move to published\n var toPublish = comparator(newDoc, maxPublished) < 0;\n\n // or stays in buffer even after the change\n var staysInBuffer = (! toPublish && self._safeAppendToBuffer) ||\n (!toPublish && maxBuffered &&\n comparator(newDoc, maxBuffered) <= 0);\n\n if (toPublish) {\n self._addPublished(id, newDoc);\n } else if (staysInBuffer) {\n // stays in buffer but changes\n self._unpublishedBuffer.set(id, newDoc);\n } else {\n // Throw away from both published set and buffer\n self._safeAppendToBuffer = false;\n // Normally this check would have been done in _removeBuffered but\n // we didn't use it, so we need to do it ourself now.\n if (! self._unpublishedBuffer.size()) {\n self._needToPollQuery();\n }\n }\n } else {\n throw new Error(\"cachedBefore implies either of publishedBefore or bufferedBefore is true.\");\n }\n }\n });\n },\n _fetchModifiedDocuments: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._registerPhaseChange(PHASE.FETCHING);\n // Defer, because nothing called from the oplog entry handler may yield,\n // but fetch() yields.\n Meteor.defer(finishIfNeedToPollQuery(function () {\n while (!self._stopped && !self._needToFetch.empty()) {\n if (self._phase === PHASE.QUERYING) {\n // While fetching, we decided to go into QUERYING mode, and then we\n // saw another oplog entry, so _needToFetch is not empty. But we\n // shouldn't fetch these documents until AFTER the query is done.\n break;\n }\n\n // Being in steady phase here would be surprising.\n if (self._phase !== PHASE.FETCHING)\n throw new Error(\"phase in fetchModifiedDocuments: \" + self._phase);\n\n self._currentlyFetching = self._needToFetch;\n var thisGeneration = ++self._fetchGeneration;\n self._needToFetch = new LocalCollection._IdMap;\n var waiting = 0;\n var fut = new Future;\n // This loop is safe, because _currentlyFetching will not be updated\n // during this loop (in fact, it is never mutated).\n self._currentlyFetching.forEach(function (cacheKey, id) {\n waiting++;\n self._mongoHandle._docFetcher.fetch(\n self._cursorDescription.collectionName, id, cacheKey,\n finishIfNeedToPollQuery(function (err, doc) {\n try {\n if (err) {\n Meteor._debug(\"Got exception while fetching documents\",\n err);\n // If we get an error from the fetcher (eg, trouble\n // connecting to Mongo), let's just abandon the fetch phase\n // altogether and fall back to polling. It's not like we're\n // getting live updates anyway.\n if (self._phase !== PHASE.QUERYING) {\n self._needToPollQuery();\n }\n } else if (!self._stopped && self._phase === PHASE.FETCHING\n && self._fetchGeneration === thisGeneration) {\n // We re-check the generation in case we've had an explicit\n // _pollQuery call (eg, in another fiber) which should\n // effectively cancel this round of fetches. (_pollQuery\n // increments the generation.)\n self._handleDoc(id, doc);\n }\n } finally {\n waiting--;\n // Because fetch() never calls its callback synchronously,\n // this is safe (ie, we won't call fut.return() before the\n // forEach is done).\n if (waiting === 0)\n fut.return();\n }\n }));\n });\n fut.wait();\n // Exit now if we've had a _pollQuery call (here or in another fiber).\n if (self._phase === PHASE.QUERYING)\n return;\n self._currentlyFetching = null;\n }\n // We're done fetching, so we can be steady, unless we've had a\n // _pollQuery call (here or in another fiber).\n if (self._phase !== PHASE.QUERYING)\n self._beSteady();\n }));\n });\n },\n _beSteady: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._registerPhaseChange(PHASE.STEADY);\n var writes = self._writesToCommitWhenWeReachSteady;\n self._writesToCommitWhenWeReachSteady = [];\n self._multiplexer.onFlush(function () {\n _.each(writes, function (w) {\n w.committed();\n });\n });\n });\n },\n _handleOplogEntryQuerying: function (op) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._needToFetch.set(idForOp(op), op.ts.toString());\n });\n },\n _handleOplogEntrySteadyOrFetching: function (op) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var id = idForOp(op);\n // If we're already fetching this one, or about to, we can't optimize;\n // make sure that we fetch it again if necessary.\n if (self._phase === PHASE.FETCHING &&\n ((self._currentlyFetching && self._currentlyFetching.has(id)) ||\n self._needToFetch.has(id))) {\n self._needToFetch.set(id, op.ts.toString());\n return;\n }\n\n if (op.op === 'd') {\n if (self._published.has(id) ||\n (self._limit && self._unpublishedBuffer.has(id)))\n self._removeMatching(id);\n } else if (op.op === 'i') {\n if (self._published.has(id))\n throw new Error(\"insert found for already-existing ID in published\");\n if (self._unpublishedBuffer && self._unpublishedBuffer.has(id))\n throw new Error(\"insert found for already-existing ID in buffer\");\n\n // XXX what if selector yields? for now it can't but later it could\n // have $where\n if (self._matcher.documentMatches(op.o).result)\n self._addMatching(op.o);\n } else if (op.op === 'u') {\n // Is this a modifier ($set/$unset, which may require us to poll the\n // database to figure out if the whole document matches the selector) or\n // a replacement (in which case we can just directly re-evaluate the\n // selector)?\n var isReplace = !_.has(op.o, '$set') && !_.has(op.o, '$unset');\n // If this modifier modifies something inside an EJSON custom type (ie,\n // anything with EJSON$), then we can't try to use\n // LocalCollection._modify, since that just mutates the EJSON encoding,\n // not the actual object.\n var canDirectlyModifyDoc =\n !isReplace && modifierCanBeDirectlyApplied(op.o);\n\n var publishedBefore = self._published.has(id);\n var bufferedBefore = self._limit && self._unpublishedBuffer.has(id);\n\n if (isReplace) {\n self._handleDoc(id, _.extend({_id: id}, op.o));\n } else if ((publishedBefore || bufferedBefore) &&\n canDirectlyModifyDoc) {\n // Oh great, we actually know what the document is, so we can apply\n // this directly.\n var newDoc = self._published.has(id)\n ? self._published.get(id) : self._unpublishedBuffer.get(id);\n newDoc = EJSON.clone(newDoc);\n\n newDoc._id = id;\n try {\n LocalCollection._modify(newDoc, op.o);\n } catch (e) {\n if (e.name !== \"MinimongoError\")\n throw e;\n // We didn't understand the modifier. Re-fetch.\n self._needToFetch.set(id, op.ts.toString());\n if (self._phase === PHASE.STEADY) {\n self._fetchModifiedDocuments();\n }\n return;\n }\n self._handleDoc(id, self._sharedProjectionFn(newDoc));\n } else if (!canDirectlyModifyDoc ||\n self._matcher.canBecomeTrueByModifier(op.o) ||\n (self._sorter && self._sorter.affectedByModifier(op.o))) {\n self._needToFetch.set(id, op.ts.toString());\n if (self._phase === PHASE.STEADY)\n self._fetchModifiedDocuments();\n }\n } else {\n throw Error(\"XXX SURPRISING OPERATION: \" + op);\n }\n });\n },\n // Yields!\n _runInitialQuery: function () {\n var self = this;\n if (self._stopped)\n throw new Error(\"oplog stopped surprisingly early\");\n\n self._runQuery({initial: true}); // yields\n\n if (self._stopped)\n return; // can happen on queryError\n\n // Allow observeChanges calls to return. (After this, it's possible for\n // stop() to be called.)\n self._multiplexer.ready();\n\n self._doneQuerying(); // yields\n },\n\n // In various circumstances, we may just want to stop processing the oplog and\n // re-run the initial query, just as if we were a PollingObserveDriver.\n //\n // This function may not block, because it is called from an oplog entry\n // handler.\n //\n // XXX We should call this when we detect that we've been in FETCHING for \"too\n // long\".\n //\n // XXX We should call this when we detect Mongo failover (since that might\n // mean that some of the oplog entries we have processed have been rolled\n // back). The Node Mongo driver is in the middle of a bunch of huge\n // refactorings, including the way that it notifies you when primary\n // changes. Will put off implementing this until driver 1.4 is out.\n _pollQuery: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (self._stopped)\n return;\n\n // Yay, we get to forget about all the things we thought we had to fetch.\n self._needToFetch = new LocalCollection._IdMap;\n self._currentlyFetching = null;\n ++self._fetchGeneration; // ignore any in-flight fetches\n self._registerPhaseChange(PHASE.QUERYING);\n\n // Defer so that we don't yield. We don't need finishIfNeedToPollQuery\n // here because SwitchedToQuery is not thrown in QUERYING mode.\n Meteor.defer(function () {\n self._runQuery();\n self._doneQuerying();\n });\n });\n },\n\n // Yields!\n _runQuery: function (options) {\n var self = this;\n options = options || {};\n var newResults, newBuffer;\n\n // This while loop is just to retry failures.\n while (true) {\n // If we've been stopped, we don't have to run anything any more.\n if (self._stopped)\n return;\n\n newResults = new LocalCollection._IdMap;\n newBuffer = new LocalCollection._IdMap;\n\n // Query 2x documents as the half excluded from the original query will go\n // into unpublished buffer to reduce additional Mongo lookups in cases\n // when documents are removed from the published set and need a\n // replacement.\n // XXX needs more thought on non-zero skip\n // XXX 2 is a \"magic number\" meaning there is an extra chunk of docs for\n // buffer if such is needed.\n var cursor = self._cursorForQuery({ limit: self._limit * 2 });\n try {\n cursor.forEach(function (doc, i) { // yields\n if (!self._limit || i < self._limit) {\n newResults.set(doc._id, doc);\n } else {\n newBuffer.set(doc._id, doc);\n }\n });\n break;\n } catch (e) {\n if (options.initial && typeof(e.code) === 'number') {\n // This is an error document sent to us by mongod, not a connection\n // error generated by the client. And we've never seen this query work\n // successfully. Probably it's a bad selector or something, so we\n // should NOT retry. Instead, we should halt the observe (which ends\n // up calling `stop` on us).\n self._multiplexer.queryError(e);\n return;\n }\n\n // During failover (eg) if we get an exception we should log and retry\n // instead of crashing.\n Meteor._debug(\"Got exception while polling query\", e);\n Meteor._sleepForMs(100);\n }\n }\n\n if (self._stopped)\n return;\n\n self._publishNewResults(newResults, newBuffer);\n },\n\n // Transitions to QUERYING and runs another query, or (if already in QUERYING)\n // ensures that we will query again later.\n //\n // This function may not block, because it is called from an oplog entry\n // handler. However, if we were not already in the QUERYING phase, it throws\n // an exception that is caught by the closest surrounding\n // finishIfNeedToPollQuery call; this ensures that we don't continue running\n // close that was designed for another phase inside PHASE.QUERYING.\n //\n // (It's also necessary whenever logic in this file yields to check that other\n // phases haven't put us into QUERYING mode, though; eg,\n // _fetchModifiedDocuments does this.)\n _needToPollQuery: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (self._stopped)\n return;\n\n // If we're not already in the middle of a query, we can query now\n // (possibly pausing FETCHING).\n if (self._phase !== PHASE.QUERYING) {\n self._pollQuery();\n throw new SwitchedToQuery;\n }\n\n // We're currently in QUERYING. Set a flag to ensure that we run another\n // query when we're done.\n self._requeryWhenDoneThisQuery = true;\n });\n },\n\n // Yields!\n _doneQuerying: function () {\n var self = this;\n\n if (self._stopped)\n return;\n self._mongoHandle._oplogHandle.waitUntilCaughtUp(); // yields\n if (self._stopped)\n return;\n if (self._phase !== PHASE.QUERYING)\n throw Error(\"Phase unexpectedly \" + self._phase);\n\n Meteor._noYieldsAllowed(function () {\n if (self._requeryWhenDoneThisQuery) {\n self._requeryWhenDoneThisQuery = false;\n self._pollQuery();\n } else if (self._needToFetch.empty()) {\n self._beSteady();\n } else {\n self._fetchModifiedDocuments();\n }\n });\n },\n\n _cursorForQuery: function (optionsOverwrite) {\n var self = this;\n return Meteor._noYieldsAllowed(function () {\n // The query we run is almost the same as the cursor we are observing,\n // with a few changes. We need to read all the fields that are relevant to\n // the selector, not just the fields we are going to publish (that's the\n // \"shared\" projection). And we don't want to apply any transform in the\n // cursor, because observeChanges shouldn't use the transform.\n var options = _.clone(self._cursorDescription.options);\n\n // Allow the caller to modify the options. Useful to specify different\n // skip and limit values.\n _.extend(options, optionsOverwrite);\n\n options.fields = self._sharedProjection;\n delete options.transform;\n // We are NOT deep cloning fields or selector here, which should be OK.\n var description = new CursorDescription(\n self._cursorDescription.collectionName,\n self._cursorDescription.selector,\n options);\n return new Cursor(self._mongoHandle, description);\n });\n },\n\n\n // Replace self._published with newResults (both are IdMaps), invoking observe\n // callbacks on the multiplexer.\n // Replace self._unpublishedBuffer with newBuffer.\n //\n // XXX This is very similar to LocalCollection._diffQueryUnorderedChanges. We\n // should really: (a) Unify IdMap and OrderedDict into Unordered/OrderedDict\n // (b) Rewrite diff.js to use these classes instead of arrays and objects.\n _publishNewResults: function (newResults, newBuffer) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n\n // If the query is limited and there is a buffer, shut down so it doesn't\n // stay in a way.\n if (self._limit) {\n self._unpublishedBuffer.clear();\n }\n\n // First remove anything that's gone. Be careful not to modify\n // self._published while iterating over it.\n var idsToRemove = [];\n self._published.forEach(function (doc, id) {\n if (!newResults.has(id))\n idsToRemove.push(id);\n });\n _.each(idsToRemove, function (id) {\n self._removePublished(id);\n });\n\n // Now do adds and changes.\n // If self has a buffer and limit, the new fetched result will be\n // limited correctly as the query has sort specifier.\n newResults.forEach(function (doc, id) {\n self._handleDoc(id, doc);\n });\n\n // Sanity-check that everything we tried to put into _published ended up\n // there.\n // XXX if this is slow, remove it later\n if (self._published.size() !== newResults.size()) {\n console.error('The Mongo server and the Meteor query disagree on how ' +\n 'many documents match your query. Cursor description: ',\n self._cursorDescription);\n throw Error(\n \"The Mongo server and the Meteor query disagree on how \" +\n \"many documents match your query. Maybe it is hitting a Mongo \" +\n \"edge case? The query is: \" +\n EJSON.stringify(self._cursorDescription.selector));\n }\n self._published.forEach(function (doc, id) {\n if (!newResults.has(id))\n throw Error(\"_published has a doc that newResults doesn't; \" + id);\n });\n\n // Finally, replace the buffer\n newBuffer.forEach(function (doc, id) {\n self._addBuffered(id, doc);\n });\n\n self._safeAppendToBuffer = newBuffer.size() < self._limit;\n });\n },\n\n // This stop function is invoked from the onStop of the ObserveMultiplexer, so\n // it shouldn't actually be possible to call it until the multiplexer is\n // ready.\n //\n // It's important to check self._stopped after every call in this file that\n // can yield!\n stop: function () {\n var self = this;\n if (self._stopped)\n return;\n self._stopped = true;\n _.each(self._stopHandles, function (handle) {\n handle.stop();\n });\n\n // Note: we *don't* use multiplexer.onFlush here because this stop\n // callback is actually invoked by the multiplexer itself when it has\n // determined that there are no handles left. So nothing is actually going\n // to get flushed (and it's probably not valid to call methods on the\n // dying multiplexer).\n _.each(self._writesToCommitWhenWeReachSteady, function (w) {\n w.committed(); // maybe yields?\n });\n self._writesToCommitWhenWeReachSteady = null;\n\n // Proactively drop references to potentially big things.\n self._published = null;\n self._unpublishedBuffer = null;\n self._needToFetch = null;\n self._currentlyFetching = null;\n self._oplogEntryHandle = null;\n self._listenersHandle = null;\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-oplog\", -1);\n },\n\n _registerPhaseChange: function (phase) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var now = new Date;\n\n if (self._phase) {\n var timeDiff = now - self._phaseStartTime;\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"time-spent-in-\" + self._phase + \"-phase\", timeDiff);\n }\n\n self._phase = phase;\n self._phaseStartTime = now;\n });\n }\n});\n\n// Does our oplog tailing code support this cursor? For now, we are being very\n// conservative and allowing only simple queries with simple options.\n// (This is a \"static method\".)\nOplogObserveDriver.cursorSupported = function (cursorDescription, matcher) {\n // First, check the options.\n var options = cursorDescription.options;\n\n // Did the user say no explicitly?\n // underscored version of the option is COMPAT with 1.2\n if (options.disableOplog || options._disableOplog)\n return false;\n\n // skip is not supported: to support it we would need to keep track of all\n // \"skipped\" documents or at least their ids.\n // limit w/o a sort specifier is not supported: current implementation needs a\n // deterministic way to order documents.\n if (options.skip || (options.limit && !options.sort)) return false;\n\n // If a fields projection option is given check if it is supported by\n // minimongo (some operators are not supported).\n if (options.fields) {\n try {\n LocalCollection._checkSupportedProjection(options.fields);\n } catch (e) {\n if (e.name === \"MinimongoError\") {\n return false;\n } else {\n throw e;\n }\n }\n }\n\n // We don't allow the following selectors:\n // - $where (not confident that we provide the same JS environment\n // as Mongo, and can yield!)\n // - $near (has \"interesting\" properties in MongoDB, like the possibility\n // of returning an ID multiple times, though even polling maybe\n // have a bug there)\n // XXX: once we support it, we would need to think more on how we\n // initialize the comparators when we create the driver.\n return !matcher.hasWhere() && !matcher.hasGeoQuery();\n};\n\nvar modifierCanBeDirectlyApplied = function (modifier) {\n return _.all(modifier, function (fields, operation) {\n return _.all(fields, function (value, field) {\n return !/EJSON\\$/.test(field);\n });\n });\n};\n\nMongoInternals.OplogObserveDriver = OplogObserveDriver;\n", "file_path": "packages/mongo/oplog_observe_driver.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.00026851327857002616, 0.00017111431225202978, 0.00015991253894753754, 0.0001694860402494669, 1.4311929589894135e-05]} {"hunk": {"id": 9, "code_window": [" // Keep the versions of these packages consistent with the versions\n", " // found in dev-bundle-server-package.js.\n", " \"meteor-promise\": \"0.8.7\",\n", " reify: \"0.20.4\",\n", " fibers: \"3.1.1\",\n", " // So that Babel can emit require(\"@babel/runtime/helpers/...\") calls.\n", " \"@babel/runtime\": \"7.4.4\",\n", " // For backwards compatibility with isopackets that still depend on\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" reify: \"0.20.5\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 20}, "file": "server\nbrowser\n", "file_path": "tools/static-assets/skel/.meteor/platforms", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/13048740c8eecc66afaa2944d73fd127a4281162", "dependency_score": [0.0001620291150175035, 0.0001620291150175035, 0.0001620291150175035, 0.0001620291150175035, 0.0]} {"hunk": {"id": 0, "code_window": [" const [ startKey, endKey ] = this.renderRange\n", " matches.forEach((m, i) => {\n", " m.active = i === index\n", " })\n", " // console.log(startKey, endKey)\n", " const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 166}, "file": "import virtualize from 'snabbdom-virtualize/strings'\nimport { CLASS_OR_ID, IMAGE_EXT_REG } from '../config'\nimport { conflict, isLengthEven, union, isEven, getUniqueId, loadImage, getImageSrc } from '../utils'\nimport { insertAfter, operateClassName } from '../utils/domManipulate'\nimport { tokenizer } from './parse'\nimport { validEmoji } from '../emojis'\n\nconst snabbdom = require('snabbdom')\nconst patch = snabbdom.init([ // Init patch function with chosen modules\n require('snabbdom/modules/class').default, // makes it easy to toggle classes\n require('snabbdom/modules/attributes').default,\n require('snabbdom/modules/props').default, // for setting properties on DOM elements\n require('snabbdom/modules/dataset').default\n])\nconst h = require('snabbdom/h').default // helper function for creating vnodes\nconst toHTML = require('snabbdom-to-html')\nconst toVNode = require('snabbdom/tovnode').default\n\nconst PRE_BLOCK_HASH = {\n 'code': `.${CLASS_OR_ID['AG_CODE_BLOCK']}`,\n 'html': `.${CLASS_OR_ID['AG_HTML_BLOCK']}`,\n 'frontmatter': `.${CLASS_OR_ID['AG_FRONT_MATTER']}`\n}\n\nclass StateRender {\n constructor (eventCenter) {\n this.eventCenter = eventCenter\n this.loadImageMap = new Map()\n this.container = null\n }\n\n setContainer (container) {\n this.container = container\n }\n\n checkConflicted (block, token, cursor) {\n const { start, end } = cursor\n const key = block.key\n const { start: tokenStart, end: tokenEnd } = token.range\n\n if (key !== start.key && key !== end.key) {\n return false\n } else if (key === start.key && key !== end.key) {\n return conflict([tokenStart, tokenEnd], [start.offset, start.offset])\n } else if (key !== start.key && key === end.key) {\n return conflict([tokenStart, tokenEnd], [end.offset, end.offset])\n } else {\n return conflict([tokenStart, tokenEnd], [start.offset, start.offset]) ||\n conflict([tokenStart, tokenEnd], [end.offset, end.offset])\n }\n }\n\n getClassName (outerClass, block, token, cursor) {\n return outerClass || (this.checkConflicted(block, token, cursor) ? CLASS_OR_ID['AG_GRAY'] : CLASS_OR_ID['AG_HIDE'])\n }\n\n getHighlightClassName (active) {\n return active ? CLASS_OR_ID['AG_HIGHLIGHT'] : CLASS_OR_ID['AG_SELECTION']\n }\n\n getSelector (block, cursor, activeBlocks) {\n const type = block.type === 'hr' ? 'p' : block.type\n const isActive = activeBlocks.some(b => b.key === block.key) || block.key === cursor.start.key\n\n let selector = `${type}#${block.key}.${CLASS_OR_ID['AG_PARAGRAPH']}`\n if (isActive) {\n selector += `.${CLASS_OR_ID['AG_ACTIVE']}`\n }\n if (type === 'span') {\n selector += `.${CLASS_OR_ID['AG_LINE']}`\n }\n if (block.temp) {\n selector += `.${CLASS_OR_ID['AG_TEMP']}`\n }\n return selector\n }\n\n renderLeafBlock (block, cursor, activeBlocks, matches) {\n let selector = this.getSelector(block, cursor, activeBlocks)\n // highlight search key in block\n const highlights = matches.filter(m => m.key === block.key)\n const { text, type, align, htmlContent, icon, checked, key, lang, functionType, codeBlockStyle } = block\n const data = {\n attrs: {},\n dataset: {}\n }\n let children = ''\n\n if (text) {\n children = tokenizer(text, highlights).reduce((acc, token) => [...acc, ...this[token.type](h, cursor, block, token)], [])\n }\n\n if (/th|td/.test(type) && align) {\n Object.assign(data.attrs, {\n style: `text-align:${align}`\n })\n } else if (type === 'div' && htmlContent !== undefined) {\n selector += `.${CLASS_OR_ID['AG_HTML_PREVIEW']}`\n Object.assign(data.attrs, {\n contenteditable: 'false'\n })\n children = virtualize(htmlContent)\n } else if (type === 'svg' && icon) {\n selector += '.icon'\n Object.assign(data.attrs, {\n 'aria-hidden': 'true'\n })\n children = [\n h('use', {\n attrs: {\n 'xlink:href': `#${icon}`\n }\n })\n ]\n } else if (/^h/.test(type)) {\n if (/^h\\d$/.test(type)) {\n Object.assign(data.dataset, {\n head: type\n })\n }\n Object.assign(data.dataset, {\n role: type\n })\n } else if (type === 'input') {\n Object.assign(data.attrs, {\n type: 'checkbox'\n })\n selector = `${type}#${key}.${CLASS_OR_ID['AG_TASK_LIST_ITEM_CHECKBOX']}`\n if (checked) {\n Object.assign(data.attrs, {\n checked: true\n })\n selector += `.${CLASS_OR_ID['AG_CHECKBOX_CHECKED']}`\n }\n children = ''\n } else if (type === 'pre') {\n if (lang) {\n Object.assign(data.dataset, {\n lang\n })\n }\n if (codeBlockStyle) {\n Object.assign(data.dataset, {\n codeBlockStyle\n })\n }\n selector += `.${CLASS_OR_ID['AG_CODEMIRROR_BLOCK']}`\n selector += PRE_BLOCK_HASH[functionType]\n if (functionType !== 'frontmatter') {\n children = ''\n }\n } else if (type === 'span' && functionType === 'frontmatter') {\n selector += `.${CLASS_OR_ID['AG_FRONT_MATTER_LINE']}`\n children = text\n }\n\n return h(selector, data, children)\n }\n\n renderContainerBlock (block, cursor, activeBlocks, matches) {\n let selector = this.getSelector(block, cursor, activeBlocks)\n const data = {\n attrs: {},\n dataset: {}\n }\n // handle `div` block\n if (/div/.test(block.type)) {\n if (block.toolBarType) {\n selector += `.${'ag-tool-' + block.toolBarType}.${CLASS_OR_ID['AG_TOOL_BAR']}`\n }\n if (block.functionType) {\n selector += `.${'ag-function-' + block.functionType}`\n }\n if (block.editable !== undefined && !block.editable) {\n Object.assign(data.attrs, { contenteditable: 'false' })\n }\n }\n // handle `figure` block\n if (block.type === 'figure') {\n if (block.functionType === 'html') { // HTML Block\n Object.assign(data.dataset, { role: block.functionType.toUpperCase() })\n }\n }\n // hanle list block\n if (/ul|ol/.test(block.type) && block.listType) {\n switch (block.listType) {\n case 'order':\n selector += `.${CLASS_OR_ID['AG_ORDER_LIST']}`\n break\n case 'bullet':\n selector += `.${CLASS_OR_ID['AG_BULLET_LIST']}`\n break\n case 'task':\n selector += `.${CLASS_OR_ID['AG_TASK_LIST']}`\n break\n default:\n break\n }\n }\n if (block.type === 'li' && block.label) {\n const { label } = block\n const { align } = activeBlocks[0]\n\n if (align && block.label === align) {\n selector += '.active'\n }\n Object.assign(data.dataset, { label })\n }\n if (block.type === 'li' && block.listItemType) {\n switch (block.listItemType) {\n case 'order':\n selector += `.${CLASS_OR_ID['AG_ORDER_LIST_ITEM']}`\n break\n case 'bullet':\n selector += `.${CLASS_OR_ID['AG_BULLET_LIST_ITEM']}`\n break\n case 'task':\n selector += `.${CLASS_OR_ID['AG_TASK_LIST_ITEM']}`\n break\n default:\n break\n }\n selector += block.isLooseListItem ? `.${CLASS_OR_ID['AG_LOOSE_LIST_ITEM']}` : `.${CLASS_OR_ID['AG_TIGHT_LIST_ITEM']}`\n }\n if (block.type === 'ol') {\n Object.assign(data.attrs, { start: block.start })\n }\n if (block.type === 'pre' && block.functionType === 'frontmatter') {\n Object.assign(data.dataset, { role: 'YAML' })\n selector += `.${CLASS_OR_ID['AG_FRONT_MATTER']}`\n }\n\n return h(selector, data, block.children.map(child => this.renderBlock(child, cursor, activeBlocks, matches)))\n }\n\n /**\n * [renderBlock render one block, no matter it is a container block or text block]\n */\n renderBlock (block, cursor, activeBlocks, matches) {\n const method = block.children.length > 0 ? 'renderContainerBlock' : 'renderLeafBlock'\n\n return this[method](block, cursor, activeBlocks, matches)\n }\n\n render (blocks, cursor, activeBlocks, matches) {\n const selector = `div#${CLASS_OR_ID['AG_EDITOR_ID']}`\n\n const children = blocks.map(block => {\n return this.renderBlock(block, cursor, activeBlocks, matches)\n })\n\n const newVdom = h(selector, children)\n const rootDom = document.querySelector(selector) || this.container\n const oldVdom = toVNode(rootDom)\n\n patch(oldVdom, newVdom)\n }\n\n partialRender (blocks, cursor, activeBlocks, matches, startKey, endKey) {\n const cursorOutMostBlock = activeBlocks[activeBlocks.length - 1]\n // If cursor is not in render blocks, need to render cursor block independently\n const needRenderCursorBlock = blocks.indexOf(cursorOutMostBlock) === -1\n const newVnode = h('section', blocks.map(block => this.renderBlock(block, cursor, activeBlocks, matches)))\n const html = toHTML(newVnode).replace(/^
([\\s\\S]+?)<\\/section>$/, '$1')\n\n const needToRemoved = []\n const firstOldDom = startKey\n ? document.querySelector(`#${startKey}`)\n : document.querySelector(`div#${CLASS_OR_ID['AG_EDITOR_ID']}`).firstElementChild\n needToRemoved.push(firstOldDom)\n let nextSibling = firstOldDom.nextElementSibling\n while (nextSibling && nextSibling.id !== endKey) {\n needToRemoved.push(nextSibling)\n nextSibling = nextSibling.nextElementSibling\n }\n nextSibling && needToRemoved.push(nextSibling)\n\n firstOldDom.insertAdjacentHTML('beforebegin', html)\n\n Array.from(needToRemoved).forEach(dom => dom.remove())\n\n // Render cursor block independently\n if (needRenderCursorBlock) {\n const { key } = cursorOutMostBlock\n const cursorDom = document.querySelector(`#${key}`)\n if (cursorDom) {\n const oldCursorVnode = toVNode(cursorDom)\n const newCursorVnode = this.renderBlock(cursorOutMostBlock, cursor, activeBlocks, matches)\n patch(oldCursorVnode, newCursorVnode)\n }\n }\n }\n\n hr (h, cursor, block, token, outerClass) {\n const { start, end } = token.range\n const content = this.highlight(h, block, start, end, token)\n return [\n h(`span.${CLASS_OR_ID['AG_GRAY']}.${CLASS_OR_ID['AG_REMOVE']}`, content)\n ]\n }\n\n header (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const { start, end } = token.range\n const content = this.highlight(h, block, start, end, token)\n return [\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, content)\n ]\n }\n\n ['tail_header'] (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const { start, end } = token.range\n const content = this.highlight(h, block, start, end, token)\n if (/^h\\d$/.test(block.type)) {\n return [\n h(`span.${className}`, content)\n ]\n } else {\n return content\n }\n }\n\n ['hard_line_break'] (h, cursor, block, token, outerClass) {\n const className = CLASS_OR_ID['AG_HARD_LINE_BREAK']\n const content = [ token.spaces ]\n if (block.type === 'span' && block.nextSibling) {\n return [\n h(`span.${className}`, content)\n ]\n } else {\n return content\n }\n }\n\n ['code_fense'] (h, cursor, block, token, outerClass) {\n const { start, end } = token.range\n const { marker } = token\n\n const markerContent = this.highlight(h, block, start, start + marker.length, token)\n const content = this.highlight(h, block, start + marker.length, end, token)\n\n return [\n h(`span.${CLASS_OR_ID['AG_GRAY']}`, markerContent),\n h(`span.${CLASS_OR_ID['AG_LANGUAGE']}`, content)\n ]\n }\n\n backlash (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const { start, end } = token.range\n const content = this.highlight(h, block, start, end, token)\n\n return [\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, content)\n ]\n }\n\n ['display_math'] (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const { start, end } = token.range\n const { marker } = token\n\n const startMarker = this.highlight(h, block, start, start + marker.length, token)\n const endMarker = this.highlight(h, block, end - marker.length, end, token)\n const content = this.highlight(h, block, start + marker.length, end - marker.length, token)\n\n const { content: math, type } = token\n\n return [\n h(`span.${className}.${CLASS_OR_ID['AG_MATH_MARKER']}`, startMarker),\n h(`span.${className}.${CLASS_OR_ID['AG_MATH']}`, [\n h(`span.${CLASS_OR_ID['AG_MATH_TEXT']}`, content),\n h(`span.${CLASS_OR_ID['AG_MATH_RENDER']}`, {\n dataset: { math, type },\n attrs: { contenteditable: 'false' }\n }, 'Loading')\n ]),\n h(`span.${className}.${CLASS_OR_ID['AG_MATH_MARKER']}`, endMarker)\n ]\n }\n\n ['inline_math'] (h, cursor, block, token, outerClass) {\n return this['display_math'](h, cursor, block, token, outerClass)\n }\n\n ['inline_code'] (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const { marker } = token\n const { start, end } = token.range\n\n const startMarker = this.highlight(h, block, start, start + marker.length, token)\n const endMarker = this.highlight(h, block, end - marker.length, end, token)\n const content = this.highlight(h, block, start + marker.length, end - marker.length, token)\n\n return [\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, startMarker),\n h('code', content),\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, endMarker)\n ]\n }\n\n // change text to highlight vdom\n highlight (h, block, rStart, rEnd, token) {\n const { text } = block\n const { highlights } = token\n let result = []\n let unions = []\n let pos = rStart\n\n if (highlights) {\n for (const light of highlights) {\n const un = union({ start: rStart, end: rEnd }, light)\n if (un) unions.push(un)\n }\n }\n\n if (unions.length) {\n for (const u of unions) {\n const { start, end, active } = u\n const className = this.getHighlightClassName(active)\n\n if (pos < start) {\n result.push(text.substring(pos, start))\n }\n\n result.push(h(`span.${className}`, text.substring(start, end)))\n pos = end\n }\n if (pos < rEnd) {\n result.push(block.text.substring(pos, rEnd))\n }\n } else {\n result = [ text.substring(rStart, rEnd) ]\n }\n\n return result\n }\n // render token of text type to vdom.\n text (h, cursor, block, token) {\n const { start, end } = token.range\n return this.highlight(h, block, start, end, token)\n }\n // render token of emoji to vdom\n emoji (h, cursor, block, token, outerClass) {\n const { start: rStart, end: rEnd } = token.range\n const className = this.getClassName(outerClass, block, token, cursor)\n const validation = validEmoji(token.content)\n const finalClass = validation ? className : CLASS_OR_ID['AG_WARN']\n const CONTENT_CLASSNAME = `span.${finalClass}.${CLASS_OR_ID['AG_EMOJI_MARKED_TEXT']}`\n let startMarkerCN = `span.${finalClass}.${CLASS_OR_ID['AG_EMOJI_MARKER']}`\n let endMarkerCN = startMarkerCN\n let content = token.content\n let pos = rStart + token.marker.length\n\n if (token.highlights && token.highlights.length) {\n content = []\n for (const light of token.highlights) {\n let { start, end, active } = light\n const HIGHLIGHT_CLASSNAME = this.getHighlightClassName(active)\n if (start === rStart) {\n startMarkerCN += `.${HIGHLIGHT_CLASSNAME}`\n start++\n }\n if (end === rEnd) {\n endMarkerCN += `.${HIGHLIGHT_CLASSNAME}`\n end--\n }\n if (pos < start) {\n content.push(block.text.substring(pos, start))\n }\n if (start < end) {\n content.push(h(`span.${HIGHLIGHT_CLASSNAME}`, block.text.substring(start, end)))\n }\n pos = end\n }\n if (pos < rEnd - token.marker.length) {\n content.push(block.text.substring(pos, rEnd - 1))\n }\n }\n\n const emojiVdom = validation\n ? h(CONTENT_CLASSNAME, {\n dataset: {\n emoji: validation.emoji\n }\n }, content)\n : h(CONTENT_CLASSNAME, content)\n\n return [\n h(startMarkerCN, token.marker),\n emojiVdom,\n h(endMarkerCN, token.marker)\n ]\n }\n\n // render factory of `del`,`em`,`strong`\n delEmStrongFac (type, h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const COMMON_MARKER = `span.${className}.${CLASS_OR_ID['AG_REMOVE']}`\n const { marker } = token\n const { start, end } = token.range\n const backlashStart = end - marker.length - token.backlash.length\n const content = [\n ...token.children.reduce((acc, to) => {\n const chunk = this[to.type](h, cursor, block, to, className)\n return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]\n }, []),\n ...this.backlashInToken(token.backlash, className, backlashStart, token)\n ]\n const startMarker = this.highlight(h, block, start, start + marker.length, token)\n const endMarker = this.highlight(h, block, end - marker.length, end, token)\n\n if (isLengthEven(token.backlash)) {\n return [\n h(COMMON_MARKER, startMarker),\n h(type, content),\n h(COMMON_MARKER, endMarker)\n ]\n } else {\n return [\n ...startMarker,\n ...content,\n ...endMarker\n ]\n }\n }\n // TODO HIGHLIGHT\n backlashInToken (backlashes, outerClass, start, token) {\n const { highlights = [] } = token\n const chunks = backlashes.split('')\n const len = chunks.length\n const result = []\n let i\n\n for (i = 0; i < len; i++) {\n const chunk = chunks[i]\n const light = highlights.filter(light => union({ start: start + i, end: start + i + 1 }, light))\n let selector = 'span'\n if (light.length) {\n const className = this.getHighlightClassName(light[0].active)\n selector += `.${className}`\n }\n if (isEven(i)) {\n result.push(\n h(`${selector}.${outerClass}`, chunk)\n )\n } else {\n result.push(\n h(`${selector}.${CLASS_OR_ID['AG_BACKLASH']}`, chunk)\n )\n }\n }\n\n return result\n }\n\n loadImageAsync (src, alt, className, imageClass) {\n let id\n let isSuccess\n\n if (!this.loadImageMap.has(src)) {\n id = getUniqueId()\n loadImage(src)\n .then(url => {\n const imageWrapper = document.querySelector(`#${id}`)\n const img = document.createElement('img')\n img.src = url\n if (alt) img.alt = alt\n if (imageClass) {\n img.classList.add(imageClass)\n }\n if (imageWrapper) {\n insertAfter(img, imageWrapper)\n operateClassName(imageWrapper, 'add', className)\n }\n this.loadImageMap.set(src, {\n id,\n isSuccess: true\n })\n })\n .catch(() => {\n const imageWrapper = document.querySelector(`#${id}`)\n if (imageWrapper) {\n operateClassName(imageWrapper, 'add', CLASS_OR_ID['AG_IMAGE_FAIL'])\n }\n this.loadImageMap.set(src, {\n id,\n isSuccess: false\n })\n })\n } else {\n const imageInfo = this.loadImageMap.get(src)\n id = imageInfo.id\n isSuccess = imageInfo.isSuccess\n }\n\n return { id, isSuccess }\n }\n\n // I dont want operate dom directly, is there any better method? need help!\n image (h, cursor, block, token, outerClass) {\n const { eventCenter } = this\n const { start: cursorStart, end: cursorEnd } = cursor\n const { start, end } = token.range\n if (\n cursorStart.key === cursorEnd.key &&\n cursorStart.offset === cursorEnd.offset &&\n cursorStart.offset === end - 1 &&\n !IMAGE_EXT_REG.test(token.src)\n ) {\n eventCenter.dispatch('image-path', token.src)\n }\n\n const className = this.getClassName(outerClass, block, token, cursor)\n const imageClass = CLASS_OR_ID['AG_IMAGE_MARKED_TEXT']\n\n const titleContent = this.highlight(h, block, start, start + 2 + token.title.length, token)\n\n const srcContent = this.highlight(\n h, block,\n start + 2 + token.title.length + token.backlash.first.length + 2,\n start + 2 + token.title.length + token.backlash.first.length + 2 + token.src.length,\n token\n )\n\n const firstBracketContent = this.highlight(h, block, start, start + 2, token)\n\n const secondBracketContent = this.highlight(\n h, block,\n start + 2 + token.title.length + token.backlash.first.length,\n start + 2 + token.title.length + token.backlash.first.length + 2,\n token\n )\n\n const lastBracketContent = this.highlight(h, block, end - 1, end, token)\n\n const firstBacklashStart = start + 2 + token.title.length\n\n const secondBacklashStart = end - 1 - token.backlash.second.length\n\n if (isLengthEven(token.backlash.first) && isLengthEven(token.backlash.second)) {\n let id\n let isSuccess\n let selector\n const src = getImageSrc(token.src + encodeURI(token.backlash.second))\n const alt = token.title + encodeURI(token.backlash.first)\n\n if (src) {\n ({ id, isSuccess } = this.loadImageAsync(src, alt, className))\n }\n\n selector = id ? `span#${id}.${imageClass}.${CLASS_OR_ID['AG_REMOVE']}` : `span.${imageClass}.${CLASS_OR_ID['AG_REMOVE']}`\n\n if (isSuccess) {\n selector += `.${className}`\n } else {\n selector += `.${CLASS_OR_ID['AG_IMAGE_FAIL']}`\n }\n const children = [\n ...titleContent,\n ...this.backlashInToken(token.backlash.first, className, firstBacklashStart, token),\n ...secondBracketContent,\n h(`span.${CLASS_OR_ID['AG_IMAGE_SRC']}`, srcContent),\n ...this.backlashInToken(token.backlash.second, className, secondBacklashStart, token),\n ...lastBracketContent\n ]\n\n return isSuccess\n ? [\n h(selector, children),\n h('img', { props: { alt, src } })\n ]\n : [h(selector, children)]\n } else {\n return [\n ...firstBracketContent,\n ...token.children.reduce((acc, to) => {\n const chunk = this[to.type](h, cursor, block, to, className)\n return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]\n }, []),\n ...this.backlashInToken(token.backlash.first, className, firstBacklashStart, token),\n ...secondBracketContent,\n ...srcContent,\n ...this.backlashInToken(token.backlash.second, className, secondBacklashStart, token),\n ...lastBracketContent\n ]\n }\n }\n\n // html_image\n ['html_image'] (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const imageClass = CLASS_OR_ID['AG_IMAGE_MARKED_TEXT']\n const { start, end } = token.range\n const tag = this.highlight(h, block, start, end, token)\n const { src: rawSrc, alt } = token\n const src = getImageSrc(rawSrc)\n let id\n let isSuccess\n let selector\n if (src) {\n ({ id, isSuccess } = this.loadImageAsync(src, alt, className, CLASS_OR_ID['AG_COPY_REMOVE']))\n }\n selector = id ? `span#${id}.${imageClass}.${CLASS_OR_ID['AG_HTML_TAG']}` : `span.${imageClass}.${CLASS_OR_ID['AG_HTML_TAG']}`\n selector += `.${CLASS_OR_ID['AG_OUTPUT_REMOVE']}`\n if (isSuccess) {\n selector += `.${className}`\n } else {\n selector += `.${CLASS_OR_ID['AG_IMAGE_FAIL']}`\n }\n\n return isSuccess\n ? [\n h(selector, tag),\n h(`img.${CLASS_OR_ID['AG_COPY_REMOVE']}`, { props: { alt, src } })\n ]\n : [h(selector, tag)]\n }\n\n // render auto_link to vdom\n ['auto_link'] (h, cursor, block, token, outerClass) {\n const { start, end } = token.range\n const content = this.highlight(h, block, start, end, token)\n\n return [\n h('a', {\n props: {\n href: token.href\n }\n }, content)\n ]\n }\n\n // `a_link`: `anchor`\n ['a_link'] (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const tagClassName = className === CLASS_OR_ID['AG_HIDE'] ? className : CLASS_OR_ID['AG_HTML_TAG']\n const { start, end } = token.range\n const openTag = this.highlight(h, block, start, start + token.openTag.length, token)\n const anchor = token.children.reduce((acc, to) => {\n const chunk = this[to.type](h, cursor, block, to, className)\n return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]\n }, [])\n const closeTag = this.highlight(h, block, end - token.closeTag.length, end, token)\n\n return [\n h(`span.${tagClassName}.${CLASS_OR_ID['AG_OUTPUT_REMOVE']}`, openTag),\n h(`a.${CLASS_OR_ID['AG_A_LINK']}`, {\n dataset: {\n href: token.href\n }\n }, anchor),\n h(`span.${tagClassName}.${CLASS_OR_ID['AG_OUTPUT_REMOVE']}`, closeTag)\n ]\n }\n\n ['html_tag'] (h, cursor, block, token, outerClass) {\n const className = CLASS_OR_ID['AG_HTML_TAG']\n const { start, end } = token.range\n const tag = this.highlight(h, block, start, end, token)\n const isBr = /)/.test(token.tag)\n return [\n h(`span.${className}`, isBr ? [...tag, h('br')] : tag)\n ]\n }\n\n // 'link': /^(\\[)((?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*?)(\\\\*)\\]\\((.*?)(\\\\*)\\)/, // can nest\n link (h, cursor, block, token, outerClass) {\n const className = this.getClassName(outerClass, block, token, cursor)\n const linkClassName = className === CLASS_OR_ID['AG_HIDE'] ? className : CLASS_OR_ID['AG_LINK_IN_BRACKET']\n const { start, end } = token.range\n const firstMiddleBracket = this.highlight(h, block, start, start + 3, token)\n\n const firstBracket = this.highlight(h, block, start, start + 1, token)\n const middleBracket = this.highlight(\n h, block,\n start + 1 + token.anchor.length + token.backlash.first.length,\n start + 1 + token.anchor.length + token.backlash.first.length + 2,\n token\n )\n const hrefContent = this.highlight(\n h, block,\n start + 1 + token.anchor.length + token.backlash.first.length + 2,\n start + 1 + token.anchor.length + token.backlash.first.length + 2 + token.href.length,\n token\n )\n const middleHref = this.highlight(\n h, block, start + 1 + token.anchor.length + token.backlash.first.length,\n block, start + 1 + token.anchor.length + token.backlash.first.length + 2 + token.href.length,\n token\n )\n\n const lastBracket = this.highlight(h, block, end - 1, end, token)\n\n const firstBacklashStart = start + 1 + token.anchor.length\n const secondBacklashStart = end - 1 - token.backlash.second.length\n\n if (isLengthEven(token.backlash.first) && isLengthEven(token.backlash.second)) {\n if (!token.children.length && !token.backlash.first) { // no-text-link\n return [\n h(`span.${CLASS_OR_ID['AG_GRAY']}.${CLASS_OR_ID['AG_REMOVE']}`, firstMiddleBracket),\n h(`a.${CLASS_OR_ID['AG_NOTEXT_LINK']}`, {\n props: {\n href: token.href + encodeURI(token.backlash.second)\n }\n }, [\n ...hrefContent,\n ...this.backlashInToken(token.backlash.second, className, secondBacklashStart, token)\n ]),\n h(`span.${CLASS_OR_ID['AG_GRAY']}.${CLASS_OR_ID['AG_REMOVE']}`, lastBracket)\n ]\n } else { // has children\n return [\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, firstBracket),\n h('a', {\n dataset: {\n href: token.href + encodeURI(token.backlash.second)\n }\n }, [\n ...token.children.reduce((acc, to) => {\n const chunk = this[to.type](h, cursor, block, to, className)\n return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]\n }, []),\n ...this.backlashInToken(token.backlash.first, className, firstBacklashStart, token)\n ]),\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, middleBracket),\n h(`span.${linkClassName}.${CLASS_OR_ID['AG_REMOVE']}`, [\n ...hrefContent,\n ...this.backlashInToken(token.backlash.second, className, secondBacklashStart, token)\n ]),\n h(`span.${className}.${CLASS_OR_ID['AG_REMOVE']}`, lastBracket)\n ]\n }\n } else {\n return [\n ...firstBracket,\n ...token.children.reduce((acc, to) => {\n const chunk = this[to.type](h, cursor, block, to, className)\n return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]\n }, []),\n ...this.backlashInToken(token.backlash.first, className, firstBacklashStart, token),\n ...middleHref,\n ...this.backlashInToken(token.backlash.second, className, secondBacklashStart, token),\n ...lastBracket\n ]\n }\n }\n\n del (h, cursor, block, token, outerClass) {\n return this.delEmStrongFac('del', h, cursor, block, token, outerClass)\n }\n\n em (h, cursor, block, token, outerClass) {\n return this.delEmStrongFac('em', h, cursor, block, token, outerClass)\n }\n\n strong (h, cursor, block, token, outerClass) {\n return this.delEmStrongFac('strong', h, cursor, block, token, outerClass)\n }\n}\n\nexport default StateRender\n", "file_path": "src/editor/parser/StateRender.js", "label": 1, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.9972180128097534, 0.019410759210586548, 0.00016443990170955658, 0.00017963448772206903, 0.12341687828302383]} {"hunk": {"id": 0, "code_window": [" const [ startKey, endKey ] = this.renderRange\n", " matches.forEach((m, i) => {\n", " m.active = i === index\n", " })\n", " // console.log(startKey, endKey)\n", " const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 166}, "file": "import Vue from 'vue'\nimport LandingPage from '@/components/LandingPage'\n\ndescribe('LandingPage.vue', () => {\n it('should render correct contents', () => {\n const vm = new Vue({\n el: document.createElement('div'),\n render: h => h(LandingPage)\n }).$mount()\n\n expect(vm.$el.querySelector('.title').textContent).to.contain('Welcome to your new project!')\n })\n})\n", "file_path": "test/unit/specs/LandingPage.spec.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.0001772169634932652, 0.00017614199896343052, 0.00017506704898551106, 0.00017614199896343052, 1.0749572538770735e-06]} {"hunk": {"id": 0, "code_window": [" const [ startKey, endKey ] = this.renderRange\n", " matches.forEach((m, i) => {\n", " m.active = i === index\n", " })\n", " // console.log(startKey, endKey)\n", " const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 166}, "file": "# Commented sections below can be used to run tests on the CI server\n# https://simulatedgreg.gitbooks.io/electron-vue/content/en/testing.html#on-the-subject-of-ci-testing\nosx_image: xcode9.2\nsudo: required\ndist: trusty\n\nlanguage: node_js\nnode_js:\n - 8\n\nmatrix:\n include:\n - os: osx\n env: CC=clang CXX=clang++ npm_config_clang=1\n compiler: clang\n - os: linux\n env: CC=clang CXX=clang++ npm_config_clang=1\n compiler: clang\n\ncache:\n directories:\n - node_modules\n - \"$HOME/.electron\"\n - \"$HOME/.cache\"\n\naddons:\n apt:\n packages:\n - libgnome-keyring-dev\n - icnsutils\n - graphicsmagick\n - xz-utils\n #- xvfb\n\nbefore_install:\n #- if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then sudo apt-get -qq update ; fi\n #- if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then\n # wget -qO - https://dl.winehq.org/wine-builds/Release.key | sudo apt-key add -;\n # sudo apt-add-repository https://dl.winehq.org/wine-builds/ubuntu/;\n # fi\n - if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then sudo apt-get -qq update ; fi\n #- if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then sudo apt-get install --install-recommends winehq-stable ; fi\n\n #- if [[ \"$TRAVIS_OS_NAME\" == \"osx\" ]]; then brew update ; fi\n\ninstall:\n #- if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then export DISPLAY=':99.0' ; fi\n #- if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & ; fi\n - curl -o- -L https://yarnpkg.com/install.sh | bash\n - source ~/.bashrc\n - npm install -g xvfb-maybe\n\n - $CC --version\n - $CXX --version\n - npm --version\n - yarn --version\n\n - yarn\n\nscript:\n #- xvfb-maybe node_modules/.bin/karma start test/unit/karma.conf.js\n #- yarn run pack && xvfb-maybe node_modules/.bin/mocha test/e2e\n - if [[ \"$TRAVIS_OS_NAME\" == \"linux\" ]]; then yarn run release:linux ; fi\n - if [[ \"$TRAVIS_OS_NAME\" == \"osx\" ]]; then yarn run release ; fi\n\nbranches:\n only:\n - master\n", "file_path": ".travis.yml", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.00017604093591216952, 0.00017260454478673637, 0.00016662639973219484, 0.00017272861441597342, 3.020911208295729e-06]} {"hunk": {"id": 0, "code_window": [" const [ startKey, endKey ] = this.renderRange\n", " matches.forEach((m, i) => {\n", " m.active = i === index\n", " })\n", " // console.log(startKey, endKey)\n", " const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 166}, "file": "!macro customUnInstall\n MessageBox MB_YESNO \"Do you want to delete user settings?\" /SD IDNO IDNO SkipRemoval\n SetShellVarContext current\n RMDir /r \"$APPDATA\\marktext\"\n SkipRemoval:\n!macroend\n", "file_path": "build/windows/installer.nsh", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.0001763606269378215, 0.0001763606269378215, 0.0001763606269378215, 0.0001763606269378215, 0.0]} {"hunk": {"id": 1, "code_window": [" const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n", " // console.log(JSON.stringify(needRenderBlocks, null, 2), startKey, endKey)\n", " this.setNextRenderRange()\n", " this.stateRender.partialRender(needRenderBlocks, cursor, activeBlocks, matches, startKey, endKey)\n", " this.pre2CodeMirror(true, [...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n", " this.renderMath([...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["\n"], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 170}, "file": "import { HAS_TEXT_BLOCK_REG } from '../config'\nimport { setCursorAtLastLine } from '../codeMirror'\nimport { getUniqueId } from '../utils'\nimport selection from '../selection'\nimport StateRender from '../parser/StateRender'\nimport enterCtrl from './enterCtrl'\nimport updateCtrl from './updateCtrl'\nimport backspaceCtrl from './backspaceCtrl'\nimport codeBlockCtrl from './codeBlockCtrl'\nimport tableBlockCtrl from './tableBlockCtrl'\nimport History from './history'\nimport arrowCtrl from './arrowCtrl'\nimport pasteCtrl from './pasteCtrl'\nimport copyCutCtrl from './copyCutCtrl'\nimport paragraphCtrl from './paragraphCtrl'\nimport tabCtrl from './tabCtrl'\nimport formatCtrl from './formatCtrl'\nimport searchCtrl from './searchCtrl'\nimport mathCtrl from './mathCtrl'\nimport imagePathCtrl from './imagePathCtrl'\nimport htmlBlockCtrl from './htmlBlock'\nimport importMarkdown from '../utils/importMarkdown'\n\nconst prototypes = [\n tabCtrl,\n enterCtrl,\n updateCtrl,\n backspaceCtrl,\n codeBlockCtrl,\n arrowCtrl,\n pasteCtrl,\n copyCutCtrl,\n tableBlockCtrl,\n paragraphCtrl,\n formatCtrl,\n searchCtrl,\n mathCtrl,\n imagePathCtrl,\n htmlBlockCtrl,\n importMarkdown\n]\n\nclass ContentState {\n constructor (options) {\n const { eventCenter } = options\n Object.assign(this, options)\n // Use to cache the keys which you don't want to remove.\n this.exemption = new Set()\n this.blocks = [ this.createBlockP() ]\n this.stateRender = new StateRender(eventCenter)\n this.codeBlocks = new Map()\n this.loadMathMap = new Map()\n this.renderRange = [ null, null ]\n this.currentCursor = null\n this.prevCursor = null\n this.historyTimer = null\n this.history = new History(this)\n this.init()\n }\n\n set cursor (cursor) {\n if (this.currentCursor) {\n const { start, end } = this.currentCursor\n if (\n start.key === cursor.start.key &&\n start.offset === cursor.start.offset &&\n end.key === cursor.end.key &&\n end.offset === cursor.end.offset\n ) {\n return\n }\n }\n\n const handler = () => {\n const { blocks, renderRange, currentCursor } = this\n this.history.push({\n type: 'normal',\n blocks,\n renderRange,\n cursor: currentCursor\n })\n }\n this.prevCursor = this.currentCursor\n this.currentCursor = cursor\n\n if (!cursor.noHistory) {\n if (\n this.prevCursor && (this.prevCursor.start.key !== cursor.start.key || this.prevCursor.end.key !== cursor.end.key)\n ) {\n handler()\n } else {\n if (this.historyTimer) clearTimeout(this.historyTimer)\n this.historyTimer = setTimeout(handler, 2000)\n }\n } else {\n cursor.noHistory && delete cursor.noHistory\n }\n }\n\n get cursor () {\n return this.currentCursor\n }\n\n init () {\n const lastBlock = this.getLastBlock()\n const { key, text } = lastBlock\n const offset = text.length\n this.searchMatches = {\n value: '', // the search value\n matches: [], // matches\n index: -1 // active match\n }\n this.cursor = {\n start: { key, offset },\n end: { key, offset }\n }\n }\n\n setCursor () {\n const { start: { key } } = this.cursor\n const block = this.getBlock(key)\n if (block.type === 'pre' && block.functionType !== 'frontmatter') {\n const cm = this.codeBlocks.get(key)\n const { pos } = block\n if (pos) {\n cm.focus()\n cm.setCursor(pos)\n } else {\n setCursorAtLastLine(cm)\n }\n } else {\n selection.setCursorRange(this.cursor)\n }\n }\n\n setNextRenderRange () {\n const { start, end } = this.cursor\n // console.log(JSON.stringify(this.cursor, null, 2))\n const startBlock = this.getBlock(start.key)\n const endBlock = this.getBlock(end.key)\n const startOutMostBlock = this.findOutMostBlock(startBlock)\n const endOutMostBlock = this.findOutMostBlock(endBlock)\n this.renderRange = [ startOutMostBlock.preSibling, endOutMostBlock.nextSibling ]\n }\n\n render (isRenderCursor = true) {\n const { blocks, cursor, searchMatches: { matches, index } } = this\n const activeBlocks = this.getActiveBlocks()\n matches.forEach((m, i) => {\n m.active = i === index\n })\n this.setNextRenderRange()\n this.stateRender.render(blocks, cursor, activeBlocks, matches)\n this.pre2CodeMirror(isRenderCursor)\n this.renderMath()\n if (isRenderCursor) this.setCursor()\n }\n\n partialRender () {\n const { blocks, cursor, searchMatches: { matches, index } } = this\n const activeBlocks = this.getActiveBlocks()\n const cursorOutMostBlock = activeBlocks[activeBlocks.length - 1]\n const [ startKey, endKey ] = this.renderRange\n matches.forEach((m, i) => {\n m.active = i === index\n })\n // console.log(startKey, endKey)\n const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n const needRenderBlocks = blocks.slice(startIndex, endIndex)\n // console.log(JSON.stringify(needRenderBlocks, null, 2), startKey, endKey)\n this.setNextRenderRange()\n this.stateRender.partialRender(needRenderBlocks, cursor, activeBlocks, matches, startKey, endKey)\n this.pre2CodeMirror(true, [...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n this.renderMath([...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n this.setCursor()\n }\n\n /**\n * A block in Aganippe present a paragraph(block syntax in GFM) or a line in paragraph.\n * a line block must in a `p block` or `pre block(frontmatter)` and `p block`'s children must be line blocks.\n */\n createBlock (type = 'span', text = '') { // span type means it is a line block.\n const key = getUniqueId()\n return {\n key,\n type,\n text,\n parent: null,\n preSibling: null,\n nextSibling: null,\n children: []\n }\n }\n\n createBlockP (text = '') {\n const pBlock = this.createBlock('p')\n const lineBlock = this.createBlock('span', text)\n this.appendChild(pBlock, lineBlock)\n return pBlock\n }\n\n isCollapse (cursor = this.cursor) {\n const { start, end } = cursor\n return start.key === end.key && start.offset === end.offset\n }\n\n // getBlocks\n getBlocks () {\n return this.blocks\n }\n\n getCursor () {\n return this.cursor\n }\n\n getBlock (key) {\n if (!key) return null\n let result = null\n const travel = blocks => {\n for (const block of blocks) {\n if (block.key === key) {\n result = block\n return\n }\n const { children } = block\n if (children.length) {\n travel(children)\n }\n }\n }\n travel(this.blocks)\n return result\n }\n\n getParent (block) {\n if (block && block.parent) {\n return this.getBlock(block.parent)\n }\n return null\n }\n // return block and its parents\n getParents (block) {\n const result = []\n result.push(block)\n let parent = this.getParent(block)\n while (parent) {\n result.push(parent)\n parent = this.getParent(parent)\n }\n return result\n }\n\n getPreSibling (block) {\n return block.preSibling ? this.getBlock(block.preSibling) : null\n }\n\n getNextSibling (block) {\n return block.nextSibling ? this.getBlock(block.nextSibling) : null\n }\n\n /**\n * if target is descendant of parent return true, else return false\n * @param {[type]} parent [description]\n * @param {[type]} target [description]\n * @return {Boolean} [description]\n */\n isInclude (parent, target) {\n const children = parent.children\n if (children.length === 0) {\n return false\n } else {\n if (children.some(child => child.key === target.key)) {\n return true\n } else {\n return children.some(child => this.isInclude(child, target))\n }\n }\n }\n\n removeTextOrBlock (block) {\n const checkerIn = block => {\n if (this.exemption.has(block.key)) {\n return true\n } else {\n const parent = this.getBlock(block.parent)\n return parent ? checkerIn(parent) : false\n }\n }\n\n const checkerOut = block => {\n const children = block.children\n if (children.length) {\n if (children.some(child => this.exemption.has(child.key))) {\n return true\n } else {\n return children.some(child => checkerOut(child))\n }\n } else {\n return false\n }\n }\n\n if (checkerIn(block) || checkerOut(block)) {\n block.text = ''\n const { children } = block\n if (children.length) {\n children.forEach(child => this.removeTextOrBlock(child))\n }\n } else {\n this.removeBlock(block)\n }\n }\n // help func in removeBlocks\n findFigure (block) {\n if (block.type === 'figure') {\n return block.key\n } else {\n const parent = this.getBlock(block.parent)\n return this.findFigure(parent)\n }\n }\n\n /**\n * remove blocks between before and after, and includes after block.\n */\n removeBlocks (before, after, isRemoveAfter = true, isRecursion = false) {\n if (!isRecursion) {\n if (/td|th/.test(before.type)) {\n this.exemption.add(this.findFigure(before))\n }\n if (/td|th/.test(after.type)) {\n this.exemption.add(this.findFigure(after))\n }\n }\n let nextSibling = this.getBlock(before.nextSibling)\n let beforeEnd = false\n while (nextSibling) {\n if (nextSibling.key === after.key || this.isInclude(nextSibling, after)) {\n beforeEnd = true\n break\n }\n this.removeTextOrBlock(nextSibling)\n nextSibling = this.getBlock(nextSibling.nextSibling)\n }\n if (!beforeEnd) {\n const parent = this.getParent(before)\n if (parent) {\n this.removeBlocks(parent, after, false, true)\n }\n }\n let preSibling = this.getBlock(after.preSibling)\n let afterEnd = false\n while (preSibling) {\n if (preSibling.key === before.key || this.isInclude(preSibling, before)) {\n afterEnd = true\n break\n }\n this.removeTextOrBlock(preSibling)\n preSibling = this.getBlock(preSibling.preSibling)\n }\n if (!afterEnd) {\n const parent = this.getParent(after)\n if (parent) {\n const isOnlyChild = this.isOnlyChild(after)\n this.removeBlocks(before, parent, isOnlyChild, true)\n }\n }\n if (isRemoveAfter) {\n this.removeTextOrBlock(after)\n }\n if (!isRecursion) {\n this.exemption.clear()\n }\n }\n\n removeBlock (block, fromBlocks = this.blocks) {\n if (block.type === 'pre') {\n const codeBlockId = block.key\n if (this.codeBlocks.has(codeBlockId)) {\n this.codeBlocks.delete(codeBlockId)\n }\n }\n const remove = (blocks, block) => {\n const len = blocks.length\n let i\n for (i = 0; i < len; i++) {\n if (blocks[i].key === block.key) {\n const preSibling = this.getBlock(block.preSibling)\n const nextSibling = this.getBlock(block.nextSibling)\n\n if (preSibling) {\n preSibling.nextSibling = nextSibling ? nextSibling.key : null\n }\n if (nextSibling) {\n nextSibling.preSibling = preSibling ? preSibling.key : null\n }\n\n return blocks.splice(i, 1)\n } else {\n if (blocks[i].children.length) {\n remove(blocks[i].children, block)\n }\n }\n }\n }\n remove(Array.isArray(fromBlocks) ? fromBlocks : fromBlocks.children, block)\n }\n\n getActiveBlocks () {\n let result = []\n let block = this.getBlock(this.cursor.start.key)\n if (block) result.push(block)\n while (block && block.parent) {\n block = this.getBlock(block.parent)\n result.push(block)\n }\n return result\n }\n\n insertAfter (newBlock, oldBlock) {\n const siblings = oldBlock.parent ? this.getBlock(oldBlock.parent).children : this.blocks\n const oldNextSibling = this.getBlock(oldBlock.nextSibling)\n const index = this.findIndex(siblings, oldBlock)\n siblings.splice(index + 1, 0, newBlock)\n oldBlock.nextSibling = newBlock.key\n newBlock.parent = oldBlock.parent\n newBlock.preSibling = oldBlock.key\n if (oldNextSibling) {\n newBlock.nextSibling = oldNextSibling.key\n oldNextSibling.preSibling = newBlock.key\n }\n }\n\n insertBefore (newBlock, oldBlock) {\n const siblings = oldBlock.parent ? this.getBlock(oldBlock.parent).children : this.blocks\n const oldPreSibling = this.getBlock(oldBlock.preSibling)\n const index = this.findIndex(siblings, oldBlock)\n siblings.splice(index, 0, newBlock)\n oldBlock.preSibling = newBlock.key\n newBlock.parent = oldBlock.parent\n newBlock.nextSibling = oldBlock.key\n newBlock.preSibling = null\n\n if (oldPreSibling) {\n oldPreSibling.nextSibling = newBlock.key\n newBlock.preSibling = oldPreSibling.key\n }\n }\n\n findOutMostBlock (block) {\n const parent = this.getBlock(block.parent)\n return parent ? this.findOutMostBlock(parent) : block\n }\n\n findIndex (children, block) {\n return children.findIndex(child => child === block)\n }\n\n prependChild (parent, block) {\n if (parent.children.length) {\n const firstChild = parent.children[0]\n this.insertBefore(block, firstChild)\n } else {\n this.appendChild(parent, block)\n }\n }\n\n appendChild (parent, block) {\n const len = parent.children.length\n const lastChild = parent.children[len - 1]\n parent.children.push(block)\n block.parent = parent.key\n if (lastChild) {\n lastChild.nextSibling = block.key\n block.preSibling = lastChild.key\n } else {\n block.preSibling = null\n }\n block.nextSibling = null\n }\n\n replaceBlock (newBlock, oldBlock) {\n const blockList = oldBlock.parent ? this.getParent(oldBlock).children : this.blocks\n const index = this.findIndex(blockList, oldBlock)\n\n blockList.splice(index, 1, newBlock)\n newBlock.parent = oldBlock.parent\n newBlock.preSibling = oldBlock.preSibling\n newBlock.nextSibling = oldBlock.nextSibling\n }\n\n isFirstChild (block) {\n return !block.preSibling\n }\n\n isLastChild (block) {\n return !block.nextSibling\n }\n\n isOnlyChild (block) {\n return !block.nextSibling && !block.preSibling\n }\n\n getLastChild (block) {\n const len = block.children.length\n if (len) {\n return block.children[len - 1]\n }\n return null\n }\n\n firstInDescendant (block) {\n const children = block.children\n if (block.children.length === 0 && HAS_TEXT_BLOCK_REG.test(block.type)) {\n return block\n } else if (children.length) {\n if (children[0].type === 'input' || (children[0].type === 'div' && children[0].editable === false)) { // handle task item\n return this.firstInDescendant(children[1])\n } else {\n return this.firstInDescendant(children[0])\n }\n }\n }\n\n lastInDescendant (block) {\n if (block.children.length === 0 && HAS_TEXT_BLOCK_REG.test(block.type)) {\n return block\n } else if (block.children.length) {\n const children = block.children\n let lastChild = children[children.length - 1]\n while (lastChild.editable === false) {\n lastChild = this.getPreSibling(lastChild)\n }\n return this.lastInDescendant(lastChild)\n }\n }\n\n findPreBlockInLocation (block) {\n const parent = this.getParent(block)\n const preBlock = this.getPreSibling(block)\n if (block.preSibling && preBlock.type !== 'input' && preBlock.type !== 'div' && preBlock.editable !== false) { // handle task item and table\n return this.lastInDescendant(preBlock)\n } else if (parent) {\n return this.findPreBlockInLocation(parent)\n } else {\n return null\n }\n }\n\n findNextBlockInLocation (block) {\n const parent = this.getParent(block)\n const nextBlock = this.getNextSibling(block)\n\n if (nextBlock && nextBlock.editable !== false) {\n return this.firstInDescendant(nextBlock)\n } else if (parent) {\n return this.findNextBlockInLocation(parent)\n } else {\n return null\n }\n }\n\n getLastBlock () {\n const { blocks } = this\n const len = blocks.length\n return this.lastInDescendant(blocks[len - 1])\n }\n\n clear () {\n this.codeBlocks.clear()\n }\n}\n\nprototypes.forEach(ctrl => ctrl(ContentState))\n\nexport default ContentState\n", "file_path": "src/editor/contentState/index.js", "label": 1, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.9966506361961365, 0.03528527542948723, 0.00016354031686205417, 0.0003599533811211586, 0.18086878955364227]} {"hunk": {"id": 1, "code_window": [" const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n", " // console.log(JSON.stringify(needRenderBlocks, null, 2), startKey, endKey)\n", " this.setNextRenderRange()\n", " this.stateRender.partialRender(needRenderBlocks, cursor, activeBlocks, matches, startKey, endKey)\n", " this.pre2CodeMirror(true, [...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n", " this.renderMath([...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["\n"], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 170}, "file": "import { ipcMain } from 'electron'\nimport { getMenuItem } from '../utils'\n\nconst DISABLE_LABELS = [\n // paragraph menu items\n 'Heading 1', 'Heading 2', 'Heading 3', 'Heading 4', 'Heading 5', 'Heading 6',\n 'Upgrade Heading Level', 'Degrade Heading Level',\n 'Table',\n // formats menu items\n 'Hyperlink', 'Image'\n]\n\nconst LABEL_MAP = {\n 'Heading 1': 'h1',\n 'Heading 2': 'h2',\n 'Heading 3': 'h3',\n 'Heading 4': 'h4',\n 'Heading 5': 'h5',\n 'Heading 6': 'h6',\n 'Table': 'figure',\n 'Code Fences': 'pre',\n 'Quote Block': 'blockquote',\n 'Order List': 'ol',\n 'Bullet List': 'ul',\n 'Task List': 'ul',\n 'Paragraph': 'p',\n 'Horizontal Line': 'hr',\n 'YAML Front Matter': 'pre'\n}\n\nconst setParagraphMenuItemStatus = bool => {\n const paragraphMenuItem = getMenuItem('Paragraph')\n paragraphMenuItem.submenu.items\n .forEach(item => (item.enabled = bool))\n}\n\nconst disableNoMultiple = (disableLabels) => {\n const paragraphMenuItem = getMenuItem('Paragraph')\n\n paragraphMenuItem.submenu.items\n .filter(item => disableLabels.includes(item.label))\n .forEach(item => (item.enabled = false))\n}\n\nconst setCheckedMenuItem = affiliation => {\n const paragraphMenuItem = getMenuItem('Paragraph')\n paragraphMenuItem.submenu.items.forEach(item => (item.checked = false))\n paragraphMenuItem.submenu.items.forEach(item => {\n if (item.label === 'Loose List Item') {\n let checked = false\n if (affiliation.length >= 1 && /ul|ol/.test(affiliation[0].type)) {\n checked = affiliation[0].children[0].isLooseListItem\n } else if (affiliation.length >= 3 && affiliation[1].type === 'li') {\n checked = affiliation[1].isLooseListItem\n }\n item.checked = checked\n } else if (affiliation.some(b => {\n if (b.type === 'ul') {\n if (b.listType === 'bullet') {\n return item.label === 'Bullet List'\n } else {\n return item.label === 'Task List'\n }\n } else if (b.type === 'pre' && b.functionType) {\n if (b.functionType === 'frontmatter') {\n return item.label === 'YAML Front Matter'\n } else if (b.functionType === 'code') {\n return item.label === 'Code Fences'\n }\n } else {\n return b.type === LABEL_MAP[item.label]\n }\n })) {\n item.checked = true\n }\n })\n}\n\nexport const paragraph = (win, type) => {\n win.webContents.send('AGANI::paragraph', { type })\n}\n\nipcMain.on('AGANI::selection-change', (e, { start, end, affiliation }) => {\n // format menu\n const formatMenuItem = getMenuItem('Format')\n formatMenuItem.submenu.items.forEach(item => (item.enabled = true))\n // handle menu checked\n setCheckedMenuItem(affiliation)\n // handle disable\n setParagraphMenuItemStatus(true)\n if (\n (/th|td/.test(start.type) && /th|td/.test(end.type)) ||\n (start.type === 'span' && start.block.functionType === 'frontmatter') ||\n (end.type === 'span' && end.block.functionType === 'frontmatter')\n ) {\n setParagraphMenuItemStatus(false)\n } else if (start.key !== end.key) {\n formatMenuItem.submenu.items\n .filter(item => DISABLE_LABELS.includes(item.label))\n .forEach(item => (item.enabled = false))\n disableNoMultiple(DISABLE_LABELS)\n } else if (!affiliation.slice(0, 3).some(p => /ul|ol/.test(p.type))) {\n disableNoMultiple(['Loose List Item'])\n }\n})\n", "file_path": "src/main/actions/paragraph.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.0002276264422107488, 0.0001812968257581815, 0.00016272942593786865, 0.0001736020640237257, 2.1601077605737373e-05]} {"hunk": {"id": 1, "code_window": [" const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n", " // console.log(JSON.stringify(needRenderBlocks, null, 2), startKey, endKey)\n", " this.setNextRenderRange()\n", " this.stateRender.partialRender(needRenderBlocks, cursor, activeBlocks, matches, startKey, endKey)\n", " this.pre2CodeMirror(true, [...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n", " this.renderMath([...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["\n"], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 170}, "file": ".icon {\n width: 1em; height: 1em;\n vertical-align: -0.15em;\n fill: currentColor;\n overflow: hidden;\n}", "file_path": "src/editor/assets/symbolIcon/index.css", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.00017174912500195205, 0.00017174912500195205, 0.00017174912500195205, 0.00017174912500195205, 0.0]} {"hunk": {"id": 1, "code_window": [" const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n", " const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n", " const needRenderBlocks = blocks.slice(startIndex, endIndex)\n", " // console.log(JSON.stringify(needRenderBlocks, null, 2), startKey, endKey)\n", " this.setNextRenderRange()\n", " this.stateRender.partialRender(needRenderBlocks, cursor, activeBlocks, matches, startKey, endKey)\n", " this.pre2CodeMirror(true, [...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n", " this.renderMath([...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["\n"], "file_path": "src/editor/contentState/index.js", "type": "replace", "edit_start_line_idx": 170}, "file": ".ag-float-box {\n position: absolute;\n left: -1000px;\n top: -1000px;\n opacity: 0;\n max-height: 168px;\n min-width: 130px;\n max-width: 150px;\n margin: 0;\n padding: 5px 0;\n border: 1px solid #ebeef5;\n border-radius: 4px;\n box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);\n list-style: none;\n transition: opacity .15s ease-in;\n overflow: auto;\n background: #fff;\n z-index: 10000;\n}\n\n.ag-float-box::-webkit-scrollbar:vertical {\n width: 5px;\n}\n\n.ag-show-float-box {\n opacity: 1;\n}\n\n.ag-float-item {\n padding: 0 .2em;\n height: 28px;\n line-height: 28px;\n box-sizing: border-box;\n color: #606266;\n cursor: pointer;\n font-size: 12px;\n display: flex;\n font-weight: 400;\n}\n\n.ag-float-item span:nth-of-type(2n) {\n overflow: hidden;\n text-overflow:ellipsis;\n white-space: nowrap;\n}\n\n.ag-float-box:hover .ag-float-item-active {\n background: #fff;\n color: #606266;\n}\n.ag-float-item-active, .ag-float-box .ag-float-item:hover {\n background-color: #ecf5ff;\n color: #66b1ff;\n}\n\n.ag-float-item-icon {\n font-size: 14px;\n width: 28px;\n height: 28px;\n text-align: center;\n display: inline-block;\n vertical-align: middle;\n flex-shrink: 0;\n margin-right: .1em;\n}\n", "file_path": "src/editor/floatBox/index.css", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.00017342684441246092, 0.0001696730760158971, 0.00016203915583901107, 0.00017056510841939598, 3.7833881378901424e-06]} {"hunk": {"id": 2, "code_window": [" }\n", " } else {\n", " result = [ text.substring(rStart, rEnd) ]\n", " }\n", "\n", " return result\n", " }\n", " // render token of text type to vdom.\n", " text (h, cursor, block, token) {\n", " const { start, end } = token.range\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" // fix snabbdom-to-html bug https://github.com/snabbdom/snabbdom-to-html/issues/41\n", " if (result.length === 1 && result[0] === '') result.length = 0\n"], "file_path": "src/editor/parser/StateRender.js", "type": "replace", "edit_start_line_idx": 435}, "file": "import { HAS_TEXT_BLOCK_REG } from '../config'\nimport { setCursorAtLastLine } from '../codeMirror'\nimport { getUniqueId } from '../utils'\nimport selection from '../selection'\nimport StateRender from '../parser/StateRender'\nimport enterCtrl from './enterCtrl'\nimport updateCtrl from './updateCtrl'\nimport backspaceCtrl from './backspaceCtrl'\nimport codeBlockCtrl from './codeBlockCtrl'\nimport tableBlockCtrl from './tableBlockCtrl'\nimport History from './history'\nimport arrowCtrl from './arrowCtrl'\nimport pasteCtrl from './pasteCtrl'\nimport copyCutCtrl from './copyCutCtrl'\nimport paragraphCtrl from './paragraphCtrl'\nimport tabCtrl from './tabCtrl'\nimport formatCtrl from './formatCtrl'\nimport searchCtrl from './searchCtrl'\nimport mathCtrl from './mathCtrl'\nimport imagePathCtrl from './imagePathCtrl'\nimport htmlBlockCtrl from './htmlBlock'\nimport importMarkdown from '../utils/importMarkdown'\n\nconst prototypes = [\n tabCtrl,\n enterCtrl,\n updateCtrl,\n backspaceCtrl,\n codeBlockCtrl,\n arrowCtrl,\n pasteCtrl,\n copyCutCtrl,\n tableBlockCtrl,\n paragraphCtrl,\n formatCtrl,\n searchCtrl,\n mathCtrl,\n imagePathCtrl,\n htmlBlockCtrl,\n importMarkdown\n]\n\nclass ContentState {\n constructor (options) {\n const { eventCenter } = options\n Object.assign(this, options)\n // Use to cache the keys which you don't want to remove.\n this.exemption = new Set()\n this.blocks = [ this.createBlockP() ]\n this.stateRender = new StateRender(eventCenter)\n this.codeBlocks = new Map()\n this.loadMathMap = new Map()\n this.renderRange = [ null, null ]\n this.currentCursor = null\n this.prevCursor = null\n this.historyTimer = null\n this.history = new History(this)\n this.init()\n }\n\n set cursor (cursor) {\n if (this.currentCursor) {\n const { start, end } = this.currentCursor\n if (\n start.key === cursor.start.key &&\n start.offset === cursor.start.offset &&\n end.key === cursor.end.key &&\n end.offset === cursor.end.offset\n ) {\n return\n }\n }\n\n const handler = () => {\n const { blocks, renderRange, currentCursor } = this\n this.history.push({\n type: 'normal',\n blocks,\n renderRange,\n cursor: currentCursor\n })\n }\n this.prevCursor = this.currentCursor\n this.currentCursor = cursor\n\n if (!cursor.noHistory) {\n if (\n this.prevCursor && (this.prevCursor.start.key !== cursor.start.key || this.prevCursor.end.key !== cursor.end.key)\n ) {\n handler()\n } else {\n if (this.historyTimer) clearTimeout(this.historyTimer)\n this.historyTimer = setTimeout(handler, 2000)\n }\n } else {\n cursor.noHistory && delete cursor.noHistory\n }\n }\n\n get cursor () {\n return this.currentCursor\n }\n\n init () {\n const lastBlock = this.getLastBlock()\n const { key, text } = lastBlock\n const offset = text.length\n this.searchMatches = {\n value: '', // the search value\n matches: [], // matches\n index: -1 // active match\n }\n this.cursor = {\n start: { key, offset },\n end: { key, offset }\n }\n }\n\n setCursor () {\n const { start: { key } } = this.cursor\n const block = this.getBlock(key)\n if (block.type === 'pre' && block.functionType !== 'frontmatter') {\n const cm = this.codeBlocks.get(key)\n const { pos } = block\n if (pos) {\n cm.focus()\n cm.setCursor(pos)\n } else {\n setCursorAtLastLine(cm)\n }\n } else {\n selection.setCursorRange(this.cursor)\n }\n }\n\n setNextRenderRange () {\n const { start, end } = this.cursor\n // console.log(JSON.stringify(this.cursor, null, 2))\n const startBlock = this.getBlock(start.key)\n const endBlock = this.getBlock(end.key)\n const startOutMostBlock = this.findOutMostBlock(startBlock)\n const endOutMostBlock = this.findOutMostBlock(endBlock)\n this.renderRange = [ startOutMostBlock.preSibling, endOutMostBlock.nextSibling ]\n }\n\n render (isRenderCursor = true) {\n const { blocks, cursor, searchMatches: { matches, index } } = this\n const activeBlocks = this.getActiveBlocks()\n matches.forEach((m, i) => {\n m.active = i === index\n })\n this.setNextRenderRange()\n this.stateRender.render(blocks, cursor, activeBlocks, matches)\n this.pre2CodeMirror(isRenderCursor)\n this.renderMath()\n if (isRenderCursor) this.setCursor()\n }\n\n partialRender () {\n const { blocks, cursor, searchMatches: { matches, index } } = this\n const activeBlocks = this.getActiveBlocks()\n const cursorOutMostBlock = activeBlocks[activeBlocks.length - 1]\n const [ startKey, endKey ] = this.renderRange\n matches.forEach((m, i) => {\n m.active = i === index\n })\n // console.log(startKey, endKey)\n const startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0\n const endIndex = endKey ? blocks.findIndex(block => block.key === endKey) + 1 : blocks.length\n const needRenderBlocks = blocks.slice(startIndex, endIndex)\n // console.log(JSON.stringify(needRenderBlocks, null, 2), startKey, endKey)\n this.setNextRenderRange()\n this.stateRender.partialRender(needRenderBlocks, cursor, activeBlocks, matches, startKey, endKey)\n this.pre2CodeMirror(true, [...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n this.renderMath([...new Set([cursorOutMostBlock, ...needRenderBlocks])])\n this.setCursor()\n }\n\n /**\n * A block in Aganippe present a paragraph(block syntax in GFM) or a line in paragraph.\n * a line block must in a `p block` or `pre block(frontmatter)` and `p block`'s children must be line blocks.\n */\n createBlock (type = 'span', text = '') { // span type means it is a line block.\n const key = getUniqueId()\n return {\n key,\n type,\n text,\n parent: null,\n preSibling: null,\n nextSibling: null,\n children: []\n }\n }\n\n createBlockP (text = '') {\n const pBlock = this.createBlock('p')\n const lineBlock = this.createBlock('span', text)\n this.appendChild(pBlock, lineBlock)\n return pBlock\n }\n\n isCollapse (cursor = this.cursor) {\n const { start, end } = cursor\n return start.key === end.key && start.offset === end.offset\n }\n\n // getBlocks\n getBlocks () {\n return this.blocks\n }\n\n getCursor () {\n return this.cursor\n }\n\n getBlock (key) {\n if (!key) return null\n let result = null\n const travel = blocks => {\n for (const block of blocks) {\n if (block.key === key) {\n result = block\n return\n }\n const { children } = block\n if (children.length) {\n travel(children)\n }\n }\n }\n travel(this.blocks)\n return result\n }\n\n getParent (block) {\n if (block && block.parent) {\n return this.getBlock(block.parent)\n }\n return null\n }\n // return block and its parents\n getParents (block) {\n const result = []\n result.push(block)\n let parent = this.getParent(block)\n while (parent) {\n result.push(parent)\n parent = this.getParent(parent)\n }\n return result\n }\n\n getPreSibling (block) {\n return block.preSibling ? this.getBlock(block.preSibling) : null\n }\n\n getNextSibling (block) {\n return block.nextSibling ? this.getBlock(block.nextSibling) : null\n }\n\n /**\n * if target is descendant of parent return true, else return false\n * @param {[type]} parent [description]\n * @param {[type]} target [description]\n * @return {Boolean} [description]\n */\n isInclude (parent, target) {\n const children = parent.children\n if (children.length === 0) {\n return false\n } else {\n if (children.some(child => child.key === target.key)) {\n return true\n } else {\n return children.some(child => this.isInclude(child, target))\n }\n }\n }\n\n removeTextOrBlock (block) {\n const checkerIn = block => {\n if (this.exemption.has(block.key)) {\n return true\n } else {\n const parent = this.getBlock(block.parent)\n return parent ? checkerIn(parent) : false\n }\n }\n\n const checkerOut = block => {\n const children = block.children\n if (children.length) {\n if (children.some(child => this.exemption.has(child.key))) {\n return true\n } else {\n return children.some(child => checkerOut(child))\n }\n } else {\n return false\n }\n }\n\n if (checkerIn(block) || checkerOut(block)) {\n block.text = ''\n const { children } = block\n if (children.length) {\n children.forEach(child => this.removeTextOrBlock(child))\n }\n } else {\n this.removeBlock(block)\n }\n }\n // help func in removeBlocks\n findFigure (block) {\n if (block.type === 'figure') {\n return block.key\n } else {\n const parent = this.getBlock(block.parent)\n return this.findFigure(parent)\n }\n }\n\n /**\n * remove blocks between before and after, and includes after block.\n */\n removeBlocks (before, after, isRemoveAfter = true, isRecursion = false) {\n if (!isRecursion) {\n if (/td|th/.test(before.type)) {\n this.exemption.add(this.findFigure(before))\n }\n if (/td|th/.test(after.type)) {\n this.exemption.add(this.findFigure(after))\n }\n }\n let nextSibling = this.getBlock(before.nextSibling)\n let beforeEnd = false\n while (nextSibling) {\n if (nextSibling.key === after.key || this.isInclude(nextSibling, after)) {\n beforeEnd = true\n break\n }\n this.removeTextOrBlock(nextSibling)\n nextSibling = this.getBlock(nextSibling.nextSibling)\n }\n if (!beforeEnd) {\n const parent = this.getParent(before)\n if (parent) {\n this.removeBlocks(parent, after, false, true)\n }\n }\n let preSibling = this.getBlock(after.preSibling)\n let afterEnd = false\n while (preSibling) {\n if (preSibling.key === before.key || this.isInclude(preSibling, before)) {\n afterEnd = true\n break\n }\n this.removeTextOrBlock(preSibling)\n preSibling = this.getBlock(preSibling.preSibling)\n }\n if (!afterEnd) {\n const parent = this.getParent(after)\n if (parent) {\n const isOnlyChild = this.isOnlyChild(after)\n this.removeBlocks(before, parent, isOnlyChild, true)\n }\n }\n if (isRemoveAfter) {\n this.removeTextOrBlock(after)\n }\n if (!isRecursion) {\n this.exemption.clear()\n }\n }\n\n removeBlock (block, fromBlocks = this.blocks) {\n if (block.type === 'pre') {\n const codeBlockId = block.key\n if (this.codeBlocks.has(codeBlockId)) {\n this.codeBlocks.delete(codeBlockId)\n }\n }\n const remove = (blocks, block) => {\n const len = blocks.length\n let i\n for (i = 0; i < len; i++) {\n if (blocks[i].key === block.key) {\n const preSibling = this.getBlock(block.preSibling)\n const nextSibling = this.getBlock(block.nextSibling)\n\n if (preSibling) {\n preSibling.nextSibling = nextSibling ? nextSibling.key : null\n }\n if (nextSibling) {\n nextSibling.preSibling = preSibling ? preSibling.key : null\n }\n\n return blocks.splice(i, 1)\n } else {\n if (blocks[i].children.length) {\n remove(blocks[i].children, block)\n }\n }\n }\n }\n remove(Array.isArray(fromBlocks) ? fromBlocks : fromBlocks.children, block)\n }\n\n getActiveBlocks () {\n let result = []\n let block = this.getBlock(this.cursor.start.key)\n if (block) result.push(block)\n while (block && block.parent) {\n block = this.getBlock(block.parent)\n result.push(block)\n }\n return result\n }\n\n insertAfter (newBlock, oldBlock) {\n const siblings = oldBlock.parent ? this.getBlock(oldBlock.parent).children : this.blocks\n const oldNextSibling = this.getBlock(oldBlock.nextSibling)\n const index = this.findIndex(siblings, oldBlock)\n siblings.splice(index + 1, 0, newBlock)\n oldBlock.nextSibling = newBlock.key\n newBlock.parent = oldBlock.parent\n newBlock.preSibling = oldBlock.key\n if (oldNextSibling) {\n newBlock.nextSibling = oldNextSibling.key\n oldNextSibling.preSibling = newBlock.key\n }\n }\n\n insertBefore (newBlock, oldBlock) {\n const siblings = oldBlock.parent ? this.getBlock(oldBlock.parent).children : this.blocks\n const oldPreSibling = this.getBlock(oldBlock.preSibling)\n const index = this.findIndex(siblings, oldBlock)\n siblings.splice(index, 0, newBlock)\n oldBlock.preSibling = newBlock.key\n newBlock.parent = oldBlock.parent\n newBlock.nextSibling = oldBlock.key\n newBlock.preSibling = null\n\n if (oldPreSibling) {\n oldPreSibling.nextSibling = newBlock.key\n newBlock.preSibling = oldPreSibling.key\n }\n }\n\n findOutMostBlock (block) {\n const parent = this.getBlock(block.parent)\n return parent ? this.findOutMostBlock(parent) : block\n }\n\n findIndex (children, block) {\n return children.findIndex(child => child === block)\n }\n\n prependChild (parent, block) {\n if (parent.children.length) {\n const firstChild = parent.children[0]\n this.insertBefore(block, firstChild)\n } else {\n this.appendChild(parent, block)\n }\n }\n\n appendChild (parent, block) {\n const len = parent.children.length\n const lastChild = parent.children[len - 1]\n parent.children.push(block)\n block.parent = parent.key\n if (lastChild) {\n lastChild.nextSibling = block.key\n block.preSibling = lastChild.key\n } else {\n block.preSibling = null\n }\n block.nextSibling = null\n }\n\n replaceBlock (newBlock, oldBlock) {\n const blockList = oldBlock.parent ? this.getParent(oldBlock).children : this.blocks\n const index = this.findIndex(blockList, oldBlock)\n\n blockList.splice(index, 1, newBlock)\n newBlock.parent = oldBlock.parent\n newBlock.preSibling = oldBlock.preSibling\n newBlock.nextSibling = oldBlock.nextSibling\n }\n\n isFirstChild (block) {\n return !block.preSibling\n }\n\n isLastChild (block) {\n return !block.nextSibling\n }\n\n isOnlyChild (block) {\n return !block.nextSibling && !block.preSibling\n }\n\n getLastChild (block) {\n const len = block.children.length\n if (len) {\n return block.children[len - 1]\n }\n return null\n }\n\n firstInDescendant (block) {\n const children = block.children\n if (block.children.length === 0 && HAS_TEXT_BLOCK_REG.test(block.type)) {\n return block\n } else if (children.length) {\n if (children[0].type === 'input' || (children[0].type === 'div' && children[0].editable === false)) { // handle task item\n return this.firstInDescendant(children[1])\n } else {\n return this.firstInDescendant(children[0])\n }\n }\n }\n\n lastInDescendant (block) {\n if (block.children.length === 0 && HAS_TEXT_BLOCK_REG.test(block.type)) {\n return block\n } else if (block.children.length) {\n const children = block.children\n let lastChild = children[children.length - 1]\n while (lastChild.editable === false) {\n lastChild = this.getPreSibling(lastChild)\n }\n return this.lastInDescendant(lastChild)\n }\n }\n\n findPreBlockInLocation (block) {\n const parent = this.getParent(block)\n const preBlock = this.getPreSibling(block)\n if (block.preSibling && preBlock.type !== 'input' && preBlock.type !== 'div' && preBlock.editable !== false) { // handle task item and table\n return this.lastInDescendant(preBlock)\n } else if (parent) {\n return this.findPreBlockInLocation(parent)\n } else {\n return null\n }\n }\n\n findNextBlockInLocation (block) {\n const parent = this.getParent(block)\n const nextBlock = this.getNextSibling(block)\n\n if (nextBlock && nextBlock.editable !== false) {\n return this.firstInDescendant(nextBlock)\n } else if (parent) {\n return this.findNextBlockInLocation(parent)\n } else {\n return null\n }\n }\n\n getLastBlock () {\n const { blocks } = this\n const len = blocks.length\n return this.lastInDescendant(blocks[len - 1])\n }\n\n clear () {\n this.codeBlocks.clear()\n }\n}\n\nprototypes.forEach(ctrl => ctrl(ContentState))\n\nexport default ContentState\n", "file_path": "src/editor/contentState/index.js", "label": 1, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.9556717872619629, 0.1112714409828186, 0.00016425090143457055, 0.006517433561384678, 0.259982168674469]} {"hunk": {"id": 2, "code_window": [" }\n", " } else {\n", " result = [ text.substring(rStart, rEnd) ]\n", " }\n", "\n", " return result\n", " }\n", " // render token of text type to vdom.\n", " text (h, cursor, block, token) {\n", " const { start, end } = token.range\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" // fix snabbdom-to-html bug https://github.com/snabbdom/snabbdom-to-html/issues/41\n", " if (result.length === 1 && result[0] === '') result.length = 0\n"], "file_path": "src/editor/parser/StateRender.js", "type": "replace", "edit_start_line_idx": 435}, "file": "'use strict'\n\nimport fs from 'fs'\n// import chokidar from 'chokidar'\nimport path from 'path'\nimport { BrowserWindow, dialog, ipcMain } from 'electron'\nimport createWindow, { forceClose, windows } from '../createWindow'\nimport { EXTENSION_HASN, EXTENSIONS } from '../config'\nimport { writeFile, writeMarkdownFile } from '../filesystem'\nimport { clearRecentlyUsedDocuments } from '../menu'\nimport { getPath, isMarkdownFile, log, isFile } from '../utils'\nimport userPreference from '../preference'\n\n// TODO(fxha): Do we still need this?\nconst watchAndReload = (pathname, win) => { // when i build, and failed.\n // const watcher = chokidar.watch(pathname, {\n // persistent: true\n // })\n // const filename = path.basename(pathname)\n // watcher.on('change', path => {\n // fs.readFile(pathname, 'utf-8', (err, file) => {\n // if (err) return console.log(err)\n // win.webContents.send('AGANI::file-change', {\n // file,\n // filename,\n // pathname\n // })\n // })\n // })\n}\n\n// handle the response from render process.\nconst handleResponseForExport = (e, { type, content, filename, pathname }) => {\n const win = BrowserWindow.fromWebContents(e.sender)\n const extension = EXTENSION_HASN[type]\n const dirname = pathname ? path.dirname(pathname) : getPath('documents')\n const nakedFilename = pathname ? path.basename(pathname, '.md') : 'untitled'\n const defaultPath = `${dirname}/${nakedFilename}${extension}`\n const filePath = dialog.showSaveDialog(win, {\n defaultPath\n })\n\n if (!content && type === 'pdf') {\n win.webContents.printToPDF({ printBackground: true }, (err, data) => {\n if (err) log(err)\n writeFile(filePath, data, extension, e)\n })\n } else {\n writeFile(filePath, content, extension, e)\n }\n}\n\nconst handleResponseForSave = (e, { markdown, pathname, options, quitAfterSave = false }) => {\n const win = BrowserWindow.fromWebContents(e.sender)\n if (pathname) {\n writeMarkdownFile(pathname, markdown, '', options, win, e, quitAfterSave)\n } else {\n const filePath = dialog.showSaveDialog(win, {\n defaultPath: getPath('documents') + '/Untitled.md'\n })\n writeMarkdownFile(filePath, markdown, '.md', options, win, e, quitAfterSave)\n }\n}\n\nipcMain.on('AGANI::response-file-save-as', (e, { markdown, pathname, options }) => {\n const win = BrowserWindow.fromWebContents(e.sender)\n let filePath = dialog.showSaveDialog(win, {\n defaultPath: pathname || getPath('documents') + '/Untitled.md'\n })\n writeMarkdownFile(filePath, markdown, '.md', options, win, e)\n})\n\nipcMain.on('AGANI::response-close-confirm', (e, { filename, pathname, markdown, options }) => {\n const win = BrowserWindow.fromWebContents(e.sender)\n dialog.showMessageBox(win, {\n type: 'warning',\n buttons: ['Save', 'Cancel', 'Delete'],\n defaultId: 0,\n message: `Do you want to save the changes you made to ${filename}?`,\n detail: `Your changes will be lost if you don't save them.`,\n cancelId: 1,\n noLink: true\n }, index => {\n switch (index) {\n case 2:\n forceClose(win)\n break\n case 0:\n setTimeout(() => {\n handleResponseForSave(e, { pathname, markdown, options, quitAfterSave: true })\n })\n break\n }\n })\n})\n\nipcMain.on('AGANI::response-file-save', handleResponseForSave)\n\nipcMain.on('AGANI::response-export', handleResponseForExport)\n\nipcMain.on('AGANI::close-window', e => {\n const win = BrowserWindow.fromWebContents(e.sender)\n forceClose(win)\n})\n\nipcMain.on('AGANI::window::drop', (e, fileList) => {\n for (const file of fileList) {\n if (isMarkdownFile(file)) {\n createWindow(file)\n break\n }\n }\n})\n\nipcMain.on('AGANI::rename', (e, {\n pathname,\n newPathname\n}) => {\n const win = BrowserWindow.fromWebContents(e.sender)\n if (!isFile(newPathname)) {\n fs.renameSync(pathname, newPathname)\n e.sender.send('AGANI::set-pathname', {\n pathname: newPathname,\n filename: path.basename(newPathname)\n })\n } else {\n dialog.showMessageBox(win, {\n type: 'warning',\n buttons: ['Replace', 'Cancel'],\n defaultId: 1,\n message: `The file ${path.basename(newPathname)} is already exists. Do you want to replace it?`,\n cancelId: 1,\n noLink: true\n }, index => {\n if (index === 0) {\n fs.renameSync(pathname, newPathname)\n e.sender.send('AGANI::set-pathname', {\n pathname: newPathname,\n filename: path.basename(newPathname)\n })\n }\n })\n }\n})\n\nipcMain.on('AGANI::response-file-move-to', (e, { pathname }) => {\n const win = BrowserWindow.fromWebContents(e.sender)\n let newPath = dialog.showSaveDialog(win, {\n buttonLabel: 'Move to',\n nameFieldLabel: 'Filename:',\n defaultPath: pathname\n })\n if (newPath === undefined) return\n fs.renameSync(pathname, newPath)\n e.sender.send('AGANI::set-pathname', { pathname: newPath, filename: path.basename(newPath) })\n})\n\nexport const exportFile = (win, type) => {\n win.webContents.send('AGANI::export', { type })\n}\n\nexport const print = win => {\n win.webContents.print({ silent: false, printBackground: true, deviceName: '' })\n}\n\nexport const openDocument = filePath => {\n if (isFile(filePath)) {\n const newWindow = createWindow(filePath)\n watchAndReload(filePath, newWindow)\n }\n}\n\nexport const open = win => {\n const filename = dialog.showOpenDialog(win, {\n properties: ['openFile'],\n filters: [{\n name: 'text',\n extensions: EXTENSIONS\n }]\n })\n if (filename && filename[0]) {\n openDocument(filename[0])\n }\n}\n\nexport const newFile = () => {\n createWindow()\n}\n\nexport const save = win => {\n win.webContents.send('AGANI::ask-file-save')\n}\n\nexport const saveAs = win => {\n win.webContents.send('AGANI::ask-file-save-as')\n}\n\nexport const autoSave = (menuItem, browserWindow) => {\n const { checked } = menuItem\n userPreference.setItem('autoSave', checked)\n .then(() => {\n for (const win of windows.values()) {\n win.webContents.send('AGANI::user-preference', { autoSave: checked })\n }\n })\n .catch(log)\n}\n\nexport const moveTo = win => {\n win.webContents.send('AGANI::ask-file-move-to')\n}\n\nexport const rename = win => {\n win.webContents.send('AGANI::ask-file-rename')\n}\n\nexport const clearRecentlyUsed = () => {\n clearRecentlyUsedDocuments()\n}\n", "file_path": "src/main/actions/file.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.00017475566710345447, 0.00017195571854244918, 0.00016727160254959017, 0.0001723291934467852, 2.2456808892457047e-06]} {"hunk": {"id": 2, "code_window": [" }\n", " } else {\n", " result = [ text.substring(rStart, rEnd) ]\n", " }\n", "\n", " return result\n", " }\n", " // render token of text type to vdom.\n", " text (h, cursor, block, token) {\n", " const { start, end } = token.range\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" // fix snabbdom-to-html bug https://github.com/snabbdom/snabbdom-to-html/issues/41\n", " if (result.length === 1 && result[0] === '') result.length = 0\n"], "file_path": "src/editor/parser/StateRender.js", "type": "replace", "edit_start_line_idx": 435}, "file": "import { app } from 'electron'\nimport { showAboutDialog } from '../actions/help'\nimport * as actions from '../actions/marktext'\n\nexport default {\n label: 'Mark Text',\n submenu: [{\n label: 'About Mark Text',\n click (menuItem, browserWindow) {\n showAboutDialog(browserWindow)\n }\n }, {\n label: 'Check for updates...',\n click (menuItem, browserWindow) {\n actions.checkUpdates(menuItem, browserWindow)\n }\n }, {\n label: 'Preferences',\n accelerator: 'Cmd+,',\n click (menuItem, browserWindow) {\n actions.userSetting(menuItem, browserWindow)\n }\n }, {\n type: 'separator'\n }, {\n label: 'Services',\n role: 'services',\n submenu: []\n }, {\n type: 'separator'\n }, {\n label: 'Hide Mark Text',\n accelerator: 'Command+H',\n role: 'hide'\n }, {\n label: 'Hide Others',\n accelerator: 'Command+Alt+H',\n role: 'hideothers'\n }, {\n label: 'Show All',\n role: 'unhide'\n }, {\n type: 'separator'\n }, {\n label: 'Quit',\n accelerator: 'Command+Q',\n click: app.quit\n }]\n}\n", "file_path": "src/main/menus/marktext.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.00017353073053527623, 0.00017118811956606805, 0.00016862782649695873, 0.00017141799617093056, 1.5726303672636277e-06]} {"hunk": {"id": 2, "code_window": [" }\n", " } else {\n", " result = [ text.substring(rStart, rEnd) ]\n", " }\n", "\n", " return result\n", " }\n", " // render token of text type to vdom.\n", " text (h, cursor, block, token) {\n", " const { start, end } = token.range\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" // fix snabbdom-to-html bug https://github.com/snabbdom/snabbdom-to-html/issues/41\n", " if (result.length === 1 && result[0] === '') result.length = 0\n"], "file_path": "src/editor/parser/StateRender.js", "type": "replace", "edit_start_line_idx": 435}, "file": "import { ipcMain } from 'electron'\nimport { getMenuItem } from '../utils'\n\nconst FORMAT_MAP = {\n 'Strong': 'strong',\n 'Emphasis': 'em',\n 'Inline Code': 'inline_code',\n 'Strike': 'del',\n 'Hyperlink': 'link',\n 'Image': 'image'\n}\n\nconst selectFormat = formats => {\n const formatMenuItem = getMenuItem('Format')\n formatMenuItem.submenu.items.forEach(item => (item.checked = false))\n formatMenuItem.submenu.items\n .forEach(item => {\n if (formats.some(format => format.type === FORMAT_MAP[item.label])) {\n item.checked = true\n }\n })\n}\n\nexport const format = (win, type) => {\n win.webContents.send('AGANI::format', { type })\n}\n\nipcMain.on('AGANI::selection-formats', (e, formats) => {\n selectFormat(formats)\n})\n", "file_path": "src/main/actions/format.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.00019130339205730706, 0.0001757754507707432, 0.0001675031817285344, 0.00017214761464856565, 9.166390555037651e-06]} {"hunk": {"id": 3, "code_window": [" click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'undo')\n", " }\n", " }, {\n", " label: 'Redo',\n", " accelerator: 'CmdOrCtrl+Y',\n", " click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'redo')\n", " }\n", " }, {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" accelerator: 'Shift+CmdOrCtrl+Z',\n"], "file_path": "src/main/menus/edit.js", "type": "replace", "edit_start_line_idx": 15}, "file": "import * as actions from '../actions/edit'\nimport userPreference from '../preference'\n\nconst { aidou } = userPreference.getAll()\n\nexport default {\n label: 'Edit',\n submenu: [{\n label: 'Undo',\n accelerator: 'CmdOrCtrl+Z',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'undo')\n }\n }, {\n label: 'Redo',\n accelerator: 'CmdOrCtrl+Y',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'redo')\n }\n }, {\n type: 'separator'\n }, {\n label: 'Cut',\n accelerator: 'CmdOrCtrl+X',\n role: 'cut'\n }, {\n label: 'Copy',\n accelerator: 'CmdOrCtrl+C',\n role: 'copy'\n }, {\n label: 'Paste',\n accelerator: 'CmdOrCtrl+V',\n role: 'paste'\n }, {\n label: 'Select All',\n accelerator: 'CmdOrCtrl+A',\n role: 'selectall'\n }, {\n type: 'separator'\n }, {\n label: 'Find',\n accelerator: 'CmdOrCtrl+F',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'find')\n }\n }, {\n label: 'Find Next',\n accelerator: 'Alt+CmdOrCtrl+U',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'fineNext')\n }\n }, {\n label: 'FindPrev',\n accelerator: 'Shift+CmdOrCtrl+U',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'findPrev')\n }\n }, {\n label: 'Replace',\n accelerator: 'Alt+CmdOrCtrl+F',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'replace')\n }\n }, {\n type: 'separator'\n }, {\n label: 'Aidou',\n visible: aidou,\n accelerator: 'CmdOrCtrl+/',\n click: (menuItem, browserWindow) => {\n actions.edit(browserWindow, 'aidou')\n }\n }, {\n label: 'Insert Image',\n submenu: [{\n label: 'Absolute Path',\n click (menuItem, browserWindow) {\n actions.insertImage(browserWindow, 'absolute')\n }\n }, {\n label: 'Relative Path',\n click (menuItem, browserWindow) {\n actions.insertImage(browserWindow, 'relative')\n }\n }, {\n label: 'Upload to Cloud (EXP)',\n click (menuItem, browserWindow) {\n actions.insertImage(browserWindow, 'upload')\n }\n }]\n }, {\n type: 'separator'\n }, {\n label: 'Line Ending',\n submenu: [{\n id: 'crlfLineEndingMenuEntry',\n label: 'Carriage return and line feed (CRLF)',\n type: 'radio',\n click (menuItem, browserWindow) {\n actions.lineEnding(browserWindow, 'crlf')\n }\n }, {\n id: 'lfLineEndingMenuEntry',\n label: 'Line feed (LF)',\n type: 'radio',\n click (menuItem, browserWindow) {\n actions.lineEnding(browserWindow, 'lf')\n }\n }]\n }]\n}\n", "file_path": "src/main/menus/edit.js", "label": 1, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.9967349171638489, 0.08621244877576828, 0.0001655348314670846, 0.0043486799113452435, 0.2745445966720581]} {"hunk": {"id": 3, "code_window": [" click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'undo')\n", " }\n", " }, {\n", " label: 'Redo',\n", " accelerator: 'CmdOrCtrl+Y',\n", " click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'redo')\n", " }\n", " }, {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" accelerator: 'Shift+CmdOrCtrl+Z',\n"], "file_path": "src/main/menus/edit.js", "type": "replace", "edit_start_line_idx": 15}, "file": "import fs from 'fs'\nimport path from 'path'\nimport { app, Menu } from 'electron'\nimport configureMenu, { dockMenu } from './menus'\nimport { isFile, ensureDir, getPath, log } from './utils'\n\nconst MAX_RECENTLY_USED_DOCUMENTS = 12\nconst FILE_NAME = 'recently-used-documents.json'\nconst recentlyUsedDocumentsPath = path.join(getPath('userData'), FILE_NAME)\nconst isOsxOrWindows = /darwin|win32/.test(process.platform)\nlet initMacDock = false\n\nexport const addRecentlyUsedDocuments = filePath => {\n if (isOsxOrWindows) app.addRecentDocument(filePath)\n if (process.platform === 'darwin') return\n\n let recentDocuments = getRecentlyUsedDocuments()\n const index = recentDocuments.indexOf(filePath)\n let needSave = index !== 0\n if (index > 0) {\n recentDocuments.splice(index, 1)\n }\n if (index !== 0) {\n recentDocuments.unshift(filePath)\n }\n\n if (recentDocuments.length > MAX_RECENTLY_USED_DOCUMENTS) {\n needSave = true\n recentDocuments.splice(MAX_RECENTLY_USED_DOCUMENTS, recentDocuments.length - MAX_RECENTLY_USED_DOCUMENTS)\n }\n\n updateApplicationMenu(recentDocuments)\n\n if (needSave) {\n ensureDir(getPath('userData'))\n const json = JSON.stringify(recentDocuments, null, 2)\n fs.writeFileSync(recentlyUsedDocumentsPath, json, 'utf-8')\n }\n}\n\nexport const clearRecentlyUsedDocuments = () => {\n if (isOsxOrWindows) app.clearRecentDocuments()\n if (process.platform === 'darwin') return\n\n const recentDocuments = []\n updateApplicationMenu(recentDocuments)\n const json = JSON.stringify(recentDocuments, null, 2)\n ensureDir(getPath('userData'))\n fs.writeFileSync(recentlyUsedDocumentsPath, json, 'utf-8')\n}\n\nexport const getRecentlyUsedDocuments = () => {\n if (!isFile(recentlyUsedDocumentsPath)) {\n return []\n }\n\n try {\n let recentDocuments = JSON.parse(fs.readFileSync(recentlyUsedDocumentsPath, 'utf-8'))\n .filter(f => f && isFile(f))\n if (recentDocuments.length > MAX_RECENTLY_USED_DOCUMENTS) {\n recentDocuments.splice(MAX_RECENTLY_USED_DOCUMENTS, recentDocuments.length - MAX_RECENTLY_USED_DOCUMENTS)\n }\n return recentDocuments\n } catch (err) {\n log(err)\n return []\n }\n}\n\nexport const updateApplicationMenu = (recentUsedDocuments) => {\n if (!recentUsedDocuments) {\n recentUsedDocuments = getRecentlyUsedDocuments()\n }\n\n // \"we don't support changing menu object after calling setMenu, the behavior\n // is undefined if user does that.\" That means we have to recreate the\n // application menu each time.\n\n const menu = Menu.buildFromTemplate(configureMenu(recentUsedDocuments))\n Menu.setApplicationMenu(menu)\n if (!initMacDock && process.platform === 'darwin') {\n // app.dock is only for macosx\n app.dock.setMenu(dockMenu)\n }\n initMacDock = true\n}\n\nexport const updateLineEndingnMenu = lineEnding => {\n const menus = Menu.getApplicationMenu()\n const crlfMenu = menus.getMenuItemById('crlfLineEndingMenuEntry')\n const lfMenu = menus.getMenuItemById('lfLineEndingMenuEntry')\n if (lineEnding === 'crlf') {\n crlfMenu.checked = true\n } else {\n lfMenu.checked = true\n }\n}\n", "file_path": "src/main/menu.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.0001768655056366697, 0.00017174969252664596, 0.00016869489627424628, 0.00017053220653906465, 2.7599953682511114e-06]} {"hunk": {"id": 3, "code_window": [" click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'undo')\n", " }\n", " }, {\n", " label: 'Redo',\n", " accelerator: 'CmdOrCtrl+Y',\n", " click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'redo')\n", " }\n", " }, {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" accelerator: 'Shift+CmdOrCtrl+Z',\n"], "file_path": "src/main/menus/edit.js", "type": "replace", "edit_start_line_idx": 15}, "file": "import resource from './resource'\n\nconst state = {\n aiLoading: false,\n aiList: []\n}\n\nconst mutations = {\n SET_AI_LIST (state, { data, type }) {\n if (type === 'search' || type === 'collect') {\n state.aiList = data\n } else {\n state.aiList = [...state.aiList, ...data]\n }\n },\n SET_AI_STATUS (state, bool) {\n state.aiLoading = bool\n }\n}\n\nconst actions = {\n AI_LIST ({ commit }, data) {\n commit('SET_AI_LIST', data)\n },\n AI_SEARCH ({ commit }, { params, type }) {\n commit('SET_AI_STATUS', true)\n return resource.sogou(params)\n .then(({ data, total }) => {\n commit('SET_AI_LIST', { data, type })\n commit('SET_AI_STATUS', false)\n return { data, total }\n })\n .catch(err => {\n console.log(err)\n commit('SET_AI_STATUS', false)\n })\n }\n}\n\nexport default { state, mutations, actions }\n", "file_path": "src/renderer/store/aidou.js", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.014273511245846748, 0.003545958548784256, 0.00016730779316276312, 0.0001739380822982639, 0.005470167379826307]} {"hunk": {"id": 3, "code_window": [" click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'undo')\n", " }\n", " }, {\n", " label: 'Redo',\n", " accelerator: 'CmdOrCtrl+Y',\n", " click: (menuItem, browserWindow) => {\n", " actions.edit(browserWindow, 'redo')\n", " }\n", " }, {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" accelerator: 'Shift+CmdOrCtrl+Z',\n"], "file_path": "src/main/menus/edit.js", "type": "replace", "edit_start_line_idx": 15}, "file": "{\n \"name\": \"marktext\",\n \"version\": \"0.10.21\",\n \"author\": \"Jocs \",\n \"description\": \"Next generation markdown editor\",\n \"license\": \"MIT\",\n \"main\": \"./dist/electron/main.js\",\n \"scripts\": {\n \"release:win:linux\": \"node .electron-vue/build.js && electron-builder --win --linux\",\n \"release\": \"node .electron-vue/build.js && electron-builder -mwl\",\n \"release:linux\": \"node .electron-vue/build.js && electron-builder --linux\",\n \"release:mac\": \"node .electron-vue/build.js && electron-builder --mac\",\n \"release:win\": \"node .electron-vue/build.js && electron-builder --win\",\n \"build\": \"node .electron-vue/build.js && electron-builder\",\n \"build:dir\": \"node .electron-vue/build.js && electron-builder --dir\",\n \"build:clean\": \"cross-env BUILD_TARGET=clean node .electron-vue/build.js\",\n \"build:dev\": \"node .electron-vue/build.js\",\n \"build:web\": \"cross-env BUILD_TARGET=web node .electron-vue/build.js\",\n \"dev\": \"node .electron-vue/dev-runner.js\",\n \"e2e\": \"npm run pack && mocha test/e2e\",\n \"lint\": \"eslint --ext .js,.vue -f ./node_modules/eslint-friendly-formatter src test\",\n \"lint:fix\": \"eslint --ext .js,.vue -f ./node_modules/eslint-friendly-formatter --fix src test\",\n \"pack\": \"npm run pack:main && npm run pack:renderer\",\n \"pack:main\": \"cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.main.config.js\",\n \"pack:renderer\": \"cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.renderer.config.js\",\n \"test\": \"npm run unit && npm run e2e\",\n \"unit\": \"karma start test/unit/karma.conf.js\",\n \"postinstall\": \"npm run lint:fix\"\n },\n \"build\": {\n \"productName\": \"Mark Text\",\n \"appId\": \"com.github.marktext.marktext\",\n \"asar\": true,\n \"directories\": {\n \"output\": \"build\"\n },\n \"fileAssociations\": {\n \"ext\": [\n \"md\",\n \"markdown\",\n \"mmd\",\n \"mdown\",\n \"mdtxt\",\n \"mdtext\"\n ],\n \"role\": \"Editor\"\n },\n \"files\": [\n \"dist/electron/**/*\"\n ],\n \"dmg\": {\n \"contents\": [\n {\n \"x\": 410,\n \"y\": 150,\n \"type\": \"link\",\n \"path\": \"/Applications\"\n },\n {\n \"x\": 130,\n \"y\": 150,\n \"type\": \"file\"\n }\n ]\n },\n \"mac\": {\n \"icon\": \"build/icons/icon.icns\"\n },\n \"win\": {\n \"icon\": \"build/icons/icon.ico\",\n \"target\": [\n {\n \"target\": \"nsis\",\n \"arch\": [\n \"ia32\",\n \"x64\"\n ]\n }\n ],\n \"requestedExecutionLevel\": \"asInvoker\"\n },\n \"nsis\": {\n \"perMachine\": true,\n \"oneClick\": false,\n \"allowToChangeInstallationDirectory\": true,\n \"include\": \"build/windows/installer.nsh\"\n },\n \"linux\": {\n \"category\": \"Office;TextEditor;Utility\",\n \"icon\": \"build/icons\"\n },\n \"snap\": {\n \"confinement\": \"classic\",\n \"grade\": \"stable\",\n \"plugs\": [\n \"default\",\n \"classic-support\",\n \"wayland\"\n ]\n }\n },\n \"dependencies\": {\n \"axios\": \"^0.18.0\",\n \"cheerio\": \"^1.0.0-rc.2\",\n \"codemirror\": \"^5.36.0\",\n \"css-tree\": \"^1.0.0-alpha.28\",\n \"dompurify\": \"^1.0.3\",\n \"electron-window-state\": \"^4.1.1\",\n \"element-ui\": \"^2.3.3\",\n \"file-icons-js\": \"^1.0.3\",\n \"fs-extra\": \"^5.0.0\",\n \"fuzzaldrin\": \"^2.1.0\",\n \"html-tags\": \"^2.0.0\",\n \"katex\": \"^0.9.0\",\n \"mousetrap\": \"^1.6.1\",\n \"parse5\": \"^3.0.3\",\n \"snabbdom\": \"^0.7.1\",\n \"snabbdom-to-html\": \"^5.1.0\",\n \"snabbdom-virtualize\": \"^0.7.0\",\n \"to\": \"^0.2.9\",\n \"turndown\": \"^4.0.1\",\n \"turndown-plugin-gfm\": \"^1.0.1\",\n \"update\": \"^0.7.4\",\n \"vue\": \"^2.5.16\",\n \"vue-electron\": \"^1.0.6\",\n \"vuex\": \"^2.3.1\"\n },\n \"devDependencies\": {\n \"babel-core\": \"^6.25.0\",\n \"babel-eslint\": \"^7.2.3\",\n \"babel-loader\": \"^7.1.1\",\n \"babel-plugin-component\": \"^1.1.0\",\n \"babel-plugin-istanbul\": \"^4.1.6\",\n \"babel-plugin-transform-runtime\": \"^6.23.0\",\n \"babel-preset-env\": \"^1.6.0\",\n \"babel-preset-stage-0\": \"^6.24.1\",\n \"babel-register\": \"^6.24.1\",\n \"babili-webpack-plugin\": \"^0.1.2\",\n \"cfonts\": \"^1.2.0\",\n \"chai\": \"^4.0.0\",\n \"chalk\": \"^2.1.0\",\n \"copy-webpack-plugin\": \"^4.0.1\",\n \"cross-env\": \"^5.0.5\",\n \"css-loader\": \"^0.28.4\",\n \"del\": \"^3.0.0\",\n \"devtron\": \"^1.4.0\",\n \"electron\": \"^2.0.0\",\n \"electron-builder\": \"^20.8.2\",\n \"electron-debug\": \"^1.5.0\",\n \"electron-devtools-installer\": \"^2.2.0\",\n \"electron-updater\": \"^2.21.8\",\n \"eslint\": \"^4.19.1\",\n \"eslint-config-standard\": \"^10.2.1\",\n \"eslint-friendly-formatter\": \"^3.0.0\",\n \"eslint-loader\": \"^1.9.0\",\n \"eslint-plugin-html\": \"^3.1.1\",\n \"eslint-plugin-import\": \"^2.10.0\",\n \"eslint-plugin-node\": \"^5.1.1\",\n \"eslint-plugin-promise\": \"^3.5.0\",\n \"eslint-plugin-standard\": \"^3.0.1\",\n \"extract-text-webpack-plugin\": \"^3.0.0\",\n \"file-loader\": \"^0.11.2\",\n \"html-webpack-plugin\": \"^2.30.1\",\n \"inject-loader\": \"^3.0.0\",\n \"karma\": \"^1.3.0\",\n \"karma-chai\": \"^0.1.0\",\n \"karma-coverage\": \"^1.1.1\",\n \"karma-electron\": \"^5.3.0\",\n \"karma-mocha\": \"^1.2.0\",\n \"karma-sourcemap-loader\": \"^0.3.7\",\n \"karma-spec-reporter\": \"^0.0.31\",\n \"karma-webpack\": \"^2.0.1\",\n \"mocha\": \"^3.0.2\",\n \"multispinner\": \"^0.2.1\",\n \"node-loader\": \"^0.6.0\",\n \"require-dir\": \"^0.3.0\",\n \"spectron\": \"^3.7.1\",\n \"style-loader\": \"^0.18.2\",\n \"url-loader\": \"^0.5.9\",\n \"vue-html-loader\": \"^1.2.4\",\n \"vue-loader\": \"^14.2.2\",\n \"vue-style-loader\": \"^3.0.1\",\n \"vue-template-compiler\": \"^2.4.2\",\n \"webpack\": \"^3.5.2\",\n \"webpack-dev-server\": \"^2.7.1\",\n \"webpack-hot-middleware\": \"^2.22.0\",\n \"webpack-merge\": \"^4.1.0\"\n }\n}\n", "file_path": "package.json", "label": 0, "commit_url": "https://github.com/marktext/marktext/commit/dcb50e3de2b0951196c841cde42d0c820ee85d7d", "dependency_score": [0.0001754840195644647, 0.00017299503087997437, 0.00016851097461767495, 0.00017326686065644026, 1.6872206742846174e-06]} {"hunk": {"id": 0, "code_window": ["Package.describe({\n", " summary: \"Cross browser API for Persistant Storage, PubSub and Request.\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"API for Persistant Storage, PubSub and Request\"\n"], "file_path": "packages/amplify/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "Package.describe({\n summary: \"Automatically preserve all form fields that have a unique id\"\n});\n\nPackage.on_use(function (api, where) {\n api.use(['underscore', 'spark']);\n api.add_files(\"preserve-inputs.js\", \"client\");\n});\n", "file_path": "packages/preserve-inputs/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0004882013890892267, 0.0004882013890892267, 0.0004882013890892267, 0.0004882013890892267, 0.0]} {"hunk": {"id": 0, "code_window": ["Package.describe({\n", " summary: \"Cross browser API for Persistant Storage, PubSub and Request.\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"API for Persistant Storage, PubSub and Request\"\n"], "file_path": "packages/amplify/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "/*!\njQuery Waypoints - v1.1.2\nCopyright (c) 2011 Caleb Troughton\nDual licensed under the MIT license and GPL license.\nhttps://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt\nhttps://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt\n*/\n\n/*\nWaypoints is a small jQuery plugin that makes it easy to execute a function\nwhenever you scroll to an element.\n\nGitHub Repository: https://github.com/imakewebthings/jquery-waypoints\nDocumentation and Examples: http://imakewebthings.github.com/jquery-waypoints\n\nChangelog:\n v1.1.2\n - Fixed error thrown by waypoints with triggerOnce option that were\n triggered via resize refresh.\n\tv1.1.1\n\t\t- Fixed bug in initialization where all offsets were being calculated\n\t\t as if set to 0 initially, causing unwarranted triggers during the\n\t\t subsequent refresh.\n\t\t- Added onlyOnScroll, an option for individual waypoints that disables\n\t\t triggers due to an offset refresh that crosses the current scroll\n\t\t point. (All credit to @knuton on this one.)\n\tv1.1\n\t\t- Moved the continuous option out of global settings and into the options\n\t\t object for individual waypoints.\n\t\t- Added the context option, which allows for using waypoints within any\n\t\t scrollable element, not just the window.\n\tv1.0.2\n\t\t- Moved scroll and resize handler bindings out of load. Should play nicer\n\t\t with async loaders like Head JS and LABjs.\n\t\t- Fixed a 1px off error when using certain % offsets.\n\t\t- Added unit tests.\n\tv1.0.1\n\t\t- Added $.waypoints('viewportHeight').\n\t\t- Fixed iOS bug (using the new viewportHeight method).\n\t\t- Added offset function alias: 'bottom-in-view'.\n\tv1.0\n\t\t- Initial release.\n\t\nSupport:\n\t- jQuery versions 1.4.3+\n\t- IE6+, FF3+, Chrome 6+, Safari 4+, Opera 11\n\t- Other versions and browsers may work, these are just the ones I've looked at.\n*/\n\n(function($, wp, wps, window, undefined){\n\t'$:nomunge';\n\t\n\tvar $w = $(window),\n\t\n\t// Keeping common strings as variables = better minification\n\teventName = 'waypoint.reached',\n\t\n\t/*\n\tFor the waypoint and direction passed in, trigger the waypoint.reached\n\tevent and deal with the triggerOnce option.\n\t*/\n\ttriggerWaypoint = function(way, dir) {\n\t\tway.element.trigger(eventName, dir);\n\t\tif (way.options.triggerOnce) {\n\t\t\tway.element[wp]('destroy');\n\t\t}\n\t},\n\t\n\t/*\n\tGiven a jQuery element and Context, returns the index of that element in the waypoints\n\tarray. Returns the index, or -1 if the element is not a waypoint.\n\t*/\n\twaypointIndex = function(el, context) {\n\t\tvar i = context.waypoints.length - 1;\n\t\twhile (i >= 0 && context.waypoints[i].element[0] !== el[0]) {\n\t\t\ti -= 1;\n\t\t}\n\t\treturn i;\n\t},\n\t\n\t// Private list of all elements used as scrolling contexts for waypoints.\n\tcontexts = [],\n\t\n\t/*\n\tContext Class - represents a scrolling context. Properties include:\n\t\telement: jQuery object containing a single HTML element.\n\t\twaypoints: Array of waypoints operating under this scroll context.\n\t\toldScroll: Keeps the previous scroll position to determine scroll direction.\n\t\tdidScroll: Flag used in scrolling the context's scroll event.\n\t\tdidResize: Flag used in scrolling the context's resize event.\n\t\tdoScroll: Function that checks for crossed waypoints. Called from throttler.\n\t*/\n\tContext = function(context) {\n\t\t$.extend(this, {\n\t\t\t'element': $(context),\n\t\t\t\n\t\t\t/*\n\t\t\tStarting at a ridiculous negative number allows for a 'down' trigger of 0 or\n\t\t\tnegative offset waypoints on load. Useful for setting initial states.\n\t\t\t*/\n\t\t\t'oldScroll': -99999,\n\t\t\t\n\t\t\t/*\n\t\t\tList of all elements that have been registered as waypoints.\n\t\t\tEach object in the array contains:\n\t\t\t\telement: jQuery object containing a single HTML element.\n\t\t\t\toffset: The window scroll offset, in px, that triggers the waypoint event.\n\t\t\t\toptions: Options object that was passed to the waypoint fn function.\n\t\t\t*/\n\t\t\t'waypoints': [],\n\t\t\t\n\t\t\tdidScroll: false,\n\t\t\tdidResize: false,\n\t\n\t\t\tdoScroll: $.proxy(function() {\n\t\t\t\tvar newScroll = this.element.scrollTop(),\n\t\t\t\t\n\t\t\t\t// Are we scrolling up or down? Used for direction argument in callback.\n\t\t\t\tisDown = newScroll > this.oldScroll,\n\t\t\t\tthat = this,\n\n\t\t\t\t// Get a list of all waypoints that were crossed since last scroll move.\n\t\t\t\tpointsHit = $.grep(this.waypoints, function(el, i) {\n\t\t\t\t\treturn isDown ?\n\t\t\t\t\t\t(el.offset > that.oldScroll && el.offset <= newScroll) :\n\t\t\t\t\t\t(el.offset <= that.oldScroll && el.offset > newScroll);\n\t\t\t\t}),\n\t\t\t\tlen = pointsHit.length;\n\t\t\t\t\n\t\t\t\t// iOS adjustment\n\t\t\t\tif (!this.oldScroll || !newScroll) {\n\t\t\t\t\t$[wps]('refresh');\n\t\t\t\t}\n\n\t\t\t\t// Done with scroll comparisons, store new scroll before ejection\n\t\t\t\tthis.oldScroll = newScroll;\n\n\t\t\t\t// No waypoints crossed? Eject.\n\t\t\t\tif (!len) return;\n\n\t\t\t\t// If several waypoints triggered, need to do so in reverse order going up\n\t\t\t\tif (!isDown) pointsHit.reverse();\n\n\t\t\t\t/*\n\t\t\t\tOne scroll move may cross several waypoints. If the waypoint's continuous\n\t\t\t\toption is true it should fire even if it isn't the last waypoint. If false,\n\t\t\t\tit will only fire if it's the last one.\n\t\t\t\t*/\n\t\t\t\t$.each(pointsHit, function(i, point) {\n\t\t\t\t\tif (point.options.continuous || i === len - 1) {\n\t\t\t\t\t\ttriggerWaypoint(point, [isDown ? 'down' : 'up']);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}, this)\n\t\t});\n\t\t\n\t\t// Setup scroll and resize handlers. Throttled at the settings-defined rate limits.\n\t\t$(context).scroll($.proxy(function() {\n\t\t\tif (!this.didScroll) {\n\t\t\t\tthis.didScroll = true;\n\t\t\t\twindow.setTimeout($.proxy(function() {\n\t\t\t\t\tthis.doScroll();\n\t\t\t\t\tthis.didScroll = false;\n\t\t\t\t}, this), $[wps].settings.scrollThrottle);\n\t\t\t}\n\t\t}, this)).resize($.proxy(function() {\n\t\t\tif (!this.didResize) {\n\t\t\t\tthis.didResize = true;\n\t\t\t\twindow.setTimeout($.proxy(function() {\n\t\t\t\t\t$[wps]('refresh');\n\t\t\t\t\tthis.didResize = false;\n\t\t\t\t}, this), $[wps].settings.resizeThrottle);\n\t\t\t}\n\t\t}, this));\n\t\t\n\t\t$w.load($.proxy(function() {\n\t\t\t/*\n\t\t\tFire a scroll check, should the page be loaded at a non-zero scroll value,\n\t\t\tas with a fragment id link or a page refresh.\n\t\t\t*/\n\t\t\tthis.doScroll();\n\t\t}, this));\n\t},\n\t\n\t/* Returns a Context object from the contexts array, given the raw HTML element\n\tfor that context. */\n\tgetContextByElement = function(element) {\n\t\tvar found = null;\n\t\t\n\t\t$.each(contexts, function(i, c) {\n\t\t\tif (c.element[0] === element) {\n\t\t\t\tfound = c;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\t\t\n\t\treturn found;\n\t},\n\t\n\t// Methods exposed to the effin' object \n\tmethods = {\n\t\t/*\n\t\tjQuery.fn.waypoint([handler], [options])\n\t\t\n\t\thandler\n\t\t\tfunction, optional\n\t\t\tA callback function called when the user scrolls past the element.\n\t\t\tThe function signature is function(event, direction) where event is\n\t\t\ta standard jQuery Event Object and direction is a string, either 'down'\n\t\t\tor 'up' indicating which direction the user is scrolling.\n\t\t\t\n\t\toptions\n\t\t\tobject, optional\n\t\t\tA map of options to apply to this set of waypoints, including where on\n\t\t\tthe browser window the waypoint is triggered. For a full list of\n\t\t\toptions and their defaults, see $.fn.waypoint.defaults.\n\t\t\t\n\t\tThis is how you register an element as a waypoint. When the user scrolls past\n\t\tthat element it triggers waypoint.reached, a custom event. Since the\n\t\tparameters for creating a waypoint are optional, we have a few different\n\t\tpossible signatures. Let’s look at each of them.\n\n\t\tsomeElements.waypoint();\n\t\t\t\n\t\tCalling .waypoint with no parameters will register the elements as waypoints\n\t\tusing the default options. The elements will fire the waypoint.reached event,\n\t\tbut calling it in this way does not bind any handler to the event. You can\n\t\tbind to the event yourself, as with any other event, like so:\n\n\t\tsomeElements.bind('waypoint.reached', function(event, direction) {\n\t\t // make it rain\n\t\t});\n\t\t\t\n\t\tYou will usually want to create a waypoint and immediately bind a function to\n\t\twaypoint.reached, and can do so by passing a handler as the first argument to\n\t\t.waypoint:\n\n\t\tsomeElements.waypoint(function(event, direction) {\n\t\t if (direction === 'down') {\n\t\t // do this on the way down\n\t\t }\n\t\t else {\n\t\t // do this on the way back up through the waypoint\n\t\t }\n\t\t});\n\t\t\t\n\t\tThis will still use the default options, which will trigger the waypoint when\n\t\tthe top of the element hits the top of the window. We can pass .waypoint an\n\t\toptions object to customize things:\n\n\t\tsomeElements.waypoint(function(event, direction) {\n\t\t // do something amazing\n\t\t}, {\n\t\t offset: '50%' // middle of the page\n\t\t});\n\t\t\t\n\t\tYou can also pass just an options object.\n\n\t\tsomeElements.waypoint({\n\t\t offset: 100 // 100px from the top\n\t\t});\n\t\t\t\n\t\tThis behaves like .waypoint(), in that it registers the elements as waypoints\n\t\tbut binds no event handlers.\n\n\t\tCalling .waypoint on an existing waypoint will extend the previous options.\n\t\tIf the call includes a handler, it will be bound to waypoint.reached without\n\t\tunbinding any other handlers.\n\t\t*/\n\t\tinit: function(f, options) {\n\t\t\t// Register each element as a waypoint, add to array.\n\t\t\tthis.each(function() {\n\t\t\t\tvar cElement = $.fn[wp].defaults.context,\n\t\t\t\tcontext,\n\t\t\t\t$this = $(this);\n\n\t\t\t\t// Default window context or a specific element?\n\t\t\t\tif (options && options.context) {\n\t\t\t\t\tcElement = options.context;\n\t\t\t\t}\n\n\t\t\t\t// Find the closest element that matches the context\n\t\t\t\tif (!$.isWindow(cElement)) {\n\t\t\t\t\tcElement = $this.closest(cElement)[0];\n\t\t\t\t}\n\t\t\t\tcontext = getContextByElement(cElement);\n\n\t\t\t\t// Not a context yet? Create and push.\n\t\t\t\tif (!context) {\n\t\t\t\t\tcontext = new Context(cElement);\n\t\t\t\t\tcontexts.push(context);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Extend default and preexisting options\n\t\t\t\tvar ndx = waypointIndex($this, context),\n\t\t\t\tbase = ndx < 0 ? $.fn[wp].defaults : context.waypoints[ndx].options,\n\t\t\t\topts = $.extend({}, base, options);\n\t\t\t\t\n\t\t\t\t// Offset aliases\n\t\t\t\topts.offset = opts.offset === \"bottom-in-view\" ?\n\t\t\t\t\tfunction() {\n\t\t\t\t\t\tvar cHeight = $.isWindow(cElement) ? $[wps]('viewportHeight')\n\t\t\t\t\t\t\t: $(cElement).height();\n\t\t\t\t\t\treturn cHeight - $(this).outerHeight();\n\t\t\t\t\t} : opts.offset;\n\n\t\t\t\t// Update, or create new waypoint\n\t\t\t\tif (ndx < 0) {\n\t\t\t\t\tcontext.waypoints.push({\n\t\t\t\t\t\t'element': $this,\n\t\t\t\t\t\t'offset': null,\n\t\t\t\t\t\t'options': opts\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcontext.waypoints[ndx].options = opts;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Bind the function if it was passed in.\n\t\t\t\tif (f) {\n\t\t\t\t\t$this.bind(eventName, f);\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\t// Need to re-sort+refresh the waypoints array after new elements are added.\n\t\t\t$[wps]('refresh');\n\t\t\t\n\t\t\treturn this;\n\t\t},\n\t\t\n\t\t\n\t\t/*\n\t\tjQuery.fn.waypoint('remove')\n\t\t\n\t\tPassing the string 'remove' to .waypoint unregisters the elements as waypoints\n\t\tand wipes any custom options, but leaves the waypoint.reached events bound.\n\t\tCalling .waypoint again in the future would reregister the waypoint and the old\n\t\thandlers would continue to work.\n\t\t*/\n\t\tremove: function() {\n\t\t\treturn this.each(function(i, el) {\n\t\t\t\tvar $el = $(el);\n\t\t\t\t\n\t\t\t\t$.each(contexts, function(i, c) {\n\t\t\t\t\tvar ndx = waypointIndex($el, c);\n\n\t\t\t\t\tif (ndx >= 0) {\n\t\t\t\t\t\tc.waypoints.splice(ndx, 1);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t\t\n\t\t/*\n\t\tjQuery.fn.waypoint('destroy')\n\t\t\n\t\tPassing the string 'destroy' to .waypoint will unbind all waypoint.reached\n\t\tevent handlers on those elements and unregisters them as waypoints.\n\t\t*/\n\t\tdestroy: function() {\n\t\t\treturn this.unbind(eventName)[wp]('remove');\n\t\t}\n\t},\n\t\n\t/*\n\tMethods used by the jQuery object extension.\n\t*/\n\tjQMethods = {\n\t\t\n\t\t/*\n\t\tjQuery.waypoints('refresh')\n\t\t\n\t\tThis will force a recalculation of each waypoint’s trigger point based on\n\t\tits offset option and context. This is called automatically whenever the window\n\t\t(or other defined context) is resized, new waypoints are added, or a waypoint’s\n\t\toptions are modified. If your project is changing the DOM or page layout without\n\t\tdoing one of these things, you may want to manually call this refresh.\n\t\t*/\n\t\trefresh: function() {\n\t\t\t$.each(contexts, function(i, c) {\n\t\t\t\tvar isWin = $.isWindow(c.element[0]),\n\t\t\t\tcontextOffset = isWin ? 0 : c.element.offset().top,\n\t\t\t\tcontextHeight = isWin ? $[wps]('viewportHeight') : c.element.height(),\n\t\t\t\tcontextScroll = isWin ? 0 : c.element.scrollTop();\n\t\t\t\t\n\t\t\t\t$.each(c.waypoints, function(j, o) {\n\t\t\t\t /* $.each isn't safe from element removal due to triggerOnce.\n\t\t\t\t Should rewrite the loop but this is way easier. */\n\t\t\t\t if (!o) return;\n\t\t\t\t \n\t\t\t\t\t// Adjustment is just the offset if it's a px value\n\t\t\t\t\tvar adjustment = o.options.offset,\n\t\t\t\t\toldOffset = o.offset;\n\t\t\t\t\t\n\t\t\t\t\t// Set adjustment to the return value if offset is a function.\n\t\t\t\t\tif (typeof o.options.offset === \"function\") {\n\t\t\t\t\t\tadjustment = o.options.offset.apply(o.element);\n\t\t\t\t\t}\n\t\t\t\t\t// Calculate the adjustment if offset is a percentage.\n\t\t\t\t\telse if (typeof o.options.offset === \"string\") {\n\t\t\t\t\t\tvar amount = parseFloat(o.options.offset);\n\t\t\t\t\t\tadjustment = o.options.offset.indexOf(\"%\") ?\n\t\t\t\t\t\t\tMath.ceil(contextHeight * (amount / 100)) : amount;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* \n\t\t\t\t\tSet the element offset to the window scroll offset, less\n\t\t\t\t\tall our adjustments.\n\t\t\t\t\t*/\n\t\t\t\t\to.offset = o.element.offset().top - contextOffset\n\t\t\t\t\t\t+ contextScroll - adjustment;\n\n\t\t\t\t\t/*\n\t\t\t\t\tAn element offset change across the current scroll point triggers\n\t\t\t\t\tthe event, just as if we scrolled past it unless prevented by an\n\t\t\t\t\toptional flag.\n\t\t\t\t\t*/\n\t\t\t\t\tif (o.options.onlyOnScroll) return;\n\t\t\t\t\t\n\t\t\t\t\tif (oldOffset !== null && c.oldScroll > oldOffset && c.oldScroll <= o.offset) {\n\t\t\t\t\t\ttriggerWaypoint(o, ['up']);\n\t\t\t\t\t}\n\t\t\t\t\telse if (oldOffset !== null && c.oldScroll < oldOffset && c.oldScroll >= o.offset) {\n\t\t\t\t\t\ttriggerWaypoint(o, ['down']);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t// Keep waypoints sorted by offset value.\n\t\t\t\tc.waypoints.sort(function(a, b) {\n\t\t\t\t\treturn a.offset - b.offset;\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t\t\n\t\t\n\t\t/*\n\t\tjQuery.waypoints('viewportHeight')\n\t\t\n\t\tThis will return the height of the viewport, adjusting for inconsistencies\n\t\tthat come with calling $(window).height() in iOS. Recommended for use\n\t\twithin any offset functions.\n\t\t*/\n\t\tviewportHeight: function() {\n\t\t\treturn (window.innerHeight ? window.innerHeight : $w.height());\n\t\t},\n\t\t\n\t\t\n\t\t/*\n\t\tjQuery.waypoints()\n\t\t\n\t\tThis will return a jQuery object with a collection of all registered waypoint\n\t\telements.\n\n\t\t$('.post').waypoint();\n\t\t$('.ad-unit').waypoint(function(event, direction) {\n\t\t // Passed an ad unit\n\t\t});\n\t\tconsole.log($.waypoints());\n\t\t\n\t\tThe example above would log a jQuery object containing all .post and .ad-unit\n\t\telements.\n\t\t*/\n\t\taggregate: function() {\n\t\t\tvar points = $();\n\t\t\t$.each(contexts, function(i, c) {\n\t\t\t\t$.each(c.waypoints, function(i, e) {\n\t\t\t\t\tpoints = points.add(e.element);\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn points;\n\t\t}\n\t};\n\n\t\n\t/*\n\tfn extension. Delegates to appropriate method.\n\t*/\n\t$.fn[wp] = function(method) {\n\t\t\n\t\tif (methods[method]) {\n\t\t\treturn methods[method].apply(this, Array.prototype.slice.call(arguments, 1));\n\t\t}\n\t\telse if (typeof method === \"function\" || !method) {\n\t\t\treturn methods.init.apply(this, arguments);\n\t\t}\n\t\telse if (typeof method === \"object\") {\n\t\t\treturn methods.init.apply(this, [null, method]);\n\t\t}\n\t\telse {\n\t\t\t$.error( 'Method ' + method + ' does not exist on jQuery ' + wp );\n\t\t}\n\t};\n\t\n\t\n\t/*\n\tThe default options object that is extended when calling .waypoint. It has the\n\tfollowing properties:\n\t\n\tcontext\n\t\tstring | element | jQuery*\n\t\tdefault: window\n\t\tThe context defines which scrollable element the waypoint belongs to and acts\n\t\twithin. The default, window, means the waypoint offset is calculated with relation\n\t\tto the whole viewport. You can set this to another element to use the waypoints\n\t\twithin that element. Accepts a selector string, *but if you use jQuery 1.6+ it\n\t\talso accepts a raw HTML element or jQuery object.\n\t\n\tcontinuous\n\t\tboolean\n\t\tdefault: true\n\t\tIf true, and multiple waypoints are triggered in one scroll, this waypoint will\n\t\ttrigger even if it is not the last waypoint reached. If false, it will only\n\t\ttrigger if it is the last waypoint.\n\n\toffset\n\t\tnumber | string | function\n\t\tdefault: 0\n\t\tDetermines how far the top of the element must be from the top of the browser\n\t\twindow to trigger a waypoint. It can be a number, which is taken as a number\n\t\tof pixels, a string representing a percentage of the viewport height, or a\n\t\tfunction that will return a number of pixels.\n\t\t\n\tonlyOnScroll\n\t\tboolean\n\t\tdefault: false\n\t\tIf true, this waypoint will not trigger if an offset change during a refresh\n\t\tcauses it to pass the current scroll point.\n\t\t\n\ttriggerOnce\n\t\tboolean\n\t\tdefault: false\n\t\tIf true, the waypoint will be destroyed when triggered.\n\t\n\tAn offset of 250 would trigger the waypoint when the top of the element is 250px\n\tfrom the top of the viewport. Negative values for any offset work as you might\n\texpect. A value of -100 would trigger the waypoint when the element is 100px above\n\tthe top of the window.\n\n\toffset: '100%'\n\t\n\tA string percentage will determine the pixel offset based on the height of the\n\twindow. When resizing the window, this offset will automatically be recalculated\n\twithout needing to call $.waypoints('refresh').\n\n\t// The bottom of the element is in view\n\toffset: function() {\n\t return $.waypoints('viewportHeight') - $(this).outerHeight();\n\t}\n\t\n\tOffset can take a function, which must return a number of pixels from the top of\n\tthe window. The this value will always refer to the raw HTML element of the\n\twaypoint. As with % values, functions are recalculated automatically when the\n\twindow resizes. For more on recalculating offsets, see $.waypoints('refresh').\n\t\n\tAn offset value of 'bottom-in-view' will act as an alias for the function in the\n\texample above, as this is a common usage.\n\t\n\toffset: 'bottom-in-view'\n\t\n\tYou can see this alias in use on the Scroll Analytics example page.\n\n\tThe triggerOnce flag, if true, will destroy the waypoint after the first trigger.\n\tThis is just a shortcut for calling .waypoint('destroy') within the waypoint\n\thandler. This is useful in situations such as scroll analytics, where you only\n\twant to record an event once for each page visit.\n\t\n\tThe context option lets you use Waypoints within an element other than the window.\n\tYou can define the context with a selector string and the waypoint will act within\n\tthe nearest ancestor that matches this selector.\n\t\n\t$('.something-scrollable .waypoint').waypoint({\n\t context: '.something-scrollable'\n\t});\n\t\n\tYou can see this in action on the Dial Controls example.\n\t*/\n\t$.fn[wp].defaults = {\n\t\tcontinuous: true,\n\t\toffset: 0,\n\t\ttriggerOnce: false,\n\t\tcontext: window\n\t};\n\t\n\t\n\t\n\t\n\t\n\t/*\n\tjQuery object extension. Delegates to appropriate methods above.\n\t*/\n\t$[wps] = function(method) {\n\t\tif (jQMethods[method]) {\n\t\t\treturn jQMethods[method].apply(this);\n\t\t}\n\t\telse {\n\t\t\treturn jQMethods['aggregate']();\n\t\t}\n\t};\n\t\n\t\n\t/*\n\t$.waypoints.settings\n\t\n\tSettings object that determines some of the plugin’s behavior.\n\t\t\n\tresizeThrottle\n\t\tnumber\n\t\tdefault: 200\n\t\tFor performance reasons, the refresh performed during resizes is\n\t\tthrottled. This value is the rate-limit in milliseconds between resize\n\t\trefreshes. For more information on throttling, check out Ben Alman’s\n\t\tthrottle / debounce plugin.\n\t\thttp://benalman.com/projects/jquery-throttle-debounce-plugin/\n\t\t\n\tscrollThrottle\n\t\tnumber\n\t\tdefault: 100\n\t\tFor performance reasons, checking for any crossed waypoints during a\n\t\tscroll event is throttled. This value is the rate-limit in milliseconds\n\t\tbetween scroll checks. For more information on throttling, check out Ben\n\t\tAlman’s throttle / debounce plugin.\n\t\thttp://benalman.com/projects/jquery-throttle-debounce-plugin/\n\t*/\n\t$[wps].settings = {\n\t\tresizeThrottle: 200,\n\t\tscrollThrottle: 100\n\t};\n\t\n\t$w.load(function() {\n\t\t// Calculate everything once on load.\n\t\t$[wps]('refresh');\n\t});\n})(jQuery, 'waypoint', 'waypoints', this);\n", "file_path": "packages/jquery-waypoints/waypoints.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0006739001255482435, 0.00017718742310535163, 0.000163700693519786, 0.0001689266209723428, 6.262813985813409e-05]} {"hunk": {"id": 0, "code_window": ["Package.describe({\n", " summary: \"Cross browser API for Persistant Storage, PubSub and Request.\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"API for Persistant Storage, PubSub and Request\"\n"], "file_path": "packages/amplify/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "\nTinytest.add(\"universal-events - basic\", function(test) {\n\n var runTest = function (testMissingHandlers) {\n var msgs = [];\n var listeners = [];\n\n var createListener = function () {\n var out = [];\n msgs.push(out);\n var ret = new UniversalEventListener(function(event) {\n var node = event.currentTarget;\n if (DomUtils.elementContains(document.body, node)) {\n out.push(event.currentTarget.nodeName.toLowerCase());\n }\n }, testMissingHandlers);\n listeners.push(ret);\n return ret;\n };\n\n var L1 = createListener();\n\n var check = function (event, expected) {\n _.each(msgs, function (m) {\n m.length = 0;\n });\n simulateEvent(DomUtils.find(d.node(), \"b\"), event);\n for (var i = 0; i < listeners.length; i++)\n test.equal(msgs[i], testMissingHandlers ? [] : expected[i]);\n };\n\n var d = OnscreenDiv(Meteor.render(\"
Hello
\"));\n L1.addType('mousedown');\n if (!testMissingHandlers)\n L1.installHandler(d.node(), 'mousedown');\n var x = ['b', 'span', 'div', 'div'];\n check('mousedown', [x]);\n\n check('mouseup', [[]]);\n\n L1.removeType('mousedown');\n check('mousedown', [[]]);\n L1.removeType('mousedown');\n check('mousedown', [[]]);\n\n L1.addType('mousedown');\n check('mousedown', [x]);\n L1.addType('mousedown');\n check('mousedown', [x]);\n L1.removeType('mousedown');\n check('mousedown', [[]]);\n\n var L2 = createListener();\n if (!testMissingHandlers)\n L2.installHandler(d.node(), 'mousedown');\n\n L1.addType('mousedown');\n check('mousedown', [x, []]);\n L2.addType('mousedown');\n check('mousedown', [x, x]);\n L2.addType('mousedown');\n check('mousedown', [x, x]);\n L1.removeType('mousedown');\n check('mousedown', [[], x]);\n L1.removeType('mousedown');\n check('mousedown', [[], x]);\n L2.removeType('mousedown');\n check('mousedown', [[], []]);\n L1.addType('mousedown');\n check('mousedown', [x, []]);\n L1.removeType('mousedown');\n check('mousedown', [[], []]);\n L2.addType('mousedown');\n check('mousedown', [[], x]);\n L2.removeType('mousedown');\n check('mousedown', [[], []]);\n\n d.kill();\n };\n\n runTest(false);\n runTest(true);\n});\n", "file_path": "packages/universal-events/event_tests.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017908976587932557, 0.00017588208720553666, 0.0001716880506137386, 0.00017621993902139366, 2.1967559860058827e-06]} {"hunk": {"id": 0, "code_window": ["Package.describe({\n", " summary: \"Cross browser API for Persistant Storage, PubSub and Request.\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"API for Persistant Storage, PubSub and Request\"\n"], "file_path": "packages/amplify/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "if (Meteor.isServer) {\n // XXX namespacing\n var Future = __meteor_bootstrap__.require('fibers/future');\n}\n\n// list of subscription tokens outstanding during a\n// captureDependencies run. only set when we're doing a run. The fact\n// that this is a singleton means we can't do recursive\n// Meteor.subscriptions(). But what would that even mean?\n// XXX namespacing\nMeteor._capture_subs = null;\n\n// @param url {String|Object} URL to Meteor app or sockjs endpoint (deprecated),\n// or an object as a test hook (see code)\n// Options:\n// reloadOnUpdate: should we try to reload when the server says\n// there's new code available?\n// reloadWithOutstanding: is it OK to reload if there are outstanding methods?\nMeteor._LivedataConnection = function (url, options) {\n var self = this;\n options = _.extend({\n reloadOnUpdate: false,\n reloadWithOutstanding: false\n }, options);\n\n // as a test hook, allow passing a stream instead of a url.\n if (typeof url === \"object\") {\n self.stream = url;\n // if we have two test streams, auto reload stuff will break because\n // the url is used as a key for the migration data.\n self.url = \"/debug\";\n } else {\n self.url = url;\n }\n\n self.last_session_id = null;\n self.stores = {}; // name -> object with methods\n self.method_handlers = {}; // name -> func\n self.next_method_id = 1;\n\n // --- Three classes of outstanding methods ---\n\n // 1. either already sent, or waiting to be sent with no special\n // consideration once we reconnect\n self.outstanding_methods = []; // each item has keys: msg, callback\n\n // 2. the sole outstanding method that needs to be waited on, or null\n // same keys as outstanding_methods (notably wait is implicitly true\n // but not set)\n self.outstanding_wait_method = null; // same keys as outstanding_methods\n // stores response from `outstanding_wait_method` while we wait for\n // previous method calls to complete, as received in _livedata_result\n self.outstanding_wait_method_response = null;\n\n // 3. methods blocked on outstanding_wait_method being completed.\n self.blocked_methods = []; // each item has keys: msg, callback, wait\n\n // if set, called when we reconnect, queuing method calls _before_\n // the existing outstanding ones\n self.onReconnect = null;\n // waiting for data from method\n self.unsatisfied_methods = {}; // map from method_id -> true\n // sub was ready, is no longer (due to reconnect)\n self.unready_subscriptions = {}; // map from sub._id -> true\n // messages from the server that have not been applied\n self.pending_data = []; // array of pending data messages\n // name -> updates for (yet to be created) collection\n self.queued = {};\n // if we're blocking a migration, the retry func\n self._retryMigrate = null;\n\n // metadata for subscriptions\n self.subs = new LocalCollection;\n // keyed by subs._id. value is unset or an array. if set, sub is not\n // yet ready.\n self.sub_ready_callbacks = {};\n\n // Per-connection scratch area. This is only used internally, but we\n // should have real and documented API for this sort of thing someday.\n self.sessionData = {};\n\n // just for testing\n self.quiesce_callbacks = [];\n\n // Block auto-reload while we're waiting for method responses.\n if (!options.reloadWithOutstanding) {\n Meteor._reload.onMigrate(function (retry) {\n if (!self._readyToMigrate()) {\n if (self._retryMigrate)\n throw new Error(\"Two migrations in progress?\");\n self._retryMigrate = retry;\n return false;\n } else {\n return [true];\n }\n });\n }\n\n // Setup stream (if not overriden above)\n self.stream = self.stream || new Meteor._Stream(self.url);\n\n self.stream.on('message', function (raw_msg) {\n try {\n var msg = JSON.parse(raw_msg);\n } catch (err) {\n Meteor._debug(\"discarding message with invalid JSON\", raw_msg);\n return;\n }\n if (typeof msg !== 'object' || !msg.msg) {\n Meteor._debug(\"discarding invalid livedata message\", msg);\n return;\n }\n\n if (msg.msg === 'connected')\n self._livedata_connected(msg);\n else if (msg.msg === 'data')\n self._livedata_data(msg);\n else if (msg.msg === 'nosub')\n self._livedata_nosub(msg);\n else if (msg.msg === 'result')\n self._livedata_result(msg);\n else if (msg.msg === 'error')\n self._livedata_error(msg);\n else\n Meteor._debug(\"discarding unknown livedata message type\", msg);\n });\n\n self.stream.on('reset', function () {\n // Send a connect message at the beginning of the stream.\n // NOTE: reset is called even on the first connection, so this is\n // the only place we send this message.\n var msg = {msg: 'connect'};\n if (self.last_session_id)\n msg.session = self.last_session_id;\n self.stream.send(JSON.stringify(msg));\n\n // Now, to minimize setup latency, go ahead and blast out all of\n // our pending methods ands subscriptions before we've even taken\n // the necessary RTT to know if we successfully reconnected. (1)\n // They're supposed to be idempotent; (2) even if we did\n // reconnect, we're not sure what messages might have gotten lost\n // (in either direction) since we were disconnected (TCP being\n // sloppy about that.)\n\n // XXX we may have an issue where we lose 'data' messages sent\n // immediately before disconnection.. do we need to add app-level\n // acking of data messages?\n\n // If an `onReconnect` handler is set, call it first. Go through\n // some hoops to ensure that methods that are called from within\n // `onReconnect` get executed _before_ ones that were originally\n // outstanding (since `onReconnect` is used to re-establish auth\n // certificates)\n if (self.onReconnect)\n self._callOnReconnectAndSendAppropriateOutstandingMethods();\n else\n self._sendOutstandingMethods();\n\n // add new subscriptions at the end. this way they take effect after\n // the handlers and we don't see flicker.\n self.subs.find().forEach(function (sub) {\n self.stream.send(JSON.stringify(\n {msg: 'sub', id: sub._id, name: sub.name, params: sub.args}));\n });\n });\n\n if (options.reloadOnUpdate) {\n self.stream.on('update_available', function () {\n // Start trying to migrate to a new version. Until all packages\n // signal that they're ready for a migration, the app will\n // continue running normally.\n Meteor._reload.reload();\n });\n }\n\n // we never terminate the observe(), since there is no way to\n // destroy a LivedataConnection.. but this shouldn't matter, since we're\n // the only one that holds a reference to the self.subs collection\n self.subs_token = self.subs.find({}).observe({\n added: function (sub) {\n self.stream.send(JSON.stringify({\n msg: 'sub', id: sub._id, name: sub.name, params: sub.args}));\n },\n changed: function (sub) {\n if (sub.count <= 0) {\n // minimongo not re-entrant.\n _.defer(function () { self.subs.remove({_id: sub._id}); });\n }\n },\n removed: function (obj) {\n self.stream.send(JSON.stringify({msg: 'unsub', id: obj._id}));\n }\n });\n};\n\n_.extend(Meteor._LivedataConnection.prototype, {\n // 'name' is the name of the data on the wire that should go in the\n // store. 'store' should be an object with methods beginUpdate,\n // update, endUpdate, reset. see Collection for an example.\n registerStore: function (name, store) {\n var self = this;\n\n if (name in self.stores)\n return false;\n self.stores[name] = store;\n\n var queued = self.queued[name] || [];\n store.beginUpdate(queued.length);\n _.each(queued, function (msg) {\n store.update(msg);\n });\n store.endUpdate();\n delete self.queued[name];\n\n return true;\n },\n\n subscribe: function (name /* .. [arguments] .. callback */) {\n var self = this;\n var id;\n\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length && typeof args[args.length - 1] === \"function\")\n var callback = args.pop();\n\n // Look for existing subs (ignore those with count=0, since they're going to\n // get removed on the next time through the event loop).\n var existing = self.subs.find(\n {name: name, args: args, count: {$gt: 0}},\n {reactive: false}).fetch();\n\n if (existing && existing[0]) {\n // already subbed, inc count.\n id = existing[0]._id;\n self.subs.update({_id: id}, {$inc: {count: 1}});\n\n if (callback) {\n if (self.sub_ready_callbacks[id])\n self.sub_ready_callbacks[id].push(callback);\n else\n callback(); // XXX maybe _.defer?\n }\n } else {\n // new sub, add object.\n // generate our own id so we can know it w/ a find afterwards.\n id = LocalCollection.uuid();\n self.subs.insert({_id: id, name: name, args: args, count: 1});\n\n self.sub_ready_callbacks[id] = [];\n\n if (callback)\n self.sub_ready_callbacks[id].push(callback);\n }\n\n // return an object with a stop method.\n var token = {stop: function () {\n if (!id) return; // must have an id (local from above).\n // just update the database. observe takes care of the rest.\n self.subs.update({_id: id}, {$inc: {count: -1}});\n }};\n\n if (Meteor._capture_subs)\n Meteor._capture_subs.push(token);\n\n return token;\n },\n\n methods: function (methods) {\n var self = this;\n _.each(methods, function (func, name) {\n if (self.method_handlers[name])\n throw new Error(\"A method named '\" + name + \"' is already defined\");\n self.method_handlers[name] = func;\n });\n },\n\n call: function (name /* .. [arguments] .. callback */) {\n // if it's a function, the last argument is the result callback,\n // not a parameter to the remote method.\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length && typeof args[args.length - 1] === \"function\")\n var callback = args.pop();\n return this.apply(name, args, callback);\n },\n\n // @param options {Optional Object}\n // wait: Boolean - Should we block subsequent method calls on this\n // method's result having been received?\n // (does not affect methods called from within this method)\n // @param callback {Optional Function}\n apply: function (name, args, options, callback) {\n var self = this;\n\n // We were passed 3 arguments. They may be either (name, args, options)\n // or (name, args, callback)\n if (!callback && typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n if (callback) {\n // XXX would it be better form to do the binding in stream.on,\n // or caller, instead of here?\n callback = Meteor.bindEnvironment(callback, function (e) {\n // XXX improve error message (and how we report it)\n Meteor._debug(\"Exception while delivering result of invoking '\" +\n name + \"'\", e.stack);\n });\n }\n\n if (Meteor.isClient) {\n // If on a client, run the stub, if we have one. The stub is\n // supposed to make some temporary writes to the database to\n // give the user a smooth experience until the actual result of\n // executing the method comes back from the server (whereupon\n // the temporary writes to the database will be reversed during\n // the beginUpdate/endUpdate process.)\n //\n // Normally, we ignore the return value of the stub (even if it\n // is an exception), in favor of the real return value from the\n // server. The exception is if the *caller* is a stub. In that\n // case, we're not going to do a RPC, so we use the return value\n // of the stub as our return value.\n var stub = self.method_handlers[name];\n if (stub) {\n var setUserId = function(userId) {\n self.setUserId(userId);\n };\n var invocation = new Meteor._MethodInvocation({\n isSimulation: true,\n userId: self.userId(), setUserId: setUserId,\n sessionData: self.sessionData\n });\n try {\n var ret = Meteor._CurrentInvocation.withValue(invocation,function () {\n return stub.apply(invocation, args);\n });\n }\n catch (e) {\n var exception = e;\n }\n }\n\n // If we're in a simulation, stop and return the result we have,\n // rather than going on to do an RPC. If there was no stub,\n // we'll end up returning undefined.\n var enclosing = Meteor._CurrentInvocation.get();\n var isSimulation = enclosing && enclosing.isSimulation;\n if (isSimulation) {\n if (callback) {\n callback(exception, ret);\n return;\n }\n if (exception)\n throw exception;\n return ret;\n }\n\n // If an exception occurred in a stub, and we're ignoring it\n // because we're doing an RPC and want to use what the server\n // returns instead, log it so the developer knows.\n //\n // Tests can set the 'expected' flag on an exception so it won't\n // go to log.\n if (exception && !exception.expected)\n Meteor._debug(\"Exception while simulating the effect of invoking '\" +\n name + \"'\", exception.stack);\n }\n\n // At this point we're definitely doing an RPC, and we're going to\n // return the value of the RPC to the caller.\n\n // If the caller didn't give a callback, decide what to do.\n if (!callback) {\n if (Meteor.isClient)\n // On the client, we don't have fibers, so we can't block. The\n // only thing we can do is to return undefined and discard the\n // result of the RPC.\n callback = function () {};\n else {\n // On the server, make the function synchronous.\n var future = new Future;\n callback = function (err, result) {\n future['return']([err, result]);\n };\n }\n }\n\n // Send the RPC. Note that on the client, it is important that the\n // stub have finished before we send the RPC (or at least we need\n // to guaranteed that the snapshot is not restored until the stub\n // has stopped doing writes.)\n var msg = {\n msg: 'method',\n method: name,\n params: args,\n id: '' + (self.next_method_id++)\n };\n\n if (self.outstanding_wait_method) {\n self.blocked_methods.push({\n msg: msg,\n callback: callback,\n wait: options.wait\n });\n } else {\n var method_object = {\n msg: msg,\n callback: callback\n };\n\n if (options.wait)\n self.outstanding_wait_method = method_object;\n else\n self.outstanding_methods.push(method_object);\n\n self.stream.send(JSON.stringify(msg));\n }\n\n // Even if we are waiting on other method calls mark this method\n // as unsatisfied so that the user never ends up seeing\n // intermediate versions of the server's datastream\n self.unsatisfied_methods[msg.id] = true;\n\n // If we're using the default callback on the server,\n // synchronously return the result from the remote host.\n if (future) {\n var outcome = future.wait();\n if (outcome[0])\n throw outcome[0];\n return outcome[1];\n }\n },\n\n status: function (/*passthrough args*/) {\n var self = this;\n return self.stream.status.apply(self.stream, arguments);\n },\n\n reconnect: function (/*passthrough args*/) {\n var self = this;\n return self.stream.reconnect.apply(self.stream, arguments);\n },\n\n ///\n /// Reactive user system\n /// XXX Can/should this be generalized pattern?\n ///\n userId: function () {\n var self = this;\n if (self._userIdListeners)\n self._userIdListeners.addCurrentContext();\n return self._userId;\n },\n\n setUserId: function (userId) {\n var self = this;\n self._userId = userId;\n if (self._userIdListeners)\n self._userIdListeners.invalidateAll();\n },\n\n _userId: null,\n _userIdListeners: Meteor.deps && new Meteor.deps._ContextSet,\n\n // PRIVATE: called when we are up-to-date with the server. intended\n // for use only in tests. currently, you are very limited in what\n // you may do inside your callback -- in particular, don't do\n // anything that could result in another call to onQuiesce, or\n // results are undefined.\n onQuiesce: function (f) {\n var self = this;\n\n f = Meteor.bindEnvironment(f, function (e) {\n Meteor._debug(\"Exception in quiesce callback\", e.stack);\n });\n\n for (var method_id in self.unsatisfied_methods) {\n // we are not quiesced -- wait until we are\n self.quiesce_callbacks.push(f);\n return;\n }\n\n f();\n },\n\n _livedata_connected: function (msg) {\n var self = this;\n\n if (typeof (msg.session) === \"string\") {\n var reconnected = (self.last_session_id === msg.session);\n self.last_session_id = msg.session;\n }\n\n if (reconnected)\n // successful reconnection -- pick up where we left off.\n return;\n\n // Server doesn't have our data any more. Re-sync a new session.\n\n // Put a reset message into the pending data queue and discard any\n // previous messages (they are unimportant now).\n self.pending_data = [\"reset\"];\n self.queued = {};\n\n // Mark all currently ready subscriptions as 'unready'.\n var all_subs = self.subs.find({}).fetch();\n self.unready_subscriptions = {};\n _.each(all_subs, function (sub) {\n if (!self.sub_ready_callbacks[sub._id])\n self.unready_subscriptions[sub._id] = true;\n });\n\n // Do not clear the database here. That happens once all the subs\n // are re-ready and we process pending_data.\n },\n\n _livedata_data: function (msg) {\n var self = this;\n\n // Add the data message to the queue\n self.pending_data.push(msg);\n\n // Process satisfied methods and subscriptions.\n // NOTE: does not fire callbacks here, that happens when\n // the data message is processed for real. This is just for\n // quiescing.\n _.each(msg.methods || [], function (method_id) {\n delete self.unsatisfied_methods[method_id];\n });\n _.each(msg.subs || [], function (sub_id) {\n delete self.unready_subscriptions[sub_id];\n });\n\n // If there are still method invocations in flight, stop\n for (var method_id in self.unsatisfied_methods)\n return;\n // If there are still uncomplete subscriptions, stop\n for (var sub_id in self.unready_subscriptions)\n return;\n\n // We have quiesced. Blow away local changes and replace\n // with authoritative changes from server.\n\n var messagesPerStore = {};\n _.each(self.pending_data, function (msg) {\n if (msg.collection && msg.id && self.stores[msg.collection]) {\n if (_.has(messagesPerStore, msg.collection))\n ++messagesPerStore[msg.collection];\n else\n messagesPerStore[msg.collection] = 1;\n }\n });\n\n _.each(self.stores, function (s, name) {\n s.beginUpdate(_.has(messagesPerStore, name) ? messagesPerStore[name] : 0);\n });\n\n _.each(self.pending_data, function (msg) {\n // Reset message from reconnect. Blow away everything.\n //\n // XXX instead of reset message, we could have a flag, and pass\n // that to beginUpdate. This would be more efficient since we don't\n // have to restore a snapshot if we're just going to blow away the\n // db.\n if (msg === \"reset\") {\n _.each(self.stores, function (s) { s.reset(); });\n return;\n }\n\n if (msg.collection && msg.id) {\n var store = self.stores[msg.collection];\n\n if (!store) {\n // Nobody's listening for this data. Queue it up until\n // someone wants it.\n // XXX memory use will grow without bound if you forget to\n // create a collection.. going to have to do something about\n // that.\n if (!(msg.collection in self.queued))\n self.queued[msg.collection] = [];\n self.queued[msg.collection].push(msg);\n return;\n }\n\n store.update(msg);\n }\n\n if (msg.subs) {\n _.each(msg.subs, function (id) {\n var arr = self.sub_ready_callbacks[id];\n if (arr) _.each(arr, function (c) { c(); });\n delete self.sub_ready_callbacks[id];\n });\n }\n });\n\n _.each(self.stores, function (s) { s.endUpdate(); });\n\n _.each(self.quiesce_callbacks, function (cb) { cb(); });\n self.quiesce_callbacks = [];\n\n self.pending_data = [];\n },\n\n _livedata_nosub: function (msg) {\n var self = this;\n // Meteor._debug(\"NOSUB\", msg);\n },\n\n _livedata_result: function (msg) {\n // id, result or error. error has error (code), reason, details\n\n var self = this;\n // find the outstanding request\n // should be O(1) in nearly all realistic use cases\n var m;\n if (self.outstanding_wait_method &&\n self.outstanding_wait_method.msg.id === msg.id) {\n m = self.outstanding_wait_method;\n self.outstanding_wait_method_response = msg;\n } else {\n for (var i = 0; i < self.outstanding_methods.length; i++) {\n m = self.outstanding_methods[i];\n if (m.msg.id === msg.id)\n break;\n }\n\n // remove\n self.outstanding_methods.splice(i, 1);\n }\n\n if (!m) {\n Meteor._debug(\"Can't match method response to original method call\", msg);\n return;\n }\n\n if (self.outstanding_wait_method) {\n // Wait until we have completed all outstanding methods.\n if (self.outstanding_methods.length === 0 &&\n self.outstanding_wait_method_response) {\n\n // Start by saving the outstanding wait method details, since\n // we're going to reshift the blocked ones and try to send\n // them *before* calling the method callback. It is necessary\n // to call method callbacks last since they might themselves\n // call other methods\n var savedOutstandingWaitMethod = self.outstanding_wait_method;\n var savedOutstandingWaitMethodResponse = self.outstanding_wait_method_response;\n self.outstanding_wait_method_response = null;\n self.outstanding_wait_method = null;\n\n // Find first blocked method with wait: true\n var i;\n for (i = 0; i < self.blocked_methods.length; i++)\n if (self.blocked_methods[i].wait)\n break;\n\n // Move as many blocked methods as we can into\n // outstanding_methods and outstanding_wait_method if needed\n self.outstanding_methods = _.first(self.blocked_methods, i);\n if (i !== self.blocked_methods.length) {\n self.outstanding_wait_method = self.blocked_methods[i];\n self.blocked_methods = _.rest(self.blocked_methods, i+1);\n } else {\n self.blocked_methods = [];\n }\n\n // Send any new outstanding methods after we reshift the\n // blocked methods. Intentionally do this before calling the\n // method response because they might call additional methods\n // that shouldn't be sent twice.\n self._sendOutstandingMethods();\n\n // Fire necessary outstanding method callbacks, making sure we\n // only fire the outstanding wait method after all other outstanding\n // methods' callbacks were fired\n if (m === savedOutstandingWaitMethod) {\n self._deliverMethodResponse(savedOutstandingWaitMethod,\n savedOutstandingWaitMethodResponse /*(=== msg)*/);\n } else {\n self._deliverMethodResponse(m, msg);\n self._deliverMethodResponse(savedOutstandingWaitMethod,\n savedOutstandingWaitMethodResponse /*(!== msg)*/);\n }\n } else {\n if (m !== self.outstanding_wait_method)\n self._deliverMethodResponse(m, msg);\n }\n } else {\n self._deliverMethodResponse(m, msg);\n }\n\n // if we were blocking a migration, see if it's now possible to\n // continue\n if (self._retryMigrate && self._readyToMigrate()) {\n self._retryMigrate();\n self._retryMigrate = null;\n }\n },\n\n // @param method {Object} as in `outstanding_methods`\n // @param response {Object{id, result | error}}\n _deliverMethodResponse: function(method, response) {\n // callback will have already been bindEnvironment'd by apply(),\n // so no need to catch exceptions\n if ('error' in response) {\n method.callback(new Meteor.Error(\n response.error.error, response.error.reason,\n response.error.details));\n } else {\n // msg.result may be undefined if the method didn't return a\n // value\n method.callback(undefined, response.result);\n }\n },\n\n _sendOutstandingMethods: function() {\n var self = this;\n _.each(self.outstanding_methods, function (m) {\n self.stream.send(JSON.stringify(m.msg));\n });\n if (self.outstanding_wait_method)\n self.stream.send(JSON.stringify(self.outstanding_wait_method.msg));\n },\n\n _livedata_error: function (msg) {\n Meteor._debug(\"Received error from server: \", msg.reason);\n if (msg.offending_message)\n Meteor._debug(\"For: \", msg.offending_message);\n },\n\n _callOnReconnectAndSendAppropriateOutstandingMethods: function() {\n var self = this;\n var old_outstanding_methods = self.outstanding_methods;\n var old_outstanding_wait_method = self.outstanding_wait_method;\n var old_blocked_methods = self.blocked_methods;\n self.outstanding_methods = [];\n self.outstanding_wait_method = null;\n self.blocked_methods = [];\n\n self.onReconnect();\n\n if (self.outstanding_wait_method) {\n // self.onReconnect() caused us to wait on a method. Add all old\n // methods to blocked_methods, and we don't need to send any\n // additional methods\n self.blocked_methods = self.blocked_methods.concat(\n old_outstanding_methods);\n\n if (old_outstanding_wait_method) {\n self.blocked_methods.push(_.extend(\n old_outstanding_wait_method, {wait: true}));\n }\n\n self.blocked_methods = self.blocked_methods.concat(\n old_blocked_methods);\n } else {\n // self.onReconnect() did not cause us to wait on a method. Add\n // as many methods as we can to outstanding_methods and send\n // them\n _.each(old_outstanding_methods, function(method) {\n self.outstanding_methods.push(method);\n self.stream.send(JSON.stringify(method.msg));\n });\n\n self.outstanding_wait_method = old_outstanding_wait_method;\n if (self.outstanding_wait_method)\n self.stream.send(JSON.stringify(self.outstanding_wait_method.msg));\n\n self.blocked_methods = old_blocked_methods;\n }\n },\n\n _readyToMigrate: function() {\n var self = this;\n return self.outstanding_methods.length === 0 &&\n !self.outstanding_wait_method &&\n self.blocked_methods.length === 0;\n }\n});\n\n_.extend(Meteor, {\n // @param url {String} URL to Meteor app, or to sockjs endpoint (deprecated),\n // e.g.:\n // \"subdomain.meteor.com\",\n // \"http://subdomain.meteor.com\",\n // \"/\",\n // \"http://subdomain.meteor.com/sockjs\" (deprecated),\n // \"/sockjs\" (deprecated)\n connect: function (url, _reloadOnUpdate) {\n var ret = new Meteor._LivedataConnection(\n url, {reloadOnUpdate: _reloadOnUpdate});\n Meteor._LivedataConnection._allConnections.push(ret); // hack. see below.\n return ret;\n },\n\n autosubscribe: function (sub_func) {\n var local_subs = [];\n var context = new Meteor.deps.Context();\n\n context.onInvalidate(function () {\n // recurse.\n Meteor.autosubscribe(sub_func);\n // unsub after re-subbing, to avoid bouncing.\n _.each(local_subs, function (x) { x.stop(); });\n });\n\n context.run(function () {\n if (Meteor._capture_subs)\n throw new Error(\"Meteor.autosubscribe may not be called recursively\");\n\n Meteor._capture_subs = [];\n try {\n sub_func();\n } finally {\n local_subs = Meteor._capture_subs;\n Meteor._capture_subs = null;\n }\n });\n }\n});\n\n\n// Hack for `spiderable` package: a way to see if the page is done\n// loading all the data it needs.\nMeteor._LivedataConnection._allConnections = [];\nMeteor._LivedataConnection._allSubscriptionsReady = function () {\n return _.all(Meteor._LivedataConnection._allConnections, function (conn) {\n for (var k in conn.sub_ready_callbacks)\n return false;\n return true;\n });\n};\n", "file_path": "packages/livedata/livedata_connection.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0001752033131197095, 0.00016897810564842075, 0.00016251156921498477, 0.00016881138435564935, 2.6313248326914618e-06]} {"hunk": {"id": 1, "code_window": ["Package.describe({\n", " summary: \"Automatically publish all data in the database to every client\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " api.use('livedata', 'server');\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically publish the entire database to all clients\"\n"], "file_path": "packages/autopublish/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "Package.describe({\n summary: \"Require this application always use transport layer encryption\"\n});\n\nPackage.on_use(function (api) {\n api.use('underscore', 'server');\n // make sure we come after livedata, so we load after the sockjs\n // server has been instantiated.\n api.use('livedata', 'server');\n\n api.add_files('force_ssl_common.js', ['client', 'server']);\n api.add_files('force_ssl_server.js', 'server');\n\n // Another thing we could do is add a force_ssl_client.js file that\n // makes sure document.location.protocol is 'https'. If it detected\n // the code was loaded from a non-localhost non-https site, it would\n // stop the app from working and pop up an error box or something.\n});\n", "file_path": "packages/force-ssl/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.09602677822113037, 0.04812264442443848, 0.00021850733901374042, 0.04812264442443848, 0.04790413752198219]} {"hunk": {"id": 1, "code_window": ["Package.describe({\n", " summary: \"Automatically publish all data in the database to every client\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " api.use('livedata', 'server');\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically publish the entire database to all clients\"\n"], "file_path": "packages/autopublish/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "\n", "file_path": "docs/client/packages/force-ssl.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017680514429230243, 0.000168204540386796, 0.0001637052046135068, 0.000164103286806494, 6.083712833060417e-06]} {"hunk": {"id": 1, "code_window": ["Package.describe({\n", " summary: \"Automatically publish all data in the database to every client\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " api.use('livedata', 'server');\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically publish the entire database to all clients\"\n"], "file_path": "packages/autopublish/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "/// METEOR WRAPPER\n//\n// XXX this should get packaged and moved into the Meteor.crypto\n// namespace, along with other hash functions.\nif (typeof Meteor._srp === \"undefined\")\n Meteor._srp = {};\nMeteor._srp.SHA256 = (function () {\n\n\n/**\n*\n* Secure Hash Algorithm (SHA256)\n* http://www.webtoolkit.info/javascript-sha256.html\n* http://anmar.eu.org/projects/jssha2/\n*\n* Original code by Angel Marin, Paul Johnston.\n*\n**/\n \nfunction SHA256(s){\n \n\tvar chrsz = 8;\n\tvar hexcase = 0;\n \n\tfunction safe_add (x, y) {\n\t\tvar lsw = (x & 0xFFFF) + (y & 0xFFFF);\n\t\tvar msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n\t\treturn (msw << 16) | (lsw & 0xFFFF);\n\t}\n \n\tfunction S (X, n) { return ( X >>> n ) | (X << (32 - n)); }\n\tfunction R (X, n) { return ( X >>> n ); }\n\tfunction Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }\n\tfunction Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }\n\tfunction Sigma0256(x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); }\n\tfunction Sigma1256(x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); }\n\tfunction Gamma0256(x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); }\n\tfunction Gamma1256(x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); }\n \n\tfunction core_sha256 (m, l) {\n\t\tvar K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2);\n\t\tvar HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);\n\t\tvar W = new Array(64);\n\t\tvar a, b, c, d, e, f, g, h, i, j;\n\t\tvar T1, T2;\n \n\t\tm[l >> 5] |= 0x80 << (24 - l % 32);\n\t\tm[((l + 64 >> 9) << 4) + 15] = l;\n \n\t\tfor ( var i = 0; i>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);\n\t\t}\n\t\treturn bin;\n\t}\n \n\tfunction Utf8Encode(string) {\n\t\t// METEOR change:\n\t\t// The webtoolkit.info version of this code added this\n\t\t// Utf8Encode function (which does seem necessary for dealing\n\t\t// with arbitrary Unicode), but the following line seems\n\t\t// problematic:\n\t\t//\n\t\t// string = string.replace(/\\r\\n/g,\"\\n\");\n\t\tvar utftext = \"\";\n \n\t\tfor (var n = 0; n < string.length; n++) {\n \n\t\t\tvar c = string.charCodeAt(n);\n \n\t\t\tif (c < 128) {\n\t\t\t\tutftext += String.fromCharCode(c);\n\t\t\t}\n\t\t\telse if((c > 127) && (c < 2048)) {\n\t\t\t\tutftext += String.fromCharCode((c >> 6) | 192);\n\t\t\t\tutftext += String.fromCharCode((c & 63) | 128);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tutftext += String.fromCharCode((c >> 12) | 224);\n\t\t\t\tutftext += String.fromCharCode(((c >> 6) & 63) | 128);\n\t\t\t\tutftext += String.fromCharCode((c & 63) | 128);\n\t\t\t}\n \n\t\t}\n \n\t\treturn utftext;\n\t}\n \n\tfunction binb2hex (binarray) {\n\t\tvar hex_tab = hexcase ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n\t\tvar str = \"\";\n\t\tfor(var i = 0; i < binarray.length * 4; i++) {\n\t\t\tstr += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\n\t\t\thex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);\n\t\t}\n\t\treturn str;\n\t}\n \n\ts = Utf8Encode(s);\n\treturn binb2hex(core_sha256(str2binb(s), s.length * chrsz));\n \n}\n\n/// METEOR WRAPPER\nreturn SHA256;\n})();\n", "file_path": "packages/srp/sha256.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0001750253140926361, 0.0001721666776575148, 0.00016871723346412182, 0.0001720533473417163, 1.862871840785374e-06]} {"hunk": {"id": 1, "code_window": ["Package.describe({\n", " summary: \"Automatically publish all data in the database to every client\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " api.use('livedata', 'server');\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically publish the entire database to all clients\"\n"], "file_path": "packages/autopublish/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "/*!\n * AmplifyJS 1.1.0 - Core, Store, Request\n * \n * Copyright 2011 appendTo LLC. (http://appendto.com/team)\n * Dual licensed under the MIT or GPL licenses.\n * http://appendto.com/open-source-licenses\n * \n * http://amplifyjs.com\n */\n/*!\n * Amplify Core 1.1.0\n * \n * Copyright 2011 appendTo LLC. (http://appendto.com/team)\n * Dual licensed under the MIT or GPL licenses.\n * http://appendto.com/open-source-licenses\n * \n * http://amplifyjs.com\n */\n(function( global, undefined ) {\n\nvar slice = [].slice,\n\tsubscriptions = {};\n\nvar amplify = global.amplify = {\n\tpublish: function( topic ) {\n\t\tvar args = slice.call( arguments, 1 ),\n\t\t\ttopicSubscriptions,\n\t\t\tsubscription,\n\t\t\tlength,\n\t\t\ti = 0,\n\t\t\tret;\n\n\t\tif ( !subscriptions[ topic ] ) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttopicSubscriptions = subscriptions[ topic ].slice();\n\t\tfor ( length = topicSubscriptions.length; i < length; i++ ) {\n\t\t\tsubscription = topicSubscriptions[ i ];\n\t\t\tret = subscription.callback.apply( subscription.context, args );\n\t\t\tif ( ret === false ) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn ret !== false;\n\t},\n\n\tsubscribe: function( topic, context, callback, priority ) {\n\t\tif ( arguments.length === 3 && typeof callback === \"number\" ) {\n\t\t\tpriority = callback;\n\t\t\tcallback = context;\n\t\t\tcontext = null;\n\t\t}\n\t\tif ( arguments.length === 2 ) {\n\t\t\tcallback = context;\n\t\t\tcontext = null;\n\t\t}\n\t\tpriority = priority || 10;\n\n\t\tvar topicIndex = 0,\n\t\t\ttopics = topic.split( /\\s/ ),\n\t\t\ttopicLength = topics.length,\n\t\t\tadded;\n\t\tfor ( ; topicIndex < topicLength; topicIndex++ ) {\n\t\t\ttopic = topics[ topicIndex ];\n\t\t\tadded = false;\n\t\t\tif ( !subscriptions[ topic ] ) {\n\t\t\t\tsubscriptions[ topic ] = [];\n\t\t\t}\n\t\n\t\t\tvar i = subscriptions[ topic ].length - 1,\n\t\t\t\tsubscriptionInfo = {\n\t\t\t\t\tcallback: callback,\n\t\t\t\t\tcontext: context,\n\t\t\t\t\tpriority: priority\n\t\t\t\t};\n\t\n\t\t\tfor ( ; i >= 0; i-- ) {\n\t\t\t\tif ( subscriptions[ topic ][ i ].priority <= priority ) {\n\t\t\t\t\tsubscriptions[ topic ].splice( i + 1, 0, subscriptionInfo );\n\t\t\t\t\tadded = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( !added ) {\n\t\t\t\tsubscriptions[ topic ].unshift( subscriptionInfo );\n\t\t\t}\n\t\t}\n\n\t\treturn callback;\n\t},\n\n\tunsubscribe: function( topic, callback ) {\n\t\tif ( !subscriptions[ topic ] ) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar length = subscriptions[ topic ].length,\n\t\t\ti = 0;\n\n\t\tfor ( ; i < length; i++ ) {\n\t\t\tif ( subscriptions[ topic ][ i ].callback === callback ) {\n\t\t\t\tsubscriptions[ topic ].splice( i, 1 );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n};\n\n}( this ) );\n/*!\n * Amplify Store - Persistent Client-Side Storage 1.1.0\n * \n * Copyright 2011 appendTo LLC. (http://appendto.com/team)\n * Dual licensed under the MIT or GPL licenses.\n * http://appendto.com/open-source-licenses\n * \n * http://amplifyjs.com\n */\n(function( amplify, undefined ) {\n\nvar store = amplify.store = function( key, value, options, type ) {\n\tvar type = store.type;\n\tif ( options && options.type && options.type in store.types ) {\n\t\ttype = options.type;\n\t}\n\treturn store.types[ type ]( key, value, options || {} );\n};\n\nstore.types = {};\nstore.type = null;\nstore.addType = function( type, storage ) {\n\tif ( !store.type ) {\n\t\tstore.type = type;\n\t}\n\n\tstore.types[ type ] = storage;\n\tstore[ type ] = function( key, value, options ) {\n\t\toptions = options || {};\n\t\toptions.type = type;\n\t\treturn store( key, value, options );\n\t};\n}\nstore.error = function() {\n\treturn \"amplify.store quota exceeded\"; \n};\n\nvar rprefix = /^__amplify__/;\nfunction createFromStorageInterface( storageType, storage ) {\n\tstore.addType( storageType, function( key, value, options ) {\n\t\tvar storedValue, parsed, i, remove,\n\t\t\tret = value,\n\t\t\tnow = (new Date()).getTime();\n\n\t\tif ( !key ) {\n\t\t\tret = {};\n\t\t\tremove = [];\n\t\t\ti = 0;\n\t\t\ttry {\n\t\t\t\t// accessing the length property works around a localStorage bug\n\t\t\t\t// in Firefox 4.0 where the keys don't update cross-page\n\t\t\t\t// we assign to key just to avoid Closure Compiler from removing\n\t\t\t\t// the access as \"useless code\"\n\t\t\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=662511\n\t\t\t\tkey = storage.length;\n\n\t\t\t\twhile ( key = storage.key( i++ ) ) {\n\t\t\t\t\tif ( rprefix.test( key ) ) {\n\t\t\t\t\t\tparsed = JSON.parse( storage.getItem( key ) );\n\t\t\t\t\t\tif ( parsed.expires && parsed.expires <= now ) {\n\t\t\t\t\t\t\tremove.push( key );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tret[ key.replace( rprefix, \"\" ) ] = parsed.data;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twhile ( key = remove.pop() ) {\n\t\t\t\t\tstorage.removeItem( key );\n\t\t\t\t}\n\t\t\t} catch ( error ) {}\n\t\t\treturn ret;\n\t\t}\n\n\t\t// protect against name collisions with direct storage\n\t\tkey = \"__amplify__\" + key;\n\n\t\tif ( value === undefined ) {\n\t\t\tstoredValue = storage.getItem( key );\n\t\t\tparsed = storedValue ? JSON.parse( storedValue ) : { expires: -1 };\n\t\t\tif ( parsed.expires && parsed.expires <= now ) {\n\t\t\t\tstorage.removeItem( key );\n\t\t\t} else {\n\t\t\t\treturn parsed.data;\n\t\t\t}\n\t\t} else {\n\t\t\tif ( value === null ) {\n\t\t\t\tstorage.removeItem( key );\n\t\t\t} else {\n\t\t\t\tparsed = JSON.stringify({\n\t\t\t\t\tdata: value,\n\t\t\t\t\texpires: options.expires ? now + options.expires : null\n\t\t\t\t});\n\t\t\t\ttry {\n\t\t\t\t\tstorage.setItem( key, parsed );\n\t\t\t\t// quota exceeded\n\t\t\t\t} catch( error ) {\n\t\t\t\t\t// expire old data and try again\n\t\t\t\t\tstore[ storageType ]();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstorage.setItem( key, parsed );\n\t\t\t\t\t} catch( error ) {\n\t\t\t\t\t\tthrow store.error();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t});\n}\n\n// localStorage + sessionStorage\n// IE 8+, Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10.5+, iPhone 2+, Android 2+\nfor ( var webStorageType in { localStorage: 1, sessionStorage: 1 } ) {\n\t// try/catch for file protocol in Firefox\n\ttry {\n\t\tif ( window[ webStorageType ].getItem ) {\n\t\t\tcreateFromStorageInterface( webStorageType, window[ webStorageType ] );\n\t\t}\n\t} catch( e ) {}\n}\n\n// globalStorage\n// non-standard: Firefox 2+\n// https://developer.mozilla.org/en/dom/storage#globalStorage\nif ( window.globalStorage ) {\n\t// try/catch for file protocol in Firefox\n\ttry {\n\t\tcreateFromStorageInterface( \"globalStorage\",\n\t\t\twindow.globalStorage[ window.location.hostname ] );\n\t\t// Firefox 2.0 and 3.0 have sessionStorage and globalStorage\n\t\t// make sure we default to globalStorage\n\t\t// but don't default to globalStorage in 3.5+ which also has localStorage\n\t\tif ( store.type === \"sessionStorage\" ) {\n\t\t\tstore.type = \"globalStorage\";\n\t\t}\n\t} catch( e ) {}\n}\n\n// userData\n// non-standard: IE 5+\n// http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx\n(function() {\n\t// IE 9 has quirks in userData that are a huge pain\n\t// rather than finding a way to detect these quirks\n\t// we just don't register userData if we have localStorage\n\tif ( store.types.localStorage ) {\n\t\treturn;\n\t}\n\n\t// append to html instead of body so we can do this from the head\n\tvar div = document.createElement( \"div\" ),\n\t\tattrKey = \"amplify\";\n\tdiv.style.display = \"none\";\n\tdocument.getElementsByTagName( \"head\" )[ 0 ].appendChild( div );\n\n\t// we can't feature detect userData support\n\t// so just try and see if it fails\n\t// surprisingly, even just adding the behavior isn't enough for a failure\n\t// so we need to load the data as well\n\ttry {\n\t\tdiv.addBehavior( \"#default#userdata\" );\n\t\tdiv.load( attrKey );\n\t} catch( e ) {\n\t\tdiv.parentNode.removeChild( div );\n\t\treturn;\n\t}\n\n\tstore.addType( \"userData\", function( key, value, options ) {\n\t\tdiv.load( attrKey );\n\t\tvar attr, parsed, prevValue, i, remove,\n\t\t\tret = value,\n\t\t\tnow = (new Date()).getTime();\n\n\t\tif ( !key ) {\n\t\t\tret = {};\n\t\t\tremove = [];\n\t\t\ti = 0;\n\t\t\twhile ( attr = div.XMLDocument.documentElement.attributes[ i++ ] ) {\n\t\t\t\tparsed = JSON.parse( attr.value );\n\t\t\t\tif ( parsed.expires && parsed.expires <= now ) {\n\t\t\t\t\tremove.push( attr.name );\n\t\t\t\t} else {\n\t\t\t\t\tret[ attr.name ] = parsed.data;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile ( key = remove.pop() ) {\n\t\t\t\tdiv.removeAttribute( key );\n\t\t\t}\n\t\t\tdiv.save( attrKey );\n\t\t\treturn ret;\n\t\t}\n\n\t\t// convert invalid characters to dashes\n\t\t// http://www.w3.org/TR/REC-xml/#NT-Name\n\t\t// simplified to assume the starting character is valid\n\t\t// also removed colon as it is invalid in HTML attribute names\n\t\tkey = key.replace( /[^-._0-9A-Za-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u37f-\\u1fff\\u200c-\\u200d\\u203f\\u2040\\u2070-\\u218f]/g, \"-\" );\n\n\t\tif ( value === undefined ) {\n\t\t\tattr = div.getAttribute( key );\n\t\t\tparsed = attr ? JSON.parse( attr ) : { expires: -1 };\n\t\t\tif ( parsed.expires && parsed.expires <= now ) {\n\t\t\t\tdiv.removeAttribute( key );\n\t\t\t} else {\n\t\t\t\treturn parsed.data;\n\t\t\t}\n\t\t} else {\n\t\t\tif ( value === null ) {\n\t\t\t\tdiv.removeAttribute( key );\n\t\t\t} else {\n\t\t\t\t// we need to get the previous value in case we need to rollback\n\t\t\t\tprevValue = div.getAttribute( key );\n\t\t\t\tparsed = JSON.stringify({\n\t\t\t\t\tdata: value,\n\t\t\t\t\texpires: (options.expires ? (now + options.expires) : null)\n\t\t\t\t});\n\t\t\t\tdiv.setAttribute( key, parsed );\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tdiv.save( attrKey );\n\t\t// quota exceeded\n\t\t} catch ( error ) {\n\t\t\t// roll the value back to the previous value\n\t\t\tif ( prevValue === null ) {\n\t\t\t\tdiv.removeAttribute( key );\n\t\t\t} else {\n\t\t\t\tdiv.setAttribute( key, prevValue );\n\t\t\t}\n\n\t\t\t// expire old data and try again\n\t\t\tstore.userData();\n\t\t\ttry {\n\t\t\t\tdiv.setAttribute( key, parsed );\n\t\t\t\tdiv.save( attrKey );\n\t\t\t} catch ( error ) {\n\t\t\t\t// roll the value back to the previous value\n\t\t\t\tif ( prevValue === null ) {\n\t\t\t\t\tdiv.removeAttribute( key );\n\t\t\t\t} else {\n\t\t\t\t\tdiv.setAttribute( key, prevValue );\n\t\t\t\t}\n\t\t\t\tthrow store.error();\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t});\n}() );\n\n// in-memory storage\n// fallback for all browsers to enable the API even if we can't persist data\n(function() {\n\tvar memory = {},\n\t\ttimeout = {};\n\n\tfunction copy( obj ) {\n\t\treturn obj === undefined ? undefined : JSON.parse( JSON.stringify( obj ) );\n\t}\n\n\tstore.addType( \"memory\", function( key, value, options ) {\n\t\tif ( !key ) {\n\t\t\treturn copy( memory );\n\t\t}\n\n\t\tif ( value === undefined ) {\n\t\t\treturn copy( memory[ key ] );\n\t\t}\n\n\t\tif ( timeout[ key ] ) {\n\t\t\tclearTimeout( timeout[ key ] );\n\t\t\tdelete timeout[ key ];\n\t\t}\n\n\t\tif ( value === null ) {\n\t\t\tdelete memory[ key ];\n\t\t\treturn null;\n\t\t}\n\n\t\tmemory[ key ] = value;\n\t\tif ( options.expires ) {\n\t\t\ttimeout[ key ] = setTimeout(function() {\n\t\t\t\tdelete memory[ key ];\n\t\t\t\tdelete timeout[ key ];\n\t\t\t}, options.expires );\n\t\t}\n\n\t\treturn value;\n\t});\n}() );\n\n}( this.amplify = this.amplify || {} ) );\n/*!\n * Amplify Request 1.1.0\n * \n * Copyright 2011 appendTo LLC. (http://appendto.com/team)\n * Dual licensed under the MIT or GPL licenses.\n * http://appendto.com/open-source-licenses\n * \n * http://amplifyjs.com\n */\n(function( amplify, undefined ) {\n\nfunction noop() {}\nfunction isFunction( obj ) {\n\treturn ({}).toString.call( obj ) === \"[object Function]\";\n}\n\nfunction async( fn ) {\n\tvar isAsync = false;\n\tsetTimeout(function() {\n\t\tisAsync = true;\n\t}, 1 );\n\treturn function() {\n\t\tvar that = this,\n\t\t\targs = arguments;\n\t\tif ( isAsync ) {\n\t\t\tfn.apply( that, args );\n\t\t} else {\n\t\t\tsetTimeout(function() {\n\t\t\t\tfn.apply( that, args );\n\t\t\t}, 1 );\n\t\t}\n\t};\n}\n\namplify.request = function( resourceId, data, callback ) {\n\t// default to an empty hash just so we can handle a missing resourceId\n\t// in one place\n\tvar settings = resourceId || {};\n\n\tif ( typeof settings === \"string\" ) {\n\t\tif ( isFunction( data ) ) {\n\t\t\tcallback = data;\n\t\t\tdata = {};\n\t\t}\n\t\tsettings = {\n\t\t\tresourceId: resourceId,\n\t\t\tdata: data || {},\n\t\t\tsuccess: callback\n\t\t};\n\t}\n\n\tvar request = { abort: noop },\n\t\tresource = amplify.request.resources[ settings.resourceId ],\n\t\tsuccess = settings.success || noop,\n\t\terror = settings.error || noop;\n\tsettings.success = async( function( data, status ) {\n\t\tstatus = status || \"success\";\n\t\tamplify.publish( \"request.success\", settings, data, status );\n\t\tamplify.publish( \"request.complete\", settings, data, status );\n\t\tsuccess( data, status );\n\t});\n\tsettings.error = async( function( data, status ) {\n\t\tstatus = status || \"error\";\n\t\tamplify.publish( \"request.error\", settings, data, status );\n\t\tamplify.publish( \"request.complete\", settings, data, status );\n\t\terror( data, status );\n\t});\n\n\tif ( !resource ) {\n\t\tif ( !settings.resourceId ) {\n\t\t\tthrow \"amplify.request: no resourceId provided\";\n\t\t}\n\t\tthrow \"amplify.request: unknown resourceId: \" + settings.resourceId;\n\t}\n\n\tif ( !amplify.publish( \"request.before\", settings ) ) {\n\t\tsettings.error( null, \"abort\" );\n\t\treturn;\n\t}\n\n\tamplify.request.resources[ settings.resourceId ]( settings, request );\n\treturn request;\n};\n\namplify.request.types = {};\namplify.request.resources = {};\namplify.request.define = function( resourceId, type, settings ) {\n\tif ( typeof type === \"string\" ) {\n\t\tif ( !( type in amplify.request.types ) ) {\n\t\t\tthrow \"amplify.request.define: unknown type: \" + type;\n\t\t}\n\n\t\tsettings.resourceId = resourceId;\n\t\tamplify.request.resources[ resourceId ] =\n\t\t\tamplify.request.types[ type ]( settings );\n\t} else {\n\t\t// no pre-processor or settings for one-off types (don't invoke)\n\t\tamplify.request.resources[ resourceId ] = type;\n\t}\n};\n\n}( amplify ) );\n\n\n\n\n\n(function( amplify, $, undefined ) {\n\nvar xhrProps = [ \"status\", \"statusText\", \"responseText\", \"responseXML\", \"readyState\" ],\n rurlData = /\\{([^\\}]+)\\}/g;\n\namplify.request.types.ajax = function( defnSettings ) {\n\tdefnSettings = $.extend({\n\t\ttype: \"GET\"\n\t}, defnSettings );\n\n\treturn function( settings, request ) {\n\t\tvar xhr,\n\t\t\turl = defnSettings.url,\n\t\t\tabort = request.abort,\n\t\t\tajaxSettings = $.extend( true, {}, defnSettings, { data: settings.data } ),\n\t\t\taborted = false,\n\t\t\tampXHR = {\n\t\t\t\treadyState: 0,\n\t\t\t\tsetRequestHeader: function( name, value ) {\n\t\t\t\t\treturn xhr.setRequestHeader( name, value );\n\t\t\t\t},\n\t\t\t\tgetAllResponseHeaders: function() {\n\t\t\t\t\treturn xhr.getAllResponseHeaders();\n\t\t\t\t},\n\t\t\t\tgetResponseHeader: function( key ) {\n\t\t\t\t\treturn xhr.getResponseHeader( key );\n\t\t\t\t},\n\t\t\t\toverrideMimeType: function( type ) {\n\t\t\t\t\treturn xhr.overrideMideType( type );\n\t\t\t\t},\n\t\t\t\tabort: function() {\n\t\t\t\t\taborted = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\txhr.abort();\n\t\t\t\t\t// IE 7 throws an error when trying to abort\n\t\t\t\t\t} catch( e ) {}\n\t\t\t\t\thandleResponse( null, \"abort\" );\n\t\t\t\t},\n\t\t\t\tsuccess: function( data, status ) {\n\t\t\t\t\tsettings.success( data, status );\n\t\t\t\t},\n\t\t\t\terror: function( data, status ) {\n\t\t\t\t\tsettings.error( data, status );\n\t\t\t\t}\n\t\t\t};\n\n\t\tamplify.publish( \"request.ajax.preprocess\",\n\t\t\tdefnSettings, settings, ajaxSettings, ampXHR );\n\n\t\t$.extend( ajaxSettings, {\n\t\t\tsuccess: function( data, status ) {\n\t\t\t\thandleResponse( data, status );\n\t\t\t},\n\t\t\terror: function( _xhr, status ) {\n\t\t\t\thandleResponse( null, status );\n\t\t\t},\n\t\t\tbeforeSend: function( _xhr, _ajaxSettings ) {\n\t\t\t\txhr = _xhr;\n\t\t\t\tajaxSettings = _ajaxSettings;\n\t\t\t\tvar ret = defnSettings.beforeSend ?\n\t\t\t\t\tdefnSettings.beforeSend.call( this, ampXHR, ajaxSettings ) : true;\n\t\t\t\treturn ret && amplify.publish( \"request.before.ajax\",\n\t\t\t\t\tdefnSettings, settings, ajaxSettings, ampXHR );\n\t\t\t}\n\t\t});\n\t\t$.ajax( ajaxSettings );\n\n\t\tfunction handleResponse( data, status ) {\n\t\t\t$.each( xhrProps, function( i, key ) {\n\t\t\t\ttry {\n\t\t\t\t\tampXHR[ key ] = xhr[ key ];\n\t\t\t\t} catch( e ) {}\n\t\t\t});\n\t\t\t// Playbook returns \"HTTP/1.1 200 OK\"\n\t\t\t// TODO: something also returns \"OK\", what?\n\t\t\tif ( /OK$/.test( ampXHR.statusText ) ) {\n\t\t\t\tampXHR.statusText = \"success\";\n\t\t\t}\n\t\t\tif ( data === undefined ) {\n\t\t\t\t// TODO: add support for ajax errors with data\n\t\t\t\tdata = null;\n\t\t\t}\n\t\t\tif ( aborted ) {\n\t\t\t\tstatus = \"abort\";\n\t\t\t}\n\t\t\tif ( /timeout|error|abort/.test( status ) ) {\n\t\t\t\tampXHR.error( data, status );\n\t\t\t} else {\n\t\t\t\tampXHR.success( data, status );\n\t\t\t}\n\t\t\t// avoid handling a response multiple times\n\t\t\t// this can happen if a request is aborted\n\t\t\t// TODO: figure out if this breaks polling or multi-part responses\n\t\t\thandleResponse = $.noop;\n\t\t}\n\n\t\trequest.abort = function() {\n\t\t\tampXHR.abort();\n\t\t\tabort.call( this );\n\t\t};\n\t};\n};\n\n\n\namplify.subscribe( \"request.ajax.preprocess\", function( defnSettings, settings, ajaxSettings ) {\n\tvar mappedKeys = [],\n\t\tdata = ajaxSettings.data;\n\n\tif ( typeof data === \"string\" ) {\n\t\treturn;\n\t}\n\n\tdata = $.extend( true, {}, defnSettings.data, data );\n\n\tajaxSettings.url = ajaxSettings.url.replace( rurlData, function ( m, key ) {\n\t\tif ( key in data ) {\n\t\t mappedKeys.push( key );\n\t\t return data[ key ];\n\t\t}\n\t});\n\n\t// We delete the keys later so duplicates are still replaced\n\t$.each( mappedKeys, function ( i, key ) {\n\t\tdelete data[ key ];\n\t});\n\n\tajaxSettings.data = data;\n});\n\n\n\namplify.subscribe( \"request.ajax.preprocess\", function( defnSettings, settings, ajaxSettings ) {\n\tvar data = ajaxSettings.data,\n\t\tdataMap = defnSettings.dataMap;\n\n\tif ( !dataMap || typeof data === \"string\" ) {\n\t\treturn;\n\t}\n\n\tif ( $.isFunction( dataMap ) ) {\n\t\tajaxSettings.data = dataMap( data );\n\t} else {\n\t\t$.each( defnSettings.dataMap, function( orig, replace ) {\n\t\t\tif ( orig in data ) {\n\t\t\t\tdata[ replace ] = data[ orig ];\n\t\t\t\tdelete data[ orig ];\n\t\t\t}\n\t\t});\n\t\tajaxSettings.data = data;\n\t}\n});\n\n\n\nvar cache = amplify.request.cache = {\n\t_key: function( resourceId, url, data ) {\n\t\tdata = url + data;\n\t\tvar length = data.length,\n\t\t\ti = 0,\n\t\t\tchecksum = chunk();\n\n\t\twhile ( i < length ) {\n\t\t\tchecksum ^= chunk();\n\t\t}\n\n\t\tfunction chunk() {\n\t\t\treturn data.charCodeAt( i++ ) << 24 |\n\t\t\t\tdata.charCodeAt( i++ ) << 16 |\n\t\t\t\tdata.charCodeAt( i++ ) << 8 |\n\t\t\t\tdata.charCodeAt( i++ ) << 0;\n\t\t}\n\n\t\treturn \"request-\" + resourceId + \"-\" + checksum;\n\t},\n\n\t_default: (function() {\n\t\tvar memoryStore = {};\n\t\treturn function( resource, settings, ajaxSettings, ampXHR ) {\n\t\t\t// data is already converted to a string by the time we get here\n\t\t\tvar cacheKey = cache._key( settings.resourceId,\n\t\t\t\t\tajaxSettings.url, ajaxSettings.data ),\n\t\t\t\tduration = resource.cache;\n\n\t\t\tif ( cacheKey in memoryStore ) {\n\t\t\t\tampXHR.success( memoryStore[ cacheKey ] );\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar success = ampXHR.success;\n\t\t\tampXHR.success = function( data ) {\n\t\t\t\tmemoryStore[ cacheKey ] = data;\n\t\t\t\tif ( typeof duration === \"number\" ) {\n\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\tdelete memoryStore[ cacheKey ];\n\t\t\t\t\t}, duration );\n\t\t\t\t}\n\t\t\t\tsuccess.apply( this, arguments );\n\t\t\t};\n\t\t};\n\t}())\n};\n\nif ( amplify.store ) {\n\t$.each( amplify.store.types, function( type ) {\n\t\tcache[ type ] = function( resource, settings, ajaxSettings, ampXHR ) {\n\t\t\tvar cacheKey = cache._key( settings.resourceId,\n\t\t\t\t\tajaxSettings.url, ajaxSettings.data ),\n\t\t\t\tcached = amplify.store[ type ]( cacheKey );\n\n\t\t\tif ( cached ) {\n\t\t\t\tajaxSettings.success( cached );\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar success = ampXHR.success;\n\t\t\tampXHR.success = function( data ) {\t\n\t\t\t\tamplify.store[ type ]( cacheKey, data, { expires: resource.cache.expires } );\n\t\t\t\tsuccess.apply( this, arguments );\n\t\t\t};\n\t\t};\n\t});\n\tcache.persist = cache[ amplify.store.type ];\n}\n\namplify.subscribe( \"request.before.ajax\", function( resource ) {\n\tvar cacheType = resource.cache;\n\tif ( cacheType ) {\n\t\t// normalize between objects and strings/booleans/numbers\n\t\tcacheType = cacheType.type || cacheType;\n\t\treturn cache[ cacheType in cache ? cacheType : \"_default\" ]\n\t\t\t.apply( this, arguments );\n\t}\n});\n\n\n\namplify.request.decoders = {\n\t// http://labs.omniti.com/labs/jsend\n\tjsend: function( data, status, ampXHR, success, error ) {\n\t\tif ( data.status === \"success\" ) {\n\t\t\tsuccess( data.data );\n\t\t} else if ( data.status === \"fail\" ) {\n\t\t\terror( data.data, \"fail\" );\n\t\t} else if ( data.status === \"error\" ) {\n\t\t\tdelete data.status;\n\t\t\terror( data, \"error\" );\n\t\t}\n\t}\n};\n\namplify.subscribe( \"request.before.ajax\", function( resource, settings, ajaxSettings, ampXHR ) {\n\tvar _success = ampXHR.success,\n\t\t_error = ampXHR.error,\n\t\tdecoder = $.isFunction( resource.decoder )\n\t\t\t? resource.decoder\n\t\t\t: resource.decoder in amplify.request.decoders\n\t\t\t\t? amplify.request.decoders[ resource.decoder ]\n\t\t\t\t: amplify.request.decoders._default;\n\n\tif ( !decoder ) {\n\t\treturn;\n\t}\n\n\tfunction success( data, status ) {\n\t\t_success( data, status );\n\t}\n\tfunction error( data, status ) {\n\t\t_error( data, status );\n\t}\n\tampXHR.success = function( data, status ) {\n\t\tdecoder( data, status, ampXHR, success, error );\n\t};\n\tampXHR.error = function( data, status ) {\n\t\tdecoder( data, status, ampXHR, success, error );\n\t};\n});\n\n}( amplify, jQuery ) );\n", "file_path": "packages/amplify/amplify.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017644288891460747, 0.00017001645755954087, 0.00016143724496942014, 0.00016969996795523912, 2.9330788038350875e-06]} {"hunk": {"id": 2, "code_window": ["Package.describe({\n", " summary: \"Require this application always use transport layer encryption\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Require this application to use secure transport (HTTPS)\"\n"], "file_path": "packages/force-ssl/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "Package.describe({\n summary: \"Cross browser API for Persistant Storage, PubSub and Request.\"\n});\n\nPackage.on_use(function (api) {\n api.add_files('amplify.js', 'client');\n});\n", "file_path": "packages/amplify/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0019197462825104594, 0.0019197462825104594, 0.0019197462825104594, 0.0019197462825104594, 0.0]} {"hunk": {"id": 2, "code_window": ["Package.describe({\n", " summary: \"Require this application always use transport layer encryption\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Require this application to use secure transport (HTTPS)\"\n"], "file_path": "packages/force-ssl/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "// XXX this is hella confusing. this package really only has the\n// handlebars *runtime*, for precompiled templates. so really it is an\n// internal package that should get shipped down to the client iff you\n// have a precompiled handlebars template in your project.\n\nPackage.describe({\n summary: \"Simple semantic templating language\"\n});\n\nrequire('../../packages/handlebars/parse.js'); // XXX lame!!\n\nPackage.on_use(function (api) {\n // XXX should only be sent if we have handlebars templates in the app..\n api.add_files('evaluate.js', 'client');\n api.use('underscore', 'client');\n});\n\n// XXX lots more to do here .. registering this a templating engine,\n// making it the default default, providing the compiler code,\n// depending on the node package (or packaging the compiler\n// ourselves..)\n", "file_path": "packages/handlebars/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0007296986877918243, 0.0004160827083978802, 0.00017944633145816624, 0.00033910322235897183, 0.00023114035138860345]} {"hunk": {"id": 2, "code_window": ["Package.describe({\n", " summary: \"Require this application always use transport layer encryption\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Require this application to use secure transport (HTTPS)\"\n"], "file_path": "packages/force-ssl/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "(function () {\n\nvar TEST_RESPONDER_ROUTE = \"/spark_test_responder\";\n\nvar respond = function(req, res) {\n\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"text/html\");\n if (req.url === '/blank')\n res.end();\n else\n res.end('');\n};\n\nvar run_responder = function() {\n\n var app = __meteor_bootstrap__.app;\n app.stack.unshift({ route: TEST_RESPONDER_ROUTE, handle: respond });\n};\n\nrun_responder();\n\n})();\n", "file_path": "packages/spark/test_form_responder.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00016579736256971955, 0.0001644424191908911, 0.00016333008534274995, 0.00016419985331594944, 1.0217626140729408e-06]} {"hunk": {"id": 2, "code_window": ["Package.describe({\n", " summary: \"Require this application always use transport layer encryption\"\n", "});\n", "\n", "Package.on_use(function (api) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Require this application to use secure transport (HTTPS)\"\n"], "file_path": "packages/force-ssl/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "var crypto = __meteor_bootstrap__.require(\"crypto\");\nvar querystring = __meteor_bootstrap__.require(\"querystring\");\n\n// An OAuth1 wrapper around http calls which helps get tokens and\n// takes care of HTTP headers\n//\n// @param consumerKey {String} As supplied by the OAuth1 provider\n// @param consumerSecret {String} As supplied by the OAuth1 provider\n// @param urls {Object}\n// - requestToken (String): url\n// - authorize (String): url\n// - accessToken (String): url\n// - authenticate (String): url\nOAuth1Binding = function(consumerKey, consumerSecret, urls) {\n this._consumerKey = consumerKey;\n this._secret = consumerSecret;\n this._urls = urls;\n};\n\nOAuth1Binding.prototype.prepareRequestToken = function(callbackUrl) {\n var self = this;\n\n var headers = self._buildHeader({\n oauth_callback: callbackUrl\n });\n\n var response = self._call('POST', self._urls.requestToken, headers);\n var tokens = querystring.parse(response.content);\n\n // XXX should we also store oauth_token_secret here?\n if (!tokens.oauth_callback_confirmed)\n throw new Error(\"oauth_callback_confirmed false when requesting oauth1 token\", tokens);\n self.requestToken = tokens.oauth_token;\n};\n\nOAuth1Binding.prototype.prepareAccessToken = function(query) {\n var self = this;\n\n var headers = self._buildHeader({\n oauth_token: query.oauth_token\n });\n\n var params = {\n oauth_verifier: query.oauth_verifier\n };\n\n var response = self._call('POST', self._urls.accessToken, headers, params);\n var tokens = querystring.parse(response.content);\n\n self.accessToken = tokens.oauth_token;\n self.accessTokenSecret = tokens.oauth_token_secret;\n};\n\nOAuth1Binding.prototype.call = function(method, url) {\n var self = this;\n\n var headers = self._buildHeader({\n oauth_token: self.accessToken\n });\n\n var response = self._call(method, url, headers);\n return response.data;\n};\n\nOAuth1Binding.prototype.get = function(url) {\n return this.call('GET', url);\n};\n\nOAuth1Binding.prototype._buildHeader = function(headers) {\n var self = this;\n return _.extend({\n oauth_consumer_key: self._consumerKey,\n oauth_nonce: Meteor.uuid().replace(/\\W/g, ''),\n oauth_signature_method: 'HMAC-SHA1',\n oauth_timestamp: (new Date().valueOf()/1000).toFixed().toString(),\n oauth_version: '1.0'\n }, headers);\n};\n\nOAuth1Binding.prototype._getSignature = function(method, url, rawHeaders, accessTokenSecret) {\n var self = this;\n var headers = self._encodeHeader(rawHeaders);\n\n var parameters = _.map(headers, function(val, key) {\n return key + '=' + val;\n }).sort().join('&');\n\n var signatureBase = [\n method,\n encodeURIComponent(url),\n encodeURIComponent(parameters)\n ].join('&');\n\n var signingKey = encodeURIComponent(self._secret) + '&';\n if (accessTokenSecret)\n signingKey += encodeURIComponent(accessTokenSecret);\n\n return crypto.createHmac('SHA1', signingKey).update(signatureBase).digest('base64');\n};\n\nOAuth1Binding.prototype._call = function(method, url, headers, params) {\n var self = this;\n\n // Get the signature\n headers.oauth_signature = self._getSignature(method, url, headers, self.accessTokenSecret);\n\n // Make a authorization string according to oauth1 spec\n var authString = self._getAuthHeaderString(headers);\n\n // Make signed request\n var response = Meteor.http.call(method, url, {\n params: params,\n headers: {\n Authorization: authString\n }\n });\n\n if (response.error) {\n Meteor._debug('Error sending OAuth1 HTTP call', response.content, method, url, params, authString);\n throw response.error;\n }\n\n return response;\n};\n\nOAuth1Binding.prototype._encodeHeader = function(header) {\n return _.reduce(header, function(memo, val, key) {\n memo[encodeURIComponent(key)] = encodeURIComponent(val);\n return memo;\n }, {});\n};\n\nOAuth1Binding.prototype._getAuthHeaderString = function(headers) {\n return 'OAuth ' + _.map(headers, function(val, key) {\n return encodeURIComponent(key) + '=\"' + encodeURIComponent(val) + '\"';\n }).sort().join(', ');\n};\n", "file_path": "packages/accounts-oauth1-helper/oauth1_binding.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0003018955758307129, 0.0001790707028703764, 0.000165652614668943, 0.00016947918629739434, 3.4117903851438314e-05]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " summary: \"Automatically preserve all form fields that have a unique id\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically preserve all form fields with a unique id\"\n"], "file_path": "packages/preserve-inputs/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "Package.describe({\n summary: \"Cross browser API for Persistant Storage, PubSub and Request.\"\n});\n\nPackage.on_use(function (api) {\n api.add_files('amplify.js', 'client');\n});\n", "file_path": "packages/amplify/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0021132081747055054, 0.0021132081747055054, 0.0021132081747055054, 0.0021132081747055054, 0.0]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " summary: \"Automatically preserve all form fields that have a unique id\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically preserve all form fields with a unique id\"\n"], "file_path": "packages/preserve-inputs/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "# Meteor packages used by this project, one per line.\n#\n# 'meteor add' and 'meteor remove' will edit this file for you,\n# but you can also edit it by hand.\n\nautopublish\n", "file_path": "examples/unfinished/controls/.meteor/packages", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0001740480656735599, 0.0001740480656735599, 0.0001740480656735599, 0.0001740480656735599, 0.0]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " summary: \"Automatically preserve all form fields that have a unique id\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically preserve all form fields with a unique id\"\n"], "file_path": "packages/preserve-inputs/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "// checks that ranges balance and that node and index pointers are\n// correct. if both of these things are true, then everything\n// contained by 'range' must be a valid subtree. (assuming that\n// visit() is actually working.)\nvar check_liverange_integrity = function (range) {\n var stack = [];\n\n var check_node = function (node) {\n var data = node[range.tag] || [[], []];\n for (var i = 0; i < data[0].length; i++) {\n if (data[0][i]._start !== node)\n throw new Error(\"integrity check failed - incorrect _start\");\n if (data[0][i]._startIndex !== i)\n throw new Error(\"integrity check failed - incorrect _startIndex\");\n }\n for (var i = 0; i < data[1].length; i++) {\n if (data[1][i]._end !== node)\n throw new Error(\"integrity check failed - incorrect _end\");\n if (data[1][i]._endIndex !== i)\n throw new Error(\"integrity check failed - incorrect _endIndex\");\n }\n };\n\n range.visit(function (isStart, range) {\n if (isStart)\n stack.push(range);\n else\n if (range !== stack.pop())\n throw new Error(\"integrity check failed - unbalanced range\");\n }, function (isStart, node) {\n if (isStart) {\n check_node(node);\n stack.push(node);\n }\n else\n if (node !== stack.pop())\n throw new Error(\"integrity check failed - unbalanced node\");\n });\n\n if (stack.length)\n throw new Error(\"integrity check failed - missing close tags\");\n};\n", "file_path": "packages/liverange/liverange_test_helpers.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017632231174502522, 0.0001738654391374439, 0.0001685031020315364, 0.00017498660599812865, 2.7533753836905817e-06]} {"hunk": {"id": 3, "code_window": ["Package.describe({\n", " summary: \"Automatically preserve all form fields that have a unique id\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" summary: \"Automatically preserve all form fields with a unique id\"\n"], "file_path": "packages/preserve-inputs/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "////////// Main client application logic //////////\n\n//////\n////// Utility functions\n//////\n\nvar player = function () {\n return Players.findOne(Session.get('player_id'));\n};\n\nvar game = function () {\n var me = player();\n return me && me.game_id && Games.findOne(me.game_id);\n};\n\nvar create_my_player = function (name) {\n // kill my bad words after 5 seconds.\n Words.find({player_id: Session.get('player_id'), state: 'bad'})\n .observe({\n added: function (word) {\n setTimeout(function () {\n $('#word_' + word._id).fadeOut(1000, function () {\n Words.remove(word._id);\n });\n }, 5000);\n }});\n};\n\nvar set_selected_positions = function (word) {\n var paths = paths_for_word(game().board, word.toUpperCase());\n var in_a_path = [];\n var last_in_a_path = [];\n\n for (var i = 0; i < paths.length; i++) {\n in_a_path = in_a_path.concat(paths[i]);\n last_in_a_path.push(paths[i].slice(-1)[0]);\n }\n\n for (var pos = 0; pos < 16; pos++) {\n if (last_in_a_path.indexOf(pos) !== -1)\n Session.set('selected_' + pos, 'last_in_path');\n else if (in_a_path.indexOf(pos) !== -1)\n Session.set('selected_' + pos, 'in_path');\n else\n Session.set('selected_' + pos, false);\n }\n};\n\nvar clear_selected_positions = function () {\n for (var pos = 0; pos < 16; pos++)\n Session.set('selected_' + pos, false);\n};\n\n//////\n////// lobby template: shows everyone not currently playing, and\n////// offers a button to start a fresh game.\n//////\n\nTemplate.lobby.show = function () {\n // only show lobby if we're not in a game\n return !game();\n};\n\nTemplate.lobby.waiting = function () {\n var players = Players.find({_id: {$ne: Session.get('player_id')},\n name: {$ne: ''},\n game_id: {$exists: false}});\n\n return players;\n};\n\nTemplate.lobby.count = function () {\n var players = Players.find({_id: {$ne: Session.get('player_id')},\n name: {$ne: ''},\n game_id: {$exists: false}});\n\n return players.count();\n};\n\nTemplate.lobby.disabled = function () {\n var me = player();\n if (me && me.name)\n return '';\n return 'disabled=\"disabled\"';\n};\n\n\nTemplate.lobby.events({\n 'keyup input#myname': function (evt) {\n var name = $('#lobby input#myname').val().trim();\n Players.update(Session.get('player_id'), {$set: {name: name}});\n },\n 'click button.startgame': function () {\n Meteor.call('start_new_game');\n }\n});\n\n//////\n////// board template: renders the board and the clock given the\n////// current game. if there is no game, show a splash screen.\n//////\nvar SPLASH = ['','','','',\n 'W', 'O', 'R', 'D',\n 'P', 'L', 'A', 'Y',\n '','','',''];\n\nTemplate.board.square = function (i) {\n var g = game();\n return g && g.board && g.board[i] || SPLASH[i];\n};\n\nTemplate.board.selected = function (i) {\n return Session.get('selected_' + i);\n};\n\nTemplate.board.clock = function () {\n var clock = game() && game().clock;\n\n if (!clock || clock === 0)\n return;\n\n // format into M:SS\n var min = Math.floor(clock / 60);\n var sec = clock % 60;\n return min + ':' + (sec < 10 ? ('0' + sec) : sec);\n};\n\nTemplate.board.events({\n 'click .square': function (evt) {\n var textbox = $('#scratchpad input');\n textbox.val(textbox.val() + evt.target.innerHTML);\n textbox.focus();\n }\n});\n\n//////\n////// scratchpad is where we enter new words.\n//////\n\nTemplate.scratchpad.show = function () {\n return game() && game().clock > 0;\n};\n\nTemplate.scratchpad.events({\n 'click button, keyup input': function (evt) {\n var textbox = $('#scratchpad input');\n // if we clicked the button or hit enter\n if (evt.type === \"click\" ||\n (evt.type === \"keyup\" && evt.which === 13)) {\n\n var word_id = Words.insert({player_id: Session.get('player_id'),\n game_id: game() && game()._id,\n word: textbox.val().toUpperCase(),\n state: 'pending'});\n Meteor.call('score_word', word_id);\n textbox.val('');\n textbox.focus();\n clear_selected_positions();\n } else {\n set_selected_positions(textbox.val());\n }\n }\n});\n\nTemplate.postgame.show = function () {\n return game() && game().clock === 0;\n};\n\nTemplate.postgame.events({\n 'click button': function (evt) {\n Players.update(Session.get('player_id'), {$set: {game_id: null}});\n }\n});\n\n//////\n////// scores shows everyone's score and word list.\n//////\n\nTemplate.scores.show = function () {\n return !!game();\n};\n\nTemplate.scores.players = function () {\n return game() && game().players;\n};\n\nTemplate.player.winner = function () {\n var g = game();\n if (g.winners && _.include(g.winners, this._id))\n return 'winner';\n return '';\n};\n\nTemplate.player.total_score = function () {\n var words = Words.find({game_id: game() && game()._id,\n player_id: this._id});\n\n var score = 0;\n words.forEach(function (word) {\n if (word.score)\n score += word.score;\n });\n return score;\n};\n\nTemplate.words.words = function () {\n return Words.find({game_id: game() && game()._id,\n player_id: this._id});\n};\n\n\n//////\n////// Initialization\n//////\n\nMeteor.startup(function () {\n // Allocate a new player id.\n //\n // XXX this does not handle hot reload. In the reload case,\n // Session.get('player_id') will return a real id. We should check for\n // a pre-existing player, and if it exists, make sure the server still\n // knows about us.\n var player_id = Players.insert({name: '', idle: false});\n Session.set('player_id', player_id);\n\n // subscribe to all the players, the game i'm in, and all\n // the words in that game.\n Meteor.autosubscribe(function () {\n Meteor.subscribe('players');\n\n if (Session.get('player_id')) {\n var me = player();\n if (me && me.game_id) {\n Meteor.subscribe('games', me.game_id);\n Meteor.subscribe('words', me.game_id, Session.get('player_id'));\n }\n }\n });\n\n // send keepalives so the server can tell when we go away.\n //\n // XXX this is not a great idiom. meteor server does not yet have a\n // way to expose connection status to user code. Once it does, this\n // code can go away.\n Meteor.setInterval(function() {\n if (Meteor.status().connected)\n Meteor.call('keepalive', Session.get('player_id'));\n }, 20*1000);\n});\n", "file_path": "examples/wordplay/client/wordplay.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017617525008972734, 0.00017184129683300853, 0.0001611817569937557, 0.00017271576507482678, 3.901528089045314e-06]} {"hunk": {"id": 4, "code_window": ["Package.describe({\n", " summary: \"Collection of small helper functions (map, each, bind, ...)\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " where = where || ['client', 'server'];\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Collection of small helper functions: _.map, _.each, ...\"\n"], "file_path": "packages/underscore/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "Package.describe({\n summary: \"Require this application always use transport layer encryption\"\n});\n\nPackage.on_use(function (api) {\n api.use('underscore', 'server');\n // make sure we come after livedata, so we load after the sockjs\n // server has been instantiated.\n api.use('livedata', 'server');\n\n api.add_files('force_ssl_common.js', ['client', 'server']);\n api.add_files('force_ssl_server.js', 'server');\n\n // Another thing we could do is add a force_ssl_client.js file that\n // makes sure document.location.protocol is 'https'. If it detected\n // the code was loaded from a non-localhost non-https site, it would\n // stop the app from working and pop up an error box or something.\n});\n", "file_path": "packages/force-ssl/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.0012115142308175564, 0.000735454261302948, 0.00025939432089217007, 0.000735454261302948, 0.0004760599404107779]} {"hunk": {"id": 4, "code_window": ["Package.describe({\n", " summary: \"Collection of small helper functions (map, each, bind, ...)\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " where = where || ['client', 'server'];\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Collection of small helper functions: _.map, _.each, ...\"\n"], "file_path": "packages/underscore/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "body {\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-weight: 200;\n margin: 50px 0;\n padding: 0;\n -webkit-user-select: none;\n -khtml-user-select: none;\n -moz-user-select: none;\n -o-user-select: none;\n user-select: none;\n}\n\n#outer {\n width: 600px;\n margin: 0 auto; \n}\n\n.player {\n cursor: pointer;\n padding: 5px;\n}\n\n.player .name {\n display: inline-block;\n width: 300px;\n font-size: 1.75em;\n}\n\n.player .score {\n display: inline-block;\n width: 100px;\n text-align: right;\n font-size: 2em;\n font-weight: bold;\n color: #777;\n}\n\n.player.selected {\n background-color: yellow;\n}\n\n.player.selected .score {\n color: black;\n}\n\n.details, .none {\n font-weight: bold;\n font-size: 2em;\n border-style: dashed none none none;\n border-color: #ccc;\n border-width: 4px;\n margin: 50px 10px;\n padding: 10px 0px;\n}\n\n.none {\n color: #777;\n}\n\n.inc {\n cursor: pointer;\n}\n", "file_path": "examples/leaderboard/leaderboard.css", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017859405488707125, 0.0001760352315614, 0.00017440725059714168, 0.00017551380733493716, 1.3556555131799541e-06]} {"hunk": {"id": 4, "code_window": ["Package.describe({\n", " summary: \"Collection of small helper functions (map, each, bind, ...)\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " where = where || ['client', 'server'];\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Collection of small helper functions: _.map, _.each, ...\"\n"], "file_path": "packages/underscore/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "// Underscore.js 1.3.3\n// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.\n// Underscore is freely distributable under the MIT license.\n// Portions of Underscore are inspired or borrowed from Prototype,\n// Oliver Steele's Functional, and John Resig's Micro-Templating.\n// For all details and documentation:\n// http://documentcloud.github.com/underscore\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `global` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Establish the object that gets returned to break out of a loop iteration.\n var breaker = {};\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var slice = ArrayProto.slice,\n unshift = ArrayProto.unshift,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeForEach = ArrayProto.forEach,\n nativeMap = ArrayProto.map,\n nativeReduce = ArrayProto.reduce,\n nativeReduceRight = ArrayProto.reduceRight,\n nativeFilter = ArrayProto.filter,\n nativeEvery = ArrayProto.every,\n nativeSome = ArrayProto.some,\n nativeIndexOf = ArrayProto.indexOf,\n nativeLastIndexOf = ArrayProto.lastIndexOf,\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind;\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) { return new wrapper(obj); };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object via a string identifier,\n // for Closure Compiler \"advanced\" mode.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root['_'] = _;\n }\n\n // Current version.\n _.VERSION = '1.3.3';\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles objects with the built-in `forEach`, arrays, and raw objects.\n // Delegates to **ECMAScript 5**'s native `forEach` if available.\n var each = _.each = _.forEach = function(obj, iterator, context) {\n if (obj == null) return;\n if (nativeForEach && obj.forEach === nativeForEach) {\n obj.forEach(iterator, context);\n } else if (obj.length === +obj.length) {\n for (var i = 0, l = obj.length; i < l; i++) {\n if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;\n }\n } else {\n for (var key in obj) {\n if (_.has(obj, key)) {\n if (iterator.call(context, obj[key], key, obj) === breaker) return;\n }\n }\n }\n };\n\n // Return the results of applying the iterator to each element.\n // Delegates to **ECMAScript 5**'s native `map` if available.\n _.map = _.collect = function(obj, iterator, context) {\n var results = [];\n if (obj == null) return results;\n if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);\n each(obj, function(value, index, list) {\n results[results.length] = iterator.call(context, value, index, list);\n });\n if (obj.length === +obj.length) results.length = obj.length;\n return results;\n };\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.\n _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {\n var initial = arguments.length > 2;\n if (obj == null) obj = [];\n if (nativeReduce && obj.reduce === nativeReduce) {\n if (context) iterator = _.bind(iterator, context);\n return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);\n }\n each(obj, function(value, index, list) {\n if (!initial) {\n memo = value;\n initial = true;\n } else {\n memo = iterator.call(context, memo, value, index, list);\n }\n });\n if (!initial) throw new TypeError('Reduce of empty array with no initial value');\n return memo;\n };\n\n // The right-associative version of reduce, also known as `foldr`.\n // Delegates to **ECMAScript 5**'s native `reduceRight` if available.\n _.reduceRight = _.foldr = function(obj, iterator, memo, context) {\n var initial = arguments.length > 2;\n if (obj == null) obj = [];\n if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {\n if (context) iterator = _.bind(iterator, context);\n return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);\n }\n var reversed = _.toArray(obj).reverse();\n if (context && !initial) iterator = _.bind(iterator, context);\n return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);\n };\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, iterator, context) {\n var result;\n any(obj, function(value, index, list) {\n if (iterator.call(context, value, index, list)) {\n result = value;\n return true;\n }\n });\n return result;\n };\n\n // Return all the elements that pass a truth test.\n // Delegates to **ECMAScript 5**'s native `filter` if available.\n // Aliased as `select`.\n _.filter = _.select = function(obj, iterator, context) {\n var results = [];\n if (obj == null) return results;\n if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);\n each(obj, function(value, index, list) {\n if (iterator.call(context, value, index, list)) results[results.length] = value;\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, iterator, context) {\n var results = [];\n if (obj == null) return results;\n each(obj, function(value, index, list) {\n if (!iterator.call(context, value, index, list)) results[results.length] = value;\n });\n return results;\n };\n\n // Determine whether all of the elements match a truth test.\n // Delegates to **ECMAScript 5**'s native `every` if available.\n // Aliased as `all`.\n _.every = _.all = function(obj, iterator, context) {\n var result = true;\n if (obj == null) return result;\n if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);\n each(obj, function(value, index, list) {\n if (!(result = result && iterator.call(context, value, index, list))) return breaker;\n });\n return !!result;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Delegates to **ECMAScript 5**'s native `some` if available.\n // Aliased as `any`.\n var any = _.some = _.any = function(obj, iterator, context) {\n iterator || (iterator = _.identity);\n var result = false;\n if (obj == null) return result;\n if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);\n each(obj, function(value, index, list) {\n if (result || (result = iterator.call(context, value, index, list))) return breaker;\n });\n return !!result;\n };\n\n // Determine if a given value is included in the array or object using `===`.\n // Aliased as `contains`.\n _.include = _.contains = function(obj, target) {\n var found = false;\n if (obj == null) return found;\n if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;\n found = any(obj, function(value) {\n return value === target;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (_.isFunction(method) ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.max.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.min.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return Infinity;\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.\n _.sortBy = function(obj, val, context) {\n var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value : value,\n criteria : iterator.call(context, value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria, b = right.criteria;\n if (a === void 0) return 1;\n if (b === void 0) return -1;\n return a < b ? -1 : a > b ? 1 : 0;\n }), 'value');\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = function(obj, val) {\n var result = {};\n var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };\n each(obj, function(value, index) {\n var key = iterator(value, index);\n (result[key] || (result[key] = [])).push(value);\n });\n return result;\n };\n\n // Use a comparator function to figure out at what index an object should\n // be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iterator) {\n iterator || (iterator = _.identity);\n var low = 0, high = array.length;\n while (low < high) {\n var mid = (low + high) >> 1;\n iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;\n }\n return low;\n };\n\n // Safely convert anything iterable into a real, live array.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (_.isArguments(obj)) return slice.call(obj);\n if (obj.toArray && _.isFunction(obj.toArray)) return obj.toArray();\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n return _.isArray(obj) ? obj.length : _.keys(obj).length;\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n return (n != null) && !guard ? slice.call(array, 0, n) : array[0];\n };\n\n // Returns everything but the last entry of the array. Especcialy useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N. The **guard** check allows it to work with\n // `_.map`.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array. The **guard** check allows it to work with `_.map`.\n _.last = function(array, n, guard) {\n if ((n != null) && !guard) {\n return slice.call(array, Math.max(array.length - n, 0));\n } else {\n return array[array.length - 1];\n }\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail`.\n // Especially useful on the arguments object. Passing an **index** will return\n // the rest of the values in the array from that index onward. The **guard**\n // check allows it to work with `_.map`.\n _.rest = _.tail = function(array, index, guard) {\n return slice.call(array, (index == null) || guard ? 1 : index);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, function(value){ return !!value; });\n };\n\n // Return a completely flattened version of an array.\n _.flatten = function(array, shallow) {\n return _.reduce(array, function(memo, value) {\n if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));\n memo[memo.length] = value;\n return memo;\n }, []);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iterator) {\n var initial = iterator ? _.map(array, iterator) : array;\n var results = [];\n // The `isSorted` flag is irrelevant if the array only contains two elements.\n if (array.length < 3) isSorted = true;\n _.reduce(initial, function (memo, value, index) {\n if (isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) {\n memo.push(value);\n results.push(array[index]);\n }\n return memo;\n }, []);\n return results;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(_.flatten(arguments, true));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays. (Aliased as \"intersect\" for back-compat.)\n _.intersection = _.intersect = function(array) {\n var rest = slice.call(arguments, 1);\n return _.filter(_.uniq(array), function(item) {\n return _.every(rest, function(other) {\n return _.indexOf(other, item) >= 0;\n });\n });\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = _.flatten(slice.call(arguments, 1), true);\n return _.filter(array, function(value){ return !_.include(rest, value); });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n var args = slice.call(arguments);\n var length = _.max(_.pluck(args, 'length'));\n var results = new Array(length);\n for (var i = 0; i < length; i++) results[i] = _.pluck(args, \"\" + i);\n return results;\n };\n\n // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),\n // we need this function. Return the position of the first occurrence of an\n // item in an array, or -1 if the item is not included in the array.\n // Delegates to **ECMAScript 5**'s native `indexOf` if available.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = function(array, item, isSorted) {\n if (array == null) return -1;\n var i, l;\n if (isSorted) {\n i = _.sortedIndex(array, item);\n return array[i] === item ? i : -1;\n }\n if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);\n for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;\n return -1;\n };\n\n // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.\n _.lastIndexOf = function(array, item) {\n if (array == null) return -1;\n if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);\n var i = array.length;\n while (i--) if (i in array && array[i] === item) return i;\n return -1;\n };\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (arguments.length <= 1) {\n stop = start || 0;\n start = 0;\n }\n step = arguments[2] || 1;\n\n var len = Math.max(Math.ceil((stop - start) / step), 0);\n var idx = 0;\n var range = new Array(len);\n\n while(idx < len) {\n range[idx++] = start;\n start += step;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Reusable constructor function for prototype setting.\n var ctor = function(){};\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Binding with arguments is also known as `curry`.\n // Delegates to **ECMAScript 5**'s native `Function.bind` if available.\n // We check for `func.bind` first, to fail fast when `func` is undefined.\n _.bind = function bind(func, context) {\n var bound, args;\n if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError;\n args = slice.call(arguments, 2);\n return bound = function() {\n if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));\n ctor.prototype = func.prototype;\n var self = new ctor;\n var result = func.apply(self, args.concat(slice.call(arguments)));\n if (Object(result) === result) return result;\n return self;\n };\n };\n\n // Bind all of an object's methods to that object. Useful for ensuring that\n // all callbacks defined on an object belong to it.\n _.bindAll = function(obj) {\n var funcs = slice.call(arguments, 1);\n if (funcs.length == 0) funcs = _.functions(obj);\n each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memo = {};\n hasher || (hasher = _.identity);\n return function() {\n var key = hasher.apply(this, arguments);\n return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));\n };\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){ return func.apply(null, args); }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = function(func) {\n return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));\n };\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time.\n _.throttle = function(func, wait) {\n var context, args, timeout, throttling, more, result;\n var whenDone = _.debounce(function(){ more = throttling = false; }, wait);\n return function() {\n context = this; args = arguments;\n var later = function() {\n timeout = null;\n if (more) func.apply(context, args);\n whenDone();\n };\n if (!timeout) timeout = setTimeout(later, wait);\n if (throttling) {\n more = true;\n } else {\n result = func.apply(context, args);\n }\n whenDone();\n throttling = true;\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout;\n return function() {\n var context = this, args = arguments;\n var later = function() {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n if (immediate && !timeout) func.apply(context, args);\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = function(func) {\n var ran = false, memo;\n return function() {\n if (ran) return memo;\n ran = true;\n return memo = func.apply(this, arguments);\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return function() {\n var args = [func].concat(slice.call(arguments, 0));\n return wrapper.apply(this, args);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var funcs = arguments;\n return function() {\n var args = arguments;\n for (var i = funcs.length - 1; i >= 0; i--) {\n args = [funcs[i].apply(this, args)];\n }\n return args[0];\n };\n };\n\n // Returns a function that will only be executed after being called N times.\n _.after = function(times, func) {\n if (times <= 0) return func();\n return function() {\n if (--times < 1) { return func.apply(this, arguments); }\n };\n };\n\n // Object Functions\n // ----------------\n\n // Retrieve the names of an object's properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = nativeKeys || function(obj) {\n if (obj !== Object(obj)) throw new TypeError('Invalid object');\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n return _.map(obj, _.identity);\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = function(obj) {\n each(slice.call(arguments, 1), function(source) {\n for (var prop in source) {\n obj[prop] = source[prop];\n }\n });\n return obj;\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(obj) {\n var result = {};\n each(_.flatten(slice.call(arguments, 1)), function(key) {\n if (key in obj) result[key] = obj[key];\n });\n return result;\n };\n\n // Fill in a given object with default properties.\n _.defaults = function(obj) {\n each(slice.call(arguments, 1), function(source) {\n for (var prop in source) {\n if (obj[prop] == null) obj[prop] = source[prop];\n }\n });\n return obj;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Internal recursive comparison function.\n function eq(a, b, stack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.\n if (a === b) return a !== 0 || 1 / a == 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a._chain) a = a._wrapped;\n if (b._chain) b = b._wrapped;\n // Invoke a custom `isEqual` method if one is provided.\n if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);\n if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className != toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, dates, and booleans are compared by value.\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return a == String(b);\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for\n // other numeric values.\n return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a == +b;\n // RegExps are compared by their source patterns and flags.\n case '[object RegExp]':\n return a.source == b.source &&\n a.global == b.global &&\n a.multiline == b.multiline &&\n a.ignoreCase == b.ignoreCase;\n }\n if (typeof a != 'object' || typeof b != 'object') return false;\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n var length = stack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (stack[length] == a) return true;\n }\n // Add the first object to the stack of traversed objects.\n stack.push(a);\n var size = 0, result = true;\n // Recursively compare objects and arrays.\n if (className == '[object Array]') {\n // Compare array lengths to determine if a deep comparison is necessary.\n size = a.length;\n result = size == b.length;\n if (result) {\n // Deep compare the contents, ignoring non-numeric properties.\n while (size--) {\n // Ensure commutative equality for sparse arrays.\n if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;\n }\n }\n } else {\n // Objects with different constructors are not equivalent.\n if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;\n // Deep compare objects.\n for (var key in a) {\n if (_.has(a, key)) {\n // Count the expected number of properties.\n size++;\n // Deep compare each member.\n if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;\n }\n }\n // Ensure that both objects contain the same number of properties.\n if (result) {\n for (key in b) {\n if (_.has(b, key) && !(size--)) break;\n }\n result = !size;\n }\n }\n // Remove the first object from the stack of traversed objects.\n stack.pop();\n return result;\n }\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b, []);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;\n for (var key in obj) if (_.has(obj, key)) return false;\n return true;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType == 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) == '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n return obj === Object(obj);\n };\n\n // Is a given variable an arguments object?\n _.isArguments = function(obj) {\n return toString.call(obj) == '[object Arguments]';\n };\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return !!(obj && _.has(obj, 'callee'));\n };\n }\n\n // Is a given value a function?\n _.isFunction = function(obj) {\n return toString.call(obj) == '[object Function]';\n };\n\n // Is a given value a string?\n _.isString = function(obj) {\n return toString.call(obj) == '[object String]';\n };\n\n // Is a given value a number?\n _.isNumber = function(obj) {\n return toString.call(obj) == '[object Number]';\n };\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return _.isNumber(obj) && isFinite(obj);\n };\n\n // Is the given value `NaN`?\n _.isNaN = function(obj) {\n // `NaN` is the only value for which `===` is not reflexive.\n return obj !== obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) == '[object Boolean]';\n };\n\n // Is a given value a date?\n _.isDate = function(obj) {\n return toString.call(obj) == '[object Date]';\n };\n\n // Is the given value a regular expression?\n _.isRegExp = function(obj) {\n return toString.call(obj) == '[object RegExp]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Has own property?\n _.has = function(obj, key) {\n return hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iterators.\n _.identity = function(value) {\n return value;\n };\n\n // Run a function **n** times.\n _.times = function (n, iterator, context) {\n for (var i = 0; i < n; i++) iterator.call(context, i);\n };\n\n // Escape a string for HTML interpolation.\n _.escape = function(string) {\n return (''+string).replace(/&/g, '&').replace(//g, '>').replace(/\"/g, '"').replace(/'/g, ''').replace(/\\//g,'/');\n };\n\n // If the value of the named property is a function then invoke it;\n // otherwise, return it.\n _.result = function(object, property) {\n if (object == null) return null;\n var value = object[property];\n return _.isFunction(value) ? value.call(object) : value;\n };\n\n // Add your own custom functions to the Underscore object, ensuring that\n // they're correctly added to the OOP wrapper as well.\n _.mixin = function(obj) {\n each(_.functions(obj), function(name){\n addToWrapper(name, _[name] = obj[name]);\n });\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = idCounter++;\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /.^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n 'r': '\\r',\n 'n': '\\n',\n 't': '\\t',\n 'u2028': '\\u2028',\n 'u2029': '\\u2029'\n };\n\n for (var p in escapes) escapes[escapes[p]] = p;\n var escaper = /\\\\|'|\\r|\\n|\\t|\\u2028|\\u2029/g;\n var unescaper = /\\\\(\\\\|'|r|n|t|u2028|u2029)/g;\n\n // Within an interpolation, evaluation, or escaping, remove HTML escaping\n // that had been previously added.\n var unescape = function(code) {\n return code.replace(unescaper, function(match, escape) {\n return escapes[escape];\n });\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n _.template = function(text, data, settings) {\n settings = _.defaults(settings || {}, _.templateSettings);\n\n // Compile the template source, taking care to escape characters that\n // cannot be included in a string literal and then unescape them in code\n // blocks.\n var source = \"__p+='\" + text\n .replace(escaper, function(match) {\n return '\\\\' + escapes[match];\n })\n .replace(settings.escape || noMatch, function(match, code) {\n return \"'+\\n_.escape(\" + unescape(code) + \")+\\n'\";\n })\n .replace(settings.interpolate || noMatch, function(match, code) {\n return \"'+\\n(\" + unescape(code) + \")+\\n'\";\n })\n .replace(settings.evaluate || noMatch, function(match, code) {\n return \"';\\n\" + unescape(code) + \"\\n;__p+='\";\n }) + \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __p='';\" +\n \"var print=function(){__p+=Array.prototype.join.call(arguments, '')};\\n\" +\n source + \"return __p;\\n\";\n\n var render = new Function(settings.variable || 'obj', '_', source);\n if (data) return render(data, _);\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled function source as a convenience for build time\n // precompilation.\n template.source = 'function(' + (settings.variable || 'obj') + '){\\n' +\n source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function, which will delegate to the wrapper.\n _.chain = function(obj) {\n return _(obj).chain();\n };\n\n // The OOP Wrapper\n // ---------------\n\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n var wrapper = function(obj) { this._wrapped = obj; };\n\n // Expose `wrapper.prototype` as `_.prototype`\n _.prototype = wrapper.prototype;\n\n // Helper function to continue chaining intermediate results.\n var result = function(obj, chain) {\n return chain ? _(obj).chain() : obj;\n };\n\n // A method to easily add functions to the OOP wrapper.\n var addToWrapper = function(name, func) {\n wrapper.prototype[name] = function() {\n var args = slice.call(arguments);\n unshift.call(args, this._wrapped);\n return result(func.apply(_, args), this._chain);\n };\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n wrapper.prototype[name] = function() {\n var wrapped = this._wrapped;\n method.apply(wrapped, arguments);\n var length = wrapped.length;\n if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];\n return result(wrapped, this._chain);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n wrapper.prototype[name] = function() {\n return result(method.apply(this._wrapped, arguments), this._chain);\n };\n });\n\n // Start chaining a wrapped Underscore object.\n wrapper.prototype.chain = function() {\n this._chain = true;\n return this;\n };\n\n // Extracts the result from a wrapped and chained object.\n wrapper.prototype.value = function() {\n return this._wrapped;\n };\n\n}).call(this);\n", "file_path": "app/server/underscore.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.003486288944259286, 0.00022571317094843835, 0.00016242712445091456, 0.00017111824126914144, 0.00034080655314028263]} {"hunk": {"id": 4, "code_window": ["Package.describe({\n", " summary: \"Collection of small helper functions (map, each, bind, ...)\"\n", "});\n", "\n", "Package.on_use(function (api, where) {\n", " where = where || ['client', 'server'];\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" summary: \"Collection of small helper functions: _.map, _.each, ...\"\n"], "file_path": "packages/underscore/package.js", "type": "replace", "edit_start_line_idx": 1}, "file": "var simulateEvent = function (node, event, args) {\n node = (node instanceof $ ? node[0] : node);\n\n if (document.createEvent) {\n var e = document.createEvent(\"Event\");\n e.initEvent(event, true, true);\n _.extend(e, args);\n node.dispatchEvent(e);\n } else {\n var e = document.createEventObject();\n _.extend(e, args);\n node.fireEvent(\"on\" + event, e);\n }\n};\n\nvar focusElement = function(elem) {\n // This sequence is for benefit of IE 8 and 9;\n // test there before changing.\n window.focus();\n elem.focus();\n elem.focus();\n\n // focus() should set document.activeElement\n if (document.activeElement !== elem)\n throw new Error(\"focus() didn't set activeElement\");\n};\n\nvar blurElement = function(elem) {\n elem.blur();\n if (document.activeElement === elem)\n throw new Error(\"blur() didn't affect activeElement\");\n};\n\nvar clickElement = function(elem) {\n if (elem.click)\n elem.click(); // supported by form controls cross-browser; most native way\n else\n simulateEvent(elem, 'click');\n};\n", "file_path": "packages/test-helpers/event_simulation.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/2c6f991228dd1cf39c4829ff6e9a8fdd620d988d", "dependency_score": [0.00017730824765749276, 0.00017367591499350965, 0.00017105192819144577, 0.00017317174933850765, 2.320181465620408e-06]} {"hunk": {"id": 0, "code_window": [" return v8::FunctionTemplate::New(SetHiddenValue);\n", " else if (name->Equals(v8::String::New(\"SetDestructor\")))\n", " return v8::FunctionTemplate::New(SetDestructor);\n", " else if (name->Equals(v8::String::New(\"GetNextObjectId\")))\n", " return v8::FunctionTemplate::New(GetNextObjectId);\n", " else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n", " return v8::FunctionTemplate::New(GetAbsolutePath);\n", " else if (name->Equals(v8::String::New(\"AllocateObject\")))\n", " return v8::FunctionTemplate::New(AllocateObject);\n", " else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 140}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_bindings.h\"\n\n#include \"base/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"base/command_line.h\"\n#include \"chrome/renderer/static_v8_external_string_resource.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/object_life_monitor.h\"\n#include \"content/public/renderer/render_view.h\"\n#include \"content/public/renderer/render_thread.h\"\n#include \"content/public/renderer/v8_value_converter.h\"\n#include \"grit/nw_resources.h\"\n#include \"third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h\"\n#include \"third_party/WebKit/Source/WebKit/chromium/public/WebView.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n\nusing content::RenderView;\nusing content::V8ValueConverter;\nusing WebKit::WebFrame;\nusing WebKit::WebView;\n\nnamespace api {\n\nnamespace {\n\nbase::StringPiece GetStringResource(int resource_id) {\n return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);\n}\n\nRenderView* GetCurrentRenderView() {\n WebFrame* frame = WebFrame::frameForCurrentContext();\n DCHECK(frame);\n if (!frame)\n return NULL;\n\n WebView* view = frame->view();\n if (!view)\n return NULL; // can happen during closing.\n\n RenderView* render_view = RenderView::FromWebView(view);\n DCHECK(render_view);\n return render_view;\n}\n\nv8::Handle WrapSource(v8::Handle source) {\n v8::HandleScope handle_scope;\n v8::Handle left =\n v8::String::New(\"(function(nw, exports) {\");\n v8::Handle right = v8::String::New(\"\\n})\");\n return handle_scope.Close(\n v8::String::Concat(left, v8::String::Concat(source, right)));\n}\n\n// Similar to node's `require` function, save functions in `exports`.\nvoid RequireFromResource(v8::Handle root,\n v8::Handle gui,\n v8::Handle name,\n int resource_id) {\n v8::HandleScope scope;\n\n v8::Handle source = v8::String::NewExternal(\n new StaticV8ExternalAsciiStringResource(\n GetStringResource(resource_id)));\n v8::Handle wrapped_source = WrapSource(source);\n\n v8::Handle script(v8::Script::New(wrapped_source, name));\n v8::Handle func = v8::Handle::Cast(script->Run());\n v8::Handle args[] = { root, gui };\n func->Call(root, 2, args);\n}\n\nbool MakePathAbsolute(FilePath* file_path) {\n DCHECK(file_path);\n\n FilePath current_directory;\n if (!file_util::GetCurrentDirectory(¤t_directory))\n return false;\n\n if (file_path->IsAbsolute())\n return true;\n\n if (current_directory.empty())\n return file_util::AbsolutePath(file_path);\n\n if (!current_directory.IsAbsolute())\n return false;\n\n *file_path = current_directory.Append(*file_path);\n return true;\n}\n\n} // namespace\n\nDispatcherBindings::DispatcherBindings()\n : v8::Extension(\"dispatcher_bindings.js\",\n GetStringResource(\n IDR_NW_API_DISPATCHER_BINDINGS_JS).data(),\n 0, // num dependencies.\n NULL, // dependencies array.\n GetStringResource(\n IDR_NW_API_DISPATCHER_BINDINGS_JS).size()) {\n}\n\nDispatcherBindings::~DispatcherBindings() {\n}\n\nv8::Handle\nDispatcherBindings::GetNativeFunction(v8::Handle name) {\n if (name->Equals(v8::String::New(\"RequireNwGui\")))\n return v8::FunctionTemplate::New(RequireNwGui);\n else if (name->Equals(v8::String::New(\"GetConstructorName\")))\n return v8::FunctionTemplate::New(GetConstructorName);\n else if (name->Equals(v8::String::New(\"GetHiddenValue\")))\n return v8::FunctionTemplate::New(GetHiddenValue);\n else if (name->Equals(v8::String::New(\"SetHiddenValue\")))\n return v8::FunctionTemplate::New(SetHiddenValue);\n else if (name->Equals(v8::String::New(\"SetDestructor\")))\n return v8::FunctionTemplate::New(SetDestructor);\n else if (name->Equals(v8::String::New(\"GetNextObjectId\")))\n return v8::FunctionTemplate::New(GetNextObjectId);\n else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n return v8::FunctionTemplate::New(GetAbsolutePath);\n else if (name->Equals(v8::String::New(\"AllocateObject\")))\n return v8::FunctionTemplate::New(AllocateObject);\n else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n return v8::FunctionTemplate::New(DeallocateObject);\n else if (name->Equals(v8::String::New(\"CallObjectMethod\")))\n return v8::FunctionTemplate::New(CallObjectMethod);\n else if (name->Equals(v8::String::New(\"CallObjectMethodSync\")))\n return v8::FunctionTemplate::New(CallObjectMethodSync);\n else if (name->Equals(v8::String::New(\"CallStaticMethod\")))\n return v8::FunctionTemplate::New(CallStaticMethod);\n else if (name->Equals(v8::String::New(\"CallStaticMethodSync\")))\n return v8::FunctionTemplate::New(CallStaticMethodSync);\n\n NOTREACHED() << \"Trying to get an non-exist function in DispatcherBindings:\"\n << *v8::String::Utf8Value(name);\n return v8::FunctionTemplate::New();\n}\n\n// static\nv8::Handle\nDispatcherBindings::RequireNwGui(const v8::Arguments& args) {\n v8::HandleScope scope;\n\n // Initialize lazily\n v8::Local NwGuiSymbol = v8::String::NewSymbol(\"nwGui\");\n v8::Local NwGuiHidden = args.This()->Get(NwGuiSymbol);\n if (NwGuiHidden->IsObject())\n return scope.Close(NwGuiHidden);\n\n v8::Local NwGui = v8::Object::New();\n args.This()->Set(NwGuiSymbol, NwGui);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"base.js\"), IDR_NW_API_BASE_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"menuitem.js\"), IDR_NW_API_MENUITEM_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"menu.js\"), IDR_NW_API_MENU_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"tray.js\"), IDR_NW_API_TRAY_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"clipboard.js\"), IDR_NW_API_CLIPBOARD_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"window.js\"), IDR_NW_API_WINDOW_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"shell.js\"), IDR_NW_API_SHELL_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"app.js\"), IDR_NW_API_APP_JS);\n\n return scope.Close(NwGui);\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetNextObjectId(const v8::Arguments& args) {\n static int next_object_id = 1;\n return v8::Integer::New(next_object_id++);\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n FilePath path = FilePath::FromUTF8Unsafe(*v8::String::Utf8Value(args[0]));\n MakePathAbsolute(&path);\n#if defined(OS_POSIX)\n return v8::String::New(path.value().c_str());\n#else\n return v8::String::New(path.AsUTF8Unsafe().c_str());\n#endif\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetHiddenValue(const v8::Arguments& args) {\n return args.This()->GetHiddenValue(args[0]->ToString());\n}\n\n// static\nv8::Handle\nDispatcherBindings::SetHiddenValue(const v8::Arguments& args) {\n args.This()->SetHiddenValue(args[0]->ToString(), args[1]);\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetConstructorName(const v8::Arguments& args) {\n if (args.Length() < 1 || !args[0]->IsObject())\n return v8::Undefined();\n\n return args[0]->ToObject()->GetConstructorName();\n}\n\n// static\nv8::Handle\nDispatcherBindings::SetDestructor(const v8::Arguments& args) {\n ObjectLifeMonitor::BindTo(args.This(), args[0]);\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::AllocateObject(const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"AllocateObject requries 3 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n std::string name = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n converter->SetStripNullFromObjects(true);\n\n scoped_ptr value_option(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_option.get() ||\n !value_option->IsType(base::Value::TYPE_DICTIONARY)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'option' passed to AllocateObject\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in AllocateObject\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Allocate_Object(\n render_view->GetRoutingID(),\n object_id,\n name,\n *static_cast(value_option.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::DeallocateObject(const v8::Arguments& args) {\n if (args.Length() < 1) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"DeallocateObject requries 1 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in DeallocateObject\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Deallocate_Object(\n render_view->GetRoutingID(), object_id));\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::CallObjectMethod(const v8::Arguments& args) {\n if (args.Length() < 4) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallObjectMethod requries 4 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n std::string type = *v8::String::Utf8Value(args[1]);\n std::string method = *v8::String::Utf8Value(args[2]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[3], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallObjectMethod\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallObjectMethod\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Call_Object_Method(\n render_view->GetRoutingID(),\n object_id,\n type,\n method,\n *static_cast(value_args.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle DispatcherBindings::CallObjectMethodSync(\n const v8::Arguments& args) {\n if (args.Length() < 4) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallObjectMethodSync requries 4 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n std::string type = *v8::String::Utf8Value(args[1]);\n std::string method = *v8::String::Utf8Value(args[2]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[3], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallObjectMethodSync\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallObjectMethodSync\")));\n }\n\n base::ListValue result;\n render_view->Send(new ShellViewHostMsg_Call_Object_Method_Sync(\n MSG_ROUTING_NONE,\n object_id,\n type,\n method,\n *static_cast(value_args.get()),\n &result));\n return converter->ToV8Value(&result, v8::Context::GetCurrent());\n}\n\n// static\nv8::Handle DispatcherBindings::CallStaticMethod(\n const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallStaticMethod requries 3 arguments\")));\n }\n\n std::string type = *v8::String::Utf8Value(args[0]);\n std::string method = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallStaticMethod\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethod\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Call_Static_Method(\n render_view->GetRoutingID(),\n type,\n method,\n *static_cast(value_args.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle DispatcherBindings::CallStaticMethodSync(\n const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallStaticMethodSync requries 3 arguments\")));\n }\n\n std::string type = *v8::String::Utf8Value(args[0]);\n std::string method = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallStaticMethodSync\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethodSync\")));\n }\n\n base::ListValue result;\n render_view->Send(new ShellViewHostMsg_Call_Static_Method_Sync(\n MSG_ROUTING_NONE,\n type,\n method,\n *static_cast(value_args.get()),\n &result));\n return converter->ToV8Value(&result, v8::Context::GetCurrent());\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_bindings.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.9966705441474915, 0.04330078512430191, 0.00015995631110854447, 0.00017375475727021694, 0.1975065916776657]} {"hunk": {"id": 0, "code_window": [" return v8::FunctionTemplate::New(SetHiddenValue);\n", " else if (name->Equals(v8::String::New(\"SetDestructor\")))\n", " return v8::FunctionTemplate::New(SetDestructor);\n", " else if (name->Equals(v8::String::New(\"GetNextObjectId\")))\n", " return v8::FunctionTemplate::New(GetNextObjectId);\n", " else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n", " return v8::FunctionTemplate::New(GetAbsolutePath);\n", " else if (name->Equals(v8::String::New(\"AllocateObject\")))\n", " return v8::FunctionTemplate::New(AllocateObject);\n", " else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 140}, "file": "var mkdirp = require('../');\nvar path = require('path');\nvar fs = require('fs');\nvar test = require('tap').test;\n\ntest('umask sync modes', function (t) {\n t.plan(2);\n var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);\n var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);\n var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);\n\n var file = '/tmp/' + [x,y,z].join('/');\n\n try {\n mkdirp.sync(file);\n } catch (err) {\n t.fail(err);\n return t.end();\n }\n\n path.exists(file, function (ex) {\n if (!ex) t.fail('file not created')\n else fs.stat(file, function (err, stat) {\n if (err) t.fail(err)\n else {\n t.equal(stat.mode & 0777, (0777 & (~process.umask())));\n t.ok(stat.isDirectory(), 'target not a directory');\n t.end();\n }\n });\n });\n});\n", "file_path": "tests/node/node_modules/tar/node_modules/fstream/node_modules/mkdirp/test/umask_sync.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017711019609123468, 0.00017250869132112712, 0.00016850985412020236, 0.00017220736481249332, 3.2459654448757647e-06]} {"hunk": {"id": 0, "code_window": [" return v8::FunctionTemplate::New(SetHiddenValue);\n", " else if (name->Equals(v8::String::New(\"SetDestructor\")))\n", " return v8::FunctionTemplate::New(SetDestructor);\n", " else if (name->Equals(v8::String::New(\"GetNextObjectId\")))\n", " return v8::FunctionTemplate::New(GetNextObjectId);\n", " else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n", " return v8::FunctionTemplate::New(GetAbsolutePath);\n", " else if (name->Equals(v8::String::New(\"AllocateObject\")))\n", " return v8::FunctionTemplate::New(AllocateObject);\n", " else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 140}, "file": "-----BEGIN CERTIFICATE-----\nMIICvTCCAiYCCQDn+P/MSbDsWjANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMC\nVVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMRAwDgYDVQQKEwdyZXF1\nZXN0MSYwJAYDVQQLEx1yZXF1ZXN0IENlcnRpZmljYXRlIEF1dGhvcml0eTESMBAG\nA1UEAxMJcmVxdWVzdENBMSYwJAYJKoZIhvcNAQkBFhdtaWtlYWxAbWlrZWFscm9n\nZXJzLmNvbTAeFw0xMjAzMDEyMjUwNTZaFw0yMjAyMjcyMjUwNTZaMIGiMQswCQYD\nVQQGEwJVUzELMAkGA1UECBMCQ0ExEDAOBgNVBAcTB09ha2xhbmQxEDAOBgNVBAoT\nB3JlcXVlc3QxJjAkBgNVBAsTHXJlcXVlc3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5\nMRIwEAYDVQQDEwlyZXF1ZXN0Q0ExJjAkBgkqhkiG9w0BCQEWF21pa2VhbEBtaWtl\nYWxyb2dlcnMuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7t9pQUAK4\n5XJYTI6NrF0n3G2HZsfN+rPYSVzzL8SuVyb1tHXos+vbPm3NKI4E8X1yVAXU8CjJ\n5SqXnp4DAypAhaseho81cbhk7LXUhFz78OvAa+OD+xTAEAnNQ8tGUr4VGyplEjfD\nxsBVuqV2j8GPNTftr+drOCFlqfAgMrBn4wIDAQABMA0GCSqGSIb3DQEBBQUAA4GB\nADVdTlVAL45R+PACNS7Gs4o81CwSclukBu4FJbxrkd4xGQmurgfRrYYKjtqiopQm\nD7ysRamS3HMN9/VKq2T7r3z1PMHPAy7zM4uoXbbaTKwlnX4j/8pGPn8Ca3qHXYlo\n88L/OOPc6Di7i7qckS3HFbXQCTiULtxWmy97oEuTwrAj\n-----END CERTIFICATE-----\n", "file_path": "tests/node/node_modules/request/tests/ssl/ca/ca.crt", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00028090697014704347, 0.00024453605874441564, 0.0002081651327898726, 0.00024453605874441564, 3.637091867858544e-05]} {"hunk": {"id": 0, "code_window": [" return v8::FunctionTemplate::New(SetHiddenValue);\n", " else if (name->Equals(v8::String::New(\"SetDestructor\")))\n", " return v8::FunctionTemplate::New(SetDestructor);\n", " else if (name->Equals(v8::String::New(\"GetNextObjectId\")))\n", " return v8::FunctionTemplate::New(GetNextObjectId);\n", " else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n", " return v8::FunctionTemplate::New(GetAbsolutePath);\n", " else if (name->Equals(v8::String::New(\"AllocateObject\")))\n", " return v8::FunctionTemplate::New(AllocateObject);\n", " else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 140}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_API_WINDOW_WINDOW_H_\n#define CONTENT_NW_SRC_API_WINDOW_WINDOW_H_\n\n#include \"base/compiler_specific.h\"\n#include \"content/nw/src/api/base/base.h\"\n\nnamespace content {\nclass Shell;\n}\n\nnamespace api {\n\nclass Window : public Base {\n public:\n Window(int id,\n DispatcherHost* dispatcher_host,\n const base::DictionaryValue& option);\n virtual ~Window();\n\n virtual void Call(const std::string& method,\n const base::ListValue& arguments) OVERRIDE;\n\n private:\n content::Shell* shell_;\n\n DISALLOW_COPY_AND_ASSIGN(Window);\n};\n\n} // namespace api\n\n#endif // CONTENT_NW_SRC_API_WINDOW_WINDOW_H_\n", "file_path": "src/api/window/window.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017714854038786143, 0.00017169746570289135, 0.00016528184642083943, 0.00017197828856296837, 3.878614279528847e-06]} {"hunk": {"id": 1, "code_window": [" return scope.Close(NwGui);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetNextObjectId(const v8::Arguments& args) {\n", " static int next_object_id = 1;\n", " return v8::Integer::New(next_object_id++);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar nwDispatcher = nwDispatcher || {};\n\n(function() {\n native function RequireNwGui();\n native function GetNextObjectId();\n native function GetAbsolutePath();\n\n native function AllocateObject();\n native function DeallocateObject();\n native function CallObjectMethod();\n native function CallObjectMethodSync();\n native function CallStaticMethod();\n native function CallStaticMethodSync();\n\n native function GetConstructorName();\n native function GetHiddenValue();\n native function SetHiddenValue();\n native function SetDestructor();\n\n nwDispatcher.requireNwGui = RequireNwGui;\n\n // Request a new object from browser\n nwDispatcher.allocateObject = function(object, option) {\n var id = GetNextObjectId();\n AllocateObject(id, GetConstructorName(object), option);\n\n // Store object id and make it readonly\n Object.defineProperty(object, 'id', {\n value: id,\n writable: false\n });\n\n // Deallcoate on destroy\n object.setDestructor(nwDispatcher.deallocateObject);\n\n // Store id to object relations, there is no delete in deallocateObject\n // since this is a weak map.\n global.__nwObjectsRegistry.set(id, object);\n }\n\n // Free a object in browser\n nwDispatcher.deallocateObject = function(object) {\n DeallocateObject(object.id);\n };\n\n // Call method of a object in browser.\n nwDispatcher.callObjectMethod = function(object, method, args) {\n CallObjectMethod(object.id, GetConstructorName(object), method, args);\n };\n\n // Call sync method of a object in browser and return results.\n nwDispatcher.callObjectMethodSync = function(object, method, args) {\n return CallObjectMethodSync(\n object.id, GetConstructorName(object), method, args);\n };\n\n // Call a static method.\n nwDispatcher.callStaticMethod = CallStaticMethod;\n\n // Call a sync method of static class in browse and return.\n nwDispatcher.callStaticMethodSync = CallStaticMethodSync;\n\n nwDispatcher.handleEvent = function(object_id, ev, args) {\n var object = global.__nwObjectsRegistry.get(object_id);\n args.splice(0, 0, ev);\n object.handleEvent.apply(object, args);\n }\n\n nwDispatcher.getAbsolutePath = GetAbsolutePath;\n nwDispatcher.getConstructorName = GetConstructorName;\n\n // Extended prototype of objects.\n nwDispatcher.getHiddenValue = GetHiddenValue;\n nwDispatcher.setHiddenValue = SetHiddenValue;\n nwDispatcher.setDestructor = SetDestructor;\n nwDispatcher.inherits = function(ctor, superCtor) {\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n})();\n", "file_path": "src/api/dispatcher_bindings.js", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.9977491497993469, 0.11086549609899521, 0.00016731290088500828, 0.00019513978622853756, 0.2864118814468384]} {"hunk": {"id": 1, "code_window": [" return scope.Close(NwGui);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetNextObjectId(const v8::Arguments& args) {\n", " static int next_object_id = 1;\n", " return v8::Integer::New(next_object_id++);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_SHELL_MAIN_DELEGATE_H_\n#define CONTENT_SHELL_SHELL_MAIN_DELEGATE_H_\n\n#include \"base/compiler_specific.h\"\n#include \"base/memory/scoped_ptr.h\"\n#include \"content/shell/shell_content_client.h\"\n#include \"content/public/app/content_main_delegate.h\"\n\nnamespace content {\nclass ShellContentBrowserClient;\nclass ShellContentRendererClient;\n\nclass ShellMainDelegate : public ContentMainDelegate {\n public:\n ShellMainDelegate();\n virtual ~ShellMainDelegate();\n\n // ContentMainDelegate implementation:\n virtual bool BasicStartupComplete(int* exit_code) OVERRIDE;\n virtual void PreSandboxStartup() OVERRIDE;\n virtual int RunProcess(\n const std::string& process_type,\n const MainFunctionParams& main_function_params) OVERRIDE;\n virtual ContentBrowserClient* CreateContentBrowserClient() OVERRIDE;\n virtual ContentRendererClient* CreateContentRendererClient() OVERRIDE;\n\n static void InitializeResourceBundle();\n\n private:\n scoped_ptr browser_client_;\n scoped_ptr renderer_client_;\n ShellContentClient content_client_;\n\n DISALLOW_COPY_AND_ASSIGN(ShellMainDelegate);\n};\n\n} // namespace content\n\n#endif // CONTENT_SHELL_SHELL_MAIN_DELEGATE_H_\n", "file_path": "src/shell_main_delegate.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017377015319652855, 0.00016890573897399008, 0.00016639030945952982, 0.0001676767278695479, 2.728705794652342e-06]} {"hunk": {"id": 1, "code_window": [" return scope.Close(NwGui);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetNextObjectId(const v8::Arguments& args) {\n", " static int next_object_id = 1;\n", " return v8::Integer::New(next_object_id++);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/renderer/shell_render_process_observer.h\"\n\n#include \"base/file_util.h\"\n#include \"content/public/renderer/render_thread.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/dispatcher_bindings.h\"\n#include \"webkit/glue/webkit_glue.h\"\n#include \"webkit/support/gc_extension.h\"\n#include \"third_party/node/src/node.h\"\n#include \"third_party/node/src/req_wrap.h\"\n#include \"v8/include/v8.h\"\n\nnamespace content {\n\nShellRenderProcessObserver::ShellRenderProcessObserver() {\n RenderThread::Get()->AddObserver(this);\n}\n\nShellRenderProcessObserver::~ShellRenderProcessObserver() {\n}\n\nbool ShellRenderProcessObserver::OnControlMessageReceived(\n const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(ShellRenderProcessObserver, message)\n IPC_MESSAGE_HANDLER(ShellViewMsg_Open, OnOpen)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid ShellRenderProcessObserver::OnRenderProcessWillShutdown() {\n // process.emit('exit');\n node::EmitExit(node::process);\n node::RunAtExit();\n}\n\nvoid ShellRenderProcessObserver::WebKitInitialized() {\n webkit_glue::SetJavaScriptFlags(\" --expose-gc\");\n RenderThread::Get()->RegisterExtension(extensions_v8::GCExtension::Get());\n RenderThread::Get()->RegisterExtension(new api::DispatcherBindings());\n}\n\nvoid ShellRenderProcessObserver::OnOpen(const std::string& path) {\n v8::HandleScope handle_scope;\n\n // the App object is stored in process[\"_nw_app\"].\n v8::Local process = node::g_context->Global()->Get(\n node::process_symbol)->ToObject();\n v8::Local app_symbol = v8::String::NewSymbol(\"_nw_app\");\n if (process->Has(app_symbol)) {\n // process[\"_nw_app\"].emit(path).\n v8::Local app = process->Get(app_symbol)->ToObject();\n v8::Local emit = v8::Local::Cast(\n app->Get(v8::String::New(\"emit\")));\n v8::Local argv[] = {\n v8::String::New(\"open\"), v8::String::New(path.c_str())\n };\n emit->Call(app, 2, argv);\n }\n}\n\n} // namespace content\n", "file_path": "src/renderer/shell_render_process_observer.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.004631625954061747, 0.0010612187907099724, 0.00016839067393448204, 0.0001736086851451546, 0.0016393143450841308]} {"hunk": {"id": 1, "code_window": [" return scope.Close(NwGui);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetNextObjectId(const v8::Arguments& args) {\n", " static int next_object_id = 1;\n", " return v8::Integer::New(next_object_id++);\n", "}\n", "\n", "// static\n", "v8::Handle\n", "DispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "{\n \"author\": {\n \"name\": \"Isaac Z. Schlueter\",\n \"email\": \"i@izs.me\",\n \"url\": \"http://blog.izs.me/\"\n },\n \"name\": \"block-stream\",\n \"description\": \"a stream of blocks\",\n \"version\": \"0.0.6\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/isaacs/block-stream.git\"\n },\n \"engines\": {\n \"node\": \"0.4 || >=0.5.8\"\n },\n \"main\": \"block-stream.js\",\n \"dependencies\": {\n \"inherits\": \"~1.0.0\"\n },\n \"devDependencies\": {\n \"tap\": \"0.x\"\n },\n \"scripts\": {\n \"test\": \"tap test/\"\n },\n \"license\": \"BSD\",\n \"readme\": \"# block-stream\\n\\nA stream of blocks.\\n\\nWrite data into it, and it'll output data in buffer blocks the size you\\nspecify, padding with zeroes if necessary.\\n\\n```javascript\\nvar block = new BlockStream(512)\\nfs.createReadStream(\\\"some-file\\\").pipe(block)\\nblock.pipe(fs.createWriteStream(\\\"block-file\\\"))\\n```\\n\\nWhen `.end()` or `.flush()` is called, it'll pad the block with zeroes.\\n\",\n \"_id\": \"block-stream@0.0.6\",\n \"_from\": \"block-stream@*\"\n}\n", "file_path": "tests/node/node_modules/tar/node_modules/block-stream/package.json", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017267081420868635, 0.00017064101120922714, 0.00016721131396479905, 0.0001713409583317116, 2.0541965568554588e-06]} {"hunk": {"id": 2, "code_window": [" private:\n", " // Helper functions for bindings.\n", " static v8::Handle RequireNwGui(const v8::Arguments& args);\n", " static v8::Handle GetIDWeakMapConstructor(\n", " const v8::Arguments& args);\n", " static v8::Handle GetNextObjectId(const v8::Arguments& args);\n", " static v8::Handle GetAbsolutePath(const v8::Arguments& args);\n", "\n", " // Extended prototype of objects.\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.h", "type": "replace", "edit_start_line_idx": 41}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_bindings.h\"\n\n#include \"base/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"base/command_line.h\"\n#include \"chrome/renderer/static_v8_external_string_resource.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/object_life_monitor.h\"\n#include \"content/public/renderer/render_view.h\"\n#include \"content/public/renderer/render_thread.h\"\n#include \"content/public/renderer/v8_value_converter.h\"\n#include \"grit/nw_resources.h\"\n#include \"third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h\"\n#include \"third_party/WebKit/Source/WebKit/chromium/public/WebView.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n\nusing content::RenderView;\nusing content::V8ValueConverter;\nusing WebKit::WebFrame;\nusing WebKit::WebView;\n\nnamespace api {\n\nnamespace {\n\nbase::StringPiece GetStringResource(int resource_id) {\n return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);\n}\n\nRenderView* GetCurrentRenderView() {\n WebFrame* frame = WebFrame::frameForCurrentContext();\n DCHECK(frame);\n if (!frame)\n return NULL;\n\n WebView* view = frame->view();\n if (!view)\n return NULL; // can happen during closing.\n\n RenderView* render_view = RenderView::FromWebView(view);\n DCHECK(render_view);\n return render_view;\n}\n\nv8::Handle WrapSource(v8::Handle source) {\n v8::HandleScope handle_scope;\n v8::Handle left =\n v8::String::New(\"(function(nw, exports) {\");\n v8::Handle right = v8::String::New(\"\\n})\");\n return handle_scope.Close(\n v8::String::Concat(left, v8::String::Concat(source, right)));\n}\n\n// Similar to node's `require` function, save functions in `exports`.\nvoid RequireFromResource(v8::Handle root,\n v8::Handle gui,\n v8::Handle name,\n int resource_id) {\n v8::HandleScope scope;\n\n v8::Handle source = v8::String::NewExternal(\n new StaticV8ExternalAsciiStringResource(\n GetStringResource(resource_id)));\n v8::Handle wrapped_source = WrapSource(source);\n\n v8::Handle script(v8::Script::New(wrapped_source, name));\n v8::Handle func = v8::Handle::Cast(script->Run());\n v8::Handle args[] = { root, gui };\n func->Call(root, 2, args);\n}\n\nbool MakePathAbsolute(FilePath* file_path) {\n DCHECK(file_path);\n\n FilePath current_directory;\n if (!file_util::GetCurrentDirectory(¤t_directory))\n return false;\n\n if (file_path->IsAbsolute())\n return true;\n\n if (current_directory.empty())\n return file_util::AbsolutePath(file_path);\n\n if (!current_directory.IsAbsolute())\n return false;\n\n *file_path = current_directory.Append(*file_path);\n return true;\n}\n\n} // namespace\n\nDispatcherBindings::DispatcherBindings()\n : v8::Extension(\"dispatcher_bindings.js\",\n GetStringResource(\n IDR_NW_API_DISPATCHER_BINDINGS_JS).data(),\n 0, // num dependencies.\n NULL, // dependencies array.\n GetStringResource(\n IDR_NW_API_DISPATCHER_BINDINGS_JS).size()) {\n}\n\nDispatcherBindings::~DispatcherBindings() {\n}\n\nv8::Handle\nDispatcherBindings::GetNativeFunction(v8::Handle name) {\n if (name->Equals(v8::String::New(\"RequireNwGui\")))\n return v8::FunctionTemplate::New(RequireNwGui);\n else if (name->Equals(v8::String::New(\"GetConstructorName\")))\n return v8::FunctionTemplate::New(GetConstructorName);\n else if (name->Equals(v8::String::New(\"GetHiddenValue\")))\n return v8::FunctionTemplate::New(GetHiddenValue);\n else if (name->Equals(v8::String::New(\"SetHiddenValue\")))\n return v8::FunctionTemplate::New(SetHiddenValue);\n else if (name->Equals(v8::String::New(\"SetDestructor\")))\n return v8::FunctionTemplate::New(SetDestructor);\n else if (name->Equals(v8::String::New(\"GetNextObjectId\")))\n return v8::FunctionTemplate::New(GetNextObjectId);\n else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n return v8::FunctionTemplate::New(GetAbsolutePath);\n else if (name->Equals(v8::String::New(\"AllocateObject\")))\n return v8::FunctionTemplate::New(AllocateObject);\n else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n return v8::FunctionTemplate::New(DeallocateObject);\n else if (name->Equals(v8::String::New(\"CallObjectMethod\")))\n return v8::FunctionTemplate::New(CallObjectMethod);\n else if (name->Equals(v8::String::New(\"CallObjectMethodSync\")))\n return v8::FunctionTemplate::New(CallObjectMethodSync);\n else if (name->Equals(v8::String::New(\"CallStaticMethod\")))\n return v8::FunctionTemplate::New(CallStaticMethod);\n else if (name->Equals(v8::String::New(\"CallStaticMethodSync\")))\n return v8::FunctionTemplate::New(CallStaticMethodSync);\n\n NOTREACHED() << \"Trying to get an non-exist function in DispatcherBindings:\"\n << *v8::String::Utf8Value(name);\n return v8::FunctionTemplate::New();\n}\n\n// static\nv8::Handle\nDispatcherBindings::RequireNwGui(const v8::Arguments& args) {\n v8::HandleScope scope;\n\n // Initialize lazily\n v8::Local NwGuiSymbol = v8::String::NewSymbol(\"nwGui\");\n v8::Local NwGuiHidden = args.This()->Get(NwGuiSymbol);\n if (NwGuiHidden->IsObject())\n return scope.Close(NwGuiHidden);\n\n v8::Local NwGui = v8::Object::New();\n args.This()->Set(NwGuiSymbol, NwGui);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"base.js\"), IDR_NW_API_BASE_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"menuitem.js\"), IDR_NW_API_MENUITEM_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"menu.js\"), IDR_NW_API_MENU_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"tray.js\"), IDR_NW_API_TRAY_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"clipboard.js\"), IDR_NW_API_CLIPBOARD_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"window.js\"), IDR_NW_API_WINDOW_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"shell.js\"), IDR_NW_API_SHELL_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"app.js\"), IDR_NW_API_APP_JS);\n\n return scope.Close(NwGui);\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetNextObjectId(const v8::Arguments& args) {\n static int next_object_id = 1;\n return v8::Integer::New(next_object_id++);\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n FilePath path = FilePath::FromUTF8Unsafe(*v8::String::Utf8Value(args[0]));\n MakePathAbsolute(&path);\n#if defined(OS_POSIX)\n return v8::String::New(path.value().c_str());\n#else\n return v8::String::New(path.AsUTF8Unsafe().c_str());\n#endif\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetHiddenValue(const v8::Arguments& args) {\n return args.This()->GetHiddenValue(args[0]->ToString());\n}\n\n// static\nv8::Handle\nDispatcherBindings::SetHiddenValue(const v8::Arguments& args) {\n args.This()->SetHiddenValue(args[0]->ToString(), args[1]);\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetConstructorName(const v8::Arguments& args) {\n if (args.Length() < 1 || !args[0]->IsObject())\n return v8::Undefined();\n\n return args[0]->ToObject()->GetConstructorName();\n}\n\n// static\nv8::Handle\nDispatcherBindings::SetDestructor(const v8::Arguments& args) {\n ObjectLifeMonitor::BindTo(args.This(), args[0]);\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::AllocateObject(const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"AllocateObject requries 3 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n std::string name = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n converter->SetStripNullFromObjects(true);\n\n scoped_ptr value_option(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_option.get() ||\n !value_option->IsType(base::Value::TYPE_DICTIONARY)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'option' passed to AllocateObject\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in AllocateObject\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Allocate_Object(\n render_view->GetRoutingID(),\n object_id,\n name,\n *static_cast(value_option.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::DeallocateObject(const v8::Arguments& args) {\n if (args.Length() < 1) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"DeallocateObject requries 1 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in DeallocateObject\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Deallocate_Object(\n render_view->GetRoutingID(), object_id));\n return v8::Undefined();\n}\n\n// static\nv8::Handle\nDispatcherBindings::CallObjectMethod(const v8::Arguments& args) {\n if (args.Length() < 4) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallObjectMethod requries 4 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n std::string type = *v8::String::Utf8Value(args[1]);\n std::string method = *v8::String::Utf8Value(args[2]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[3], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallObjectMethod\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallObjectMethod\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Call_Object_Method(\n render_view->GetRoutingID(),\n object_id,\n type,\n method,\n *static_cast(value_args.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle DispatcherBindings::CallObjectMethodSync(\n const v8::Arguments& args) {\n if (args.Length() < 4) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallObjectMethodSync requries 4 arguments\")));\n }\n\n int object_id = args[0]->Int32Value();\n std::string type = *v8::String::Utf8Value(args[1]);\n std::string method = *v8::String::Utf8Value(args[2]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[3], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallObjectMethodSync\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallObjectMethodSync\")));\n }\n\n base::ListValue result;\n render_view->Send(new ShellViewHostMsg_Call_Object_Method_Sync(\n MSG_ROUTING_NONE,\n object_id,\n type,\n method,\n *static_cast(value_args.get()),\n &result));\n return converter->ToV8Value(&result, v8::Context::GetCurrent());\n}\n\n// static\nv8::Handle DispatcherBindings::CallStaticMethod(\n const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallStaticMethod requries 3 arguments\")));\n }\n\n std::string type = *v8::String::Utf8Value(args[0]);\n std::string method = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallStaticMethod\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethod\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Call_Static_Method(\n render_view->GetRoutingID(),\n type,\n method,\n *static_cast(value_args.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle DispatcherBindings::CallStaticMethodSync(\n const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallStaticMethodSync requries 3 arguments\")));\n }\n\n std::string type = *v8::String::Utf8Value(args[0]);\n std::string method = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallStaticMethodSync\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethodSync\")));\n }\n\n base::ListValue result;\n render_view->Send(new ShellViewHostMsg_Call_Static_Method_Sync(\n MSG_ROUTING_NONE,\n type,\n method,\n *static_cast(value_args.get()),\n &result));\n return converter->ToV8Value(&result, v8::Context::GetCurrent());\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_bindings.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.9992714524269104, 0.13336530327796936, 0.00016642204718664289, 0.0008014346240088344, 0.3333330452442169]} {"hunk": {"id": 2, "code_window": [" private:\n", " // Helper functions for bindings.\n", " static v8::Handle RequireNwGui(const v8::Arguments& args);\n", " static v8::Handle GetIDWeakMapConstructor(\n", " const v8::Arguments& args);\n", " static v8::Handle GetNextObjectId(const v8::Arguments& args);\n", " static v8::Handle GetAbsolutePath(const v8::Arguments& args);\n", "\n", " // Extended prototype of objects.\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.h", "type": "replace", "edit_start_line_idx": 41}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/media/media_stream_devices_controller.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n\n#include \n\nnamespace {\n\n// A predicate that checks if a StreamDeviceInfo object has the same ID as the\n// device ID specified at construction.\nclass DeviceIdEquals {\n public:\n explicit DeviceIdEquals(const std::string& device_id)\n : device_id_(device_id) {\n }\n\n bool operator() (const content::MediaStreamDevice& device) {\n return device.device_id == device_id_;\n }\n\n private:\n std::string device_id_;\n};\n\n// A predicate that checks if a StreamDeviceInfo object has the same device\n// name as the device name specified at construction.\nclass DeviceNameEquals {\n public:\n explicit DeviceNameEquals(const std::string& device_name)\n : device_name_(device_name) {\n }\n\n bool operator() (const content::MediaStreamDevice& device) {\n return device.name == device_name_;\n }\n\n private:\n std::string device_name_;\n};\n\n// Whether |request| contains any device of given |type|.\nbool HasDevice(const content::MediaStreamRequest& request,\n content::MediaStreamDeviceType type) {\n content::MediaStreamDeviceMap::const_iterator device_it =\n request.devices.find(type);\n return device_it != request.devices.end() && !device_it->second.empty();\n}\n\nconst char kAudioKey[] = \"audio\";\nconst char kVideoKey[] = \"video\";\n\n} // namespace\n\nMediaStreamDevicesController::MediaStreamDevicesController(\n const content::MediaStreamRequest* request,\n const content::MediaResponseCallback& callback)\n : request_(*request),\n callback_(callback) {\n for (content::MediaStreamDeviceMap::const_iterator it =\n request_.devices.begin();\n it != request_.devices.end(); ++it) {\n if (content::IsAudioMediaType(it->first)) {\n has_audio_ |= !it->second.empty();\n } else if (content::IsVideoMediaType(it->first)) {\n has_video_ |= !it->second.empty();\n }\n }\n}\n\nMediaStreamDevicesController::~MediaStreamDevicesController() {}\n\nbool MediaStreamDevicesController::DismissInfoBarAndTakeActionOnSettings() {\n // Deny the request and don't show the infobar if there is no devices.\n if (!has_audio_ && !has_video_) {\n Deny();\n return true;\n }\n\n std::string audio, video;\n GetAlwaysAllowedDevices(&audio, &video);\n Accept(audio, video, true);\n return true;\n}\n\nvoid MediaStreamDevicesController::Accept(const std::string& audio_id,\n const std::string& video_id,\n bool always_allow) {\n content::MediaStreamDevices devices;\n std::string audio_device, video_device;\n if (has_audio_) {\n AddDeviceWithId(content::MEDIA_DEVICE_AUDIO_CAPTURE,\n audio_id, &devices, &audio_device);\n }\n if (has_video_) {\n AddDeviceWithId(content::MEDIA_DEVICE_VIDEO_CAPTURE,\n video_id, &devices, &video_device);\n }\n DCHECK(!devices.empty());\n\n callback_.Run(devices);\n}\n\nvoid MediaStreamDevicesController::Deny() {\n callback_.Run(content::MediaStreamDevices());\n}\n\nvoid MediaStreamDevicesController::AddDeviceWithId(\n content::MediaStreamDeviceType type,\n const std::string& id,\n content::MediaStreamDevices* devices,\n std::string* device_name) {\n DCHECK(devices);\n content::MediaStreamDeviceMap::const_iterator device_it =\n request_.devices.find(type);\n if (device_it == request_.devices.end())\n return;\n\n content::MediaStreamDevices::const_iterator it = std::find_if(\n device_it->second.begin(), device_it->second.end(), DeviceIdEquals(id));\n if (it == device_it->second.end())\n return;\n\n devices->push_back(*it);\n *device_name = it->name;\n}\n\nvoid MediaStreamDevicesController::GetAlwaysAllowedDevices(\n std::string* audio_id, std::string* video_id) {\n DCHECK(audio_id->empty());\n DCHECK(video_id->empty());\n if (has_audio_) {\n *audio_id =\n GetFirstDeviceId(content::MEDIA_DEVICE_AUDIO_CAPTURE);\n }\n if (has_video_) {\n *video_id =\n GetFirstDeviceId(content::MEDIA_DEVICE_VIDEO_CAPTURE);\n }\n}\n\nstd::string MediaStreamDevicesController::GetDeviceIdByName(\n content::MediaStreamDeviceType type,\n const std::string& name) {\n content::MediaStreamDeviceMap::const_iterator device_it =\n request_.devices.find(type);\n if (device_it != request_.devices.end()) {\n content::MediaStreamDevices::const_iterator it = std::find_if(\n device_it->second.begin(), device_it->second.end(),\n DeviceNameEquals(name));\n if (it != device_it->second.end())\n return it->device_id;\n }\n\n // Device is not available, return an empty string.\n return std::string();\n}\n\nstd::string MediaStreamDevicesController::GetFirstDeviceId(\n content::MediaStreamDeviceType type) {\n content::MediaStreamDeviceMap::const_iterator device_it =\n request_.devices.find(type);\n if (device_it != request_.devices.end())\n return device_it->second.begin()->device_id;\n\n return std::string();\n}\n", "file_path": "src/media/media_stream_devices_controller.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00018533278489485383, 0.0001713686651783064, 0.00016458594473078847, 0.0001713145466055721, 4.812641236640047e-06]} {"hunk": {"id": 2, "code_window": [" private:\n", " // Helper functions for bindings.\n", " static v8::Handle RequireNwGui(const v8::Arguments& args);\n", " static v8::Handle GetIDWeakMapConstructor(\n", " const v8::Arguments& args);\n", " static v8::Handle GetNextObjectId(const v8::Arguments& args);\n", " static v8::Handle GetAbsolutePath(const v8::Arguments& args);\n", "\n", " // Extended prototype of objects.\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.h", "type": "replace", "edit_start_line_idx": 41}, "file": "var common = require('../common');\nvar assert = common.assert;\nvar fake = common.fake.create();\nvar DelayedStream = common.DelayedStream;\nvar Stream = require('stream').Stream;\n\n(function testMaxDataSize() {\n var source = new Stream();\n var delayedStream = DelayedStream.create(source, {maxDataSize: 1024, pauseStream: false});\n\n source.emit('data', new Buffer(1024));\n\n fake\n .expect(delayedStream, 'emit')\n .withArg(1, 'error');\n source.emit('data', new Buffer(1));\n fake.verify();\n})();\n", "file_path": "tests/node/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-max-data-size.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.0001790467358659953, 0.00017547354218550026, 0.00017190034850500524, 0.00017547354218550026, 3.5731936804950237e-06]} {"hunk": {"id": 2, "code_window": [" private:\n", " // Helper functions for bindings.\n", " static v8::Handle RequireNwGui(const v8::Arguments& args);\n", " static v8::Handle GetIDWeakMapConstructor(\n", " const v8::Arguments& args);\n", " static v8::Handle GetNextObjectId(const v8::Arguments& args);\n", " static v8::Handle GetAbsolutePath(const v8::Arguments& args);\n", "\n", " // Extended prototype of objects.\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.h", "type": "replace", "edit_start_line_idx": 41}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/menu/menu.h\"\n\n#include \"base/values.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/nw_shell.h\"\n\nnamespace api {\n\nMenu::Menu(int id,\n DispatcherHost* dispatcher_host,\n const base::DictionaryValue& option)\n : Base(id, dispatcher_host, option) {\n Create(option);\n}\n\nMenu::~Menu() {\n Destroy();\n}\n\nvoid Menu::Call(const std::string& method,\n const base::ListValue& arguments) {\n if (method == \"Append\") {\n int object_id = 0;\n arguments.GetInteger(0, &object_id);\n Append(dispatcher_host()->GetObject(object_id));\n } else if (method == \"Insert\") {\n int object_id = 0;\n arguments.GetInteger(0, &object_id);\n int pos = 0;\n arguments.GetInteger(1, &pos);\n Insert(dispatcher_host()->GetObject(object_id), pos);\n } else if (method == \"Remove\") {\n int object_id = 0;\n arguments.GetInteger(0, &object_id);\n int pos = 0;\n arguments.GetInteger(1, &pos);\n Remove(dispatcher_host()->GetObject(object_id), pos);\n } else if (method == \"Popup\") {\n int x = 0;\n arguments.GetInteger(0, &x);\n int y = 0;\n arguments.GetInteger(1, &y);\n Popup(x, y, content::Shell::FromRenderViewHost(\n dispatcher_host()->render_view_host()));\n } else {\n NOTREACHED() << \"Invalid call to Menu method:\" << method\n << \" arguments:\" << arguments;\n }\n}\n\n} // namespace api\n", "file_path": "src/api/menu/menu.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00020347858662717044, 0.0001763711334206164, 0.0001665931922616437, 0.00017340996419079602, 1.0698665391828399e-05]} {"hunk": {"id": 3, "code_window": ["\n", "(function() {\n", " native function RequireNwGui();\n", " native function GetNextObjectId();\n", " native function GetAbsolutePath();\n", "\n", " native function AllocateObject();\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar nwDispatcher = nwDispatcher || {};\n\n(function() {\n native function RequireNwGui();\n native function GetNextObjectId();\n native function GetAbsolutePath();\n\n native function AllocateObject();\n native function DeallocateObject();\n native function CallObjectMethod();\n native function CallObjectMethodSync();\n native function CallStaticMethod();\n native function CallStaticMethodSync();\n\n native function GetConstructorName();\n native function GetHiddenValue();\n native function SetHiddenValue();\n native function SetDestructor();\n\n nwDispatcher.requireNwGui = RequireNwGui;\n\n // Request a new object from browser\n nwDispatcher.allocateObject = function(object, option) {\n var id = GetNextObjectId();\n AllocateObject(id, GetConstructorName(object), option);\n\n // Store object id and make it readonly\n Object.defineProperty(object, 'id', {\n value: id,\n writable: false\n });\n\n // Deallcoate on destroy\n object.setDestructor(nwDispatcher.deallocateObject);\n\n // Store id to object relations, there is no delete in deallocateObject\n // since this is a weak map.\n global.__nwObjectsRegistry.set(id, object);\n }\n\n // Free a object in browser\n nwDispatcher.deallocateObject = function(object) {\n DeallocateObject(object.id);\n };\n\n // Call method of a object in browser.\n nwDispatcher.callObjectMethod = function(object, method, args) {\n CallObjectMethod(object.id, GetConstructorName(object), method, args);\n };\n\n // Call sync method of a object in browser and return results.\n nwDispatcher.callObjectMethodSync = function(object, method, args) {\n return CallObjectMethodSync(\n object.id, GetConstructorName(object), method, args);\n };\n\n // Call a static method.\n nwDispatcher.callStaticMethod = CallStaticMethod;\n\n // Call a sync method of static class in browse and return.\n nwDispatcher.callStaticMethodSync = CallStaticMethodSync;\n\n nwDispatcher.handleEvent = function(object_id, ev, args) {\n var object = global.__nwObjectsRegistry.get(object_id);\n args.splice(0, 0, ev);\n object.handleEvent.apply(object, args);\n }\n\n nwDispatcher.getAbsolutePath = GetAbsolutePath;\n nwDispatcher.getConstructorName = GetConstructorName;\n\n // Extended prototype of objects.\n nwDispatcher.getHiddenValue = GetHiddenValue;\n nwDispatcher.setHiddenValue = SetHiddenValue;\n nwDispatcher.setDestructor = SetDestructor;\n nwDispatcher.inherits = function(ctor, superCtor) {\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n})();\n", "file_path": "src/api/dispatcher_bindings.js", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.9992812275886536, 0.5377919673919678, 0.00016853990382514894, 0.9208720922470093, 0.49123603105545044]} {"hunk": {"id": 3, "code_window": ["\n", "(function() {\n", " native function RequireNwGui();\n", " native function GetNextObjectId();\n", " native function GetAbsolutePath();\n", "\n", " native function AllocateObject();\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_MEDIA_MEDIA_STREAM_DEVICES_CONTROLLER_H_\n#define CONTENT_NW_SRC_MEDIA_MEDIA_STREAM_DEVICES_CONTROLLER_H_\n\n#include \n\n#include \"content/public/browser/web_contents_delegate.h\"\n\nclass GURL;\n\nclass MediaStreamDevicesController {\n public:\n // TODO(xians): Use const content::MediaStreamRequest& instead of *.\n MediaStreamDevicesController(const content::MediaStreamRequest* request,\n const content::MediaResponseCallback& callback);\n\n virtual ~MediaStreamDevicesController();\n\n // Public method to be called before creating the MediaStreamInfoBarDelegate.\n // This function will check the content settings exceptions and take the\n // corresponding action on exception which matches the request.\n bool DismissInfoBarAndTakeActionOnSettings();\n\n // Public methods to be called by MediaStreamInfoBarDelegate;\n bool has_audio() const { return has_audio_; }\n bool has_video() const { return has_video_; }\n void Accept(const std::string& audio_id,\n const std::string& video_id,\n bool always_allow);\n void Deny();\n\n private:\n // Used by the various helper methods below to filter an operation on devices\n // of a particular type.\n typedef bool (*FilterByDeviceTypeFunc)(content::MediaStreamDeviceType);\n\n // Finds a device in the current request with the specified |id| and |type|,\n // adds it to the |devices| array and also return the name of the device.\n void AddDeviceWithId(content::MediaStreamDeviceType type,\n const std::string& id,\n content::MediaStreamDevices* devices,\n std::string* device_name);\n\n // Gets the respective \"always allowed\" devices for the origin in |request_|.\n // |audio_id| and |video_id| will be empty if there is no \"always allowed\"\n // device for the origin, or any of the devices is not listed on the devices\n // list in |request_|.\n void GetAlwaysAllowedDevices(std::string* audio_id,\n std::string* video_id);\n\n std::string GetDeviceIdByName(content::MediaStreamDeviceType type,\n const std::string& name);\n\n std::string GetFirstDeviceId(content::MediaStreamDeviceType type);\n\n bool has_audio_;\n bool has_video_;\n\n // The original request for access to devices.\n const content::MediaStreamRequest request_;\n\n // The callback that needs to be Run to notify WebRTC of whether access to\n // audio/video devices was granted or not.\n content::MediaResponseCallback callback_;\n DISALLOW_COPY_AND_ASSIGN(MediaStreamDevicesController);\n};\n\n#endif // CONTENT_NW_SRC_MEDIA_MEDIA_STREAM_DEVICES_CONTROLLER_H_\n", "file_path": "src/media/media_stream_devices_controller.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.001536575728096068, 0.000357509998138994, 0.00016626311116851866, 0.0001721061853459105, 0.00042751646833494306]} {"hunk": {"id": 3, "code_window": ["\n", "(function() {\n", " native function RequireNwGui();\n", " native function GetNextObjectId();\n", " native function GetAbsolutePath();\n", "\n", " native function AllocateObject();\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 24}, "file": "var common = module.exports;\n\nvar path = require('path');\nvar root = path.join(__dirname, '..');\n\ncommon.dir = {\n fixture: root + '/test/fixture',\n tmp: root + '/test/tmp',\n};\n\ncommon.CombinedStream = require(root);\ncommon.assert = require('assert');\n", "file_path": "tests/node/node_modules/request/node_modules/form-data/node_modules/combined-stream/test/common.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00016958400374278426, 0.0001686399627942592, 0.0001676959072938189, 0.0001686399627942592, 9.440482244826853e-07]} {"hunk": {"id": 3, "code_window": ["\n", "(function() {\n", " native function RequireNwGui();\n", " native function GetNextObjectId();\n", " native function GetAbsolutePath();\n", "\n", " native function AllocateObject();\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_API_DISPATCHER_HOST_H_\n#define CONTENT_NW_SRC_API_DISPATCHER_HOST_H_\n\n#include \"base/basictypes.h\"\n#include \"base/id_map.h\"\n#include \"content/public/browser/render_view_host_observer.h\"\n\n#include \n\nnamespace base {\nclass DictionaryValue;\nclass ListValue;\n}\n\nnamespace WebKit {\nclass WebFrame;\n}\n\nnamespace api {\n\nclass Base;\n\nclass DispatcherHost : public content::RenderViewHostObserver {\n public:\n explicit DispatcherHost(content::RenderViewHost* render_view_host);\n virtual ~DispatcherHost();\n\n // Get C++ object from its id.\n Base* GetObject(int id);\n\n // Helper function to convert type.\n template\n T* GetObject(int id) {\n return static_cast(GetObject(id));\n }\n\n // Send event to C++ object's corresponding js object.\n void SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments);\n\n virtual bool Send(IPC::Message* message) OVERRIDE;\n content::RenderViewHost* render_view_host() const {\n return content::RenderViewHostObserver::render_view_host();\n }\n\n private:\n IDMap objects_registry_;\n\n // RenderViewHostObserver implementation.\n virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;\n\n void OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option);\n void OnDeallocateObject(int object_id);\n void OnCallObjectMethod(int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments);\n void OnCallObjectMethodSync(int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result);\n void OnCallStaticMethod(const std::string& type,\n const std::string& method,\n const base::ListValue& arguments);\n void OnCallStaticMethodSync(const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result);\n void OnUncaughtException(const std::string& err);\n\n DISALLOW_COPY_AND_ASSIGN(DispatcherHost);\n};\n\n} // namespace api\n\n#endif // CONTENT_NW_SRC_API_DISPATCHER_HOST_H_\n", "file_path": "src/api/dispatcher_host.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.023390380665659904, 0.002317093312740326, 0.00016876969311852008, 0.00017446013225708157, 0.006664276123046875]} {"hunk": {"id": 4, "code_window": [" nwDispatcher.requireNwGui = RequireNwGui;\n", "\n", " // Request a new object from browser\n", " nwDispatcher.allocateObject = function(object, option) {\n", " var id = GetNextObjectId();\n", " AllocateObject(id, GetConstructorName(object), option);\n", "\n", " // Store object id and make it readonly\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var id = global.__nwObjectsRegistry.allocateId();\n"], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 43}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_API_DISPATCHER_BINDINGS_H_\n#define CONTENT_NW_SRC_API_DISPATCHER_BINDINGS_H_\n\n#include \"base/basictypes.h\"\n#include \"base/compiler_specific.h\"\n#include \"v8/include/v8.h\"\n\nnamespace api {\n\nclass DispatcherBindings : public v8::Extension {\n public:\n DispatcherBindings();\n virtual ~DispatcherBindings();\n\n // v8::Extension implementation.\n virtual v8::Handle\n GetNativeFunction(v8::Handle name) OVERRIDE;\n\n private:\n // Helper functions for bindings.\n static v8::Handle RequireNwGui(const v8::Arguments& args);\n static v8::Handle GetIDWeakMapConstructor(\n const v8::Arguments& args);\n static v8::Handle GetNextObjectId(const v8::Arguments& args);\n static v8::Handle GetAbsolutePath(const v8::Arguments& args);\n\n // Extended prototype of objects.\n static v8::Handle GetHiddenValue(const v8::Arguments& args);\n static v8::Handle SetHiddenValue(const v8::Arguments& args);\n static v8::Handle GetConstructorName(const v8::Arguments& args);\n static v8::Handle SetDestructor(const v8::Arguments& args);\n\n // Remote objects.\n static v8::Handle AllocateObject(const v8::Arguments& args);\n static v8::Handle DeallocateObject(const v8::Arguments& args);\n static v8::Handle CallObjectMethod(const v8::Arguments& args);\n static v8::Handle CallObjectMethodSync(const v8::Arguments& args);\n static v8::Handle CallStaticMethod(const v8::Arguments& args);\n static v8::Handle CallStaticMethodSync(const v8::Arguments& args);\n\n DISALLOW_COPY_AND_ASSIGN(DispatcherBindings);\n};\n\n} // namespace api\n\n#endif // CONTENT_NW_SRC_API_DISPATCHER_BINDINGS_H_\n", "file_path": "src/api/dispatcher_bindings.h", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.002250856487080455, 0.0006439160206355155, 0.00016503002552781254, 0.00017775548622012138, 0.0007663634605705738]} {"hunk": {"id": 4, "code_window": [" nwDispatcher.requireNwGui = RequireNwGui;\n", "\n", " // Request a new object from browser\n", " nwDispatcher.allocateObject = function(object, option) {\n", " var id = GetNextObjectId();\n", " AllocateObject(id, GetConstructorName(object), option);\n", "\n", " // Store object id and make it readonly\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var id = global.__nwObjectsRegistry.allocateId();\n"], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 43}, "file": "{\n \"author\": {\n \"name\": \"Felix Geisendörfer\",\n \"email\": \"felix@debuggable.com\",\n \"url\": \"http://debuggable.com/\"\n },\n \"name\": \"form-data\",\n \"description\": \"A module to create readable `\\\"multipart/form-data\\\"` streams. Can be used to submit forms and file uploads to other web applications.\",\n \"version\": \"0.0.3\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/felixge/node-form-data.git\"\n },\n \"main\": \"./lib/form_data\",\n \"engines\": {\n \"node\": \"*\"\n },\n \"dependencies\": {\n \"combined-stream\": \"0.0.3\",\n \"mime\": \"~1.2.2\",\n \"async\": \"~0.1.9\"\n },\n \"devDependencies\": {\n \"fake\": \"0.2.1\",\n \"far\": \"0.0.1\",\n \"formidable\": \"1.0.2\",\n \"request\": \"~2.9.203\"\n },\n \"_npmUser\": {\n \"name\": \"mikeal\",\n \"email\": \"mikeal.rogers@gmail.com\"\n },\n \"_id\": \"form-data@0.0.3\",\n \"optionalDependencies\": {},\n \"_engineSupported\": true,\n \"_npmVersion\": \"1.1.24\",\n \"_nodeVersion\": \"v0.8.1\",\n \"_defaultsLoaded\": true,\n \"dist\": {\n \"shasum\": \"6eea17b45790b42d779a1d581d1b3600fe0c7c0d\"\n },\n \"_from\": \"form-data\"\n}\n", "file_path": "tests/node/node_modules/request/node_modules/form-data/package.json", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017709366511553526, 0.0001761275780154392, 0.00017492387269157916, 0.0001764477783581242, 8.277683605228958e-07]} {"hunk": {"id": 4, "code_window": [" nwDispatcher.requireNwGui = RequireNwGui;\n", "\n", " // Request a new object from browser\n", " nwDispatcher.allocateObject = function(object, option) {\n", " var id = GetNextObjectId();\n", " AllocateObject(id, GetConstructorName(object), option);\n", "\n", " // Store object id and make it readonly\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var id = global.__nwObjectsRegistry.allocateId();\n"], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 43}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/media/media_internals.h\"\n\n#include \"base/memory/scoped_ptr.h\"\n#include \"base/string16.h\"\n#include \"base/stringprintf.h\"\n#include \"media/base/media_log.h\"\n#include \"media/base/media_log_event.h\"\n\nMediaInternals* MediaInternals::GetInstance() {\n return Singleton::get();\n}\n\nMediaInternals::~MediaInternals() {}\n\nvoid MediaInternals::OnDeleteAudioStream(void* host, int stream_id) {\n}\n\nvoid MediaInternals::OnSetAudioStreamPlaying(\n void* host, int stream_id, bool playing) {\n}\n\nvoid MediaInternals::OnSetAudioStreamStatus(\n void* host, int stream_id, const std::string& status) {\n}\n\nvoid MediaInternals::OnSetAudioStreamVolume(\n void* host, int stream_id, double volume) {\n}\n\nvoid MediaInternals::OnMediaEvent(\n int render_process_id, const media::MediaLogEvent& event) {\n}\n\nvoid MediaInternals::OnCaptureDevicesOpened(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) {\n}\n\nvoid MediaInternals::OnCaptureDevicesClosed(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevices& devices) {\n}\n\nvoid MediaInternals::OnMediaRequestStateChanged(\n int render_process_id,\n int render_view_id,\n const content::MediaStreamDevice& device,\n content::MediaRequestState state) {\n}\n\nMediaInternals::MediaInternals() {}\n", "file_path": "src/media/media_internals.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017775548622012138, 0.00017358563491143286, 0.00016754167154431343, 0.0001742838358040899, 3.2245593502011616e-06]} {"hunk": {"id": 4, "code_window": [" nwDispatcher.requireNwGui = RequireNwGui;\n", "\n", " // Request a new object from browser\n", " nwDispatcher.allocateObject = function(object, option) {\n", " var id = GetNextObjectId();\n", " AllocateObject(id, GetConstructorName(object), option);\n", "\n", " // Store object id and make it readonly\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var id = global.__nwObjectsRegistry.allocateId();\n"], "file_path": "src/api/dispatcher_bindings.js", "type": "replace", "edit_start_line_idx": 43}, "file": "var common = require('../common');\nvar assert = common.assert;\nvar CombinedStream = common.CombinedStream;\nvar fs = require('fs');\n\nvar FILE1 = common.dir.fixture + '/file1.txt';\nvar FILE2 = common.dir.fixture + '/file2.txt';\nvar EXPECTED = fs.readFileSync(FILE1) + fs.readFileSync(FILE2);\n\n(function testDelayedStreams() {\n var combinedStream = CombinedStream.create({pauseStreams: false});\n combinedStream.append(fs.createReadStream(FILE1));\n combinedStream.append(fs.createReadStream(FILE2));\n\n var stream1 = combinedStream._streams[0];\n var stream2 = combinedStream._streams[1];\n\n stream1.on('end', function() {\n assert.ok(stream2.dataSize > 0);\n });\n\n var tmpFile = common.dir.tmp + '/combined.txt';\n var dest = fs.createWriteStream(tmpFile);\n combinedStream.pipe(dest);\n\n dest.on('end', function() {\n var written = fs.readFileSync(tmpFile, 'utf8');\n assert.strictEqual(written, EXPECTED);\n });\n})();\n", "file_path": "tests/node/node_modules/request/node_modules/form-data/node_modules/combined-stream/test/integration/test-unpaused-streams.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/ccd132aa6015604ed88c8988ca1a9ff0152b036f", "dependency_score": [0.00017801787180360407, 0.00017631842638365924, 0.00017369627312291414, 0.00017677978030405939, 1.6780197711341316e-06]} {"hunk": {"id": 0, "code_window": ["// Copyright (c) 2012 Intel Corp\n", "// Copyright (c) 2012 The Chromium Authors\n", "// \n", "// Permission is hereby granted, free of charge, to any person obtaining a copy \n", "// of this software and associated documentation files (the \"Software\"), to deal\n", "// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n"], "labels": ["keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n", "// Permission is hereby granted, free of charge, to any person obtaining a copy\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 2}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n#define CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n\n#include \n#include \n\n#include \"base/compiler_specific.h\"\n#include \"base/memory/scoped_ptr.h\"\n#include \"content/public/browser/content_browser_client.h\"\n#include \"content/public/browser/web_contents_view.h\"\n\nnamespace printing {\nclass PrintJobManager;\n}\n\nnamespace content {\n\nclass ShellBrowserContext;\nclass ShellBrowserMainParts;\nclass ShellResourceDispatcherHostDelegate;\n\nclass ShellContentBrowserClient : public ContentBrowserClient {\n public:\n ShellContentBrowserClient();\n virtual ~ShellContentBrowserClient();\n\n // ContentBrowserClient overrides.\n virtual BrowserMainParts* CreateBrowserMainParts(\n const MainFunctionParams& parameters) OVERRIDE;\n virtual void RenderViewHostCreated(\n RenderViewHost* render_view_host) OVERRIDE;\n virtual WebContentsViewPort* OverrideCreateWebContentsView(\n WebContents* web_contents,\n RenderViewHostDelegateView** render_view_host_delegate_view) OVERRIDE;\n virtual std::string GetApplicationLocale() OVERRIDE;\n virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,\n int child_process_id) OVERRIDE;\n virtual void ResourceDispatcherHostCreated() OVERRIDE;\n virtual AccessTokenStore* CreateAccessTokenStore() OVERRIDE;\n virtual void OverrideWebkitPrefs(\n RenderViewHost* render_view_host,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) OVERRIDE;\n virtual std::string GetDefaultDownloadName() OVERRIDE;\n virtual MediaObserver* GetMediaObserver() OVERRIDE;\n virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) OVERRIDE;\n virtual bool ShouldTryToUseExistingProcessHost(\n BrowserContext* browser_context, const GURL& url) OVERRIDE;\n virtual bool IsSuitableHost(RenderProcessHost* process_host,\n const GURL& site_url) OVERRIDE;\n ShellBrowserContext* browser_context();\n ShellBrowserContext* off_the_record_browser_context();\n ShellResourceDispatcherHostDelegate* resource_dispatcher_host_delegate() {\n return resource_dispatcher_host_delegate_.get();\n }\n ShellBrowserMainParts* shell_browser_main_parts() {\n return shell_browser_main_parts_;\n }\n virtual printing::PrintJobManager* print_job_manager();\n virtual void RenderProcessHostCreated(RenderProcessHost* host) OVERRIDE;\n virtual net::URLRequestContextGetter* CreateRequestContext(\n BrowserContext* browser_context,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) OVERRIDE;\n virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(\n BrowserContext* browser_context,\n const base::FilePath& partition_path,\n bool in_memory,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) OVERRIDE;\n\n private:\n ShellBrowserContext* ShellBrowserContextForBrowserContext(\n BrowserContext* content_browser_context);\n scoped_ptr\n resource_dispatcher_host_delegate_;\n\n ShellBrowserMainParts* shell_browser_main_parts_;\n};\n\n} // namespace content\n\n#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n", "file_path": "src/shell_content_browser_client.h", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017456282512284815, 0.00016956579929683357, 0.0001645714946789667, 0.00016978300118353218, 2.9596112653962336e-06]} {"hunk": {"id": 0, "code_window": ["// Copyright (c) 2012 Intel Corp\n", "// Copyright (c) 2012 The Chromium Authors\n", "// \n", "// Permission is hereby granted, free of charge, to any person obtaining a copy \n", "// of this software and associated documentation files (the \"Software\"), to deal\n", "// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n"], "labels": ["keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n", "// Permission is hereby granted, free of charge, to any person obtaining a copy\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 2}, "file": "function assert() {\n var str = '';\n str += ('' + arguments[arguments.length - 1] + ': ');\n\n var result = true;\n for (var i = 0; i < arguments.length - 1; ++i) {\n if (!arguments[i]) {\n result = false;\n str += ('FAILED');\n str += (' at condition ' + (i + 1) + ' ');\n }\n }\n\n if (result) {\n str = '
' + str + 'PASSED';\n } else {\n str = '
' + str;\n }\n\n str += '
';\n\n $(document.body).append(str);\n}\n\n", "file_path": "tests/assert.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017436417692806572, 0.0001704623136902228, 0.00016402553592342883, 0.00017299727187491953, 4.585580882121576e-06]} {"hunk": {"id": 0, "code_window": ["// Copyright (c) 2012 Intel Corp\n", "// Copyright (c) 2012 The Chromium Authors\n", "// \n", "// Permission is hereby granted, free of charge, to any person obtaining a copy \n", "// of this software and associated documentation files (the \"Software\"), to deal\n", "// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n"], "labels": ["keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n", "// Permission is hereby granted, free of charge, to any person obtaining a copy\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 2}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_NET_SHELL_NETWORK_DELEGATE_H_\n#define CONTENT_NW_SRC_NET_SHELL_NETWORK_DELEGATE_H_\n\n#include \"base/basictypes.h\"\n#include \"base/compiler_specific.h\"\n#include \"base/files/file_path.h\"\n#include \"net/base/network_delegate.h\"\n\nnamespace content {\n\nclass ShellNetworkDelegate : public net::NetworkDelegate {\n public:\n ShellNetworkDelegate();\n virtual ~ShellNetworkDelegate();\n\n private:\n // net::NetworkDelegate implementation.\n virtual int OnBeforeURLRequest(net::URLRequest* request,\n const net::CompletionCallback& callback,\n GURL* new_url) OVERRIDE;\n virtual int OnBeforeSendHeaders(net::URLRequest* request,\n const net::CompletionCallback& callback,\n net::HttpRequestHeaders* headers) OVERRIDE;\n virtual void OnSendHeaders(net::URLRequest* request,\n const net::HttpRequestHeaders& headers) OVERRIDE;\n virtual int OnHeadersReceived(\n net::URLRequest* request,\n const net::CompletionCallback& callback,\n const net::HttpResponseHeaders* original_response_headers,\n scoped_refptr*\n override_response_headers) OVERRIDE;\n virtual void OnBeforeRedirect(net::URLRequest* request,\n const GURL& new_location) OVERRIDE;\n virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE;\n virtual void OnRawBytesRead(const net::URLRequest& request,\n int bytes_read) OVERRIDE;\n virtual void OnCompleted(net::URLRequest* request, bool started) OVERRIDE;\n virtual void OnURLRequestDestroyed(net::URLRequest* request) OVERRIDE;\n virtual void OnPACScriptError(int line_number,\n const string16& error) OVERRIDE;\n virtual AuthRequiredResponse OnAuthRequired(\n net::URLRequest* request,\n const net::AuthChallengeInfo& auth_info,\n const AuthCallback& callback,\n net::AuthCredentials* credentials) OVERRIDE;\n virtual bool OnCanGetCookies(const net::URLRequest& request,\n const net::CookieList& cookie_list) OVERRIDE;\n virtual bool OnCanSetCookie(const net::URLRequest& request,\n const std::string& cookie_line,\n net::CookieOptions* options) OVERRIDE;\n virtual bool OnCanAccessFile(const net::URLRequest& request,\n const base::FilePath& path) const OVERRIDE;\n virtual bool OnCanThrottleRequest(\n const net::URLRequest& request) const OVERRIDE;\n virtual int OnBeforeSocketStreamConnect(\n net::SocketStream* stream,\n const net::CompletionCallback& callback) OVERRIDE;\n virtual void OnRequestWaitStateChange(const net::URLRequest& request,\n RequestWaitState state) OVERRIDE;\n\n DISALLOW_COPY_AND_ASSIGN(ShellNetworkDelegate);\n};\n\n} // namespace content\n\n#endif // CONTENT_NW_SRC_NET_SHELL_NETWORK_DELEGATE_H_\n", "file_path": "src/net/shell_network_delegate.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.10693904757499695, 0.012034534476697445, 0.0001605015859240666, 0.00016974400205072016, 0.03355381637811661]} {"hunk": {"id": 0, "code_window": ["// Copyright (c) 2012 Intel Corp\n", "// Copyright (c) 2012 The Chromium Authors\n", "// \n", "// Permission is hereby granted, free of charge, to any person obtaining a copy \n", "// of this software and associated documentation files (the \"Software\"), to deal\n", "// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n"], "labels": ["keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n", "// Permission is hereby granted, free of charge, to any person obtaining a copy\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 2}, "file": "\n\n \n 1060\n 11D50b\n 851\n 1138.32\n 568.00\n \n com.apple.InterfaceBuilder.CocoaPlugin\n 851\n \n \n YES\n \n \n \n YES\n com.apple.InterfaceBuilder.CocoaPlugin\n \n \n YES\n \n YES\n \n \n YES\n \n \n \n YES\n \n NSObject\n \n \n FirstResponder\n \n \n NSApplication\n \n \n \n 268\n \n YES\n \n \n 268\n {{99, 20}, {156, 22}}\n \n _NS:3407\n 2\n YES\n \n 343014976\n 272630848\n \n \n LucidaGrande\n 13\n 1040\n \n _NS:3407\n \n YES\n \n 6\n System\n textBackgroundColor\n \n 3\n MQA\n \n \n \n 6\n System\n textColor\n \n 3\n MAA\n \n \n \n YES\n NSAllRomanInputSourcesLocaleIdentifier\n \n \n \n \n \n 268\n {{99, 52}, {156, 22}}\n \n _NS:817\n 1\n YES\n \n -1804468671\n 272630784\n \n \n _NS:817\n \n YES\n \n \n \n \n \n \n 268\n {{17, 22}, {77, 17}}\n \n _NS:4068\n YES\n \n 68288064\n 71304192\n Password:\n \n _NS:4068\n \n \n 6\n System\n controlColor\n \n 3\n MC42NjY2NjY2NjY3AA\n \n \n \n 6\n System\n controlTextColor\n \n \n \n \n \n \n 268\n {{17, 54}, {77, 17}}\n \n _NS:4068\n YES\n \n 68288064\n 71304192\n Username:\n \n _NS:4068\n \n \n \n \n \n \n {275, 94}\n \n NSView\n \n \n \n \n YES\n \n \n \n YES\n \n 0\n \n \n \n \n \n -2\n \n \n File's Owner\n \n \n -1\n \n \n First Responder\n \n \n -3\n \n \n Application\n \n \n 1\n \n \n YES\n \n \n \n \n \n \n \n \n 2\n \n \n YES\n \n \n \n \n \n 3\n \n \n \n \n 4\n \n \n YES\n \n \n \n \n \n 5\n \n \n \n \n 6\n \n \n YES\n \n \n \n \n \n 7\n \n \n \n \n 8\n \n \n YES\n \n \n \n \n \n 9\n \n \n \n \n \n \n YES\n \n YES\n -1.IBPluginDependency\n -2.IBPluginDependency\n -3.IBPluginDependency\n 1.IBEditorWindowLastContentRect\n 1.IBPluginDependency\n 1.WindowOrigin\n 1.editorWindowContentRectSynchronizationRect\n 2.IBPluginDependency\n 2.IBViewBoundsToFrameTransform\n 3.IBPluginDependency\n 4.IBPluginDependency\n 4.IBViewBoundsToFrameTransform\n 5.IBPluginDependency\n 6.IBPluginDependency\n 6.IBViewBoundsToFrameTransform\n 7.IBPluginDependency\n 8.IBPluginDependency\n 8.IBViewBoundsToFrameTransform\n 9.IBPluginDependency\n \n \n YES\n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n {{969, 1048}, {275, 94}}\n com.apple.InterfaceBuilder.CocoaPlugin\n {628, 654}\n {{357, 416}, {480, 272}}\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABBiAAAwpAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABBiAAAwiAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABCxgAAwpAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABCxgAAwiAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n \n \n \n YES\n \n \n YES\n \n \n \n \n YES\n \n \n YES\n \n \n \n 9\n \n \n 0\n IBCocoaFramework\n \n com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3\n \n \n YES\n \n 3\n \n\n", "file_path": "src/mac/English.lproj/HttpAuth.xib", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017742121417541057, 0.00017406276310794055, 0.00016706039605196565, 0.0001744367618812248, 1.9691201487148646e-06]} {"hunk": {"id": 1, "code_window": ["// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n", "// to do so, subject to the following conditions:\n", "// \n", "// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 9}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_host.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"content/browser/web_contents/web_contents_impl.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/api/base/base.h\"\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/api/shell/shell.h\"\n#include \"content/nw/src/api/tray/tray.h\"\n#include \"content/nw/src/api/window/window.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/render_process_host.h\"\n\nusing content::WebContents;\nusing content::ShellBrowserContext;\n\nnamespace api {\n\nDispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)\n : content::RenderViewHostObserver(render_view_host) {\n}\n\nDispatcherHost::~DispatcherHost() {\n}\n\nBase* DispatcherHost::GetApiObject(int id) {\n return objects_registry_.Lookup(id); \n}\n\nvoid DispatcherHost::SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments) {\n Send(new ShellViewMsg_Object_On_Event(\n routing_id(), object->id(), event, arguments));\n}\n\nbool DispatcherHost::Send(IPC::Message* message) {\n return content::RenderViewHostObserver::Send(message);\n}\n\nbool DispatcherHost::OnMessageReceived(const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,\n OnCallObjectMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,\n OnCallStaticMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,\n OnUncaughtException);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DispatcherHost::OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option) {\n DVLOG(1) << \"OnAllocateObject: object_id:\" << object_id\n << \" type:\" << type\n << \" option:\" << option;\n\n if (type == \"Menu\") {\n objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);\n } else if (type == \"MenuItem\") {\n objects_registry_.AddWithID(\n new MenuItem(object_id, this, option), object_id);\n } else if (type == \"Tray\") {\n objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);\n } else if (type == \"Clipboard\") {\n objects_registry_.AddWithID(\n new Clipboard(object_id, this, option), object_id);\n } else if (type == \"Window\") {\n objects_registry_.AddWithID(new Window(object_id, this, option), object_id);\n } else {\n LOG(ERROR) << \"Allocate an object of unknow type: \" << type;\n objects_registry_.AddWithID(new Base(object_id, this, option), object_id);\n }\n}\n\nvoid DispatcherHost::OnDeallocateObject(int object_id) {\n DLOG(INFO) << \"OnDeallocateObject: object_id:\" << object_id;\n objects_registry_.Remove(object_id);\n}\n\nvoid DispatcherHost::OnCallObjectMethod(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallObjectMethod: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->Call(method, arguments);\n}\n\nvoid DispatcherHost::OnCallObjectMethodSync(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallObjectMethodSync: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->CallSync(method, arguments, result);\n}\n\nvoid DispatcherHost::OnCallStaticMethod(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallStaticMethod: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"Shell\") {\n api::Shell::Call(method, arguments);\n return;\n } else if (type == \"App\") {\n api::App::Call(method, arguments);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnCallStaticMethodSync(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallStaticMethodSync: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"App\") {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n api::App::Call(shell, method, arguments, result);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnUncaughtException(const std::string& err) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n}\n\nvoid DispatcherHost::OnGetShellId(int* id) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n *id = shell->id();\n}\n\nvoid DispatcherHost::OnCreateShell(const std::string& url,\n const base::DictionaryValue& manifest,\n int* routing_id) {\n WebContents* base_web_contents =\n content::Shell::FromRenderViewHost(render_view_host())->web_contents();\n ShellBrowserContext* browser_context =\n static_cast(base_web_contents->GetBrowserContext());\n scoped_ptr new_manifest(manifest.DeepCopy());\n bool new_renderer = false;\n if (new_manifest->GetBoolean(switches::kmNewInstance,\n &new_renderer) && new_renderer)\n browser_context->set_pinning_renderer(false);\n\n WebContents::CreateParams create_params(browser_context,\n new_renderer ? NULL : base_web_contents->GetSiteInstance());\n\n WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(\n create_params,\n static_cast(base_web_contents));\n new content::Shell(web_contents, new_manifest.get());\n web_contents->GetController().LoadURL(\n GURL(url),\n content::Referrer(),\n content::PAGE_TRANSITION_TYPED,\n std::string());\n\n if (new_renderer)\n browser_context->set_pinning_renderer(true);\n\n *routing_id = web_contents->GetRoutingID();\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_host.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0004785278288181871, 0.00019409635569900274, 0.0001634949294384569, 0.0001699095737421885, 7.07594517734833e-05]} {"hunk": {"id": 1, "code_window": ["// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n", "// to do so, subject to the following conditions:\n", "// \n", "// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 9}, "file": "import sys,os,re\n\nnw_version_h = os.path.join(os.path.dirname(__file__), '..', 'src',\n 'nw_version.h')\n\nf = open(nw_version_h)\n\n\nfor line in f:\n if re.match('#define NW_VERSION_IS_RELEASE', line):\n release = int(line.split()[2])\n #print release\n \n", "file_path": "tools/getnwisrelease.py", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00016773476090747863, 0.00016673840582370758, 0.0001657420361880213, 0.00016673840582370758, 9.963623597286642e-07]} {"hunk": {"id": 1, "code_window": ["// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n", "// to do so, subject to the following conditions:\n", "// \n", "// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 9}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n// Get basic type definitions.\n#define IPC_MESSAGE_IMPL\n#include \"content/nw/src/common/common_message_generator.h\"\n\n// Generate constructors.\n#include \"ipc/struct_constructor_macros.h\"\n#include \"content/nw/src/common/common_message_generator.h\"\n\n// Generate destructors.\n#include \"ipc/struct_destructor_macros.h\"\n#include \"content/nw/src/common/common_message_generator.h\"\n\n// Generate param traits write methods.\n#include \"ipc/param_traits_write_macros.h\"\nnamespace IPC {\n#include \"content/nw/src/common/common_message_generator.h\"\n} // namespace IPC\n\n// Generate param traits read methods.\n#include \"ipc/param_traits_read_macros.h\"\nnamespace IPC {\n#include \"content/nw/src/common/common_message_generator.h\"\n} // namespace IPC\n\n// Generate param traits log methods.\n#include \"ipc/param_traits_log_macros.h\"\nnamespace IPC {\n#include \"content/nw/src/common/common_message_generator.h\"\n} // namespace IPC\n", "file_path": "src/api/api_messages.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017452004249207675, 0.00017009042494464666, 0.00016523362137377262, 0.00017030403250828385, 3.3462672490713885e-06]} {"hunk": {"id": 1, "code_window": ["// in the Software without restriction, including without limitation the rights\n", "// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n", "// pies of the Software, and to permit persons to whom the Software is furnished\n", "// to do so, subject to the following conditions:\n", "// \n", "// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 9}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_client.h\"\n\n#include \"base/string_piece.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/renderer/common/render_messages.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n#include \"webkit/user_agent/user_agent_util.h\"\n\nnamespace content {\n\nShellContentClient::~ShellContentClient() {\n}\n\nstd::string ShellContentClient::GetUserAgent() const {\n return webkit_glue::BuildUserAgentFromProduct(\"Chrome/27.0.1430.0\");\n}\n\nstring16 ShellContentClient::GetLocalizedString(int message_id) const {\n return l10n_util::GetStringUTF16(message_id);\n}\n\nbase::StringPiece ShellContentClient::GetDataResource(\n int resource_id,\n ui::ScaleFactor scale_factor) const {\n return ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(\n resource_id, scale_factor);\n}\n\nbase::RefCountedStaticMemory* ShellContentClient::GetDataResourceBytes(\n int resource_id) const {\n return ResourceBundle::GetSharedInstance().LoadDataResourceBytes(resource_id);\n}\n\ngfx::Image& ShellContentClient::GetNativeImageNamed(int resource_id) const {\n return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);\n}\n\n// This is for message handling after the rvh is swapped out\n// FIXME: move dispatcher_host to WebContentsObserver\n\nbool ShellContentClient::CanHandleWhileSwappedOut(\n const IPC::Message& msg) {\n switch (msg.type()) {\n case ShellViewHostMsg_Allocate_Object::ID:\n case ShellViewHostMsg_Deallocate_Object::ID:\n case ShellViewHostMsg_Call_Object_Method::ID:\n case ShellViewHostMsg_Call_Object_Method_Sync::ID:\n case ShellViewHostMsg_Call_Static_Method::ID:\n case ShellViewHostMsg_Call_Static_Method_Sync::ID:\n case ShellViewHostMsg_UncaughtException::ID:\n case ShellViewHostMsg_GetShellId::ID:\n case ShellViewHostMsg_CreateShell::ID:\n return true;\n default:\n break;\n }\n return false;\n}\n\n} // namespace content\n", "file_path": "src/shell_content_client.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0003550324181560427, 0.0001927518896991387, 0.00016160434461198747, 0.00016809582302812487, 5.894478817936033e-05]} {"hunk": {"id": 2, "code_window": ["// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n", "// \n", "// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n", "// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n", "// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n", "// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 12}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_host.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"content/browser/web_contents/web_contents_impl.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/api/base/base.h\"\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/api/shell/shell.h\"\n#include \"content/nw/src/api/tray/tray.h\"\n#include \"content/nw/src/api/window/window.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/render_process_host.h\"\n\nusing content::WebContents;\nusing content::ShellBrowserContext;\n\nnamespace api {\n\nDispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)\n : content::RenderViewHostObserver(render_view_host) {\n}\n\nDispatcherHost::~DispatcherHost() {\n}\n\nBase* DispatcherHost::GetApiObject(int id) {\n return objects_registry_.Lookup(id); \n}\n\nvoid DispatcherHost::SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments) {\n Send(new ShellViewMsg_Object_On_Event(\n routing_id(), object->id(), event, arguments));\n}\n\nbool DispatcherHost::Send(IPC::Message* message) {\n return content::RenderViewHostObserver::Send(message);\n}\n\nbool DispatcherHost::OnMessageReceived(const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,\n OnCallObjectMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,\n OnCallStaticMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,\n OnUncaughtException);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DispatcherHost::OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option) {\n DVLOG(1) << \"OnAllocateObject: object_id:\" << object_id\n << \" type:\" << type\n << \" option:\" << option;\n\n if (type == \"Menu\") {\n objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);\n } else if (type == \"MenuItem\") {\n objects_registry_.AddWithID(\n new MenuItem(object_id, this, option), object_id);\n } else if (type == \"Tray\") {\n objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);\n } else if (type == \"Clipboard\") {\n objects_registry_.AddWithID(\n new Clipboard(object_id, this, option), object_id);\n } else if (type == \"Window\") {\n objects_registry_.AddWithID(new Window(object_id, this, option), object_id);\n } else {\n LOG(ERROR) << \"Allocate an object of unknow type: \" << type;\n objects_registry_.AddWithID(new Base(object_id, this, option), object_id);\n }\n}\n\nvoid DispatcherHost::OnDeallocateObject(int object_id) {\n DLOG(INFO) << \"OnDeallocateObject: object_id:\" << object_id;\n objects_registry_.Remove(object_id);\n}\n\nvoid DispatcherHost::OnCallObjectMethod(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallObjectMethod: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->Call(method, arguments);\n}\n\nvoid DispatcherHost::OnCallObjectMethodSync(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallObjectMethodSync: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->CallSync(method, arguments, result);\n}\n\nvoid DispatcherHost::OnCallStaticMethod(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallStaticMethod: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"Shell\") {\n api::Shell::Call(method, arguments);\n return;\n } else if (type == \"App\") {\n api::App::Call(method, arguments);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnCallStaticMethodSync(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallStaticMethodSync: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"App\") {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n api::App::Call(shell, method, arguments, result);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnUncaughtException(const std::string& err) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n}\n\nvoid DispatcherHost::OnGetShellId(int* id) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n *id = shell->id();\n}\n\nvoid DispatcherHost::OnCreateShell(const std::string& url,\n const base::DictionaryValue& manifest,\n int* routing_id) {\n WebContents* base_web_contents =\n content::Shell::FromRenderViewHost(render_view_host())->web_contents();\n ShellBrowserContext* browser_context =\n static_cast(base_web_contents->GetBrowserContext());\n scoped_ptr new_manifest(manifest.DeepCopy());\n bool new_renderer = false;\n if (new_manifest->GetBoolean(switches::kmNewInstance,\n &new_renderer) && new_renderer)\n browser_context->set_pinning_renderer(false);\n\n WebContents::CreateParams create_params(browser_context,\n new_renderer ? NULL : base_web_contents->GetSiteInstance());\n\n WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(\n create_params,\n static_cast(base_web_contents));\n new content::Shell(web_contents, new_manifest.get());\n web_contents->GetController().LoadURL(\n GURL(url),\n content::Referrer(),\n content::PAGE_TRANSITION_TYPED,\n std::string());\n\n if (new_renderer)\n browser_context->set_pinning_renderer(true);\n\n *routing_id = web_contents->GetRoutingID();\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_host.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0018181136110797524, 0.00025991647271439433, 0.00016409905219916254, 0.0001698726264294237, 0.00034182542003691196]} {"hunk": {"id": 2, "code_window": ["// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n", "// \n", "// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n", "// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n", "// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n", "// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 12}, "file": "\n\n \n 1060\n 11D50b\n 851\n 1138.32\n 568.00\n \n com.apple.InterfaceBuilder.CocoaPlugin\n 851\n \n \n YES\n \n \n \n YES\n com.apple.InterfaceBuilder.CocoaPlugin\n \n \n YES\n \n YES\n \n \n YES\n \n \n \n YES\n \n NSObject\n \n \n FirstResponder\n \n \n NSApplication\n \n \n \n 268\n \n YES\n \n \n 268\n {{99, 20}, {156, 22}}\n \n _NS:3407\n 2\n YES\n \n 343014976\n 272630848\n \n \n LucidaGrande\n 13\n 1040\n \n _NS:3407\n \n YES\n \n 6\n System\n textBackgroundColor\n \n 3\n MQA\n \n \n \n 6\n System\n textColor\n \n 3\n MAA\n \n \n \n YES\n NSAllRomanInputSourcesLocaleIdentifier\n \n \n \n \n \n 268\n {{99, 52}, {156, 22}}\n \n _NS:817\n 1\n YES\n \n -1804468671\n 272630784\n \n \n _NS:817\n \n YES\n \n \n \n \n \n \n 268\n {{17, 22}, {77, 17}}\n \n _NS:4068\n YES\n \n 68288064\n 71304192\n Password:\n \n _NS:4068\n \n \n 6\n System\n controlColor\n \n 3\n MC42NjY2NjY2NjY3AA\n \n \n \n 6\n System\n controlTextColor\n \n \n \n \n \n \n 268\n {{17, 54}, {77, 17}}\n \n _NS:4068\n YES\n \n 68288064\n 71304192\n Username:\n \n _NS:4068\n \n \n \n \n \n \n {275, 94}\n \n NSView\n \n \n \n \n YES\n \n \n \n YES\n \n 0\n \n \n \n \n \n -2\n \n \n File's Owner\n \n \n -1\n \n \n First Responder\n \n \n -3\n \n \n Application\n \n \n 1\n \n \n YES\n \n \n \n \n \n \n \n \n 2\n \n \n YES\n \n \n \n \n \n 3\n \n \n \n \n 4\n \n \n YES\n \n \n \n \n \n 5\n \n \n \n \n 6\n \n \n YES\n \n \n \n \n \n 7\n \n \n \n \n 8\n \n \n YES\n \n \n \n \n \n 9\n \n \n \n \n \n \n YES\n \n YES\n -1.IBPluginDependency\n -2.IBPluginDependency\n -3.IBPluginDependency\n 1.IBEditorWindowLastContentRect\n 1.IBPluginDependency\n 1.WindowOrigin\n 1.editorWindowContentRectSynchronizationRect\n 2.IBPluginDependency\n 2.IBViewBoundsToFrameTransform\n 3.IBPluginDependency\n 4.IBPluginDependency\n 4.IBViewBoundsToFrameTransform\n 5.IBPluginDependency\n 6.IBPluginDependency\n 6.IBViewBoundsToFrameTransform\n 7.IBPluginDependency\n 8.IBPluginDependency\n 8.IBViewBoundsToFrameTransform\n 9.IBPluginDependency\n \n \n YES\n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n {{969, 1048}, {275, 94}}\n com.apple.InterfaceBuilder.CocoaPlugin\n {628, 654}\n {{357, 416}, {480, 272}}\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABBiAAAwpAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABBiAAAwiAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABCxgAAwpAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n com.apple.InterfaceBuilder.CocoaPlugin\n \n P4AAAL+AAABCxgAAwiAAAA\n \n com.apple.InterfaceBuilder.CocoaPlugin\n \n \n \n YES\n \n \n YES\n \n \n \n \n YES\n \n \n YES\n \n \n \n 9\n \n \n 0\n IBCocoaFramework\n \n com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3\n \n \n YES\n \n 3\n \n\n", "file_path": "src/mac/English.lproj/HttpAuth.xib", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0001754614495439455, 0.00017000579100567847, 0.00016509850684087723, 0.00017000576190184802, 2.285536311319447e-06]} {"hunk": {"id": 2, "code_window": ["// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n", "// \n", "// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n", "// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n", "// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n", "// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 12}, "file": "\n\n Hello World \n\n\n\n

this is node-webkit

\n\n\n\n", "file_path": "tests/app_tests/start_app/index.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017112762725446373, 0.00017054789350368083, 0.00016996815975289792, 0.00017054789350368083, 5.79733750782907e-07]} {"hunk": {"id": 2, "code_window": ["// The above copyright notice and this permission notice shall be included in al\n", "// l copies or substantial portions of the Software.\n", "// \n", "// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n", "// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n", "// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n", "// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": ["//\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 12}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/shell_login_dialog.h\"\n\n#include \"base/bind.h\"\n#include \"base/logging.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"content/public/browser/browser_thread.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"net/base/auth.h\"\n#include \"net/url_request/url_request.h\"\n#include \"ui/base/text/text_elider.h\"\n\nnamespace content {\n\nShellLoginDialog::ShellLoginDialog(\n net::AuthChallengeInfo* auth_info,\n net::URLRequest* request) : auth_info_(auth_info),\n request_(request) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&ShellLoginDialog::PrepDialog, this,\n ASCIIToUTF16(auth_info->challenger.ToString()),\n UTF8ToUTF16(auth_info->realm)));\n}\n\nvoid ShellLoginDialog::OnRequestCancelled() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&ShellLoginDialog::PlatformRequestCancelled, this));\n}\n\nvoid ShellLoginDialog::UserAcceptedAuth(const string16& username,\n const string16& password) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n base::Bind(&ShellLoginDialog::SendAuthToRequester, this,\n true, username, password));\n}\n\nvoid ShellLoginDialog::UserCancelledAuth() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n base::Bind(&ShellLoginDialog::SendAuthToRequester, this,\n false, string16(), string16()));\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&ShellLoginDialog::PlatformCleanUp, this));\n}\n\nShellLoginDialog::~ShellLoginDialog() {\n // Cannot post any tasks here; this object is going away and cannot be\n // referenced/dereferenced.\n}\n\nvoid ShellLoginDialog::PrepDialog(const string16& host,\n const string16& realm) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n // The realm is controlled by the remote server, so there is no reason to\n // believe it is of a reasonable length.\n string16 elided_realm;\n ui::ElideString(realm, 120, &elided_realm);\n\n string16 explanation =\n ASCIIToUTF16(\"The server \") + host +\n ASCIIToUTF16(\" requires a username and password.\");\n\n if (!elided_realm.empty()) {\n explanation += ASCIIToUTF16(\" The server says: \");\n explanation += elided_realm;\n explanation += ASCIIToUTF16(\".\");\n }\n\n PlatformCreateDialog(explanation);\n}\n\nvoid ShellLoginDialog::SendAuthToRequester(bool success,\n const string16& username,\n const string16& password) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n if (success)\n request_->SetAuth(net::AuthCredentials(username, password));\n else\n request_->CancelAuth();\n ResourceDispatcherHost::Get()->ClearLoginDelegateForRequest(request_);\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&ShellLoginDialog::PlatformCleanUp, this));\n}\n\n} // namespace content\n", "file_path": "src/browser/shell_login_dialog.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0018181283958256245, 0.0003053428081329912, 0.0001636677625356242, 0.00016657999367453158, 0.000456151639809832]} {"hunk": {"id": 3, "code_window": ["DispatcherHost::~DispatcherHost() {\n", "}\n", "\n", "Base* DispatcherHost::GetApiObject(int id) {\n", " return objects_registry_.Lookup(id); \n", "}\n", "\n", "void DispatcherHost::SendEvent(Base* object,\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return objects_registry_.Lookup(id);\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 52}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_browser_client.h\"\n\n#include \"base/command_line.h\"\n#include \"base/files/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/string_util.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"base/values.h\"\n#include \"content/public/browser/browser_url_handler.h\"\n#include \"content/nw/src/browser/printing/printing_message_filter.h\"\n#include \"content/public/browser/render_process_host.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/common/renderer_preferences.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/browser/printing/print_job_manager.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_resource_dispatcher_host_delegate.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/nw/src/nw_version.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"geolocation/shell_access_token_store.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"webkit/glue/webpreferences.h\"\n#include \"webkit/user_agent/user_agent_util.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n#include \"webkit/plugins/npapi/plugin_list.h\"\n\n\nnamespace content {\n\nShellContentBrowserClient::ShellContentBrowserClient()\n : shell_browser_main_parts_(NULL) {\n}\n\nShellContentBrowserClient::~ShellContentBrowserClient() {\n}\n\nBrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);\n return shell_browser_main_parts_;\n}\n\nWebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView(\n WebContents* web_contents,\n RenderViewHostDelegateView** render_view_host_delegate_view) {\n std::string user_agent, rules;\n nw::Package* package = shell_browser_main_parts()->package();\n content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs();\n if (package->root()->GetString(switches::kmUserAgent, &user_agent)) {\n std::string name, version;\n package->root()->GetString(switches::kmName, &name);\n package->root()->GetString(\"version\", &version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%name\", name);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%ver\", version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%nwver\", NW_VERSION_STRING);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%webkit_ver\", webkit_glue::GetWebKitVersion());\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%osinfo\", webkit_glue::BuildOSInfo());\n prefs->user_agent_override = user_agent;\n }\n if (package->root()->GetString(switches::kmRemotePages, &rules))\n prefs->nw_remote_page_rules = rules;\n return NULL;\n}\n\nvoid ShellContentBrowserClient::RenderViewHostCreated(\n RenderViewHost* render_view_host) {\n new api::DispatcherHost(render_view_host);\n}\n\nstd::string ShellContentBrowserClient::GetApplicationLocale() {\n return l10n_util::GetApplicationLocale(\"en-US\");\n}\n\nvoid ShellContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line,\n int child_process_id) {\n if (command_line->GetSwitchValueASCII(\"type\") != \"renderer\")\n return;\n if (child_process_id > 0) {\n content::RenderProcessHost* rph =\n content::RenderProcessHost::FromID(child_process_id);\n\n content::RenderProcessHost::RenderWidgetHostsIterator iter(\n rph->GetRenderWidgetHostsIterator());\n for (; !iter.IsAtEnd(); iter.Advance()) {\n const content::RenderWidgetHost* widget = iter.GetCurrentValue();\n DCHECK(widget);\n if (!widget || !widget->IsRenderView())\n continue;\n\n content::RenderViewHost* host = content::RenderViewHost::From(\n const_cast(widget));\n content::Shell* shell = content::Shell::FromRenderViewHost(host);\n if (shell && (shell->is_devtools() || !shell->nodejs()))\n return;\n }\n }\n nw::Package* package = shell_browser_main_parts()->package();\n if (package && package->GetUseNode()) {\n // Allow node.js\n command_line->AppendSwitch(switches::kNodejs);\n\n // Set cwd\n command_line->AppendSwitchPath(switches::kWorkingDirectory,\n package->path());\n\n // Check if we have 'node-main'.\n std::string node_main;\n if (package->root()->GetString(switches::kNodeMain, &node_main))\n command_line->AppendSwitchASCII(switches::kNodeMain, node_main);\n\n std::string snapshot_path;\n if (package->root()->GetString(switches::kSnapshot, &snapshot_path))\n command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path);\n }\n\n // without the switch, the destructor of the shell object will\n // shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and\n // destory rph immediately. Then the channel error msg is caught by\n // SuicideOnChannelErrorFilter and the renderer is killed\n // immediately\n#if defined(OS_POSIX)\n command_line->AppendSwitch(switches::kChildCleanExit);\n#endif\n}\n\nvoid ShellContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new ShellResourceDispatcherHostDelegate());\n ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nstd::string ShellContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n\nMediaObserver* ShellContentBrowserClient::GetMediaObserver() {\n return MediaInternals::GetInstance();\n}\n\nvoid ShellContentBrowserClient::BrowserURLHandlerCreated(\n BrowserURLHandler* handler) {\n}\n\nShellBrowserContext* ShellContentBrowserClient::browser_context() {\n return shell_browser_main_parts_->browser_context();\n}\n\nShellBrowserContext*\n ShellContentBrowserClient::off_the_record_browser_context() {\n return shell_browser_main_parts_->off_the_record_browser_context();\n}\n\nAccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {\n return new ShellAccessTokenStore(browser_context()->GetRequestContext());\n}\n\nvoid ShellContentBrowserClient::OverrideWebkitPrefs(\n RenderViewHost* render_view_host,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) {\n nw::Package* package = shell_browser_main_parts()->package();\n\n // Disable web security.\n prefs->dom_paste_enabled = true;\n prefs->javascript_can_access_clipboard = true;\n prefs->web_security_enabled = false;\n prefs->allow_file_access_from_file_urls = true;\n\n // Open experimental features.\n prefs->css_sticky_position_enabled = true;\n prefs->css_shaders_enabled = true;\n prefs->css_variables_enabled = true;\n\n // Disable plugins and cache by default.\n prefs->plugins_enabled = false;\n prefs->java_enabled = false;\n prefs->uses_page_cache = false;\n\n base::DictionaryValue* webkit;\n if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {\n webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);\n webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);\n webkit->GetBoolean(switches::kmPageCache, &prefs->uses_page_cache);\n FilePath plugins_dir = package->path();\n //PathService::Get(base::DIR_CURRENT, &plugins_dir);\n plugins_dir = plugins_dir.AppendASCII(\"plugins\");\n\n webkit::npapi::PluginList::Singleton()->AddExtraPluginDir(plugins_dir);\n }\n}\n\nbool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost(\n BrowserContext* browser_context, const GURL& url) {\n ShellBrowserContext* shell_browser_context =\n static_cast(browser_context);\n if (shell_browser_context->pinning_renderer())\n return true;\n else\n return false;\n}\n\nbool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n const GURL& site_url) {\n return true;\n}\n\nnet::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n BrowserContext* content_browser_context,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContext(\n blob_protocol_handler.Pass(), file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nnet::URLRequestContextGetter*\nShellContentBrowserClient::CreateRequestContextForStoragePartition(\n BrowserContext* content_browser_context,\n const base::FilePath& partition_path,\n bool in_memory,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContextForStoragePartition(\n partition_path, in_memory, blob_protocol_handler.Pass(),\n file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nShellBrowserContext*\nShellContentBrowserClient::ShellBrowserContextForBrowserContext(\n BrowserContext* content_browser_context) {\n if (content_browser_context == browser_context())\n return browser_context();\n DCHECK_EQ(content_browser_context, off_the_record_browser_context());\n return off_the_record_browser_context();\n}\n\nprinting::PrintJobManager* ShellContentBrowserClient::print_job_manager() {\n return shell_browser_main_parts_->print_job_manager();\n}\n\nvoid ShellContentBrowserClient::RenderProcessHostCreated(\n RenderProcessHost* host) {\n int id = host->GetID();\n#if defined(ENABLE_PRINTING)\n host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n#endif\n}\n} // namespace content\n", "file_path": "src/shell_content_browser_client.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.009589070454239845, 0.0006101677427068353, 0.00016568579303566366, 0.00017144005687441677, 0.0017423754325136542]} {"hunk": {"id": 3, "code_window": ["DispatcherHost::~DispatcherHost() {\n", "}\n", "\n", "Base* DispatcherHost::GetApiObject(int id) {\n", " return objects_registry_.Lookup(id); \n", "}\n", "\n", "void DispatcherHost::SendEvent(Base* object,\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return objects_registry_.Lookup(id);\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 52}, "file": "\n\n\nnode-webkit\n\n\n
\n
\n    .__   __.   ______    _______   _______         \n    |  \\ |  |  /  __  \\  |       \\ |   ____|        \n    |   \\|  | |  |  |  | |  .--.  ||  |__    ______ \n    |  . `  | |  |  |  | |  |  |  ||   __|  |______|\n    |  |\\   | |  `--'  | |  '--'  ||  |____         \n    |__| \\__|  \\______/  |_______/ |_______|        \n                                                        \n____    __    ____  _______ .______    __  ___  __  .___________.\n\\   \\  /  \\  /   / |   ____||   _  \\  |  |/  / |  | |           |\n \\   \\/    \\/   /  |  |__   |  |_)  | |  '  /  |  | `---|  |----`\n  \\            /   |   __|  |   _  <  |    <   |  |     |  |     \n   \\    /\\    /    |  |____ |  |_)  | |  .  \\  |  |     |  |     \n    \\__/  \\__/     |_______||______/  |__|\\__\\ |__|     |__|     \n
\n
\n\n\n", "file_path": "src/resources/pages/nw_blank.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017404112440999597, 0.00017006306734401733, 0.00016684165166225284, 0.00016930641140788794, 2.987472953464021e-06]} {"hunk": {"id": 3, "code_window": ["DispatcherHost::~DispatcherHost() {\n", "}\n", "\n", "Base* DispatcherHost::GetApiObject(int id) {\n", " return objects_registry_.Lookup(id); \n", "}\n", "\n", "void DispatcherHost::SendEvent(Base* object,\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return objects_registry_.Lookup(id);\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 52}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"content/nw/src/common/print_messages.h\"\n\n#include \"base/basictypes.h\"\n#include \"base/string16.h\"\n#include \"ui/gfx/size.h\"\n\nPrintMsg_Print_Params::PrintMsg_Print_Params()\n : page_size(),\n content_size(),\n printable_area(),\n margin_top(0),\n margin_left(0),\n dpi(0),\n min_shrink(0),\n max_shrink(0),\n desired_dpi(0),\n document_cookie(0),\n selection_only(false),\n supports_alpha_blend(false),\n preview_ui_id(-1),\n preview_request_id(0),\n is_first_request(false),\n print_scaling_option(WebKit::WebPrintScalingOptionSourceSize),\n print_to_pdf(false),\n display_header_footer(false),\n date(),\n title(),\n url(),\n should_print_backgrounds(false) {\n}\n\nPrintMsg_Print_Params::~PrintMsg_Print_Params() {}\n\nvoid PrintMsg_Print_Params::Reset() {\n page_size = gfx::Size();\n content_size = gfx::Size();\n printable_area = gfx::Rect();\n margin_top = 0;\n margin_left = 0;\n dpi = 0;\n min_shrink = 0;\n max_shrink = 0;\n desired_dpi = 0;\n document_cookie = 0;\n selection_only = false;\n supports_alpha_blend = false;\n preview_ui_id = -1;\n preview_request_id = 0;\n is_first_request = false;\n print_scaling_option = WebKit::WebPrintScalingOptionSourceSize;\n print_to_pdf = false;\n display_header_footer = false;\n date = string16();\n title = string16();\n url = string16();\n should_print_backgrounds = false;\n}\n\nPrintMsg_PrintPages_Params::PrintMsg_PrintPages_Params()\n : pages() {\n}\n\nPrintMsg_PrintPages_Params::~PrintMsg_PrintPages_Params() {}\n\nvoid PrintMsg_PrintPages_Params::Reset() {\n params.Reset();\n pages = std::vector();\n}\n\nPrintHostMsg_RequestPrintPreview_Params::\n PrintHostMsg_RequestPrintPreview_Params()\n : is_modifiable(false),\n webnode_only(false),\n has_selection(false),\n selection_only(false) {\n}\n\nPrintHostMsg_RequestPrintPreview_Params::\n ~PrintHostMsg_RequestPrintPreview_Params() {}\n", "file_path": "src/common/print_messages.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00021423205907922238, 0.00017723212658893317, 0.0001659317931625992, 0.00017274259880650789, 1.3819353625876829e-05]} {"hunk": {"id": 3, "code_window": ["DispatcherHost::~DispatcherHost() {\n", "}\n", "\n", "Base* DispatcherHost::GetApiObject(int id) {\n", " return objects_registry_.Lookup(id); \n", "}\n", "\n", "void DispatcherHost::SendEvent(Base* object,\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return objects_registry_.Lookup(id);\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 52}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/menu/menu.h\"\n\n#include \"base/message_loop.h\"\n#include \"base/mac/scoped_sending_event.h\"\n#include \"base/values.h\"\n#import \n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/browser/native_window_mac.h\"\n#include \"content/nw/src/nw_shell.h\"\n\nnamespace api {\n\nvoid Menu::Create(const base::DictionaryValue& option) {\n menu_ = [[NSMenu alloc] initWithTitle:@\"NW Menu\"];\n [menu_ setAutoenablesItems:NO];\n\n std::string type;\n if (option.GetString(\"type\", &type) && type == \"menubar\") {\n // Preserve the apple menu.\n [menu_ addItem:[[[NSMenuItem alloc]\n initWithTitle:@\"\" action:nil keyEquivalent:@\"\"] autorelease]];\n }\n}\n\nvoid Menu::Destroy() {\n [menu_ release];\n}\n\nvoid Menu::Append(MenuItem* menu_item) {\n [menu_ addItem:menu_item->menu_item_];\n}\n\nvoid Menu::Insert(MenuItem* menu_item, int pos) {\n [menu_ insertItem:menu_item->menu_item_ atIndex:pos];\n}\n\nvoid Menu::Remove(MenuItem* menu_item, int pos) {\n [menu_ removeItem:menu_item->menu_item_];\n}\n\nvoid Menu::Popup(int x, int y, content::Shell* shell) {\n // Fake out a context menu event for our menu\n NSWindow* window =\n static_cast(shell->window())->window();\n NSEvent* currentEvent = [NSApp currentEvent];\n NSView* web_view = shell->web_contents()->GetView()->GetNativeView();\n NSPoint position = { x, web_view.bounds.size.height - y };\n NSTimeInterval eventTime = [currentEvent timestamp];\n NSEvent* clickEvent = [NSEvent mouseEventWithType:NSRightMouseDown\n location:position\n modifierFlags:NSRightMouseDownMask\n timestamp:eventTime\n windowNumber:[window windowNumber]\n context:nil\n eventNumber:0\n clickCount:1\n pressure:1.0];\n\n {\n // Make sure events can be pumped while the menu is up.\n MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());\n\n // One of the events that could be pumped is |window.close()|.\n // User-initiated event-tracking loops protect against this by\n // setting flags in -[CrApplication sendEvent:], but since\n // web-content menus are initiated by IPC message the setup has to\n // be done manually.\n base::mac::ScopedSendingEvent sendingEventScoper;\n\n // Show the menu.\n [NSMenu popUpContextMenu:menu_\n withEvent:clickEvent\n forView:web_view];\n }\n}\n\n} // namespace api\n", "file_path": "src/api/menu/menu_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.000328538182657212, 0.00018785028078127652, 0.00016590474115218967, 0.00017222609312739223, 4.7016492317197844e-05]} {"hunk": {"id": 4, "code_window": [" << \" method:\" << method\n", " << \" arguments:\" << arguments;\n", "\n", " if (type == \"App\") {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " api::App::Call(shell, method, arguments, result);\n", " return;\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 179}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n#define CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n\n#include \n#include \n\n#include \"base/compiler_specific.h\"\n#include \"base/memory/scoped_ptr.h\"\n#include \"content/public/browser/content_browser_client.h\"\n#include \"content/public/browser/web_contents_view.h\"\n\nnamespace printing {\nclass PrintJobManager;\n}\n\nnamespace content {\n\nclass ShellBrowserContext;\nclass ShellBrowserMainParts;\nclass ShellResourceDispatcherHostDelegate;\n\nclass ShellContentBrowserClient : public ContentBrowserClient {\n public:\n ShellContentBrowserClient();\n virtual ~ShellContentBrowserClient();\n\n // ContentBrowserClient overrides.\n virtual BrowserMainParts* CreateBrowserMainParts(\n const MainFunctionParams& parameters) OVERRIDE;\n virtual void RenderViewHostCreated(\n RenderViewHost* render_view_host) OVERRIDE;\n virtual WebContentsViewPort* OverrideCreateWebContentsView(\n WebContents* web_contents,\n RenderViewHostDelegateView** render_view_host_delegate_view) OVERRIDE;\n virtual std::string GetApplicationLocale() OVERRIDE;\n virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,\n int child_process_id) OVERRIDE;\n virtual void ResourceDispatcherHostCreated() OVERRIDE;\n virtual AccessTokenStore* CreateAccessTokenStore() OVERRIDE;\n virtual void OverrideWebkitPrefs(\n RenderViewHost* render_view_host,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) OVERRIDE;\n virtual std::string GetDefaultDownloadName() OVERRIDE;\n virtual MediaObserver* GetMediaObserver() OVERRIDE;\n virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) OVERRIDE;\n virtual bool ShouldTryToUseExistingProcessHost(\n BrowserContext* browser_context, const GURL& url) OVERRIDE;\n virtual bool IsSuitableHost(RenderProcessHost* process_host,\n const GURL& site_url) OVERRIDE;\n ShellBrowserContext* browser_context();\n ShellBrowserContext* off_the_record_browser_context();\n ShellResourceDispatcherHostDelegate* resource_dispatcher_host_delegate() {\n return resource_dispatcher_host_delegate_.get();\n }\n ShellBrowserMainParts* shell_browser_main_parts() {\n return shell_browser_main_parts_;\n }\n virtual printing::PrintJobManager* print_job_manager();\n virtual void RenderProcessHostCreated(RenderProcessHost* host) OVERRIDE;\n virtual net::URLRequestContextGetter* CreateRequestContext(\n BrowserContext* browser_context,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) OVERRIDE;\n virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(\n BrowserContext* browser_context,\n const base::FilePath& partition_path,\n bool in_memory,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) OVERRIDE;\n\n private:\n ShellBrowserContext* ShellBrowserContextForBrowserContext(\n BrowserContext* content_browser_context);\n scoped_ptr\n resource_dispatcher_host_delegate_;\n\n ShellBrowserMainParts* shell_browser_main_parts_;\n};\n\n} // namespace content\n\n#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_\n", "file_path": "src/shell_content_browser_client.h", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0010757435811683536, 0.00041356950532644987, 0.00016556686023250222, 0.0001904788805404678, 0.00034225021954625845]} {"hunk": {"id": 4, "code_window": [" << \" method:\" << method\n", " << \" arguments:\" << arguments;\n", "\n", " if (type == \"App\") {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " api::App::Call(shell, method, arguments, result);\n", " return;\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 179}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n\n#include \"base/values.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"base/string16.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"ui/base/clipboard/clipboard.h\"\n\nnamespace api {\n\nClipboard::Clipboard(int id,\n DispatcherHost* dispatcher_host,\n const base::DictionaryValue& option)\n : Base(id, dispatcher_host, option) {\n}\n\nClipboard::~Clipboard() {\n}\n\nvoid Clipboard::Call(const std::string& method,\n const base::ListValue& arguments) {\n if (method == \"Set\") {\n std::string text, type;\n arguments.GetString(0, &text);\n arguments.GetString(1, &type);\n SetText(text);\n } else if (method == \"Clear\") {\n Clear();\n } else {\n NOTREACHED() << \"Invalid call to Clipboard method:\" << method\n << \" arguments:\" << arguments;\n }\n}\n\nvoid Clipboard::CallSync(const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n if (method == \"Get\") {\n result->AppendString(GetText());\n } else {\n NOTREACHED() << \"Invalid call to Clipboard method:\" << method\n << \" arguments:\" << arguments;\n }\n}\n\nvoid Clipboard::SetText(std::string& text) {\n ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();\n ui::Clipboard::ObjectMap map;\n map[ui::Clipboard::CBF_TEXT].push_back(\n std::vector(text.begin(), text.end()));\n clipboard->WriteObjects(ui::Clipboard::BUFFER_STANDARD, map, NULL);\n}\n\nstd::string Clipboard::GetText() {\n ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();\n string16 text;\n clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &text);\n return UTF16ToUTF8(text);\n}\n\nvoid Clipboard::Clear() {\n ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();\n clipboard->Clear(ui::Clipboard::BUFFER_STANDARD);\n}\n\n} // namespace api\n", "file_path": "src/api/clipboard/clipboard.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.003927577752619982, 0.0010005461517721415, 0.00016431199037469923, 0.00017442319949623197, 0.0015367273008450866]} {"hunk": {"id": 4, "code_window": [" << \" method:\" << method\n", " << \" arguments:\" << arguments;\n", "\n", " if (type == \"App\") {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " api::App::Call(shell, method, arguments, result);\n", " return;\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 179}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#import \"content/nw/src/api/menuitem/menuitem_delegate_mac.h\"\n\n#include \"base/values.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n\n@implementation MenuItemDelegate\n\n-(id)initWithMenuItem: (api::MenuItem*)item {\n if ([super init]) {\n menu_item_ = item;\n }\n\n return self;\n}\n\n-(void)invoke: (id)sender {\n menu_item_->OnClick();\n\n // Send event.\n base::ListValue args;\n menu_item_->dispatcher_host()->SendEvent(menu_item_, \"click\", args);\n}\n\n@end\n\n", "file_path": "src/api/menuitem/menuitem_delegate_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017754509462974966, 0.00017423887038603425, 0.00017187757475767285, 0.00017326520173810422, 2.369629100940074e-06]} {"hunk": {"id": 4, "code_window": [" << \" method:\" << method\n", " << \" arguments:\" << arguments;\n", "\n", " if (type == \"App\") {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " api::App::Call(shell, method, arguments, result);\n", " return;\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 179}, "file": "var path = require('path');\nvar app_test = require('./nw_test_app');\n\ndescribe('Plugin', function() {\n describe('flash', function(){\n it('should not crash', function(done) {\n var result = false;\n \n var child = app_test.createChildProcess({\n execPath: process.execPath,\n appPath: path.join('app_tests', 'plugin', 'flash'),\n end: function(data, app) { \n done();\n result = true;\n app.kill(); \n }\n });\n \n setTimeout(function(){ \n if (!result) {\n done('nw crash.');\n child.removeConnection();\n }\n }, 1000);\n \n \n })\n })\n})", "file_path": "tests/app_tests/plugin/mocha_test.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0019781310111284256, 0.0011145125608891249, 0.00017382600344717503, 0.001191580668091774, 0.0007386174984276295]} {"hunk": {"id": 5, "code_window": ["\n", " NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n", "}\n", "\n", "void DispatcherHost::OnUncaughtException(const std::string& err) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 189}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_browser_client.h\"\n\n#include \"base/command_line.h\"\n#include \"base/files/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/string_util.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"base/values.h\"\n#include \"content/public/browser/browser_url_handler.h\"\n#include \"content/nw/src/browser/printing/printing_message_filter.h\"\n#include \"content/public/browser/render_process_host.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/common/renderer_preferences.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/browser/printing/print_job_manager.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_resource_dispatcher_host_delegate.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/nw/src/nw_version.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"geolocation/shell_access_token_store.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"webkit/glue/webpreferences.h\"\n#include \"webkit/user_agent/user_agent_util.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n#include \"webkit/plugins/npapi/plugin_list.h\"\n\n\nnamespace content {\n\nShellContentBrowserClient::ShellContentBrowserClient()\n : shell_browser_main_parts_(NULL) {\n}\n\nShellContentBrowserClient::~ShellContentBrowserClient() {\n}\n\nBrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);\n return shell_browser_main_parts_;\n}\n\nWebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView(\n WebContents* web_contents,\n RenderViewHostDelegateView** render_view_host_delegate_view) {\n std::string user_agent, rules;\n nw::Package* package = shell_browser_main_parts()->package();\n content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs();\n if (package->root()->GetString(switches::kmUserAgent, &user_agent)) {\n std::string name, version;\n package->root()->GetString(switches::kmName, &name);\n package->root()->GetString(\"version\", &version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%name\", name);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%ver\", version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%nwver\", NW_VERSION_STRING);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%webkit_ver\", webkit_glue::GetWebKitVersion());\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%osinfo\", webkit_glue::BuildOSInfo());\n prefs->user_agent_override = user_agent;\n }\n if (package->root()->GetString(switches::kmRemotePages, &rules))\n prefs->nw_remote_page_rules = rules;\n return NULL;\n}\n\nvoid ShellContentBrowserClient::RenderViewHostCreated(\n RenderViewHost* render_view_host) {\n new api::DispatcherHost(render_view_host);\n}\n\nstd::string ShellContentBrowserClient::GetApplicationLocale() {\n return l10n_util::GetApplicationLocale(\"en-US\");\n}\n\nvoid ShellContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line,\n int child_process_id) {\n if (command_line->GetSwitchValueASCII(\"type\") != \"renderer\")\n return;\n if (child_process_id > 0) {\n content::RenderProcessHost* rph =\n content::RenderProcessHost::FromID(child_process_id);\n\n content::RenderProcessHost::RenderWidgetHostsIterator iter(\n rph->GetRenderWidgetHostsIterator());\n for (; !iter.IsAtEnd(); iter.Advance()) {\n const content::RenderWidgetHost* widget = iter.GetCurrentValue();\n DCHECK(widget);\n if (!widget || !widget->IsRenderView())\n continue;\n\n content::RenderViewHost* host = content::RenderViewHost::From(\n const_cast(widget));\n content::Shell* shell = content::Shell::FromRenderViewHost(host);\n if (shell && (shell->is_devtools() || !shell->nodejs()))\n return;\n }\n }\n nw::Package* package = shell_browser_main_parts()->package();\n if (package && package->GetUseNode()) {\n // Allow node.js\n command_line->AppendSwitch(switches::kNodejs);\n\n // Set cwd\n command_line->AppendSwitchPath(switches::kWorkingDirectory,\n package->path());\n\n // Check if we have 'node-main'.\n std::string node_main;\n if (package->root()->GetString(switches::kNodeMain, &node_main))\n command_line->AppendSwitchASCII(switches::kNodeMain, node_main);\n\n std::string snapshot_path;\n if (package->root()->GetString(switches::kSnapshot, &snapshot_path))\n command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path);\n }\n\n // without the switch, the destructor of the shell object will\n // shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and\n // destory rph immediately. Then the channel error msg is caught by\n // SuicideOnChannelErrorFilter and the renderer is killed\n // immediately\n#if defined(OS_POSIX)\n command_line->AppendSwitch(switches::kChildCleanExit);\n#endif\n}\n\nvoid ShellContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new ShellResourceDispatcherHostDelegate());\n ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nstd::string ShellContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n\nMediaObserver* ShellContentBrowserClient::GetMediaObserver() {\n return MediaInternals::GetInstance();\n}\n\nvoid ShellContentBrowserClient::BrowserURLHandlerCreated(\n BrowserURLHandler* handler) {\n}\n\nShellBrowserContext* ShellContentBrowserClient::browser_context() {\n return shell_browser_main_parts_->browser_context();\n}\n\nShellBrowserContext*\n ShellContentBrowserClient::off_the_record_browser_context() {\n return shell_browser_main_parts_->off_the_record_browser_context();\n}\n\nAccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {\n return new ShellAccessTokenStore(browser_context()->GetRequestContext());\n}\n\nvoid ShellContentBrowserClient::OverrideWebkitPrefs(\n RenderViewHost* render_view_host,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) {\n nw::Package* package = shell_browser_main_parts()->package();\n\n // Disable web security.\n prefs->dom_paste_enabled = true;\n prefs->javascript_can_access_clipboard = true;\n prefs->web_security_enabled = false;\n prefs->allow_file_access_from_file_urls = true;\n\n // Open experimental features.\n prefs->css_sticky_position_enabled = true;\n prefs->css_shaders_enabled = true;\n prefs->css_variables_enabled = true;\n\n // Disable plugins and cache by default.\n prefs->plugins_enabled = false;\n prefs->java_enabled = false;\n prefs->uses_page_cache = false;\n\n base::DictionaryValue* webkit;\n if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {\n webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);\n webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);\n webkit->GetBoolean(switches::kmPageCache, &prefs->uses_page_cache);\n FilePath plugins_dir = package->path();\n //PathService::Get(base::DIR_CURRENT, &plugins_dir);\n plugins_dir = plugins_dir.AppendASCII(\"plugins\");\n\n webkit::npapi::PluginList::Singleton()->AddExtraPluginDir(plugins_dir);\n }\n}\n\nbool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost(\n BrowserContext* browser_context, const GURL& url) {\n ShellBrowserContext* shell_browser_context =\n static_cast(browser_context);\n if (shell_browser_context->pinning_renderer())\n return true;\n else\n return false;\n}\n\nbool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n const GURL& site_url) {\n return true;\n}\n\nnet::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n BrowserContext* content_browser_context,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContext(\n blob_protocol_handler.Pass(), file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nnet::URLRequestContextGetter*\nShellContentBrowserClient::CreateRequestContextForStoragePartition(\n BrowserContext* content_browser_context,\n const base::FilePath& partition_path,\n bool in_memory,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContextForStoragePartition(\n partition_path, in_memory, blob_protocol_handler.Pass(),\n file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nShellBrowserContext*\nShellContentBrowserClient::ShellBrowserContextForBrowserContext(\n BrowserContext* content_browser_context) {\n if (content_browser_context == browser_context())\n return browser_context();\n DCHECK_EQ(content_browser_context, off_the_record_browser_context());\n return off_the_record_browser_context();\n}\n\nprinting::PrintJobManager* ShellContentBrowserClient::print_job_manager() {\n return shell_browser_main_parts_->print_job_manager();\n}\n\nvoid ShellContentBrowserClient::RenderProcessHostCreated(\n RenderProcessHost* host) {\n int id = host->GetID();\n#if defined(ENABLE_PRINTING)\n host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n#endif\n}\n} // namespace content\n", "file_path": "src/shell_content_browser_client.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.9794531464576721, 0.035962775349617004, 0.00016526764375157654, 0.00019896427693311125, 0.1735110729932785]} {"hunk": {"id": 5, "code_window": ["\n", " NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n", "}\n", "\n", "void DispatcherHost::OnUncaughtException(const std::string& err) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 189}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/menu/menu.h\"\n\n#include \"base/values.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/browser/native_window_win.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n#include \"skia/ext/image_operations.h\"\n#include \"ui/gfx/gdi_util.h\"\n#include \"ui/gfx/icon_util.h\"\n#include \"ui/views/controls/menu/menu_2.h\"\n#include \"ui/views/widget/widget.h\"\n\nnamespace {\n\nHBITMAP GetNativeBitmapFromSkBitmap(const SkBitmap& bitmap) {\n int width = bitmap.width();\n int height = bitmap.height();\n\n BITMAPV4HEADER native_bitmap_header;\n gfx::CreateBitmapV4Header(width, height, &native_bitmap_header);\n\n HDC dc = ::GetDC(NULL);\n void* bits;\n HBITMAP native_bitmap = ::CreateDIBSection(dc,\n reinterpret_cast(&native_bitmap_header),\n DIB_RGB_COLORS,\n &bits,\n NULL,\n 0);\n DCHECK(native_bitmap);\n ::ReleaseDC(NULL, dc);\n bitmap.copyPixelsTo(bits, width * height * 4, width * 4);\n return native_bitmap;\n}\n\n} // namespace\n\n\nnamespace ui {\n\nNwMenuModel::NwMenuModel(Delegate* delegate) : SimpleMenuModel(delegate) {\n}\n\nbool NwMenuModel::HasIcons() const {\n // Always return false, see the comment about |NwMenuModel|.\n return false;\n}\n\n} // namespace ui\n\nnamespace api {\n\n// The width of the icon for the menuitem\nstatic const int kIconWidth = 16;\n// The height of the icon for the menuitem\nstatic const int kIconHeight = 16;\n\nvoid Menu::Create(const base::DictionaryValue& option) {\n is_menu_modified_ = true;\n menu_delegate_.reset(new MenuDelegate(dispatcher_host()));\n menu_model_.reset(new ui::NwMenuModel(menu_delegate_.get()));\n menu_.reset(new views::NativeMenuWin(menu_model_.get(), NULL));\n\n std::string type;\n if (option.GetString(\"type\", &type) && type == \"menubar\")\n menu_->set_is_popup_menu(false);\n}\n\nvoid Menu::Destroy() {\n for (size_t index = 0; index < icon_bitmaps_.size(); ++index) {\n ::DeleteObject(icon_bitmaps_[index]);\n }\n}\n\nvoid Menu::Append(MenuItem* menu_item) {\n if (menu_item->submenu_)\n menu_model_->AddSubMenu(menu_item->id(), menu_item->label_,\n menu_item->submenu_->menu_model_.get());\n else if (menu_item->type_ == \"normal\")\n menu_model_->AddItem(menu_item->id(), menu_item->label_);\n else if (menu_item->type_ == \"checkbox\")\n menu_model_->AddCheckItem(menu_item->id(), menu_item->label_);\n else if (menu_item->type_ == \"separator\")\n menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);\n\n is_menu_modified_ = true;\n}\n\nvoid Menu::Insert(MenuItem* menu_item, int pos) {\n if (menu_item->submenu_)\n menu_model_->InsertSubMenuAt(pos, menu_item->id(), menu_item->label_,\n menu_item->submenu_->menu_model_.get());\n else if (menu_item->type_ == \"normal\")\n menu_model_->InsertItemAt(pos, menu_item->id(), menu_item->label_);\n else if (menu_item->type_ == \"checkbox\")\n menu_model_->InsertCheckItemAt(pos, menu_item->id(), menu_item->label_);\n else if (menu_item->type_ == \"separator\")\n menu_model_->InsertSeparatorAt(pos, ui::NORMAL_SEPARATOR);\n\n is_menu_modified_ = true;\n}\n\nvoid Menu::Remove(MenuItem* menu_item, int pos) {\n menu_model_->RemoveAt(pos);\n is_menu_modified_ = true;\n}\n\nvoid Menu::Popup(int x, int y, content::Shell* shell) {\n Rebuild();\n\n // Map point from document to screen.\n POINT screen_point = { x, y };\n ClientToScreen(shell->web_contents()->GetView()->GetNativeView(),\n &screen_point);\n\n menu_->RunMenuAt(gfx::Point(screen_point.x, screen_point.y),\n views::Menu2::ALIGN_TOPLEFT);\n}\n\nvoid Menu::Rebuild(const HMENU *parent_menu) {\n if (is_menu_modified_) {\n // Refresh menu before show.\n menu_->Rebuild(NULL);\n menu_->UpdateStates();\n for (size_t index = 0; index < icon_bitmaps_.size(); ++index) {\n ::DeleteObject(icon_bitmaps_[index]);\n }\n icon_bitmaps_.clear();\n\n HMENU native_menu = parent_menu == NULL ?\n menu_->GetNativeMenu() : *parent_menu;\n\n for (int model_index = 0;\n model_index < menu_model_->GetItemCount();\n ++model_index) {\n int command_id = menu_model_->GetCommandIdAt(model_index);\n\n if (menu_model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_COMMAND ||\n menu_model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_SUBMENU) {\n gfx::Image icon;\n menu_model_->GetIconAt(model_index, &icon);\n if (!icon.IsEmpty()) {\n SkBitmap resized_bitmap =\n skia::ImageOperations::Resize(*icon.ToSkBitmap(),\n skia::ImageOperations::RESIZE_GOOD,\n kIconWidth,\n kIconHeight);\n HBITMAP icon_bitmap = GetNativeBitmapFromSkBitmap(resized_bitmap);\n ::SetMenuItemBitmaps(native_menu, command_id, MF_BYCOMMAND,\n icon_bitmap, icon_bitmap);\n icon_bitmaps_.push_back(icon_bitmap);\n }\n }\n\n MenuItem* item = dispatcher_host()->GetApiObject(command_id);\n if (item != NULL && item->submenu_) {\n item->submenu_->Rebuild(&native_menu);\n }\n }\n\n is_menu_modified_ = false;\n }\n}\n\n} // namespace api\n", "file_path": "src/api/menu/menu_win.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.003294665366411209, 0.00042533144005574286, 0.00016728881746530533, 0.0001738221908453852, 0.0007699762936681509]} {"hunk": {"id": 5, "code_window": ["\n", " NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n", "}\n", "\n", "void DispatcherHost::OnUncaughtException(const std::string& err) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 189}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/shell_resource_context.h\"\n\n#include \"content/nw/src/net/shell_url_request_context_getter.h\"\n\nnamespace content {\n\nShellResourceContext::ShellResourceContext(\n ShellURLRequestContextGetter* getter)\n : getter_(getter) {\n}\n\nShellResourceContext::~ShellResourceContext() {\n}\n\nnet::HostResolver* ShellResourceContext::GetHostResolver() {\n return getter_->host_resolver();\n}\n\nnet::URLRequestContext* ShellResourceContext::GetRequestContext() {\n return getter_->GetURLRequestContext();\n}\n\n} // namespace content\n", "file_path": "src/browser/shell_resource_context.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.000583200657274574, 0.000261190056335181, 0.00017515569925308228, 0.0001825471845222637, 0.00016106256225612015]} {"hunk": {"id": 5, "code_window": ["\n", " NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n", "}\n", "\n", "void DispatcherHost::OnUncaughtException(const std::string& err) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 189}, "file": "\n\n\n\nThe pid of main page is: \n\n
\nThe pid of new-instance page is: \n\n\n\n\n\n\n", "file_path": "tests/app_tests/new-instance/index.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017419135838281363, 0.00017135370580945164, 0.00016903576033655554, 0.0001710938522592187, 2.0326071989984484e-06]} {"hunk": {"id": 6, "code_window": [" content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " *id = shell->id();\n", "}\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_host.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"content/browser/web_contents/web_contents_impl.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/api/base/base.h\"\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/api/shell/shell.h\"\n#include \"content/nw/src/api/tray/tray.h\"\n#include \"content/nw/src/api/window/window.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/render_process_host.h\"\n\nusing content::WebContents;\nusing content::ShellBrowserContext;\n\nnamespace api {\n\nDispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)\n : content::RenderViewHostObserver(render_view_host) {\n}\n\nDispatcherHost::~DispatcherHost() {\n}\n\nBase* DispatcherHost::GetApiObject(int id) {\n return objects_registry_.Lookup(id); \n}\n\nvoid DispatcherHost::SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments) {\n Send(new ShellViewMsg_Object_On_Event(\n routing_id(), object->id(), event, arguments));\n}\n\nbool DispatcherHost::Send(IPC::Message* message) {\n return content::RenderViewHostObserver::Send(message);\n}\n\nbool DispatcherHost::OnMessageReceived(const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,\n OnCallObjectMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,\n OnCallStaticMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,\n OnUncaughtException);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DispatcherHost::OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option) {\n DVLOG(1) << \"OnAllocateObject: object_id:\" << object_id\n << \" type:\" << type\n << \" option:\" << option;\n\n if (type == \"Menu\") {\n objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);\n } else if (type == \"MenuItem\") {\n objects_registry_.AddWithID(\n new MenuItem(object_id, this, option), object_id);\n } else if (type == \"Tray\") {\n objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);\n } else if (type == \"Clipboard\") {\n objects_registry_.AddWithID(\n new Clipboard(object_id, this, option), object_id);\n } else if (type == \"Window\") {\n objects_registry_.AddWithID(new Window(object_id, this, option), object_id);\n } else {\n LOG(ERROR) << \"Allocate an object of unknow type: \" << type;\n objects_registry_.AddWithID(new Base(object_id, this, option), object_id);\n }\n}\n\nvoid DispatcherHost::OnDeallocateObject(int object_id) {\n DLOG(INFO) << \"OnDeallocateObject: object_id:\" << object_id;\n objects_registry_.Remove(object_id);\n}\n\nvoid DispatcherHost::OnCallObjectMethod(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallObjectMethod: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->Call(method, arguments);\n}\n\nvoid DispatcherHost::OnCallObjectMethodSync(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallObjectMethodSync: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->CallSync(method, arguments, result);\n}\n\nvoid DispatcherHost::OnCallStaticMethod(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallStaticMethod: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"Shell\") {\n api::Shell::Call(method, arguments);\n return;\n } else if (type == \"App\") {\n api::App::Call(method, arguments);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnCallStaticMethodSync(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallStaticMethodSync: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"App\") {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n api::App::Call(shell, method, arguments, result);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnUncaughtException(const std::string& err) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n}\n\nvoid DispatcherHost::OnGetShellId(int* id) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n *id = shell->id();\n}\n\nvoid DispatcherHost::OnCreateShell(const std::string& url,\n const base::DictionaryValue& manifest,\n int* routing_id) {\n WebContents* base_web_contents =\n content::Shell::FromRenderViewHost(render_view_host())->web_contents();\n ShellBrowserContext* browser_context =\n static_cast(base_web_contents->GetBrowserContext());\n scoped_ptr new_manifest(manifest.DeepCopy());\n bool new_renderer = false;\n if (new_manifest->GetBoolean(switches::kmNewInstance,\n &new_renderer) && new_renderer)\n browser_context->set_pinning_renderer(false);\n\n WebContents::CreateParams create_params(browser_context,\n new_renderer ? NULL : base_web_contents->GetSiteInstance());\n\n WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(\n create_params,\n static_cast(base_web_contents));\n new content::Shell(web_contents, new_manifest.get());\n web_contents->GetController().LoadURL(\n GURL(url),\n content::Referrer(),\n content::PAGE_TRANSITION_TYPED,\n std::string());\n\n if (new_renderer)\n browser_context->set_pinning_renderer(true);\n\n *routing_id = web_contents->GetRoutingID();\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_host.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.9987340569496155, 0.17837528884410858, 0.00016806728672236204, 0.0075082420371472836, 0.3326399326324463]} {"hunk": {"id": 6, "code_window": [" content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " *id = shell->id();\n", "}\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"content/nw/src/browser/printing/printing_message_filter.h\"\n\n#include \n\n#include \"base/bind.h\"\n#include \"base/process_util.h\"\n//#include \"chrome/browser/browser_process.h\"\n#include \"content/nw/src/browser/printing/printer_query.h\"\n#include \"content/nw/src/browser/printing/print_job_manager.h\"\n//#include \"chrome/browser/profiles/profile.h\"\n//#include \"chrome/browser/profiles/profile_io_data.h\"\n//#include \"chrome/browser/ui/webui/print_preview/print_preview_ui.h\"\n#include \"content/nw/src/common/print_messages.h\"\n#include \"content/nw/src/shell_content_browser_client.h\"\n#include \"content/public/browser/browser_thread.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n\n#if defined(OS_CHROMEOS)\n#include \n\n#include \n\n#include \"base/file_util.h\"\n#include \"base/lazy_instance.h\"\n#include \"chrome/browser/printing/print_dialog_cloud.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace {\n\n#if defined(OS_CHROMEOS)\ntypedef std::map SequenceToPathMap;\n\nstruct PrintingSequencePathMap {\n SequenceToPathMap map;\n int sequence;\n};\n\n// No locking, only access on the FILE thread.\nstatic base::LazyInstance\n g_printing_file_descriptor_map = LAZY_INSTANCE_INITIALIZER;\n#endif\n\nvoid RenderParamsFromPrintSettings(const printing::PrintSettings& settings,\n PrintMsg_Print_Params* params) {\n params->page_size = settings.page_setup_device_units().physical_size();\n params->content_size.SetSize(\n settings.page_setup_device_units().content_area().width(),\n settings.page_setup_device_units().content_area().height());\n params->printable_area.SetRect(\n settings.page_setup_device_units().printable_area().x(),\n settings.page_setup_device_units().printable_area().y(),\n settings.page_setup_device_units().printable_area().width(),\n settings.page_setup_device_units().printable_area().height());\n params->margin_top = settings.page_setup_device_units().content_area().y();\n params->margin_left = settings.page_setup_device_units().content_area().x();\n params->dpi = settings.dpi();\n // Currently hardcoded at 1.25. See PrintSettings' constructor.\n params->min_shrink = settings.min_shrink;\n // Currently hardcoded at 2.0. See PrintSettings' constructor.\n params->max_shrink = settings.max_shrink;\n // Currently hardcoded at 72dpi. See PrintSettings' constructor.\n params->desired_dpi = settings.desired_dpi;\n // Always use an invalid cookie.\n params->document_cookie = 0;\n params->selection_only = settings.selection_only;\n params->supports_alpha_blend = settings.supports_alpha_blend();\n params->should_print_backgrounds = settings.should_print_backgrounds;\n params->display_header_footer = settings.display_header_footer;\n params->date = settings.date;\n params->title = settings.title;\n params->url = settings.url;\n}\n\n} // namespace\n\nPrintingMessageFilter::PrintingMessageFilter(int render_process_id)\n : print_job_manager_(NULL),\n render_process_id_(render_process_id) {\n content::ShellContentBrowserClient* browser_client =\n static_cast(content::GetContentClient()->browser());\n print_job_manager_ = browser_client->print_job_manager();\n}\n\nPrintingMessageFilter::~PrintingMessageFilter() {\n}\n\nvoid PrintingMessageFilter::OverrideThreadForMessage(\n const IPC::Message& message, BrowserThread::ID* thread) {\n#if defined(OS_CHROMEOS)\n if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID ||\n message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) {\n *thread = BrowserThread::FILE;\n }\n#endif\n}\n\nbool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message,\n bool* message_was_ok) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP_EX(PrintingMessageFilter, message, *message_was_ok)\n#if defined(OS_WIN)\n IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection)\n#endif\n#if defined(OS_CHROMEOS)\n IPC_MESSAGE_HANDLER(PrintHostMsg_AllocateTempFileForPrinting,\n OnAllocateTempFileForPrinting)\n IPC_MESSAGE_HANDLER(PrintHostMsg_TempFileForPrintingWritten,\n OnTempFileForPrintingWritten)\n#endif\n IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings,\n OnGetDefaultPrintSettings)\n IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint)\n IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_UpdatePrintSettings,\n OnUpdatePrintSettings)\n IPC_MESSAGE_HANDLER(PrintHostMsg_CheckForCancel, OnCheckForCancel)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n}\n\n#if defined(OS_WIN)\nvoid PrintingMessageFilter::OnDuplicateSection(\n base::SharedMemoryHandle renderer_handle,\n base::SharedMemoryHandle* browser_handle) {\n // Duplicate the handle in this process right now so the memory is kept alive\n // (even if it is not mapped)\n base::SharedMemory shared_buf(renderer_handle, true, peer_handle());\n shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);\n}\n#endif\n\n#if defined(OS_CHROMEOS)\nvoid PrintingMessageFilter::OnAllocateTempFileForPrinting(\n base::FileDescriptor* temp_file_fd, int* sequence_number) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n temp_file_fd->fd = *sequence_number = -1;\n temp_file_fd->auto_close = false;\n\n SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;\n *sequence_number = g_printing_file_descriptor_map.Get().sequence++;\n\n base::FilePath path;\n if (file_util::CreateTemporaryFile(&path)) {\n int fd = open(path.value().c_str(), O_WRONLY);\n if (fd >= 0) {\n SequenceToPathMap::iterator it = map->find(*sequence_number);\n if (it != map->end()) {\n NOTREACHED() << \"Sequence number already in use. seq=\" <<\n *sequence_number;\n } else {\n (*map)[*sequence_number] = path;\n temp_file_fd->fd = fd;\n temp_file_fd->auto_close = true;\n }\n }\n }\n}\n\nvoid PrintingMessageFilter::OnTempFileForPrintingWritten(int render_view_id,\n int sequence_number) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;\n SequenceToPathMap::iterator it = map->find(sequence_number);\n if (it == map->end()) {\n NOTREACHED() << \"Got a sequence that we didn't pass to the \"\n \"renderer: \" << sequence_number;\n return;\n }\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&PrintingMessageFilter::CreatePrintDialogForFile,\n this, render_view_id, it->second));\n\n // Erase the entry in the map.\n map->erase(it);\n}\n\nvoid PrintingMessageFilter::CreatePrintDialogForFile(\n int render_view_id,\n const base::FilePath& path) {\n content::WebContents* wc = GetWebContentsForRenderView(render_view_id);\n print_dialog_cloud::CreatePrintDialogForFile(\n wc->GetBrowserContext(),\n wc->GetView()->GetTopLevelNativeWindow(),\n path,\n string16(),\n string16(),\n std::string(\"application/pdf\"),\n false);\n}\n#endif // defined(OS_CHROMEOS)\n\ncontent::WebContents* PrintingMessageFilter::GetWebContentsForRenderView(\n int render_view_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n content::RenderViewHost* view = content::RenderViewHost::FromID(\n render_process_id_, render_view_id);\n return content::WebContents::FromRenderViewHost(view);\n}\n\nstruct PrintingMessageFilter::GetPrintSettingsForRenderViewParams {\n printing::PrinterQuery::GetSettingsAskParam ask_user_for_settings;\n int expected_page_count;\n bool has_selection;\n printing::MarginType margin_type;\n};\n\nvoid PrintingMessageFilter::GetPrintSettingsForRenderView(\n int render_view_id,\n GetPrintSettingsForRenderViewParams params,\n const base::Closure& callback,\n scoped_refptr printer_query) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n content::WebContents* wc = GetWebContentsForRenderView(render_view_id);\n\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n base::Bind(&printing::PrinterQuery::GetSettings, printer_query,\n params.ask_user_for_settings, wc->GetView()->GetNativeView(),\n params.expected_page_count, params.has_selection,\n params.margin_type, callback));\n}\n\nvoid PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n scoped_refptr printer_query;\n#if 0\n if (!profile_io_data_->printing_enabled()->GetValue()) {\n // Reply with NULL query.\n OnGetDefaultPrintSettingsReply(printer_query, reply_msg);\n return;\n }\n#endif\n print_job_manager_->PopPrinterQuery(0, &printer_query);\n if (!printer_query.get()) {\n printer_query = new printing::PrinterQuery;\n printer_query->SetWorkerDestination(print_job_manager_->destination());\n }\n\n // Loads default settings. This is asynchronous, only the IPC message sender\n // will hang until the settings are retrieved.\n GetPrintSettingsForRenderViewParams params;\n params.ask_user_for_settings = printing::PrinterQuery::DEFAULTS;\n params.expected_page_count = 0;\n params.has_selection = false;\n params.margin_type = printing::DEFAULT_MARGINS;\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&PrintingMessageFilter::GetPrintSettingsForRenderView, this,\n reply_msg->routing_id(), params,\n base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,\n this, printer_query, reply_msg),\n printer_query));\n}\n\nvoid PrintingMessageFilter::OnGetDefaultPrintSettingsReply(\n scoped_refptr printer_query,\n IPC::Message* reply_msg) {\n PrintMsg_Print_Params params;\n if (!printer_query.get() ||\n printer_query->last_status() != printing::PrintingContext::OK) {\n params.Reset();\n } else {\n RenderParamsFromPrintSettings(printer_query->settings(), ¶ms);\n params.document_cookie = printer_query->cookie();\n }\n PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);\n Send(reply_msg);\n // If printing was enabled.\n if (printer_query.get()) {\n // If user hasn't cancelled.\n if (printer_query->cookie() && printer_query->settings().dpi()) {\n print_job_manager_->QueuePrinterQuery(printer_query.get());\n } else {\n printer_query->StopWorker();\n }\n }\n}\n\nvoid PrintingMessageFilter::OnScriptedPrint(\n const PrintHostMsg_ScriptedPrint_Params& params,\n IPC::Message* reply_msg) {\n scoped_refptr printer_query;\n print_job_manager_->PopPrinterQuery(params.cookie, &printer_query);\n if (!printer_query.get()) {\n printer_query = new printing::PrinterQuery;\n printer_query->SetWorkerDestination(print_job_manager_->destination());\n }\n GetPrintSettingsForRenderViewParams settings_params;\n settings_params.ask_user_for_settings = printing::PrinterQuery::ASK_USER;\n settings_params.expected_page_count = params.expected_pages_count;\n settings_params.has_selection = params.has_selection;\n settings_params.margin_type = params.margin_type;\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&PrintingMessageFilter::GetPrintSettingsForRenderView, this,\n reply_msg->routing_id(), settings_params,\n base::Bind(&PrintingMessageFilter::OnScriptedPrintReply, this,\n printer_query, reply_msg),\n printer_query));\n}\n\nvoid PrintingMessageFilter::OnScriptedPrintReply(\n scoped_refptr printer_query,\n IPC::Message* reply_msg) {\n PrintMsg_PrintPages_Params params;\n if (printer_query->last_status() != printing::PrintingContext::OK ||\n !printer_query->settings().dpi()) {\n params.Reset();\n } else {\n RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);\n params.params.document_cookie = printer_query->cookie();\n params.pages =\n printing::PageRange::GetPages(printer_query->settings().ranges);\n }\n PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);\n Send(reply_msg);\n if (params.params.dpi && params.params.document_cookie) {\n print_job_manager_->QueuePrinterQuery(printer_query.get());\n } else {\n printer_query->StopWorker();\n }\n}\n\nvoid PrintingMessageFilter::OnUpdatePrintSettings(\n int document_cookie, const DictionaryValue& job_settings,\n IPC::Message* reply_msg) {\n scoped_refptr printer_query;\n#if 0\n if (!profile_io_data_->printing_enabled()->GetValue()) {\n // Reply with NULL query.\n OnUpdatePrintSettingsReply(printer_query, reply_msg);\n return;\n }\n#endif\n print_job_manager_->PopPrinterQuery(document_cookie, &printer_query);\n if (!printer_query.get()) {\n printer_query = new printing::PrinterQuery;\n printer_query->SetWorkerDestination(print_job_manager_->destination());\n }\n printer_query->SetSettings(\n job_settings,\n base::Bind(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this,\n printer_query, reply_msg));\n}\n\nvoid PrintingMessageFilter::OnUpdatePrintSettingsReply(\n scoped_refptr printer_query,\n IPC::Message* reply_msg) {\n PrintMsg_PrintPages_Params params;\n if (!printer_query.get() ||\n printer_query->last_status() != printing::PrintingContext::OK) {\n params.Reset();\n } else {\n RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);\n params.params.document_cookie = printer_query->cookie();\n params.pages =\n printing::PageRange::GetPages(printer_query->settings().ranges);\n }\n PrintHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);\n Send(reply_msg);\n // If user hasn't cancelled.\n if (printer_query.get()) {\n if (printer_query->cookie() && printer_query->settings().dpi())\n print_job_manager_->QueuePrinterQuery(printer_query.get());\n else\n printer_query->StopWorker();\n }\n}\n\nvoid PrintingMessageFilter::OnCheckForCancel(int32 preview_ui_id,\n int preview_request_id,\n bool* cancel) {\n}\n", "file_path": "src/browser/printing/printing_message_filter.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.012513281777501106, 0.0010534703033044934, 0.0001656369713600725, 0.0001752644602674991, 0.002838186454027891]} {"hunk": {"id": 6, "code_window": [" content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " *id = shell->id();\n", "}\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "\nvar path = require('path');\nvar app_test = require('./nw_test_app');\nvar server = global.server;\nvar cb;\n\ndescribe('new-instance', function() {\n\n after(function() {\n server.removeListener('connection', cb);\n });\n \n\tit('loaded event can been fired', function(done) {\n\t this.timeout(0);\n\t var result = false; \n\t var times = 0;\n\t var pid1, pid2;\n\t \n\t var child = app_test.createChildProcess({\n\t execPath: process.execPath,\n\t appPath: path.join('app_tests', 'new-instance'),\n\t no_connect: true,\n\t \n\t });\n\t \n\t \n\t server.on('connection', cb = function(socket){\n\t socket.setEncoding('utf8');\n\t \n\t socket.on('data', function(data) { \n\n\t if (times == 0) {\n\t pid1 = data;\n\t times += 1;\n\t } else {\n\t pid2 = data;\n\t \n\t if (pid1 != pid2) {\n\t done();\n\t } else {\n\t done('they are in the same process');\n\t }\n\t \n\t child.app.kill();\n\t } // if (times == 0)\n\t });\n\t }); // server.on('connection', cb = function(socket)\n\t \n\t \t \t \n\t}) \n \n \n})\n\n", "file_path": "tests/app_tests/new-instance/mocha_test.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0001777407160261646, 0.00017505195864941925, 0.00017295866564381868, 0.00017507714801467955, 1.650270519348851e-06]} {"hunk": {"id": 6, "code_window": [" content::Shell::FromRenderViewHost(render_view_host());\n", " shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n", "}\n", "\n", "void DispatcherHost::OnGetShellId(int* id) {\n", " content::Shell* shell = \n", " content::Shell::FromRenderViewHost(render_view_host());\n", " *id = shell->id();\n", "}\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" content::Shell* shell =\n"], "file_path": "src/api/dispatcher_host.cc", "type": "replace", "edit_start_line_idx": 195}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"content/nw/src/browser/shell_application_mac.h\"\n\n#include \"base/auto_reset.h\"\n#include \"base/command_line.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_content_browser_client.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n\n@implementation ShellCrApplication\n\n- (BOOL)isHandlingSendEvent {\n return handlingSendEvent_;\n}\n\n- (void)sendEvent:(NSEvent*)event {\n base::AutoReset scoper(&handlingSendEvent_, YES);\n [super sendEvent:event];\n}\n\n- (void)setHandlingSendEvent:(BOOL)handlingSendEvent {\n handlingSendEvent_ = handlingSendEvent;\n}\n\n@end\n", "file_path": "src/browser/shell_application_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017773038416635245, 0.00017310622206423432, 0.00016786101332399994, 0.00017341674538329244, 3.910531631845515e-06]} {"hunk": {"id": 7, "code_window": ["\n", "namespace content {\n", "\n", "ShellContentBrowserClient::ShellContentBrowserClient()\n", " : shell_browser_main_parts_(NULL) {\n", "}\n", "\n", "ShellContentBrowserClient::~ShellContentBrowserClient() {\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" : shell_browser_main_parts_(NULL),\n", " master_rph_(NULL) {\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 58}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_browser_client.h\"\n\n#include \"base/command_line.h\"\n#include \"base/files/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/string_util.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"base/values.h\"\n#include \"content/public/browser/browser_url_handler.h\"\n#include \"content/nw/src/browser/printing/printing_message_filter.h\"\n#include \"content/public/browser/render_process_host.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/common/renderer_preferences.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/browser/printing/print_job_manager.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_resource_dispatcher_host_delegate.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/nw/src/nw_version.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"geolocation/shell_access_token_store.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"webkit/glue/webpreferences.h\"\n#include \"webkit/user_agent/user_agent_util.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n#include \"webkit/plugins/npapi/plugin_list.h\"\n\n\nnamespace content {\n\nShellContentBrowserClient::ShellContentBrowserClient()\n : shell_browser_main_parts_(NULL) {\n}\n\nShellContentBrowserClient::~ShellContentBrowserClient() {\n}\n\nBrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);\n return shell_browser_main_parts_;\n}\n\nWebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView(\n WebContents* web_contents,\n RenderViewHostDelegateView** render_view_host_delegate_view) {\n std::string user_agent, rules;\n nw::Package* package = shell_browser_main_parts()->package();\n content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs();\n if (package->root()->GetString(switches::kmUserAgent, &user_agent)) {\n std::string name, version;\n package->root()->GetString(switches::kmName, &name);\n package->root()->GetString(\"version\", &version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%name\", name);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%ver\", version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%nwver\", NW_VERSION_STRING);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%webkit_ver\", webkit_glue::GetWebKitVersion());\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%osinfo\", webkit_glue::BuildOSInfo());\n prefs->user_agent_override = user_agent;\n }\n if (package->root()->GetString(switches::kmRemotePages, &rules))\n prefs->nw_remote_page_rules = rules;\n return NULL;\n}\n\nvoid ShellContentBrowserClient::RenderViewHostCreated(\n RenderViewHost* render_view_host) {\n new api::DispatcherHost(render_view_host);\n}\n\nstd::string ShellContentBrowserClient::GetApplicationLocale() {\n return l10n_util::GetApplicationLocale(\"en-US\");\n}\n\nvoid ShellContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line,\n int child_process_id) {\n if (command_line->GetSwitchValueASCII(\"type\") != \"renderer\")\n return;\n if (child_process_id > 0) {\n content::RenderProcessHost* rph =\n content::RenderProcessHost::FromID(child_process_id);\n\n content::RenderProcessHost::RenderWidgetHostsIterator iter(\n rph->GetRenderWidgetHostsIterator());\n for (; !iter.IsAtEnd(); iter.Advance()) {\n const content::RenderWidgetHost* widget = iter.GetCurrentValue();\n DCHECK(widget);\n if (!widget || !widget->IsRenderView())\n continue;\n\n content::RenderViewHost* host = content::RenderViewHost::From(\n const_cast(widget));\n content::Shell* shell = content::Shell::FromRenderViewHost(host);\n if (shell && (shell->is_devtools() || !shell->nodejs()))\n return;\n }\n }\n nw::Package* package = shell_browser_main_parts()->package();\n if (package && package->GetUseNode()) {\n // Allow node.js\n command_line->AppendSwitch(switches::kNodejs);\n\n // Set cwd\n command_line->AppendSwitchPath(switches::kWorkingDirectory,\n package->path());\n\n // Check if we have 'node-main'.\n std::string node_main;\n if (package->root()->GetString(switches::kNodeMain, &node_main))\n command_line->AppendSwitchASCII(switches::kNodeMain, node_main);\n\n std::string snapshot_path;\n if (package->root()->GetString(switches::kSnapshot, &snapshot_path))\n command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path);\n }\n\n // without the switch, the destructor of the shell object will\n // shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and\n // destory rph immediately. Then the channel error msg is caught by\n // SuicideOnChannelErrorFilter and the renderer is killed\n // immediately\n#if defined(OS_POSIX)\n command_line->AppendSwitch(switches::kChildCleanExit);\n#endif\n}\n\nvoid ShellContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new ShellResourceDispatcherHostDelegate());\n ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nstd::string ShellContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n\nMediaObserver* ShellContentBrowserClient::GetMediaObserver() {\n return MediaInternals::GetInstance();\n}\n\nvoid ShellContentBrowserClient::BrowserURLHandlerCreated(\n BrowserURLHandler* handler) {\n}\n\nShellBrowserContext* ShellContentBrowserClient::browser_context() {\n return shell_browser_main_parts_->browser_context();\n}\n\nShellBrowserContext*\n ShellContentBrowserClient::off_the_record_browser_context() {\n return shell_browser_main_parts_->off_the_record_browser_context();\n}\n\nAccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {\n return new ShellAccessTokenStore(browser_context()->GetRequestContext());\n}\n\nvoid ShellContentBrowserClient::OverrideWebkitPrefs(\n RenderViewHost* render_view_host,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) {\n nw::Package* package = shell_browser_main_parts()->package();\n\n // Disable web security.\n prefs->dom_paste_enabled = true;\n prefs->javascript_can_access_clipboard = true;\n prefs->web_security_enabled = false;\n prefs->allow_file_access_from_file_urls = true;\n\n // Open experimental features.\n prefs->css_sticky_position_enabled = true;\n prefs->css_shaders_enabled = true;\n prefs->css_variables_enabled = true;\n\n // Disable plugins and cache by default.\n prefs->plugins_enabled = false;\n prefs->java_enabled = false;\n prefs->uses_page_cache = false;\n\n base::DictionaryValue* webkit;\n if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {\n webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);\n webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);\n webkit->GetBoolean(switches::kmPageCache, &prefs->uses_page_cache);\n FilePath plugins_dir = package->path();\n //PathService::Get(base::DIR_CURRENT, &plugins_dir);\n plugins_dir = plugins_dir.AppendASCII(\"plugins\");\n\n webkit::npapi::PluginList::Singleton()->AddExtraPluginDir(plugins_dir);\n }\n}\n\nbool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost(\n BrowserContext* browser_context, const GURL& url) {\n ShellBrowserContext* shell_browser_context =\n static_cast(browser_context);\n if (shell_browser_context->pinning_renderer())\n return true;\n else\n return false;\n}\n\nbool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n const GURL& site_url) {\n return true;\n}\n\nnet::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n BrowserContext* content_browser_context,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContext(\n blob_protocol_handler.Pass(), file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nnet::URLRequestContextGetter*\nShellContentBrowserClient::CreateRequestContextForStoragePartition(\n BrowserContext* content_browser_context,\n const base::FilePath& partition_path,\n bool in_memory,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContextForStoragePartition(\n partition_path, in_memory, blob_protocol_handler.Pass(),\n file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nShellBrowserContext*\nShellContentBrowserClient::ShellBrowserContextForBrowserContext(\n BrowserContext* content_browser_context) {\n if (content_browser_context == browser_context())\n return browser_context();\n DCHECK_EQ(content_browser_context, off_the_record_browser_context());\n return off_the_record_browser_context();\n}\n\nprinting::PrintJobManager* ShellContentBrowserClient::print_job_manager() {\n return shell_browser_main_parts_->print_job_manager();\n}\n\nvoid ShellContentBrowserClient::RenderProcessHostCreated(\n RenderProcessHost* host) {\n int id = host->GetID();\n#if defined(ENABLE_PRINTING)\n host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n#endif\n}\n} // namespace content\n", "file_path": "src/shell_content_browser_client.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.8823962807655334, 0.0641869530081749, 0.00017112778732553124, 0.0071295322850346565, 0.1738450676202774]} {"hunk": {"id": 7, "code_window": ["\n", "namespace content {\n", "\n", "ShellContentBrowserClient::ShellContentBrowserClient()\n", " : shell_browser_main_parts_(NULL) {\n", "}\n", "\n", "ShellContentBrowserClient::~ShellContentBrowserClient() {\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" : shell_browser_main_parts_(NULL),\n", " master_rph_(NULL) {\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 58}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"chrome/browser/printing/print_job.h\"\n\n#include \"base/bind.h\"\n#include \"base/bind_helpers.h\"\n#include \"base/message_loop.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"base/timer.h\"\n#include \"content/nw/src/browser/printing/print_job_worker.h\"\n#include \"content/public/browser/notification_service.h\"\n#include \"content/public/browser/notification_types.h\"\n#include \"printing/printed_document.h\"\n#include \"printing/printed_page.h\"\n\nusing base::TimeDelta;\n\nnamespace {\n\n// Helper function to ensure |owner| is valid until at least |callback| returns.\nvoid HoldRefCallback(const scoped_refptr& owner,\n const base::Closure& callback) {\n callback.Run();\n}\n\n} // namespace\n\nnamespace printing {\n\nPrintJob::PrintJob()\n : ui_message_loop_(MessageLoop::current()),\n source_(NULL),\n worker_(),\n settings_(),\n is_job_pending_(false),\n is_canceling_(false),\n ALLOW_THIS_IN_INITIALIZER_LIST(quit_factory_(this)) {\n DCHECK(ui_message_loop_);\n // This is normally a UI message loop, but in unit tests, the message loop is\n // of the 'default' type.\n DCHECK(ui_message_loop_->type() == MessageLoop::TYPE_UI ||\n ui_message_loop_->type() == MessageLoop::TYPE_DEFAULT);\n ui_message_loop_->AddDestructionObserver(this);\n}\n\nPrintJob::~PrintJob() {\n ui_message_loop_->RemoveDestructionObserver(this);\n // The job should be finished (or at least canceled) when it is destroyed.\n DCHECK(!is_job_pending_);\n DCHECK(!is_canceling_);\n if (worker_.get())\n DCHECK(worker_->message_loop() == NULL);\n DCHECK_EQ(ui_message_loop_, MessageLoop::current());\n}\n\nvoid PrintJob::Initialize(PrintJobWorkerOwner* job,\n PrintedPagesSource* source,\n int page_count) {\n DCHECK(!source_);\n DCHECK(!worker_.get());\n DCHECK(!is_job_pending_);\n DCHECK(!is_canceling_);\n DCHECK(!document_.get());\n source_ = source;\n worker_.reset(job->DetachWorker(this));\n settings_ = job->settings();\n\n PrintedDocument* new_doc =\n new PrintedDocument(settings_, source_, job->cookie());\n new_doc->set_page_count(page_count);\n UpdatePrintedDocument(new_doc);\n\n // Don't forget to register to our own messages.\n registrar_.Add(this, content::NOTIFICATION_PRINT_JOB_EVENT,\n content::Source(this));\n}\n\nvoid PrintJob::Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n DCHECK_EQ(ui_message_loop_, MessageLoop::current());\n switch (type) {\n case content::NOTIFICATION_PRINT_JOB_EVENT: {\n OnNotifyPrintJobEvent(*content::Details(details).ptr());\n break;\n }\n default: {\n break;\n }\n }\n}\n\nvoid PrintJob::GetSettingsDone(const PrintSettings& new_settings,\n PrintingContext::Result result) {\n NOTREACHED();\n}\n\nPrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) {\n NOTREACHED();\n return NULL;\n}\n\nMessageLoop* PrintJob::message_loop() {\n return ui_message_loop_;\n}\n\nconst PrintSettings& PrintJob::settings() const {\n return settings_;\n}\n\nint PrintJob::cookie() const {\n if (!document_.get())\n // Always use an invalid cookie in this case.\n return 0;\n return document_->cookie();\n}\n\nvoid PrintJob::WillDestroyCurrentMessageLoop() {\n NOTREACHED();\n}\n\nvoid PrintJob::StartPrinting() {\n DCHECK_EQ(ui_message_loop_, MessageLoop::current());\n DCHECK(worker_->message_loop());\n DCHECK(!is_job_pending_);\n if (!worker_->message_loop() || is_job_pending_)\n return;\n\n // Real work is done in PrintJobWorker::StartPrinting().\n worker_->message_loop()->PostTask(\n FROM_HERE,\n base::Bind(&HoldRefCallback, make_scoped_refptr(this),\n base::Bind(&PrintJobWorker::StartPrinting,\n base::Unretained(worker_.get()), document_)));\n // Set the flag right now.\n is_job_pending_ = true;\n\n // Tell everyone!\n scoped_refptr details(\n new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL));\n content::NotificationService::current()->Notify(\n content::NOTIFICATION_PRINT_JOB_EVENT,\n content::Source(this),\n content::Details(details.get()));\n}\n\nvoid PrintJob::Stop() {\n DCHECK_EQ(ui_message_loop_, MessageLoop::current());\n\n if (quit_factory_.HasWeakPtrs()) {\n // In case we're running a nested message loop to wait for a job to finish,\n // and we finished before the timeout, quit the nested loop right away.\n Quit();\n quit_factory_.InvalidateWeakPtrs();\n }\n\n // Be sure to live long enough.\n scoped_refptr handle(this);\n\n MessageLoop* worker_loop = worker_->message_loop();\n if (worker_loop) {\n ControlledWorkerShutdown();\n\n is_job_pending_ = false;\n registrar_.Remove(this, content::NOTIFICATION_PRINT_JOB_EVENT,\n content::Source(this));\n }\n // Flush the cached document.\n UpdatePrintedDocument(NULL);\n}\n\nvoid PrintJob::Cancel() {\n if (is_canceling_)\n return;\n is_canceling_ = true;\n\n // Be sure to live long enough.\n scoped_refptr handle(this);\n\n DCHECK_EQ(ui_message_loop_, MessageLoop::current());\n MessageLoop* worker_loop = worker_.get() ? worker_->message_loop() : NULL;\n if (worker_loop) {\n // Call this right now so it renders the context invalid. Do not use\n // InvokeLater since it would take too much time.\n worker_->Cancel();\n }\n // Make sure a Cancel() is broadcast.\n scoped_refptr details(\n new JobEventDetails(JobEventDetails::FAILED, NULL, NULL));\n content::NotificationService::current()->Notify(\n content::NOTIFICATION_PRINT_JOB_EVENT,\n content::Source(this),\n content::Details(details.get()));\n Stop();\n is_canceling_ = false;\n}\n\nbool PrintJob::FlushJob(base::TimeDelta timeout) {\n // Make sure the object outlive this message loop.\n scoped_refptr handle(this);\n\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n base::Bind(&PrintJob::Quit, quit_factory_.GetWeakPtr()), timeout);\n\n MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());\n MessageLoop::current()->Run();\n\n return true;\n}\n\nvoid PrintJob::DisconnectSource() {\n source_ = NULL;\n if (document_.get())\n document_->DisconnectSource();\n}\n\nbool PrintJob::is_job_pending() const {\n return is_job_pending_;\n}\n\nPrintedDocument* PrintJob::document() const {\n return document_.get();\n}\n\nvoid PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {\n if (document_.get() == new_document)\n return;\n\n document_ = new_document;\n\n if (document_.get()) {\n settings_ = document_->settings();\n }\n\n if (worker_.get() && worker_->message_loop()) {\n DCHECK(!is_job_pending_);\n // Sync the document with the worker.\n worker_->message_loop()->PostTask(\n FROM_HERE,\n base::Bind(&HoldRefCallback, make_scoped_refptr(this),\n base::Bind(&PrintJobWorker::OnDocumentChanged,\n base::Unretained(worker_.get()), document_)));\n }\n}\n\nvoid PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {\n switch (event_details.type()) {\n case JobEventDetails::FAILED: {\n settings_.Clear();\n // No need to cancel since the worker already canceled itself.\n Stop();\n break;\n }\n case JobEventDetails::USER_INIT_DONE:\n case JobEventDetails::DEFAULT_INIT_DONE:\n case JobEventDetails::USER_INIT_CANCELED: {\n DCHECK_EQ(event_details.document(), document_.get());\n break;\n }\n case JobEventDetails::NEW_DOC:\n case JobEventDetails::NEW_PAGE:\n case JobEventDetails::PAGE_DONE:\n case JobEventDetails::JOB_DONE:\n case JobEventDetails::ALL_PAGES_REQUESTED: {\n // Don't care.\n break;\n }\n case JobEventDetails::DOC_DONE: {\n // This will call Stop() and broadcast a JOB_DONE message.\n MessageLoop::current()->PostTask(\n FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this));\n break;\n }\n default: {\n NOTREACHED();\n break;\n }\n }\n}\n\nvoid PrintJob::OnDocumentDone() {\n // Be sure to live long enough. The instance could be destroyed by the\n // JOB_DONE broadcast.\n scoped_refptr handle(this);\n\n // Stop the worker thread.\n Stop();\n\n scoped_refptr details(\n new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL));\n content::NotificationService::current()->Notify(\n content::NOTIFICATION_PRINT_JOB_EVENT,\n content::Source(this),\n content::Details(details.get()));\n}\n\nvoid PrintJob::ControlledWorkerShutdown() {\n DCHECK_EQ(ui_message_loop_, MessageLoop::current());\n\n // The deadlock this code works around is specific to window messaging on\n // Windows, so we aren't likely to need it on any other platforms.\n#if defined(OS_WIN)\n // We could easily get into a deadlock case if worker_->Stop() is used; the\n // printer driver created a window as a child of the browser window. By\n // canceling the job, the printer driver initiated dialog box is destroyed,\n // which sends a blocking message to its parent window. If the browser window\n // thread is not processing messages, a deadlock occurs.\n //\n // This function ensures that the dialog box will be destroyed in a timely\n // manner by the mere fact that the thread will terminate. So the potential\n // deadlock is eliminated.\n worker_->StopSoon();\n\n // Run a tight message loop until the worker terminates. It may seems like a\n // hack but I see no other way to get it to work flawlessly. The issues here\n // are:\n // - We don't want to run tasks while the thread is quitting.\n // - We want this code path to wait on the thread to quit before continuing.\n MSG msg;\n HANDLE thread_handle = worker_->thread_handle();\n for (; thread_handle;) {\n // Note that we don't do any kind of message prioritization since we don't\n // execute any pending task or timer.\n DWORD result = MsgWaitForMultipleObjects(1, &thread_handle,\n FALSE, INFINITE, QS_ALLINPUT);\n if (result == WAIT_OBJECT_0 + 1) {\n while (PeekMessage(&msg, NULL, 0, 0, TRUE) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n // Continue looping.\n } else if (result == WAIT_OBJECT_0) {\n // The thread quit.\n break;\n } else {\n // An error occurred. Assume the thread quit.\n NOTREACHED();\n break;\n }\n }\n#endif\n\n // Temporarily allow it until we fix\n // http://code.google.com/p/chromium/issues/detail?id=67044\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n\n // Now make sure the thread object is cleaned up.\n worker_->Stop();\n}\n\nvoid PrintJob::Quit() {\n MessageLoop::current()->Quit();\n}\n\n// Takes settings_ ownership and will be deleted in the receiving thread.\nJobEventDetails::JobEventDetails(Type type,\n PrintedDocument* document,\n PrintedPage* page)\n : document_(document),\n page_(page),\n type_(type) {\n}\n\nJobEventDetails::~JobEventDetails() {\n}\n\nPrintedDocument* JobEventDetails::document() const {\n return document_;\n}\n\nPrintedPage* JobEventDetails::page() const {\n return page_;\n}\n\n} // namespace printing\n", "file_path": "src/browser/printing/print_job.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.006299186497926712, 0.0003590179549064487, 0.0001661837159190327, 0.00017038379155565053, 0.0009841974824666977]} {"hunk": {"id": 7, "code_window": ["\n", "namespace content {\n", "\n", "ShellContentBrowserClient::ShellContentBrowserClient()\n", " : shell_browser_main_parts_(NULL) {\n", "}\n", "\n", "ShellContentBrowserClient::~ShellContentBrowserClient() {\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" : shell_browser_main_parts_(NULL),\n", " master_rph_(NULL) {\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 58}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/native_window_mac.h\"\n\n#include \"base/mac/mac_util.h\"\n#include \"base/sys_string_conversions.h\"\n#include \"base/values.h\"\n#import \"chrome/browser/ui/cocoa/custom_frame_view.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/browser/chrome_event_processing_window.h\"\n#include \"content/nw/src/browser/native_window_helper_mac.h\"\n#include \"content/nw/src/browser/shell_toolbar_delegate_mac.h\"\n#include \"content/nw/src/browser/standard_menus_mac.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/native_web_keyboard_event.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n#include \"extensions/common/draggable_region.h\"\n#include \"third_party/skia/include/core/SkRegion.h\"\n#import \"ui/base/cocoa/underlay_opengl_hosting_window.h\"\n\n@interface NSWindow (NSPrivateApis)\n- (void)setBottomCornerRounded:(BOOL)rounded;\n@end\n\n@interface NSView (WebContentsView)\n- (void)setMouseDownCanMoveWindow:(BOOL)can_move;\n@end\n\n// Replicate specific 10.7 SDK declarations for building with prior SDKs.\n#if !defined(MAC_OS_X_VERSION_10_7) || \\\n MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7\n\nenum {\n NSWindowCollectionBehaviorParticipatesInCycle = 1 << 5,\n NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7,\n NSWindowCollectionBehaviorFullScreenAuxiliary = 1 << 8\n};\n\nenum {\n NSWindowDocumentVersionsButton = 6,\n NSWindowFullScreenButton\n};\n\n@interface NSWindow (LionSDKDeclarations)\n- (void)toggleFullScreen:(id)sender;\n@end\n\n#endif // MAC_OS_X_VERSION_10_7\n\n@interface NativeWindowDelegate : NSObject {\n @private\n content::Shell* shell_;\n}\n- (id)initWithShell:(content::Shell*)shell;\n@end\n\n@implementation NativeWindowDelegate\n\n- (id)initWithShell:(content::Shell*)shell {\n if ((self = [super init])) {\n shell_ = shell;\n }\n return self;\n}\n\n- (BOOL)windowShouldClose:(id)window {\n // If this window is bound to a js object and is not forced to close,\n // then send event to renderer to let the user decide.\n if (!shell_->ShouldCloseWindow())\n return NO;\n\n // Clean ourselves up and do the work after clearing the stack of anything\n // that might have the shell on it.\n [self performSelectorOnMainThread:@selector(cleanup:)\n withObject:window\n waitUntilDone:NO];\n\n return YES;\n}\n\n- (void)windowWillEnterFullScreen:(NSNotification*)notification {\n static_cast(shell_->window())->\n set_is_fullscreen(true);\n shell_->SendEvent(\"enter-fullscreen\");\n}\n\n- (void)windowWillExitFullScreen:(NSNotification*)notification {\n static_cast(shell_->window())->\n set_is_fullscreen(false);\n shell_->SendEvent(\"leave-fullscreen\");\n}\n\n- (void)windowDidBecomeKey:(NSNotification *)notification {\n shell_->web_contents()->GetView()->Focus();\n shell_->SendEvent(\"focus\");\n}\n\n- (void)windowDidResignKey:(NSNotification *)notification {\n shell_->SendEvent(\"blur\");\n}\n\n- (void)windowDidMiniaturize:(NSNotification *)notification{\n shell_->SendEvent(\"minimize\");\n}\n\n- (void)windowDidDeminiaturize:(NSNotification *)notification {\n shell_->SendEvent(\"restore\");\n}\n\n- (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {\n // Cocoa doen't have concept of maximize/unmaximize, so wee need to emulate\n // them by calculating size change when zooming.\n if (newFrame.size.width < [window frame].size.width ||\n newFrame.size.height < [window frame].size.height)\n shell_->SendEvent(\"unmaximize\");\n else\n shell_->SendEvent(\"maximize\");\n\n return YES;\n}\n\n- (void)cleanup:(id)window {\n delete shell_;\n\n [self release];\n}\n\n@end\n\n@interface ControlRegionView : NSView {\n @private\n nw::NativeWindowCocoa* shellWindow_; // Weak; owns self.\n}\n@end\n\n@implementation ControlRegionView\n\n- (id)initWithShellWindow:(nw::NativeWindowCocoa*)shellWindow {\n if ((self = [super init]))\n shellWindow_ = shellWindow;\n return self;\n}\n\n- (BOOL)mouseDownCanMoveWindow {\n return NO;\n}\n\n- (NSView*)hitTest:(NSPoint)aPoint {\n if (shellWindow_->use_system_drag())\n return nil;\n if (!shellWindow_->draggable_region() ||\n !shellWindow_->draggable_region()->contains(aPoint.x, aPoint.y)) {\n return nil;\n }\n return self;\n}\n\n- (void)mouseDown:(NSEvent*)event {\n shellWindow_->HandleMouseEvent(event);\n}\n\n- (void)mouseDragged:(NSEvent*)event {\n shellWindow_->HandleMouseEvent(event);\n}\n\n@end\n\n// This is really a method on NSGrayFrame, so it should only be called on the\n// view passed into -[NSWindow drawCustomFrameRect:forView:].\n@interface NSView (PrivateMethods)\n- (CGFloat)roundedCornerRadius;\n@end\n\n@interface ShellNSWindow : ChromeEventProcessingWindow {\n @private\n content::Shell* shell_;\n}\n- (void)setShell:(content::Shell*)shell;\n- (void)showDevTools:(id)sender;\n- (void)closeAllWindows:(id)sender;\n@end\n\n@implementation ShellNSWindow\n\n- (void)setShell:(content::Shell*)shell {\n shell_ = shell;\n}\n\n- (void)showDevTools:(id)sender {\n shell_->ShowDevTools();\n}\n\n- (void)closeAllWindows:(id)sender {\n api::App::CloseAllWindows();\n}\n\n@end\n\n@interface ShellFramelessNSWindow : ShellNSWindow\n\n- (void)drawCustomFrameRect:(NSRect)rect forView:(NSView*)view;\n\n@end\n\n@implementation ShellFramelessNSWindow\n\n- (void)drawCustomFrameRect:(NSRect)rect forView:(NSView*)view {\n [super drawCustomFrameRect:rect forView:view];\n\n [[NSBezierPath bezierPathWithRect:rect] addClip];\n [[NSColor clearColor] set];\n NSRectFill(rect);\n\n // Set up our clip.\n CGFloat cornerRadius = 4.0;\n if ([view respondsToSelector:@selector(roundedCornerRadius)])\n cornerRadius = [view roundedCornerRadius];\n [[NSBezierPath bezierPathWithRoundedRect:[view bounds]\n xRadius:cornerRadius\n yRadius:cornerRadius] addClip];\n [[NSColor whiteColor] set];\n NSRectFill(rect);\n}\n\n+ (NSRect)frameRectForContentRect:(NSRect)contentRect\n styleMask:(NSUInteger)mask {\n return contentRect;\n}\n\n+ (NSRect)contentRectForFrameRect:(NSRect)frameRect\n styleMask:(NSUInteger)mask {\n return frameRect;\n}\n\n- (NSRect)frameRectForContentRect:(NSRect)contentRect {\n return contentRect;\n}\n\n- (NSRect)contentRectForFrameRect:(NSRect)frameRect {\n return frameRect;\n}\n\n@end\n\nnamespace nw {\n\nNativeWindowCocoa::NativeWindowCocoa(\n content::Shell* shell,\n base::DictionaryValue* manifest)\n : NativeWindow(shell, manifest),\n is_fullscreen_(false),\n is_kiosk_(false),\n attention_request_id_(0),\n use_system_drag_(true) {\n int width, height;\n manifest->GetInteger(switches::kmWidth, &width);\n manifest->GetInteger(switches::kmHeight, &height);\n\n NSRect main_screen_rect = [[[NSScreen screens] objectAtIndex:0] frame];\n NSRect cocoa_bounds = NSMakeRect(\n (NSWidth(main_screen_rect) - width) / 2,\n (NSHeight(main_screen_rect) - height) / 2,\n width,\n height);\n NSUInteger style_mask = NSTitledWindowMask | NSClosableWindowMask |\n NSMiniaturizableWindowMask | NSResizableWindowMask |\n NSTexturedBackgroundWindowMask;\n ShellNSWindow* shell_window;\n if (has_frame_) {\n shell_window = [[ShellNSWindow alloc]\n initWithContentRect:cocoa_bounds\n styleMask:style_mask\n backing:NSBackingStoreBuffered\n defer:NO];\n } else {\n shell_window = [[ShellFramelessNSWindow alloc]\n initWithContentRect:cocoa_bounds\n styleMask:style_mask\n backing:NSBackingStoreBuffered\n defer:NO];\n }\n window_ = shell_window;\n [shell_window setShell:shell];\n [window() setDelegate:[[NativeWindowDelegate alloc] initWithShell:shell]];\n\n // Disable fullscreen button when 'fullscreen' is specified to false.\n bool fullscreen;\n if (!(manifest->GetBoolean(switches::kmFullscreen, &fullscreen) &&\n !fullscreen)) {\n NSUInteger collectionBehavior = [window() collectionBehavior];\n collectionBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;\n [window() setCollectionBehavior:collectionBehavior];\n }\n\n if (base::mac::IsOSSnowLeopard()) {\n [window() setCollectionBehavior:\n NSWindowCollectionBehaviorParticipatesInCycle];\n }\n\n if (base::mac::IsOSSnowLeopard() &&\n [window() respondsToSelector:@selector(setBottomCornerRounded:)])\n [window() setBottomCornerRounded:NO];\n\n NSView* view = web_contents()->GetView()->GetNativeView();\n [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];\n\n // By default, the whole frameless window is not draggable.\n if (!has_frame_) {\n gfx::Rect window_bounds(\n 0, 0, NSWidth(cocoa_bounds), NSHeight(cocoa_bounds));\n system_drag_exclude_areas_.push_back(window_bounds);\n }\n\n InstallView();\n}\n\nNativeWindowCocoa::~NativeWindowCocoa() {\n}\n\nvoid NativeWindowCocoa::InstallView() {\n NSView* view = web_contents()->GetView()->GetNativeView();\n if (has_frame_) {\n [view setFrame:[[window() contentView] bounds]];\n [[window() contentView] addSubview:view];\n } else {\n // TODO(jeremya): find a cleaner way to send this information to the\n // WebContentsViewCocoa view.\n DCHECK([view\n respondsToSelector:@selector(setMouseDownCanMoveWindow:)]);\n [view setMouseDownCanMoveWindow:YES];\n\n NSView* frameView = [[window() contentView] superview];\n [view setFrame:[frameView bounds]];\n [frameView addSubview:view];\n\n [[window() standardWindowButton:NSWindowZoomButton] setHidden:YES];\n [[window() standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];\n [[window() standardWindowButton:NSWindowCloseButton] setHidden:YES];\n [[window() standardWindowButton:NSWindowFullScreenButton] setHidden:YES];\n\n InstallDraggableRegionViews();\n }\n}\n\nvoid NativeWindowCocoa::UninstallView() {\n NSView* view = web_contents()->GetView()->GetNativeView();\n [view removeFromSuperview];\n}\n\nvoid NativeWindowCocoa::Close() {\n [window() performClose:nil];\n}\n\nvoid NativeWindowCocoa::Move(const gfx::Rect& pos) {\n NSRect cocoa_bounds = NSMakeRect(pos.x(), 0,\n pos.width(),\n pos.height());\n // Flip coordinates based on the primary screen.\n NSScreen* screen = [[NSScreen screens] objectAtIndex:0];\n cocoa_bounds.origin.y =\n NSHeight([screen frame]) - pos.height() - pos.y();\n\n [window() setFrame:cocoa_bounds display:YES];\n}\n\nvoid NativeWindowCocoa::Focus(bool focus) {\n if (focus && [window() isVisible])\n [window() makeKeyAndOrderFront:nil];\n else\n [window() orderBack:nil];\n}\n\nvoid NativeWindowCocoa::Show() {\n [window() makeKeyAndOrderFront:nil];\n}\n\nvoid NativeWindowCocoa::Hide() {\n [window() orderOut:nil];\n}\n\nvoid NativeWindowCocoa::Maximize() {\n [window() zoom:nil];\n}\n\nvoid NativeWindowCocoa::Unmaximize() {\n [window() zoom:nil];\n}\n\nvoid NativeWindowCocoa::Minimize() {\n [window() miniaturize:nil];\n}\n\nvoid NativeWindowCocoa::Restore() {\n [window() deminiaturize:nil];\n}\n\nvoid NativeWindowCocoa::SetFullscreen(bool fullscreen) {\n if (fullscreen == is_fullscreen_)\n return;\n\n if (base::mac::IsOSLionOrLater()) {\n is_fullscreen_ = fullscreen;\n [window() toggleFullScreen:nil];\n return;\n }\n\n DCHECK(base::mac::IsOSSnowLeopard());\n\n SetNonLionFullscreen(fullscreen);\n}\n\nbool NativeWindowCocoa::IsFullscreen() {\n return is_fullscreen_;\n}\n\nvoid NativeWindowCocoa::SetNonLionFullscreen(bool fullscreen) {\n if (fullscreen == is_fullscreen_)\n return;\n\n is_fullscreen_ = fullscreen;\n\n // Fade to black.\n const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;\n bool did_fade_out = false;\n CGDisplayFadeReservationToken token;\n if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token) ==\n kCGErrorSuccess) {\n did_fade_out = true;\n CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,\n kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);\n }\n\n // Since frameless windows insert the WebContentsView into the NSThemeFrame\n // ([[window contentView] superview]), and since that NSThemeFrame is\n // destroyed and recreated when we change the styleMask of the window, we\n // need to remove the view from the window when we change the style, and\n // add it back afterwards.\n UninstallView();\n if (fullscreen) {\n restored_bounds_ = [window() frame];\n [window() setStyleMask:NSBorderlessWindowMask];\n [window() setFrame:[window()\n frameRectForContentRect:[[window() screen] frame]]\n display:YES];\n base::mac::RequestFullScreen(base::mac::kFullScreenModeAutoHideAll);\n } else {\n base::mac::ReleaseFullScreen(base::mac::kFullScreenModeAutoHideAll);\n NSUInteger style_mask = NSTitledWindowMask | NSClosableWindowMask |\n NSMiniaturizableWindowMask | NSResizableWindowMask |\n NSTexturedBackgroundWindowMask;\n [window() setStyleMask:style_mask];\n [window() setFrame:restored_bounds_ display:YES];\n }\n InstallView();\n\n // Fade back in.\n if (did_fade_out) {\n CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,\n kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);\n CGReleaseDisplayFadeReservation(token);\n }\n\n is_fullscreen_ = fullscreen;\n if (fullscreen)\n shell()->SendEvent(\"enter-fullscreen\");\n else\n shell()->SendEvent(\"leave-fullscreen\");\n}\n\nvoid NativeWindowCocoa::SetSize(const gfx::Size& size) {\n NSRect frame = [window_ frame];\n frame.origin.y -= size.height() - frame.size.height;\n frame.size.width = size.width();\n frame.size.height = size.height();\n\n [window() setFrame:frame display:YES];\n}\n\ngfx::Size NativeWindowCocoa::GetSize() {\n NSRect frame = [window_ frame];\n return gfx::Size(frame.size.width, frame.size.height);\n}\n\nvoid NativeWindowCocoa::SetMinimumSize(int width, int height) {\n NSSize min_size = NSMakeSize(width, height);\n NSView* content = [window() contentView];\n [window() setContentMinSize:[content convertSize:min_size toView:nil]];\n}\n\nvoid NativeWindowCocoa::SetMaximumSize(int width, int height) {\n NSSize max_size = NSMakeSize(width, height);\n NSView* content = [window() contentView];\n [window() setContentMaxSize:[content convertSize:max_size toView:nil]];\n}\n\nvoid NativeWindowCocoa::SetResizable(bool resizable) {\n if (resizable) {\n [[window() standardWindowButton:NSWindowZoomButton] setEnabled:YES];\n [window() setStyleMask:window().styleMask | NSResizableWindowMask];\n } else {\n [[window() standardWindowButton:NSWindowZoomButton] setEnabled:NO];\n [window() setStyleMask:window().styleMask ^ NSResizableWindowMask];\n }\n}\n\nvoid NativeWindowCocoa::SetAlwaysOnTop(bool top) {\n [window() setLevel:(top ? NSFloatingWindowLevel : NSNormalWindowLevel)];\n}\n\nvoid NativeWindowCocoa::SetPosition(const std::string& position) {\n if (position == \"center\")\n [window() center];\n}\n\nvoid NativeWindowCocoa::SetPosition(const gfx::Point& position) {\n Move(gfx::Rect(position, GetSize()));\n}\n\ngfx::Point NativeWindowCocoa::GetPosition() {\n NSRect frame = [window_ frame];\n NSScreen* screen = [[NSScreen screens] objectAtIndex:0];\n\n return gfx::Point(frame.origin.x,\n NSHeight([screen frame]) - frame.origin.y - frame.size.height);\n}\n\nvoid NativeWindowCocoa::SetTitle(const std::string& title) {\n [window() setTitle:base::SysUTF8ToNSString(title)];\n}\n\nvoid NativeWindowCocoa::FlashFrame(bool flash) {\n if (flash) {\n attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];\n } else {\n [NSApp cancelUserAttentionRequest:attention_request_id_];\n attention_request_id_ = 0;\n }\n}\n\nvoid NativeWindowCocoa::SetKiosk(bool kiosk) {\n if (kiosk) {\n NSApplicationPresentationOptions options =\n NSApplicationPresentationHideDock +\n NSApplicationPresentationHideMenuBar + \n NSApplicationPresentationDisableAppleMenu +\n NSApplicationPresentationDisableProcessSwitching +\n NSApplicationPresentationDisableForceQuit +\n NSApplicationPresentationDisableSessionTermination +\n NSApplicationPresentationDisableHideApplication;\n [NSApp setPresentationOptions:options];\n is_kiosk_ = true;\n SetNonLionFullscreen(true);\n } else {\n [NSApp setPresentationOptions:[NSApp currentSystemPresentationOptions]];\n is_kiosk_ = false;\n SetNonLionFullscreen(false);\n }\n}\n\nbool NativeWindowCocoa::IsKiosk() {\n return is_kiosk_;\n}\n\nvoid NativeWindowCocoa::SetMenu(api::Menu* menu) {\n StandardMenusMac standard_menus(shell_->GetPackage()->GetName());\n [NSApp setMainMenu:menu->menu_];\n standard_menus.BuildAppleMenu();\n standard_menus.BuildEditMenu();\n standard_menus.BuildWindowMenu();\n}\n\nvoid NativeWindowCocoa::HandleMouseEvent(NSEvent* event) {\n if ([event type] == NSLeftMouseDown) {\n last_mouse_location_ =\n [window() convertBaseToScreen:[event locationInWindow]];\n } else if ([event type] == NSLeftMouseDragged) {\n NSPoint current_mouse_location =\n [window() convertBaseToScreen:[event locationInWindow]];\n NSPoint frame_origin = [window() frame].origin;\n frame_origin.x += current_mouse_location.x - last_mouse_location_.x;\n frame_origin.y += current_mouse_location.y - last_mouse_location_.y;\n [window() setFrameOrigin:frame_origin];\n last_mouse_location_ = current_mouse_location;\n }\n}\n\nvoid NativeWindowCocoa::AddToolbar() {\n if (!has_frame_)\n return;\n\n // create the toolbar object\n scoped_nsobject toolbar(\n [[NSToolbar alloc] initWithIdentifier:@\"node-webkit toolbar\"]);\n\n // set initial toolbar properties\n [toolbar setAllowsUserCustomization:NO];\n [toolbar setAutosavesConfiguration:NO];\n [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];\n [toolbar setSizeMode:NSToolbarSizeModeSmall];\n\n // set our controller as the toolbar delegate\n toolbar_delegate_.reset([[ShellToolbarDelegate alloc] initWithShell:shell()]);\n [toolbar setDelegate:toolbar_delegate_];\n\n // attach the toolbar to our window\n [window() setToolbar:toolbar];\n}\n\nvoid NativeWindowCocoa::SetToolbarButtonEnabled(TOOLBAR_BUTTON button_id,\n bool enabled) {\n if (toolbar_delegate_)\n [toolbar_delegate_ setEnabled:enabled forButton:button_id];\n}\n\nvoid NativeWindowCocoa::SetToolbarUrlEntry(const std::string& url) {\n if (toolbar_delegate_)\n [toolbar_delegate_ setUrl:base::SysUTF8ToNSString(url)];\n}\n \nvoid NativeWindowCocoa::SetToolbarIsLoading(bool loading) {\n if (toolbar_delegate_)\n [toolbar_delegate_ setIsLoading:loading];\n}\n\nvoid NativeWindowCocoa::UpdateDraggableRegions(\n const std::vector& regions) {\n // Draggable region is not supported for non-frameless window.\n if (has_frame_)\n return;\n\n // To use system drag, the window has to be marked as draggable with\n // non-draggable areas being excluded via overlapping views.\n // 1) If no draggable area is provided, the window is not draggable at all.\n // 2) If only one draggable area is given, as this is the most common\n // case, use the system drag. The non-draggable areas that are opposite of\n // the draggable area are computed.\n // 3) Otherwise, use the custom drag. As such, we lose the capability to\n // support some features like snapping into other space.\n\n // Determine how to perform the drag by counting the number of draggable\n // areas.\n const extensions::DraggableRegion* draggable_area = NULL;\n use_system_drag_ = true;\n for (std::vector::const_iterator iter =\n regions.begin();\n iter != regions.end();\n ++iter) {\n if (iter->draggable) {\n // If more than one draggable area is found, use custom drag.\n if (draggable_area) {\n use_system_drag_ = false;\n break;\n }\n draggable_area = &(*iter);\n }\n }\n\n if (use_system_drag_)\n UpdateDraggableRegionsForSystemDrag(regions, draggable_area);\n else\n UpdateDraggableRegionsForCustomDrag(regions);\n\n InstallDraggableRegionViews();\n}\n\nvoid NativeWindowCocoa::HandleKeyboardEvent(\n const content::NativeWebKeyboardEvent& event) {\n DVLOG(1) << \"NativeWindowCocoa::HandleKeyboardEvent\";\n if (event.skip_in_browser ||\n event.type == content::NativeWebKeyboardEvent::Char)\n return;\n\n \n DVLOG(1) << \"NativeWindowCocoa::HandleKeyboardEvent - redispatch\";\n\n // // The event handling to get this strictly right is a tangle; cheat here a bit\n // // by just letting the menus have a chance at it.\n // if ([event.os_event type] == NSKeyDown)\n // [[NSApp mainMenu] performKeyEquivalent:event.os_event];\n ChromeEventProcessingWindow* event_window =\n static_cast(window());\n DCHECK([event_window isKindOfClass:[ChromeEventProcessingWindow class]]);\n [event_window redispatchKeyEvent:event.os_event];\n}\n\nvoid NativeWindowCocoa::UpdateDraggableRegionsForSystemDrag(\n const std::vector& regions,\n const extensions::DraggableRegion* draggable_area) {\n NSView* web_view = web_contents()->GetView()->GetNativeView();\n NSInteger web_view_width = NSWidth([web_view bounds]);\n NSInteger web_view_height = NSHeight([web_view bounds]);\n\n system_drag_exclude_areas_.clear();\n\n // The whole window is not draggable if no draggable area is given.\n if (!draggable_area) {\n gfx::Rect window_bounds(0, 0, web_view_width, web_view_height);\n system_drag_exclude_areas_.push_back(window_bounds);\n return;\n }\n\n // Otherwise, there is only one draggable area. Compute non-draggable areas\n // that are the opposite of the given draggable area, combined with the\n // remaining provided non-draggable areas.\n\n // Copy all given non-draggable areas.\n for (std::vector::const_iterator iter =\n regions.begin();\n iter != regions.end();\n ++iter) {\n if (!iter->draggable)\n system_drag_exclude_areas_.push_back(iter->bounds);\n }\n\n gfx::Rect draggable_bounds = draggable_area->bounds;\n gfx::Rect non_draggable_bounds;\n\n // Add the non-draggable area above the given draggable area.\n if (draggable_bounds.y() > 0) {\n non_draggable_bounds.SetRect(0,\n 0,\n web_view_width,\n draggable_bounds.y() - 1);\n system_drag_exclude_areas_.push_back(non_draggable_bounds);\n }\n\n // Add the non-draggable area below the given draggable area.\n if (draggable_bounds.bottom() < web_view_height) {\n non_draggable_bounds.SetRect(0,\n draggable_bounds.bottom() + 1,\n web_view_width,\n web_view_height - draggable_bounds.bottom());\n system_drag_exclude_areas_.push_back(non_draggable_bounds);\n }\n\n // Add the non-draggable area to the left of the given draggable area.\n if (draggable_bounds.x() > 0) {\n non_draggable_bounds.SetRect(0,\n draggable_bounds.y(),\n draggable_bounds.x() - 1,\n draggable_bounds.height());\n system_drag_exclude_areas_.push_back(non_draggable_bounds);\n }\n\n // Add the non-draggable area to the right of the given draggable area.\n if (draggable_bounds.right() < web_view_width) {\n non_draggable_bounds.SetRect(draggable_bounds.right() + 1,\n draggable_bounds.y(),\n web_view_width - draggable_bounds.right(),\n draggable_bounds.height());\n system_drag_exclude_areas_.push_back(non_draggable_bounds);\n }\n}\n\nvoid NativeWindowCocoa::UpdateDraggableRegionsForCustomDrag(\n const std::vector& regions) {\n // We still need one ControlRegionView to cover the whole window such that\n // mouse events could be captured.\n NSView* web_view = web_contents()->GetView()->GetNativeView();\n gfx::Rect window_bounds(\n 0, 0, NSWidth([web_view bounds]), NSHeight([web_view bounds]));\n system_drag_exclude_areas_.clear();\n system_drag_exclude_areas_.push_back(window_bounds);\n\n // Aggregate the draggable areas and non-draggable areas such that hit test\n // could be performed easily.\n SkRegion* draggable_region = new SkRegion;\n for (std::vector::const_iterator iter =\n regions.begin();\n iter != regions.end();\n ++iter) {\n const extensions::DraggableRegion& region = *iter;\n draggable_region->op(\n region.bounds.x(),\n region.bounds.y(),\n region.bounds.right(),\n region.bounds.bottom(),\n region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);\n }\n draggable_region_.reset(draggable_region);\n}\n\nvoid NativeWindowCocoa::InstallDraggableRegionViews() {\n DCHECK(!has_frame_);\n\n // All ControlRegionViews should be added as children of the WebContentsView,\n // because WebContentsView will be removed and re-added when entering and\n // leaving fullscreen mode.\n NSView* webView = web_contents()->GetView()->GetNativeView();\n NSInteger webViewHeight = NSHeight([webView bounds]);\n\n // Remove all ControlRegionViews that are added last time.\n // Note that [webView subviews] returns the view's mutable internal array and\n // it should be copied to avoid mutating the original array while enumerating\n // it.\n scoped_nsobject subviews([[webView subviews] copy]);\n for (NSView* subview in subviews.get())\n if ([subview isKindOfClass:[ControlRegionView class]])\n [subview removeFromSuperview];\n\n // Create and add ControlRegionView for each region that needs to be excluded\n // from the dragging.\n for (std::vector::const_iterator iter =\n system_drag_exclude_areas_.begin();\n iter != system_drag_exclude_areas_.end();\n ++iter) {\n scoped_nsobject controlRegion(\n [[ControlRegionView alloc] initWithShellWindow:this]);\n [controlRegion setFrame:NSMakeRect(iter->x(),\n webViewHeight - iter->bottom(),\n iter->width(),\n iter->height())];\n [webView addSubview:controlRegion];\n }\n}\n\nNativeWindow* CreateNativeWindowCocoa(content::Shell* shell,\n base::DictionaryValue* manifest) {\n return new NativeWindowCocoa(shell, manifest);\n}\n\n} // namespace nw\n", "file_path": "src/browser/native_window_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.009729955345392227, 0.0004877334868069738, 0.0001658311957726255, 0.00017089216271415353, 0.0013314213138073683]} {"hunk": {"id": 7, "code_window": ["\n", "namespace content {\n", "\n", "ShellContentBrowserClient::ShellContentBrowserClient()\n", " : shell_browser_main_parts_(NULL) {\n", "}\n", "\n", "ShellContentBrowserClient::~ShellContentBrowserClient() {\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" : shell_browser_main_parts_(NULL),\n", " master_rph_(NULL) {\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 58}, "file": "## Introduction\n\nnode-webkit is an app runtime based on `Chromium` and `node.js`. You can \nwrite native apps in HTML and Javascript with node-webkit. It also lets you\nto call Node.js modules directly from DOM and enables a new way of writing\nnative applications with all Web technologies.\n\nIt's created and developed in Intel Open Source Technology Center.\n\n[Introduction to node-webkit (slides)](https://speakerdeck.com/u/zcbenz/p/node-webkit-app-runtime-based-on-chromium-and-node-dot-js).\n\n## Features\n\n* Apps written in modern HTML5, CSS3, JS and WebGL.\n* Complete support for [Node.js APIs](http://nodejs.org/api/) and all its [third party modules](https://npmjs.org).\n* Good performance: Node and WebKit runs in the same thread: Function calls are made straightforward; objects are in the same heap and can just reference each other;\n* Easy to package and distribute apps.\n* Available on Linux, Mac OSX and Windows\n\n## Downloads\n\n[v0.4.2 release note](https://groups.google.com/d/msg/node-webkit/Fq5Mio4k2xw/McGDIUs-oSMJ)\n\nPrebuilt binaries (v0.4.2 — Feb 21, 2013):\n\n* Linux: [32bit](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-linux-ia32.tar.gz) / [64bit](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-linux-x64.tar.gz)\n* Windows: [win32](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-win-ia32.zip)\n* Mac: [32bit, 10.7+](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-osx-ia32.zip)\n\n[Looking for older versions?](https://github.com/rogerwang/node-webkit/wiki/Downloads-of-old-versions)\n\n###Demos and real apps\nYou may also be interested in [our demos repository](https://github.com/zcbenz/nw-sample-apps) and the [List of apps and companies using node-webkit](https://github.com/rogerwang/node-webkit/wiki/List-of-apps-and-companies-using-node-webkit).\n\n## Quick Start\n\nCreate `index.html`:\n\n````html\n\n\nHello World!\n\n\n

Hello World!

\nWe are using node.js \n\n\n````\n\nCreate `package.json`:\n\n````json\n{\n \"name\": \"nw-demo\",\n \"main\": \"index.html\"\n}\n````\n\nCompress `index.html` and `package.json` into a zip archive, and rename\nit to `app.nw`:\n\n app.nw\n |-- package.json\n `-- index.html\n\nDownload the prebuilt binary for your platform and use it to open the\n`app.nw` file:\n\n````bash\n$ ./nw app.nw\n````\n\nNote: on Windows, you can drag the `app.nw` to `nw.exe` to open it.\n\n## Documents\n\nFor more information on how to write/package/run apps, see:\n\n* [How to run apps](https://github.com/rogerwang/node-webkit/wiki/How-to-run-apps)\n* [How to package and distribute your apps](https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps)\n* [How to use 3rd party node.js modules in node-webkit](https://github.com/rogerwang/node-webkit/wiki/How-to-use-3rd-party-node.js-modules-in-node-webkit)\n\nAnd our [Wiki](https://github.com/rogerwang/node-webkit/wiki) for much more.\n\n## Community\n\nWe use [node-webkit group](http://groups.google.com/group/node-webkit) as\nour mailing list, subscribe via [node-webkit+subscribe@googlegroups.com](mailto:node-webkit+subscribe@googlegroups.com).\n\n## License\n\n`node-webkit`'s code uses the MIT license, see our `LICENSE` file.\n", "file_path": "README.md", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.000181495604920201, 0.0001707797055132687, 0.00016438910097349435, 0.00017085317813325673, 5.210891231399728e-06]} {"hunk": {"id": 8, "code_window": [" return false;\n", "}\n", "\n", "bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n", " const GURL& site_url) {\n", " return true;\n", "}\n", "\n", "net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return process_host == master_rph_;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 233}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_host.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"content/browser/web_contents/web_contents_impl.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/api/base/base.h\"\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/api/shell/shell.h\"\n#include \"content/nw/src/api/tray/tray.h\"\n#include \"content/nw/src/api/window/window.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/render_process_host.h\"\n\nusing content::WebContents;\nusing content::ShellBrowserContext;\n\nnamespace api {\n\nDispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)\n : content::RenderViewHostObserver(render_view_host) {\n}\n\nDispatcherHost::~DispatcherHost() {\n}\n\nBase* DispatcherHost::GetApiObject(int id) {\n return objects_registry_.Lookup(id); \n}\n\nvoid DispatcherHost::SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments) {\n Send(new ShellViewMsg_Object_On_Event(\n routing_id(), object->id(), event, arguments));\n}\n\nbool DispatcherHost::Send(IPC::Message* message) {\n return content::RenderViewHostObserver::Send(message);\n}\n\nbool DispatcherHost::OnMessageReceived(const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,\n OnCallObjectMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,\n OnCallStaticMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,\n OnUncaughtException);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DispatcherHost::OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option) {\n DVLOG(1) << \"OnAllocateObject: object_id:\" << object_id\n << \" type:\" << type\n << \" option:\" << option;\n\n if (type == \"Menu\") {\n objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);\n } else if (type == \"MenuItem\") {\n objects_registry_.AddWithID(\n new MenuItem(object_id, this, option), object_id);\n } else if (type == \"Tray\") {\n objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);\n } else if (type == \"Clipboard\") {\n objects_registry_.AddWithID(\n new Clipboard(object_id, this, option), object_id);\n } else if (type == \"Window\") {\n objects_registry_.AddWithID(new Window(object_id, this, option), object_id);\n } else {\n LOG(ERROR) << \"Allocate an object of unknow type: \" << type;\n objects_registry_.AddWithID(new Base(object_id, this, option), object_id);\n }\n}\n\nvoid DispatcherHost::OnDeallocateObject(int object_id) {\n DLOG(INFO) << \"OnDeallocateObject: object_id:\" << object_id;\n objects_registry_.Remove(object_id);\n}\n\nvoid DispatcherHost::OnCallObjectMethod(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallObjectMethod: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->Call(method, arguments);\n}\n\nvoid DispatcherHost::OnCallObjectMethodSync(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallObjectMethodSync: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->CallSync(method, arguments, result);\n}\n\nvoid DispatcherHost::OnCallStaticMethod(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallStaticMethod: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"Shell\") {\n api::Shell::Call(method, arguments);\n return;\n } else if (type == \"App\") {\n api::App::Call(method, arguments);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnCallStaticMethodSync(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallStaticMethodSync: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"App\") {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n api::App::Call(shell, method, arguments, result);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnUncaughtException(const std::string& err) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n}\n\nvoid DispatcherHost::OnGetShellId(int* id) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n *id = shell->id();\n}\n\nvoid DispatcherHost::OnCreateShell(const std::string& url,\n const base::DictionaryValue& manifest,\n int* routing_id) {\n WebContents* base_web_contents =\n content::Shell::FromRenderViewHost(render_view_host())->web_contents();\n ShellBrowserContext* browser_context =\n static_cast(base_web_contents->GetBrowserContext());\n scoped_ptr new_manifest(manifest.DeepCopy());\n bool new_renderer = false;\n if (new_manifest->GetBoolean(switches::kmNewInstance,\n &new_renderer) && new_renderer)\n browser_context->set_pinning_renderer(false);\n\n WebContents::CreateParams create_params(browser_context,\n new_renderer ? NULL : base_web_contents->GetSiteInstance());\n\n WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(\n create_params,\n static_cast(base_web_contents));\n new content::Shell(web_contents, new_manifest.get());\n web_contents->GetController().LoadURL(\n GURL(url),\n content::Referrer(),\n content::PAGE_TRANSITION_TYPED,\n std::string());\n\n if (new_renderer)\n browser_context->set_pinning_renderer(true);\n\n *routing_id = web_contents->GetRoutingID();\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_host.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.008512928150594234, 0.0010174900526180863, 0.0001633316423976794, 0.00017832341836765409, 0.0020198228303343058]} {"hunk": {"id": 8, "code_window": [" return false;\n", "}\n", "\n", "bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n", " const GURL& site_url) {\n", " return true;\n", "}\n", "\n", "net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return process_host == master_rph_;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 233}, "file": "{\n \"name\": \"nw-demo\",\n \"main\": \"index.html\",\n \"user-agent\": \"%name-a-b\",\n \"node-remote\": \"127.0.0.1:80\",\n \"version\": \"1.0\",\n \"window\": { \"show\" : false }\n}\n", "file_path": "tests/app_tests/node-remote/package.json", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0001728407951304689, 0.0001728407951304689, 0.0001728407951304689, 0.0001728407951304689, 0.0]} {"hunk": {"id": 8, "code_window": [" return false;\n", "}\n", "\n", "bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n", " const GURL& site_url) {\n", " return true;\n", "}\n", "\n", "net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return process_host == master_rph_;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 233}, "file": "\n\nContent shell remote debugging\n\n\n\n\n\n
Inspectable WebContents
\n
\n\n\n", "file_path": "src/resources/pages/shell_devtools_discovery_page.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0001764812332112342, 0.000173815424204804, 0.0001695097889751196, 0.0001751458621583879, 2.5947813355742255e-06]} {"hunk": {"id": 8, "code_window": [" return false;\n", "}\n", "\n", "bool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n", " const GURL& site_url) {\n", " return true;\n", "}\n", "\n", "net::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" return process_host == master_rph_;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "replace", "edit_start_line_idx": 233}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef CONTENT_NW_SRC_API_WINDOW_BINDINGS_H_\n#define CONTENT_NW_SRC_API_WINDOW_BINDINGS_H_\n\n#include \"base/basictypes.h\"\n#include \"base/compiler_specific.h\"\n#include \"v8/include/v8.h\"\n\nnamespace api {\n\nclass WindowBindings : public v8::Extension {\n public:\n WindowBindings();\n virtual ~WindowBindings();\n\n // v8::Extension implementation.\n virtual v8::Handle\n GetNativeFunction(v8::Handle name) OVERRIDE;\n \n private:\n // Tell browser to bind a js object to Shell.\n static v8::Handle BindToShell(const v8::Arguments& args);\n\n // Call method of an object in browser.\n static v8::Handle CallObjectMethod(const v8::Arguments& args);\n\n // Call method of an object in browser synchrounously.\n static v8::Handle CallObjectMethodSync(const v8::Arguments& args);\n\n // Get the window object of current render view.\n static v8::Handle GetWindowObject(const v8::Arguments& args);\n\n DISALLOW_COPY_AND_ASSIGN(WindowBindings);\n};\n\n} // namespace api\n\n#endif // CONTENT_NW_SRC_API_WINDOW_BINDINGS_H_\n", "file_path": "src/api/window_bindings.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00018661060312297195, 0.0001730655785650015, 0.0001648367615416646, 0.00017184147145599127, 7.137904958653962e-06]} {"hunk": {"id": 9, "code_window": ["}\n", "\n", "void ShellContentBrowserClient::RenderProcessHostCreated(\n", " RenderProcessHost* host) {\n", " int id = host->GetID();\n", "#if defined(ENABLE_PRINTING)\n", " host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n", "#endif\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" if (!master_rph_)\n", " master_rph_ = host;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 296}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_host.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"content/browser/web_contents/web_contents_impl.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/api/base/base.h\"\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/api/shell/shell.h\"\n#include \"content/nw/src/api/tray/tray.h\"\n#include \"content/nw/src/api/window/window.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/render_process_host.h\"\n\nusing content::WebContents;\nusing content::ShellBrowserContext;\n\nnamespace api {\n\nDispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)\n : content::RenderViewHostObserver(render_view_host) {\n}\n\nDispatcherHost::~DispatcherHost() {\n}\n\nBase* DispatcherHost::GetApiObject(int id) {\n return objects_registry_.Lookup(id); \n}\n\nvoid DispatcherHost::SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments) {\n Send(new ShellViewMsg_Object_On_Event(\n routing_id(), object->id(), event, arguments));\n}\n\nbool DispatcherHost::Send(IPC::Message* message) {\n return content::RenderViewHostObserver::Send(message);\n}\n\nbool DispatcherHost::OnMessageReceived(const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,\n OnCallObjectMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,\n OnCallStaticMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,\n OnUncaughtException);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DispatcherHost::OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option) {\n DVLOG(1) << \"OnAllocateObject: object_id:\" << object_id\n << \" type:\" << type\n << \" option:\" << option;\n\n if (type == \"Menu\") {\n objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);\n } else if (type == \"MenuItem\") {\n objects_registry_.AddWithID(\n new MenuItem(object_id, this, option), object_id);\n } else if (type == \"Tray\") {\n objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);\n } else if (type == \"Clipboard\") {\n objects_registry_.AddWithID(\n new Clipboard(object_id, this, option), object_id);\n } else if (type == \"Window\") {\n objects_registry_.AddWithID(new Window(object_id, this, option), object_id);\n } else {\n LOG(ERROR) << \"Allocate an object of unknow type: \" << type;\n objects_registry_.AddWithID(new Base(object_id, this, option), object_id);\n }\n}\n\nvoid DispatcherHost::OnDeallocateObject(int object_id) {\n DLOG(INFO) << \"OnDeallocateObject: object_id:\" << object_id;\n objects_registry_.Remove(object_id);\n}\n\nvoid DispatcherHost::OnCallObjectMethod(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallObjectMethod: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->Call(method, arguments);\n}\n\nvoid DispatcherHost::OnCallObjectMethodSync(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallObjectMethodSync: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->CallSync(method, arguments, result);\n}\n\nvoid DispatcherHost::OnCallStaticMethod(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallStaticMethod: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"Shell\") {\n api::Shell::Call(method, arguments);\n return;\n } else if (type == \"App\") {\n api::App::Call(method, arguments);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnCallStaticMethodSync(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallStaticMethodSync: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"App\") {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n api::App::Call(shell, method, arguments, result);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnUncaughtException(const std::string& err) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n}\n\nvoid DispatcherHost::OnGetShellId(int* id) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n *id = shell->id();\n}\n\nvoid DispatcherHost::OnCreateShell(const std::string& url,\n const base::DictionaryValue& manifest,\n int* routing_id) {\n WebContents* base_web_contents =\n content::Shell::FromRenderViewHost(render_view_host())->web_contents();\n ShellBrowserContext* browser_context =\n static_cast(base_web_contents->GetBrowserContext());\n scoped_ptr new_manifest(manifest.DeepCopy());\n bool new_renderer = false;\n if (new_manifest->GetBoolean(switches::kmNewInstance,\n &new_renderer) && new_renderer)\n browser_context->set_pinning_renderer(false);\n\n WebContents::CreateParams create_params(browser_context,\n new_renderer ? NULL : base_web_contents->GetSiteInstance());\n\n WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(\n create_params,\n static_cast(base_web_contents));\n new content::Shell(web_contents, new_manifest.get());\n web_contents->GetController().LoadURL(\n GURL(url),\n content::Referrer(),\n content::PAGE_TRANSITION_TYPED,\n std::string());\n\n if (new_renderer)\n browser_context->set_pinning_renderer(true);\n\n *routing_id = web_contents->GetRoutingID();\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_host.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.756843090057373, 0.03313421458005905, 0.0001659037807257846, 0.00017748805112205446, 0.15093795955181122]} {"hunk": {"id": 9, "code_window": ["}\n", "\n", "void ShellContentBrowserClient::RenderProcessHostCreated(\n", " RenderProcessHost* host) {\n", " int id = host->GetID();\n", "#if defined(ENABLE_PRINTING)\n", " host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n", "#endif\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" if (!master_rph_)\n", " master_rph_ = host;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 296}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/tray/tray.h\"\n\n#include \"base/values.h\"\n#import \n#include \"content/nw/src/api/menu/menu.h\"\n\nnamespace api {\n\nvoid Tray::Create(const base::DictionaryValue& option) {\n NSStatusBar *status_bar = [NSStatusBar systemStatusBar];\n status_item_ = [status_bar statusItemWithLength:NSVariableStatusItemLength];\n [status_item_ setHighlightMode:YES];\n [status_item_ retain];\n}\n\nvoid Tray::ShowAfterCreate() {\n}\n\nvoid Tray::Destroy() {\n [status_item_ release];\n}\n\nvoid Tray::SetTitle(const std::string& title) {\n [status_item_ setTitle:[NSString stringWithUTF8String:title.c_str()]];\n}\n\nvoid Tray::SetIcon(const std::string& icon) {\n if (!icon.empty()) {\n NSImage* image = [[NSImage alloc]\n initWithContentsOfFile:[NSString stringWithUTF8String:icon.c_str()]];\n [status_item_ setImage:image];\n [image release];\n } else {\n [status_item_ setImage:nil];\n }\n}\n\nvoid Tray::SetAltIcon(const std::string& alticon) {\n if (!alticon.empty()) {\n NSImage* image = [[NSImage alloc]\n initWithContentsOfFile:[NSString stringWithUTF8String:alticon.c_str()]];\n [status_item_ setAlternateImage:image];\n [image release];\n } else {\n [status_item_ setAlternateImage:nil];\n }\n}\n\nvoid Tray::SetTooltip(const std::string& tooltip) {\n [status_item_ setToolTip:[NSString stringWithUTF8String:tooltip.c_str()]];\n}\n\nvoid Tray::SetMenu(Menu* menu) {\n [status_item_ setMenu:menu->menu_];\n}\n\nvoid Tray::Remove() {\n [[NSStatusBar systemStatusBar] removeStatusItem:status_item_];\n}\n\n} // namespace api\n", "file_path": "src/api/tray/tray_mac.mm", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017803433001972735, 0.00017537869280204177, 0.00017124008445534855, 0.0001756564452080056, 2.0550432964228094e-06]} {"hunk": {"id": 9, "code_window": ["}\n", "\n", "void ShellContentBrowserClient::RenderProcessHostCreated(\n", " RenderProcessHost* host) {\n", " int id = host->GetID();\n", "#if defined(ENABLE_PRINTING)\n", " host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n", "#endif\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" if (!master_rph_)\n", " master_rph_ = host;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 296}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_main_delegate.h\"\n\n#include \"base/command_line.h\"\n#include \"base/files/file_path.h\"\n#include \"base/logging.h\"\n#include \"base/path_service.h\"\n#include \"base/utf_string_conversions.h\"\n#include \"content/public/browser/browser_main_runner.h\"\n#include \"content/public/browser/render_process_host.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/common/url_constants.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/nw_version.h\"\n#include \"content/nw/src/renderer/shell_content_renderer_client.h\"\n#include \"content/nw/src/shell_browser_main.h\"\n#include \"content/nw/src/shell_content_browser_client.h\"\n#include \"net/cookies/cookie_monster.h\"\n#include \"third_party/node/src/node_version.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n#include \"ui/base/ui_base_paths.h\"\n#include \"ui/base/ui_base_switches.h\"\n\n#include \n\nusing base::FilePath;\n\n#if defined(OS_MACOSX)\n#include \"content/shell/paths_mac.h\"\n#endif // OS_MACOSX\n\n#if defined(OS_WIN)\n#include \"base/logging_win.h\"\n#include \n#endif\n\n#include \"ipc/ipc_message.h\" // For IPC_MESSAGE_LOG_ENABLED.\n\n#if defined(IPC_MESSAGE_LOG_ENABLED)\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n#include \"content/public/common/content_ipc_logging.h\"\n#define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \\\n content::RegisterIPCLogger(msg_id, logger)\n#include \"content/nw/src/common/common_message_generator.h\"\n#endif\n\nnamespace {\n\n#if defined(OS_WIN)\n// If \"Content Shell\" doesn't show up in your list of trace providers in\n// Sawbuck, add these registry entries to your machine (NOTE the optional\n// Wow6432Node key for x64 machines):\n// 1. Find: HKLM\\SOFTWARE\\[Wow6432Node\\]Google\\Sawbuck\\Providers\n// 2. Add a subkey with the name \"{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}\"\n// 3. Add these values:\n// \"default_flags\"=dword:00000001\n// \"default_level\"=dword:00000004\n// @=\"Content Shell\"\n\n// {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}\nconst GUID kContentShellProviderName = {\n 0x6a3e50a4, 0x7e15, 0x4099,\n { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } };\n#endif\n\nvoid InitLogging() {\n logging::InitLogging(\n#if defined(OS_WIN)\n L\"debug.log\",\n#else\n \"debug.log\",\n#endif\n logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE,\n logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);\n logging::SetLogItems(true, false, true, false);\n}\n\n} // namespace\n\nnamespace content {\n\nShellMainDelegate::ShellMainDelegate() {\n}\n\nShellMainDelegate::~ShellMainDelegate() {\n}\n\nbool ShellMainDelegate::BasicStartupComplete(int* exit_code) {\n#if defined(OS_WIN)\n // Enable trace control and transport through event tracing for Windows.\n logging::LogEventProvider::Initialize(kContentShellProviderName);\n#endif\n\n InitLogging();\n net::CookieMonster::EnableFileScheme();\n\n SetContentClient(&content_client_);\n return false;\n}\n\nvoid ShellMainDelegate::PreSandboxStartup() {\n#if defined(OS_MACOSX)\n OverrideFrameworkBundlePath();\n OverrideChildProcessPath();\n#endif // OS_MACOSX\n InitializeResourceBundle();\n\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n\n // Just prevent sandbox.\n command_line->AppendSwitch(switches::kNoSandbox);\n\n // Make sure we keep using only one render process for one app, by using the\n // process-per-tab mode, we can make Chrome only create new site instance\n // when we require to, the default mode is creating different site instances\n // for different domains.\n // This is needed because we want our Window API to have full control of new \n // windows created, which require all windows to be in one render process\n // host.\n command_line->AppendSwitch(switches::kProcessPerTab);\n\n // Allow file:// URIs can read other file:// URIs by default.\n command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);\n}\n\nint ShellMainDelegate::RunProcess(\n const std::string& process_type,\n const MainFunctionParams& main_function_params) {\n if (!process_type.empty())\n return -1;\n\n return ShellBrowserMain(main_function_params);\n}\n\nvoid ShellMainDelegate::InitializeResourceBundle() {\n FilePath pak_file;\n#if defined(OS_MACOSX)\n pak_file = GetResourcesPakFilePath();\n#else\n FilePath pak_dir;\n PathService::Get(base::DIR_MODULE, &pak_dir);\n pak_file = pak_dir.Append(FILE_PATH_LITERAL(\"nw.pak\"));\n#endif\n ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);\n}\n\nContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() {\n browser_client_.reset(new ShellContentBrowserClient);\n return browser_client_.get();\n}\n\nContentRendererClient* ShellMainDelegate::CreateContentRendererClient() {\n renderer_client_.reset(new ShellContentRendererClient);\n return renderer_client_.get();\n}\n\n} // namespace content\n", "file_path": "src/shell_main_delegate.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.9012560248374939, 0.050705548375844955, 0.0001651029015192762, 0.00019137705385219306, 0.20629137754440308]} {"hunk": {"id": 9, "code_window": ["}\n", "\n", "void ShellContentBrowserClient::RenderProcessHostCreated(\n", " RenderProcessHost* host) {\n", " int id = host->GetID();\n", "#if defined(ENABLE_PRINTING)\n", " host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n", "#endif\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" if (!master_rph_)\n", " master_rph_ = host;\n"], "file_path": "src/shell_content_browser_client.cc", "type": "add", "edit_start_line_idx": 296}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Multiply-included file, no traditional include guard.\n#include \n\n#include \"base/values.h\"\n#include \"extensions/common/draggable_region.h\"\n#include \"content/public/common/common_param_traits.h\"\n#include \"ipc/ipc_message_macros.h\"\n\n#define IPC_MESSAGE_START ShellMsgStart\n\nIPC_STRUCT_TRAITS_BEGIN(extensions::DraggableRegion)\n IPC_STRUCT_TRAITS_MEMBER(draggable)\n IPC_STRUCT_TRAITS_MEMBER(bounds)\nIPC_STRUCT_TRAITS_END()\n\nIPC_MESSAGE_ROUTED3(ShellViewHostMsg_Allocate_Object,\n int /* object id */,\n std::string /* type name */,\n DictionaryValue /* option */)\n\nIPC_MESSAGE_ROUTED1(ShellViewHostMsg_Deallocate_Object,\n int /* object id */)\n\nIPC_MESSAGE_ROUTED4(ShellViewHostMsg_Call_Object_Method,\n int /* object id */,\n std::string /* type name */,\n std::string /* method name */,\n ListValue /* arguments */)\n\nIPC_SYNC_MESSAGE_ROUTED4_1(ShellViewHostMsg_Call_Object_Method_Sync,\n int /* object id */,\n std::string /* type name */,\n std::string /* method name */,\n ListValue /* arguments */,\n ListValue /* result */)\n\nIPC_MESSAGE_ROUTED3(ShellViewHostMsg_Call_Static_Method,\n std::string /* type name */,\n std::string /* method name */,\n ListValue /* arguments */)\n\nIPC_SYNC_MESSAGE_ROUTED3_1(ShellViewHostMsg_Call_Static_Method_Sync,\n std::string /* type name */,\n std::string /* method name */,\n ListValue /* arguments */,\n ListValue /* result */)\n\nIPC_MESSAGE_ROUTED3(ShellViewMsg_Object_On_Event,\n int /* object id */,\n std::string /* event name */,\n ListValue /* arguments */)\n\n// Request Shell's id for current render_view_host.\nIPC_SYNC_MESSAGE_ROUTED0_1(ShellViewHostMsg_GetShellId,\n int /* result */)\n\n// Create a Shell and returns its routing id.\nIPC_SYNC_MESSAGE_ROUTED2_1(ShellViewHostMsg_CreateShell,\n std::string /* url */,\n DictionaryValue /* manifest */,\n int /* result */)\n\n// Tell browser we have an uncaughtException from node.\nIPC_MESSAGE_ROUTED1(ShellViewHostMsg_UncaughtException,\n std::string /* err */)\n\n// Sent by the renderer when the draggable regions are updated.\nIPC_MESSAGE_ROUTED1(ShellViewHostMsg_UpdateDraggableRegions,\n std::vector /* regions */)\n\n// The browser want to open a file.\nIPC_MESSAGE_CONTROL1(ShellViewMsg_Open,\n std::string /* file name */)\n", "file_path": "src/api/api_messages.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.018636055290699005, 0.0026818562764674425, 0.00016725898603908718, 0.0002536311512812972, 0.005425082519650459]} {"hunk": {"id": 10, "code_window": ["class ShellBrowserContext;\n", "class ShellBrowserMainParts;\n", "class ShellResourceDispatcherHostDelegate;\n", "\n", "class ShellContentBrowserClient : public ContentBrowserClient {\n", " public:\n", " ShellContentBrowserClient();\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["class RenderProcessHost;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/shell_content_browser_client.h\"\n\n#include \"base/command_line.h\"\n#include \"base/files/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/string_util.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"base/values.h\"\n#include \"content/public/browser/browser_url_handler.h\"\n#include \"content/nw/src/browser/printing/printing_message_filter.h\"\n#include \"content/public/browser/render_process_host.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/resource_dispatcher_host.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/common/renderer_preferences.h\"\n#include \"content/nw/src/api/dispatcher_host.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/browser/printing/print_job_manager.h\"\n#include \"content/nw/src/browser/shell_devtools_delegate.h\"\n#include \"content/nw/src/browser/shell_resource_dispatcher_host_delegate.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/nw/src/nw_package.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/nw/src/nw_version.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/shell_browser_main_parts.h\"\n#include \"geolocation/shell_access_token_store.h\"\n#include \"googleurl/src/gurl.h\"\n#include \"webkit/glue/webpreferences.h\"\n#include \"webkit/user_agent/user_agent_util.h\"\n#include \"ui/base/l10n/l10n_util.h\"\n#include \"webkit/plugins/npapi/plugin_list.h\"\n\n\nnamespace content {\n\nShellContentBrowserClient::ShellContentBrowserClient()\n : shell_browser_main_parts_(NULL) {\n}\n\nShellContentBrowserClient::~ShellContentBrowserClient() {\n}\n\nBrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);\n return shell_browser_main_parts_;\n}\n\nWebContentsViewPort* ShellContentBrowserClient::OverrideCreateWebContentsView(\n WebContents* web_contents,\n RenderViewHostDelegateView** render_view_host_delegate_view) {\n std::string user_agent, rules;\n nw::Package* package = shell_browser_main_parts()->package();\n content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs();\n if (package->root()->GetString(switches::kmUserAgent, &user_agent)) {\n std::string name, version;\n package->root()->GetString(switches::kmName, &name);\n package->root()->GetString(\"version\", &version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%name\", name);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%ver\", version);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%nwver\", NW_VERSION_STRING);\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%webkit_ver\", webkit_glue::GetWebKitVersion());\n ReplaceSubstringsAfterOffset(&user_agent, 0, \"%osinfo\", webkit_glue::BuildOSInfo());\n prefs->user_agent_override = user_agent;\n }\n if (package->root()->GetString(switches::kmRemotePages, &rules))\n prefs->nw_remote_page_rules = rules;\n return NULL;\n}\n\nvoid ShellContentBrowserClient::RenderViewHostCreated(\n RenderViewHost* render_view_host) {\n new api::DispatcherHost(render_view_host);\n}\n\nstd::string ShellContentBrowserClient::GetApplicationLocale() {\n return l10n_util::GetApplicationLocale(\"en-US\");\n}\n\nvoid ShellContentBrowserClient::AppendExtraCommandLineSwitches(\n CommandLine* command_line,\n int child_process_id) {\n if (command_line->GetSwitchValueASCII(\"type\") != \"renderer\")\n return;\n if (child_process_id > 0) {\n content::RenderProcessHost* rph =\n content::RenderProcessHost::FromID(child_process_id);\n\n content::RenderProcessHost::RenderWidgetHostsIterator iter(\n rph->GetRenderWidgetHostsIterator());\n for (; !iter.IsAtEnd(); iter.Advance()) {\n const content::RenderWidgetHost* widget = iter.GetCurrentValue();\n DCHECK(widget);\n if (!widget || !widget->IsRenderView())\n continue;\n\n content::RenderViewHost* host = content::RenderViewHost::From(\n const_cast(widget));\n content::Shell* shell = content::Shell::FromRenderViewHost(host);\n if (shell && (shell->is_devtools() || !shell->nodejs()))\n return;\n }\n }\n nw::Package* package = shell_browser_main_parts()->package();\n if (package && package->GetUseNode()) {\n // Allow node.js\n command_line->AppendSwitch(switches::kNodejs);\n\n // Set cwd\n command_line->AppendSwitchPath(switches::kWorkingDirectory,\n package->path());\n\n // Check if we have 'node-main'.\n std::string node_main;\n if (package->root()->GetString(switches::kNodeMain, &node_main))\n command_line->AppendSwitchASCII(switches::kNodeMain, node_main);\n\n std::string snapshot_path;\n if (package->root()->GetString(switches::kSnapshot, &snapshot_path))\n command_line->AppendSwitchASCII(switches::kSnapshot, snapshot_path);\n }\n\n // without the switch, the destructor of the shell object will\n // shutdown renderwidgethost (RenderWidgetHostImpl::Shutdown) and\n // destory rph immediately. Then the channel error msg is caught by\n // SuicideOnChannelErrorFilter and the renderer is killed\n // immediately\n#if defined(OS_POSIX)\n command_line->AppendSwitch(switches::kChildCleanExit);\n#endif\n}\n\nvoid ShellContentBrowserClient::ResourceDispatcherHostCreated() {\n resource_dispatcher_host_delegate_.reset(\n new ShellResourceDispatcherHostDelegate());\n ResourceDispatcherHost::Get()->SetDelegate(\n resource_dispatcher_host_delegate_.get());\n}\n\nstd::string ShellContentBrowserClient::GetDefaultDownloadName() {\n return \"download\";\n}\n\nMediaObserver* ShellContentBrowserClient::GetMediaObserver() {\n return MediaInternals::GetInstance();\n}\n\nvoid ShellContentBrowserClient::BrowserURLHandlerCreated(\n BrowserURLHandler* handler) {\n}\n\nShellBrowserContext* ShellContentBrowserClient::browser_context() {\n return shell_browser_main_parts_->browser_context();\n}\n\nShellBrowserContext*\n ShellContentBrowserClient::off_the_record_browser_context() {\n return shell_browser_main_parts_->off_the_record_browser_context();\n}\n\nAccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {\n return new ShellAccessTokenStore(browser_context()->GetRequestContext());\n}\n\nvoid ShellContentBrowserClient::OverrideWebkitPrefs(\n RenderViewHost* render_view_host,\n const GURL& url,\n webkit_glue::WebPreferences* prefs) {\n nw::Package* package = shell_browser_main_parts()->package();\n\n // Disable web security.\n prefs->dom_paste_enabled = true;\n prefs->javascript_can_access_clipboard = true;\n prefs->web_security_enabled = false;\n prefs->allow_file_access_from_file_urls = true;\n\n // Open experimental features.\n prefs->css_sticky_position_enabled = true;\n prefs->css_shaders_enabled = true;\n prefs->css_variables_enabled = true;\n\n // Disable plugins and cache by default.\n prefs->plugins_enabled = false;\n prefs->java_enabled = false;\n prefs->uses_page_cache = false;\n\n base::DictionaryValue* webkit;\n if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {\n webkit->GetBoolean(switches::kmJava, &prefs->java_enabled);\n webkit->GetBoolean(switches::kmPlugin, &prefs->plugins_enabled);\n webkit->GetBoolean(switches::kmPageCache, &prefs->uses_page_cache);\n FilePath plugins_dir = package->path();\n //PathService::Get(base::DIR_CURRENT, &plugins_dir);\n plugins_dir = plugins_dir.AppendASCII(\"plugins\");\n\n webkit::npapi::PluginList::Singleton()->AddExtraPluginDir(plugins_dir);\n }\n}\n\nbool ShellContentBrowserClient::ShouldTryToUseExistingProcessHost(\n BrowserContext* browser_context, const GURL& url) {\n ShellBrowserContext* shell_browser_context =\n static_cast(browser_context);\n if (shell_browser_context->pinning_renderer())\n return true;\n else\n return false;\n}\n\nbool ShellContentBrowserClient::IsSuitableHost(RenderProcessHost* process_host,\n const GURL& site_url) {\n return true;\n}\n\nnet::URLRequestContextGetter* ShellContentBrowserClient::CreateRequestContext(\n BrowserContext* content_browser_context,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContext(\n blob_protocol_handler.Pass(), file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nnet::URLRequestContextGetter*\nShellContentBrowserClient::CreateRequestContextForStoragePartition(\n BrowserContext* content_browser_context,\n const base::FilePath& partition_path,\n bool in_memory,\n scoped_ptr\n blob_protocol_handler,\n scoped_ptr\n file_system_protocol_handler,\n scoped_ptr\n developer_protocol_handler,\n scoped_ptr\n chrome_protocol_handler,\n scoped_ptr\n chrome_devtools_protocol_handler) {\n ShellBrowserContext* shell_browser_context =\n ShellBrowserContextForBrowserContext(content_browser_context);\n return shell_browser_context->CreateRequestContextForStoragePartition(\n partition_path, in_memory, blob_protocol_handler.Pass(),\n file_system_protocol_handler.Pass(),\n developer_protocol_handler.Pass(), chrome_protocol_handler.Pass(),\n chrome_devtools_protocol_handler.Pass());\n}\n\nShellBrowserContext*\nShellContentBrowserClient::ShellBrowserContextForBrowserContext(\n BrowserContext* content_browser_context) {\n if (content_browser_context == browser_context())\n return browser_context();\n DCHECK_EQ(content_browser_context, off_the_record_browser_context());\n return off_the_record_browser_context();\n}\n\nprinting::PrintJobManager* ShellContentBrowserClient::print_job_manager() {\n return shell_browser_main_parts_->print_job_manager();\n}\n\nvoid ShellContentBrowserClient::RenderProcessHostCreated(\n RenderProcessHost* host) {\n int id = host->GetID();\n#if defined(ENABLE_PRINTING)\n host->GetChannel()->AddFilter(new PrintingMessageFilter(id));\n#endif\n}\n} // namespace content\n", "file_path": "src/shell_content_browser_client.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.9991326928138733, 0.6368334293365479, 0.0001664174342295155, 0.9967250227928162, 0.4725188910961151]} {"hunk": {"id": 10, "code_window": ["class ShellBrowserContext;\n", "class ShellBrowserMainParts;\n", "class ShellResourceDispatcherHostDelegate;\n", "\n", "class ShellContentBrowserClient : public ContentBrowserClient {\n", " public:\n", " ShellContentBrowserClient();\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["class RenderProcessHost;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n// IPC messages for printing.\n// Multiply-included message file, hence no include guard.\n\n#include \n#include \n\n#include \"base/values.h\"\n#include \"base/shared_memory.h\"\n#include \"ipc/ipc_message_macros.h\"\n#include \"printing/page_size_margins.h\"\n#include \"printing/print_job_constants.h\"\n#include \"third_party/WebKit/Source/WebKit/chromium/public/WebPrintScalingOption.h\"\n#include \"ui/gfx/native_widget_types.h\"\n#include \"ui/gfx/rect.h\"\n\n#ifndef NW_COMMON_PRINT_MESSAGES_H_\n#define NW_COMMON_PRINT_MESSAGES_H_\n\nstruct PrintMsg_Print_Params {\n PrintMsg_Print_Params();\n ~PrintMsg_Print_Params();\n\n // Resets the members of the struct to 0.\n void Reset();\n\n gfx::Size page_size;\n gfx::Size content_size;\n gfx::Rect printable_area;\n int margin_top;\n int margin_left;\n double dpi;\n double min_shrink;\n double max_shrink;\n int desired_dpi;\n int document_cookie;\n bool selection_only;\n bool supports_alpha_blend;\n int32 preview_ui_id;\n int preview_request_id;\n bool is_first_request;\n WebKit::WebPrintScalingOption print_scaling_option;\n bool print_to_pdf;\n bool display_header_footer;\n string16 date;\n string16 title;\n string16 url;\n bool should_print_backgrounds;\n};\n\nstruct PrintMsg_PrintPages_Params {\n PrintMsg_PrintPages_Params();\n ~PrintMsg_PrintPages_Params();\n\n // Resets the members of the struct to 0.\n void Reset();\n\n PrintMsg_Print_Params params;\n std::vector pages;\n};\n\nstruct PrintHostMsg_RequestPrintPreview_Params {\n PrintHostMsg_RequestPrintPreview_Params();\n ~PrintHostMsg_RequestPrintPreview_Params();\n bool is_modifiable;\n bool webnode_only;\n bool has_selection;\n bool selection_only;\n};\n\n#endif // CHROME_COMMON_PRINT_MESSAGES_H_\n\n#define IPC_MESSAGE_START PrintMsgStart\n\nIPC_ENUM_TRAITS(printing::MarginType)\nIPC_ENUM_TRAITS(WebKit::WebPrintScalingOption)\n\n// Parameters for a render request.\nIPC_STRUCT_TRAITS_BEGIN(PrintMsg_Print_Params)\n // Physical size of the page, including non-printable margins,\n // in pixels according to dpi.\n IPC_STRUCT_TRAITS_MEMBER(page_size)\n\n // In pixels according to dpi_x and dpi_y.\n IPC_STRUCT_TRAITS_MEMBER(content_size)\n\n // Physical printable area of the page in pixels according to dpi.\n IPC_STRUCT_TRAITS_MEMBER(printable_area)\n\n // The y-offset of the printable area, in pixels according to dpi.\n IPC_STRUCT_TRAITS_MEMBER(margin_top)\n\n // The x-offset of the printable area, in pixels according to dpi.\n IPC_STRUCT_TRAITS_MEMBER(margin_left)\n\n // Specifies dots per inch.\n IPC_STRUCT_TRAITS_MEMBER(dpi)\n\n // Minimum shrink factor. See PrintSettings::min_shrink for more information.\n IPC_STRUCT_TRAITS_MEMBER(min_shrink)\n\n // Maximum shrink factor. See PrintSettings::max_shrink for more information.\n IPC_STRUCT_TRAITS_MEMBER(max_shrink)\n\n // Desired apparent dpi on paper.\n IPC_STRUCT_TRAITS_MEMBER(desired_dpi)\n\n // Cookie for the document to ensure correctness.\n IPC_STRUCT_TRAITS_MEMBER(document_cookie)\n\n // Should only print currently selected text.\n IPC_STRUCT_TRAITS_MEMBER(selection_only)\n\n // Does the printer support alpha blending?\n IPC_STRUCT_TRAITS_MEMBER(supports_alpha_blend)\n\n // *** Parameters below are used only for print preview. ***\n\n // The print preview ui associated with this request.\n IPC_STRUCT_TRAITS_MEMBER(preview_ui_id)\n\n // The id of the preview request.\n IPC_STRUCT_TRAITS_MEMBER(preview_request_id)\n\n // True if this is the first preview request.\n IPC_STRUCT_TRAITS_MEMBER(is_first_request)\n\n // Specifies the page scaling option for preview printing.\n IPC_STRUCT_TRAITS_MEMBER(print_scaling_option)\n\n // True if print to pdf is requested.\n IPC_STRUCT_TRAITS_MEMBER(print_to_pdf)\n\n // Specifies if the header and footer should be rendered.\n IPC_STRUCT_TRAITS_MEMBER(display_header_footer)\n\n // Date string to be printed as header if requested by the user.\n IPC_STRUCT_TRAITS_MEMBER(date)\n\n // Title string to be printed as header if requested by the user.\n IPC_STRUCT_TRAITS_MEMBER(title)\n\n // URL string to be printed as footer if requested by the user.\n IPC_STRUCT_TRAITS_MEMBER(url)\n\n // True if print backgrounds is requested by the user.\n IPC_STRUCT_TRAITS_MEMBER(should_print_backgrounds)\nIPC_STRUCT_TRAITS_END()\n\nIPC_STRUCT_BEGIN(PrintMsg_PrintPage_Params)\n // Parameters to render the page as a printed page. It must always be the same\n // value for all the document.\n IPC_STRUCT_MEMBER(PrintMsg_Print_Params, params)\n\n // The page number is the indicator of the square that should be rendered\n // according to the layout specified in PrintMsg_Print_Params.\n IPC_STRUCT_MEMBER(int, page_number)\nIPC_STRUCT_END()\n\nIPC_STRUCT_TRAITS_BEGIN(PrintHostMsg_RequestPrintPreview_Params)\n IPC_STRUCT_TRAITS_MEMBER(is_modifiable)\n IPC_STRUCT_TRAITS_MEMBER(webnode_only)\n IPC_STRUCT_TRAITS_MEMBER(has_selection)\n IPC_STRUCT_TRAITS_MEMBER(selection_only)\nIPC_STRUCT_TRAITS_END()\n\nIPC_STRUCT_TRAITS_BEGIN(printing::PageSizeMargins)\n IPC_STRUCT_TRAITS_MEMBER(content_width)\n IPC_STRUCT_TRAITS_MEMBER(content_height)\n IPC_STRUCT_TRAITS_MEMBER(margin_left)\n IPC_STRUCT_TRAITS_MEMBER(margin_right)\n IPC_STRUCT_TRAITS_MEMBER(margin_top)\n IPC_STRUCT_TRAITS_MEMBER(margin_bottom)\nIPC_STRUCT_TRAITS_END()\n\nIPC_STRUCT_TRAITS_BEGIN(PrintMsg_PrintPages_Params)\n // Parameters to render the page as a printed page. It must always be the same\n // value for all the document.\n IPC_STRUCT_TRAITS_MEMBER(params)\n\n // If empty, this means a request to render all the printed pages.\n IPC_STRUCT_TRAITS_MEMBER(pages)\nIPC_STRUCT_TRAITS_END()\n\n// Parameters to describe a rendered document.\nIPC_STRUCT_BEGIN(PrintHostMsg_DidPreviewDocument_Params)\n // True when we can reuse existing preview data. |metafile_data_handle| and\n // |data_size| should not be used when this is true.\n IPC_STRUCT_MEMBER(bool, reuse_existing_data)\n\n // A shared memory handle to metafile data.\n IPC_STRUCT_MEMBER(base::SharedMemoryHandle, metafile_data_handle)\n\n // Size of metafile data.\n IPC_STRUCT_MEMBER(uint32, data_size)\n\n // Cookie for the document to ensure correctness.\n IPC_STRUCT_MEMBER(int, document_cookie)\n\n // Store the expected pages count.\n IPC_STRUCT_MEMBER(int, expected_pages_count)\n\n // Whether the preview can be modified.\n IPC_STRUCT_MEMBER(bool, modifiable)\n\n // The id of the preview request.\n IPC_STRUCT_MEMBER(int, preview_request_id)\nIPC_STRUCT_END()\n\n// Parameters to describe a rendered preview page.\nIPC_STRUCT_BEGIN(PrintHostMsg_DidPreviewPage_Params)\n // A shared memory handle to metafile data for a draft document of the page.\n IPC_STRUCT_MEMBER(base::SharedMemoryHandle, metafile_data_handle)\n\n // Size of metafile data.\n IPC_STRUCT_MEMBER(uint32, data_size)\n\n // |page_number| is zero-based and can be |printing::INVALID_PAGE_INDEX| if it\n // is just a check.\n IPC_STRUCT_MEMBER(int, page_number)\n\n // The id of the preview request.\n IPC_STRUCT_MEMBER(int, preview_request_id)\nIPC_STRUCT_END()\n\n// Parameters sent along with the page count.\nIPC_STRUCT_BEGIN(PrintHostMsg_DidGetPreviewPageCount_Params)\n // Cookie for the document to ensure correctness.\n IPC_STRUCT_MEMBER(int, document_cookie)\n\n // Total page count.\n IPC_STRUCT_MEMBER(int, page_count)\n\n // Indicates whether the previewed document is modifiable.\n IPC_STRUCT_MEMBER(bool, is_modifiable)\n\n // The id of the preview request.\n IPC_STRUCT_MEMBER(int, preview_request_id)\n\n // Indicates whether the existing preview data needs to be cleared or not.\n IPC_STRUCT_MEMBER(bool, clear_preview_data)\nIPC_STRUCT_END()\n\n// Parameters to describe a rendered page.\nIPC_STRUCT_BEGIN(PrintHostMsg_DidPrintPage_Params)\n // A shared memory handle to the EMF data. This data can be quite large so a\n // memory map needs to be used.\n IPC_STRUCT_MEMBER(base::SharedMemoryHandle, metafile_data_handle)\n\n // Size of the metafile data.\n IPC_STRUCT_MEMBER(uint32, data_size)\n\n // Cookie for the document to ensure correctness.\n IPC_STRUCT_MEMBER(int, document_cookie)\n\n // Page number.\n IPC_STRUCT_MEMBER(int, page_number)\n\n // Shrink factor used to render this page.\n IPC_STRUCT_MEMBER(double, actual_shrink)\n\n // The size of the page the page author specified.\n IPC_STRUCT_MEMBER(gfx::Size, page_size)\n\n // The printable area the page author specified.\n IPC_STRUCT_MEMBER(gfx::Rect, content_area)\nIPC_STRUCT_END()\n\n// Parameters for the IPC message ViewHostMsg_ScriptedPrint\nIPC_STRUCT_BEGIN(PrintHostMsg_ScriptedPrint_Params)\n IPC_STRUCT_MEMBER(int, cookie)\n IPC_STRUCT_MEMBER(int, expected_pages_count)\n IPC_STRUCT_MEMBER(bool, has_selection)\n IPC_STRUCT_MEMBER(printing::MarginType, margin_type)\nIPC_STRUCT_END()\n\n\n// Messages sent from the browser to the renderer.\n\n// Tells the render view to initiate print preview for the entire document.\nIPC_MESSAGE_ROUTED1(PrintMsg_InitiatePrintPreview, bool /* selection_only */)\n\n// Tells the render view to initiate printing or print preview for a particular\n// node, depending on which mode the render view is in.\nIPC_MESSAGE_ROUTED0(PrintMsg_PrintNodeUnderContextMenu)\n\n// Tells the renderer to print the print preview tab's PDF plugin without\n// showing the print dialog. (This is the final step in the print preview\n// workflow.)\nIPC_MESSAGE_ROUTED1(PrintMsg_PrintForPrintPreview,\n DictionaryValue /* settings */)\n\n// Tells the render view to switch the CSS to print media type, renders every\n// requested pages and switch back the CSS to display media type.\nIPC_MESSAGE_ROUTED0(PrintMsg_PrintPages)\n\n// Tells the render view that printing is done so it can clean up.\nIPC_MESSAGE_ROUTED1(PrintMsg_PrintingDone,\n bool /* success */)\n\n// Tells the render view whether scripted printing is blocked or not.\nIPC_MESSAGE_ROUTED1(PrintMsg_SetScriptedPrintingBlocked,\n bool /* blocked */)\n\n// Tells the render view to switch the CSS to print media type, renders every\n// requested pages for print preview using the given |settings|. This gets\n// called multiple times as the user updates settings.\nIPC_MESSAGE_ROUTED1(PrintMsg_PrintPreview,\n DictionaryValue /* settings */)\n\n// Like PrintMsg_PrintPages, but using the print preview document's frame/node.\nIPC_MESSAGE_ROUTED0(PrintMsg_PrintForSystemDialog)\n\n// Tells a renderer to stop blocking script initiated printing.\nIPC_MESSAGE_ROUTED0(PrintMsg_ResetScriptedPrintCount)\n\n// Messages sent from the renderer to the browser.\n\n#if defined(OS_WIN)\n// Duplicates a shared memory handle from the renderer to the browser. Then\n// the renderer can flush the handle.\nIPC_SYNC_MESSAGE_ROUTED1_1(PrintHostMsg_DuplicateSection,\n base::SharedMemoryHandle /* renderer handle */,\n base::SharedMemoryHandle /* browser handle */)\n#endif\n\n// Tells the browser that the renderer is done calculating the number of\n// rendered pages according to the specified settings.\nIPC_MESSAGE_ROUTED2(PrintHostMsg_DidGetPrintedPagesCount,\n int /* rendered document cookie */,\n int /* number of rendered pages */)\n\n// Sends the document cookie of the current printer query to the browser.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_DidGetDocumentCookie,\n int /* rendered document cookie */)\n\n// Tells the browser that the print dialog has been shown.\nIPC_MESSAGE_ROUTED0(PrintHostMsg_DidShowPrintDialog)\n\n// Sends back to the browser the rendered \"printed page\" that was requested by\n// a ViewMsg_PrintPage message or from scripted printing. The memory handle in\n// this message is already valid in the browser process.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_DidPrintPage,\n PrintHostMsg_DidPrintPage_Params /* page content */)\n\n// The renderer wants to know the default print settings.\nIPC_SYNC_MESSAGE_ROUTED0_1(PrintHostMsg_GetDefaultPrintSettings,\n PrintMsg_Print_Params /* default_settings */)\n\n// The renderer wants to update the current print settings with new\n// |job_settings|.\nIPC_SYNC_MESSAGE_ROUTED2_1(PrintHostMsg_UpdatePrintSettings,\n int /* document_cookie */,\n DictionaryValue /* job_settings */,\n PrintMsg_PrintPages_Params /* current_settings */)\n\n// It's the renderer that controls the printing process when it is generated\n// by javascript. This step is about showing UI to the user to select the\n// final print settings. The output parameter is the same as\n// ViewMsg_PrintPages which is executed implicitly.\nIPC_SYNC_MESSAGE_ROUTED1_1(PrintHostMsg_ScriptedPrint,\n PrintHostMsg_ScriptedPrint_Params,\n PrintMsg_PrintPages_Params\n /* settings chosen by the user*/)\n\n#if defined(USE_X11)\n// Asks the browser to create a temporary file for the renderer to fill\n// in resulting NativeMetafile in printing.\nIPC_SYNC_MESSAGE_CONTROL0_2(PrintHostMsg_AllocateTempFileForPrinting,\n base::FileDescriptor /* temp file fd */,\n int /* fd in browser*/)\nIPC_MESSAGE_CONTROL2(PrintHostMsg_TempFileForPrintingWritten,\n int /* render_view_id */,\n int /* fd in browser */)\n#endif\n\n// Asks the browser to do print preview.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_RequestPrintPreview,\n PrintHostMsg_RequestPrintPreview_Params /* params */)\n\n// Notify the browser the number of pages in the print preview document.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_DidGetPreviewPageCount,\n PrintHostMsg_DidGetPreviewPageCount_Params /* params */)\n\n// Notify the browser of the default page layout according to the currently\n// selected printer and page size.\n// |printable_area_in_points| Specifies the printable area in points.\n// |has_custom_page_size_style| is true when the printing frame has a custom\n// page size css otherwise false.\nIPC_MESSAGE_ROUTED3(PrintHostMsg_DidGetDefaultPageLayout,\n printing::PageSizeMargins /* page layout in points */,\n gfx::Rect /* printable area in points */,\n bool /* has custom page size style */)\n\n// Notify the browser a print preview page has been rendered.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_DidPreviewPage,\n PrintHostMsg_DidPreviewPage_Params /* params */)\n\n// Asks the browser whether the print preview has been cancelled.\nIPC_SYNC_MESSAGE_ROUTED2_1(PrintHostMsg_CheckForCancel,\n int32 /* PrintPreviewUI ID */,\n int /* request id */,\n bool /* print preview cancelled */)\n\n// Sends back to the browser the complete rendered document (non-draft mode,\n// used for printing) that was requested by a PrintMsg_PrintPreview message.\n// The memory handle in this message is already valid in the browser process.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_MetafileReadyForPrinting,\n PrintHostMsg_DidPreviewDocument_Params /* params */)\n\n// Tell the browser printing failed.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_PrintingFailed,\n int /* document cookie */)\n\n// Tell the browser print preview failed.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_PrintPreviewFailed,\n int /* document cookie */)\n\n// Tell the browser print preview was cancelled.\nIPC_MESSAGE_ROUTED1(PrintHostMsg_PrintPreviewCancelled,\n int /* document cookie */)\n\n// Tell the browser print preview found the selected printer has invalid\n// settings (which typically caused by disconnected network printer or printer\n// driver is bogus).\nIPC_MESSAGE_ROUTED1(PrintHostMsg_PrintPreviewInvalidPrinterSettings,\n int /* document cookie */)\n\n// Run a nested message loop in the renderer until print preview for\n// window.print() finishes.\nIPC_SYNC_MESSAGE_ROUTED1_0(PrintHostMsg_ScriptedPrintPreview,\n bool /* is_modifiable */)\n\n// Notify the browser that the PDF in the initiator renderer has disabled print\n// scaling option.\nIPC_MESSAGE_ROUTED0(PrintHostMsg_PrintPreviewScalingDisabled)\n", "file_path": "src/common/print_messages.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0012609300902113318, 0.00024514159304089844, 0.00016343899187631905, 0.00016897491877898574, 0.00022642545809503645]} {"hunk": {"id": 10, "code_window": ["class ShellBrowserContext;\n", "class ShellBrowserMainParts;\n", "class ShellResourceDispatcherHostDelegate;\n", "\n", "class ShellContentBrowserClient : public ContentBrowserClient {\n", " public:\n", " ShellContentBrowserClient();\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["class RenderProcessHost;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 24}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/browser/native_window_win.h\"\n\n#include \"base/utf_string_conversions.h\"\n#include \"base/values.h\"\n#include \"base/win/wrapped_window_proc.h\"\n#include \"chrome/browser/platform_util.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/browser/native_window_toolbar_win.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/native_web_keyboard_event.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/browser/render_widget_host_view.h\"\n#include \"content/public/browser/web_contents.h\"\n#include \"content/public/browser/web_contents_view.h\"\n#include \"extensions/common/draggable_region.h\"\n#include \"third_party/skia/include/core/SkPaint.h\"\n#include \"ui/base/hit_test.h\"\n#include \"ui/base/win/hwnd_util.h\"\n#include \"ui/gfx/path.h\"\n#include \"ui/views/controls/webview/webview.h\"\n#include \"ui/views/layout/box_layout.h\"\n#include \"ui/views/views_delegate.h\"\n#include \"ui/views/widget/widget.h\"\n#include \"ui/views/widget/native_widget_win.h\"\n#include \"ui/views/window/native_frame_view.h\"\n\nnamespace nw {\n\nnamespace {\n\nconst int kResizeInsideBoundsSize = 5;\nconst int kResizeAreaCornerSize = 16;\n\n// Returns true if |possible_parent| is a parent window of |child|.\nbool IsParent(gfx::NativeView child, gfx::NativeView possible_parent) {\n if (!child)\n return false;\n#if !defined(USE_AURA) && defined(OS_WIN)\n if (::GetWindow(child, GW_OWNER) == possible_parent)\n return true;\n#endif\n gfx::NativeView parent = child;\n while ((parent = platform_util::GetParent(parent))) {\n if (possible_parent == parent)\n return true;\n }\n\n return false;\n}\n\nclass NativeWindowClientView : public views::ClientView {\n public:\n NativeWindowClientView(views::Widget* widget,\n views::View* contents_view,\n content::Shell* shell)\n : views::ClientView(widget, contents_view),\n shell_(shell) {\n }\n virtual ~NativeWindowClientView() {}\n\n virtual bool CanClose() OVERRIDE {\n return shell_->ShouldCloseWindow();\n }\n\n private:\n content::Shell* shell_;\n};\n\nclass NativeWindowFrameView : public views::NonClientFrameView {\n public:\n static const char kViewClassName[];\n\n explicit NativeWindowFrameView(NativeWindowWin* window);\n virtual ~NativeWindowFrameView();\n\n void Init(views::Widget* frame);\n\n // views::NonClientFrameView implementation.\n virtual gfx::Rect GetBoundsForClientView() const OVERRIDE;\n virtual gfx::Rect GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const OVERRIDE;\n virtual int NonClientHitTest(const gfx::Point& point) OVERRIDE;\n virtual void GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) OVERRIDE;\n virtual void ResetWindowControls() OVERRIDE {}\n virtual void UpdateWindowIcon() OVERRIDE {}\n virtual void UpdateWindowTitle() OVERRIDE {}\n\n // views::View implementation.\n virtual gfx::Size GetPreferredSize() OVERRIDE;\n virtual void Layout() OVERRIDE;\n virtual std::string GetClassName() const OVERRIDE;\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;\n virtual gfx::Size GetMinimumSize() OVERRIDE;\n virtual gfx::Size GetMaximumSize() OVERRIDE;\n\n private:\n NativeWindowWin* window_;\n views::Widget* frame_;\n\n DISALLOW_COPY_AND_ASSIGN(NativeWindowFrameView);\n};\n\nconst char NativeWindowFrameView::kViewClassName[] =\n \"content/nw/src/browser/NativeWindowFrameView\";\n\nNativeWindowFrameView::NativeWindowFrameView(NativeWindowWin* window)\n : window_(window),\n frame_(NULL) {\n}\n\nNativeWindowFrameView::~NativeWindowFrameView() {\n}\n\nvoid NativeWindowFrameView::Init(views::Widget* frame) {\n frame_ = frame;\n}\n\ngfx::Rect NativeWindowFrameView::GetBoundsForClientView() const {\n return bounds();\n}\n\ngfx::Rect NativeWindowFrameView::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n gfx::Rect window_bounds = client_bounds;\n // Enforce minimum size (1, 1) in case that client_bounds is passed with\n // empty size. This could occur when the frameless window is being\n // initialized.\n if (window_bounds.IsEmpty()) {\n window_bounds.set_width(1);\n window_bounds.set_height(1);\n }\n return window_bounds;\n}\n\nint NativeWindowFrameView::NonClientHitTest(const gfx::Point& point) {\n if (frame_->IsFullscreen())\n return HTCLIENT;\n\n // Check the frame first, as we allow a small area overlapping the contents\n // to be used for resize handles.\n bool can_ever_resize = frame_->widget_delegate() ?\n frame_->widget_delegate()->CanResize() :\n false;\n // Don't allow overlapping resize handles when the window is maximized or\n // fullscreen, as it can't be resized in those states.\n int resize_border =\n frame_->IsMaximized() || frame_->IsFullscreen() ? 0 :\n kResizeInsideBoundsSize;\n int frame_component = GetHTComponentForFrame(point,\n resize_border,\n resize_border,\n kResizeAreaCornerSize,\n kResizeAreaCornerSize,\n can_ever_resize);\n if (frame_component != HTNOWHERE)\n return frame_component;\n\n // Ajust the point if we have a toolbar.\n gfx::Point adjusted_point(point);\n if (window_->toolbar())\n adjusted_point.set_y(adjusted_point.y() - window_->toolbar()->height());\n\n // Check for possible draggable region in the client area for the frameless\n // window.\n if (window_->draggable_region() &&\n window_->draggable_region()->contains(adjusted_point.x(),\n adjusted_point.y()))\n return HTCAPTION;\n\n int client_component = frame_->client_view()->NonClientHitTest(point);\n if (client_component != HTNOWHERE)\n return client_component;\n\n // Caption is a safe default.\n return HTCAPTION;\n}\n\nvoid NativeWindowFrameView::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n // We got nothing to say about no window mask.\n}\n\ngfx::Size NativeWindowFrameView::GetPreferredSize() {\n gfx::Size pref = frame_->client_view()->GetPreferredSize();\n gfx::Rect bounds(0, 0, pref.width(), pref.height());\n return frame_->non_client_view()->GetWindowBoundsForClientBounds(\n bounds).size();\n}\n\nvoid NativeWindowFrameView::Layout() {\n}\n\nvoid NativeWindowFrameView::OnPaint(gfx::Canvas* canvas) {\n}\n\nstd::string NativeWindowFrameView::GetClassName() const {\n return kViewClassName;\n}\n\ngfx::Size NativeWindowFrameView::GetMinimumSize() {\n return frame_->client_view()->GetMinimumSize();\n}\n\ngfx::Size NativeWindowFrameView::GetMaximumSize() {\n return frame_->client_view()->GetMaximumSize();\n}\n\n} // namespace\n\nNativeWindowWin::NativeWindowWin(content::Shell* shell,\n base::DictionaryValue* manifest)\n : NativeWindow(shell, manifest),\n web_view_(NULL),\n toolbar_(NULL),\n is_fullscreen_(false),\n is_minimized_(false),\n is_focus_(false),\n is_blur_(false),\n menu_(NULL),\n resizable_(true),\n minimum_size_(0, 0),\n maximum_size_() {\n window_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);\n params.delegate = this;\n params.remove_standard_frame = !has_frame();\n params.use_system_default_icon = true;\n window_->Init(params);\n\n views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);\n\n int width, height;\n manifest->GetInteger(switches::kmWidth, &width);\n manifest->GetInteger(switches::kmHeight, &height);\n gfx::Rect window_bounds = \n window_->non_client_view()->GetWindowBoundsForClientBounds(\n gfx::Rect(width,height));\n window_->SetSize(window_bounds.size());\n window_->CenterWindow(window_bounds.size());\n\n window_->UpdateWindowIcon();\n\n OnViewWasResized();\n}\n\nNativeWindowWin::~NativeWindowWin() {\n views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);\n}\n\nvoid NativeWindowWin::Close() {\n window_->Close();\n}\n\nvoid NativeWindowWin::Move(const gfx::Rect& bounds) {\n window_->SetBounds(bounds);\n}\n\nvoid NativeWindowWin::Focus(bool focus) {\n window_->Activate();\n}\n\nvoid NativeWindowWin::Show() {\n window_->Show();\n}\n\nvoid NativeWindowWin::Hide() {\n window_->Hide();\n}\n\nvoid NativeWindowWin::Maximize() {\n window_->Maximize();\n}\n\nvoid NativeWindowWin::Unmaximize() {\n window_->Restore();\n}\n\nvoid NativeWindowWin::Minimize() {\n window_->Minimize();\n}\n\nvoid NativeWindowWin::Restore() {\n window_->Restore();\n}\n\nvoid NativeWindowWin::SetFullscreen(bool fullscreen) {\n is_fullscreen_ = fullscreen;\n window_->SetFullscreen(fullscreen);\n if (fullscreen)\n shell()->SendEvent(\"enter-fullscreen\");\n else\n shell()->SendEvent(\"leave-fullscreen\");\n}\n\nbool NativeWindowWin::IsFullscreen() {\n return is_fullscreen_;\n}\n\nvoid NativeWindowWin::SetSize(const gfx::Size& size) {\n window_->SetSize(size);\n}\n\ngfx::Size NativeWindowWin::GetSize() {\n return window_->GetWindowBoundsInScreen().size();\n}\n\nvoid NativeWindowWin::SetMinimumSize(int width, int height) {\n minimum_size_.set_width(width);\n minimum_size_.set_height(height);\n}\n\nvoid NativeWindowWin::SetMaximumSize(int width, int height) {\n maximum_size_.set_width(width);\n maximum_size_.set_height(height);\n}\n\nvoid NativeWindowWin::SetResizable(bool resizable) {\n resizable_ = resizable;\n\n // Show/Hide the maximize button.\n DWORD style = ::GetWindowLong(window_->GetNativeView(), GWL_STYLE);\n if (resizable)\n style |= WS_MAXIMIZEBOX;\n else\n style &= ~WS_MAXIMIZEBOX;\n ::SetWindowLong(window_->GetNativeView(), GWL_STYLE, style);\n}\n\nvoid NativeWindowWin::SetAlwaysOnTop(bool top) {\n window_->SetAlwaysOnTop(top);\n}\n\nvoid NativeWindowWin::SetPosition(const std::string& position) {\n if (position == \"center\") {\n gfx::Rect bounds = window_->GetWindowBoundsInScreen();\n window_->CenterWindow(gfx::Size(bounds.width(), bounds.height()));\n }\n}\n\nvoid NativeWindowWin::SetPosition(const gfx::Point& position) {\n gfx::Rect bounds = window_->GetWindowBoundsInScreen();\n window_->SetBounds(gfx::Rect(position, bounds.size()));\n}\n\ngfx::Point NativeWindowWin::GetPosition() {\n return window_->GetWindowBoundsInScreen().origin();\n}\n\nvoid NativeWindowWin::FlashFrame(bool flash) {\n window_->FlashFrame(flash);\n}\n\nvoid NativeWindowWin::SetKiosk(bool kiosk) {\n SetFullscreen(kiosk);\n}\n\nbool NativeWindowWin::IsKiosk() {\n return IsFullscreen();\n}\n\nvoid NativeWindowWin::SetMenu(api::Menu* menu) {\n window_->set_has_menu_bar(true);\n menu_ = menu;\n\n // The menu is lazily built.\n menu->Rebuild();\n\n // menu is api::Menu, menu->menu_ is NativeMenuWin,\n ::SetMenu(window_->GetNativeWindow(), menu->menu_->GetNativeMenu());\n}\n\nvoid NativeWindowWin::SetTitle(const std::string& title) {\n title_ = title;\n window_->UpdateWindowTitle();\n}\n\nvoid NativeWindowWin::AddToolbar() {\n toolbar_ = new NativeWindowToolbarWin(shell());\n AddChildViewAt(toolbar_, 0);\n}\n\nvoid NativeWindowWin::SetToolbarButtonEnabled(TOOLBAR_BUTTON button,\n bool enabled) {\n if (toolbar_)\n toolbar_->SetButtonEnabled(button, enabled);\n}\n\nvoid NativeWindowWin::SetToolbarUrlEntry(const std::string& url) {\n if (toolbar_)\n toolbar_->SetUrlEntry(url);\n}\n \nvoid NativeWindowWin::SetToolbarIsLoading(bool loading) {\n if (toolbar_)\n toolbar_->SetIsLoading(loading);\n}\n\nviews::View* NativeWindowWin::GetContentsView() {\n return this;\n}\n\nviews::ClientView* NativeWindowWin::CreateClientView(views::Widget* widget) {\n return new NativeWindowClientView(widget, GetContentsView(), shell());\n}\n\nviews::NonClientFrameView* NativeWindowWin::CreateNonClientFrameView(\n views::Widget* widget) {\n if (has_frame())\n return new views::NativeFrameView(GetWidget());\n\n NativeWindowFrameView* frame_view = new NativeWindowFrameView(this);\n frame_view->Init(window_);\n return frame_view;\n}\n\nbool NativeWindowWin::CanResize() const {\n return resizable_;\n}\n\nbool NativeWindowWin::CanMaximize() const {\n return resizable_;\n}\n\nviews::Widget* NativeWindowWin::GetWidget() {\n return window_;\n}\n\nconst views::Widget* NativeWindowWin::GetWidget() const {\n return window_;\n}\n\nstring16 NativeWindowWin::GetWindowTitle() const {\n return UTF8ToUTF16(title_);\n}\n\nvoid NativeWindowWin::DeleteDelegate() {\n delete shell();\n}\n\nbool NativeWindowWin::ShouldShowWindowTitle() const {\n return has_frame();\n}\n\nvoid NativeWindowWin::OnNativeFocusChange(gfx::NativeView focused_before,\n gfx::NativeView focused_now) {\n gfx::NativeView this_window = GetWidget()->GetNativeView();\n if (IsParent(focused_now, this_window) ||\n IsParent(this_window, focused_now))\n return;\n\n if (focused_now == this_window) {\n if (!is_focus_)\n shell()->SendEvent(\"focus\");\n is_focus_ = true;\n is_blur_ = false;\n } else if (focused_before == this_window) {\n if (!is_blur_)\n shell()->SendEvent(\"blur\");\n is_focus_ = false;\n is_blur_ = true;\n }\n}\n\ngfx::ImageSkia NativeWindowWin::GetWindowAppIcon() {\n gfx::Image icon = app_icon();\n if (icon.IsEmpty())\n return gfx::ImageSkia();\n\n return *icon.ToImageSkia();\n}\n\ngfx::ImageSkia NativeWindowWin::GetWindowIcon() {\n return GetWindowAppIcon();\n}\n\nviews::View* NativeWindowWin::GetInitiallyFocusedView() {\n return web_view_;\n}\n\nvoid NativeWindowWin::UpdateDraggableRegions(\n const std::vector& regions) {\n // Draggable region is not supported for non-frameless window.\n if (has_frame())\n return;\n\n SkRegion* draggable_region = new SkRegion;\n\n // By default, the whole window is non-draggable. We need to explicitly\n // include those draggable regions.\n for (std::vector::const_iterator iter =\n regions.begin();\n iter != regions.end(); ++iter) {\n const extensions::DraggableRegion& region = *iter;\n draggable_region->op(\n region.bounds.x(),\n region.bounds.y(),\n region.bounds.right(),\n region.bounds.bottom(),\n region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);\n }\n\n draggable_region_.reset(draggable_region);\n OnViewWasResized();\n}\n\nvoid NativeWindowWin::HandleKeyboardEvent(\n const content::NativeWebKeyboardEvent& event) {\n // Any unhandled keyboard/character messages should be defproced.\n // This allows stuff like F10, etc to work correctly.\n DefWindowProc(event.os_event.hwnd, event.os_event.message,\n event.os_event.wParam, event.os_event.lParam);\n}\n\nvoid NativeWindowWin::Layout() {\n DCHECK(web_view_);\n if (toolbar_) {\n toolbar_->SetBounds(0, 0, width(), 34);\n web_view_->SetBounds(0, 34, width(), height() - 34);\n } else {\n web_view_->SetBounds(0, 0, width(), height());\n }\n OnViewWasResized();\n}\n\nvoid NativeWindowWin::ViewHierarchyChanged(\n bool is_add, views::View *parent, views::View *child) {\n if (is_add && child == this) {\n views::BoxLayout* layout = new views::BoxLayout(\n views::BoxLayout::kVertical, 0, 0, 0);\n SetLayoutManager(layout);\n\n web_view_ = new views::WebView(NULL);\n web_view_->SetWebContents(web_contents());\n AddChildView(web_view_);\n }\n}\n\ngfx::Size NativeWindowWin::GetMinimumSize() {\n return minimum_size_;\n}\n\ngfx::Size NativeWindowWin::GetMaximumSize() {\n return maximum_size_;\n}\n\nvoid NativeWindowWin::OnFocus() {\n web_view_->RequestFocus();\n}\n\nbool NativeWindowWin::ExecuteWindowsCommand(int command_id) {\n // Windows uses the 4 lower order bits of |command_id| for type-specific\n // information so we must exclude this when comparing.\n static const int sc_mask = 0xFFF0;\n\n if ((command_id & sc_mask) == SC_MINIMIZE) {\n is_minimized_ = true;\n shell()->SendEvent(\"minimize\");\n } else if ((command_id & sc_mask) == SC_RESTORE && is_minimized_) {\n is_minimized_ = false;\n shell()->SendEvent(\"restore\");\n } else if ((command_id & sc_mask) == SC_RESTORE && !is_minimized_) {\n shell()->SendEvent(\"unmaximize\");\n } else if ((command_id & sc_mask) == SC_MAXIMIZE) {\n shell()->SendEvent(\"maximize\");\n }\n\n return false;\n}\n\nbool NativeWindowWin::ExecuteAppCommand(int command_id) {\n if (menu_) {\n menu_->menu_delegate_->ExecuteCommand(command_id);\n menu_->menu_->UpdateStates();\n }\n\n return false;\n}\n\nvoid NativeWindowWin::SaveWindowPlacement(const gfx::Rect& bounds,\n ui::WindowShowState show_state) {\n // views::WidgetDelegate::SaveWindowPlacement(bounds, show_state);\n}\n \nvoid NativeWindowWin::OnViewWasResized() {\n // Set the window shape of the RWHV.\n DCHECK(window_);\n DCHECK(web_view_);\n gfx::Size sz = web_view_->size();\n int height = sz.height(), width = sz.width();\n gfx::Path path;\n path.addRect(0, 0, width, height);\n SetWindowRgn(web_contents()->GetView()->GetNativeView(),\n path.CreateNativeRegion(),\n 1);\n\n SkRegion* rgn = new SkRegion;\n if (!window_->IsFullscreen()) {\n if (draggable_region())\n rgn->op(*draggable_region(), SkRegion::kUnion_Op);\n if (!window_->IsMaximized()) {\n if (!has_frame()) {\n rgn->op(0, 0, width, kResizeInsideBoundsSize, SkRegion::kUnion_Op);\n rgn->op(0, 0, kResizeInsideBoundsSize, height, SkRegion::kUnion_Op);\n rgn->op(width - kResizeInsideBoundsSize, 0, width, height,\n SkRegion::kUnion_Op);\n rgn->op(0, height - kResizeInsideBoundsSize, width, height,\n SkRegion::kUnion_Op);\n }\n }\n }\n if (web_contents()->GetRenderViewHost()->GetView())\n web_contents()->GetRenderViewHost()->GetView()->SetClickthroughRegion(rgn);\n}\n\n} // namespace nw\n", "file_path": "src/browser/native_window_win.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0013994722394272685, 0.00020291906548663974, 0.00016520968347322196, 0.00017005795962177217, 0.00016401513130404055]} {"hunk": {"id": 10, "code_window": ["class ShellBrowserContext;\n", "class ShellBrowserMainParts;\n", "class ShellResourceDispatcherHostDelegate;\n", "\n", "class ShellContentBrowserClient : public ContentBrowserClient {\n", " public:\n", " ShellContentBrowserClient();\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["class RenderProcessHost;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 24}, "file": "exports.test = function() {\n return \"module2\";\n}\n\n", "file_path": "tests/tests/node/node_modules/module3/module2.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017093095812015235, 0.00017093095812015235, 0.00017093095812015235, 0.00017093095812015235, 0.0]} {"hunk": {"id": 11, "code_window": [" scoped_ptr\n", " resource_dispatcher_host_delegate_;\n", "\n", " ShellBrowserMainParts* shell_browser_main_parts_;\n", "};\n", "\n", "} // namespace content\n", "\n", "#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::RenderProcessHost* master_rph_;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 98}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_host.h\"\n\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"content/browser/web_contents/web_contents_impl.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/app/app.h\"\n#include \"content/nw/src/api/base/base.h\"\n#include \"content/nw/src/api/clipboard/clipboard.h\"\n#include \"content/nw/src/api/menu/menu.h\"\n#include \"content/nw/src/api/menuitem/menuitem.h\"\n#include \"content/nw/src/api/shell/shell.h\"\n#include \"content/nw/src/api/tray/tray.h\"\n#include \"content/nw/src/api/window/window.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n#include \"content/nw/src/shell_browser_context.h\"\n#include \"content/nw/src/nw_shell.h\"\n#include \"content/public/browser/render_process_host.h\"\n\nusing content::WebContents;\nusing content::ShellBrowserContext;\n\nnamespace api {\n\nDispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)\n : content::RenderViewHostObserver(render_view_host) {\n}\n\nDispatcherHost::~DispatcherHost() {\n}\n\nBase* DispatcherHost::GetApiObject(int id) {\n return objects_registry_.Lookup(id); \n}\n\nvoid DispatcherHost::SendEvent(Base* object,\n const std::string& event,\n const base::ListValue& arguments) {\n Send(new ShellViewMsg_Object_On_Event(\n routing_id(), object->id(), event, arguments));\n}\n\nbool DispatcherHost::Send(IPC::Message* message) {\n return content::RenderViewHostObserver::Send(message);\n}\n\nbool DispatcherHost::OnMessageReceived(const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,\n OnCallObjectMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,\n OnCallStaticMethodSync)\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,\n OnUncaughtException);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);\n IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DispatcherHost::OnAllocateObject(int object_id,\n const std::string& type,\n const base::DictionaryValue& option) {\n DVLOG(1) << \"OnAllocateObject: object_id:\" << object_id\n << \" type:\" << type\n << \" option:\" << option;\n\n if (type == \"Menu\") {\n objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);\n } else if (type == \"MenuItem\") {\n objects_registry_.AddWithID(\n new MenuItem(object_id, this, option), object_id);\n } else if (type == \"Tray\") {\n objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);\n } else if (type == \"Clipboard\") {\n objects_registry_.AddWithID(\n new Clipboard(object_id, this, option), object_id);\n } else if (type == \"Window\") {\n objects_registry_.AddWithID(new Window(object_id, this, option), object_id);\n } else {\n LOG(ERROR) << \"Allocate an object of unknow type: \" << type;\n objects_registry_.AddWithID(new Base(object_id, this, option), object_id);\n }\n}\n\nvoid DispatcherHost::OnDeallocateObject(int object_id) {\n DLOG(INFO) << \"OnDeallocateObject: object_id:\" << object_id;\n objects_registry_.Remove(object_id);\n}\n\nvoid DispatcherHost::OnCallObjectMethod(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallObjectMethod: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->Call(method, arguments);\n}\n\nvoid DispatcherHost::OnCallObjectMethodSync(\n int object_id,\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallObjectMethodSync: object_id:\" << object_id\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n Base* object = GetApiObject(object_id);\n DCHECK(object) << \"Unknown object: \" << object_id;\n object->CallSync(method, arguments, result);\n}\n\nvoid DispatcherHost::OnCallStaticMethod(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments) {\n DLOG(INFO) << \"OnCallStaticMethod: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"Shell\") {\n api::Shell::Call(method, arguments);\n return;\n } else if (type == \"App\") {\n api::App::Call(method, arguments);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnCallStaticMethodSync(\n const std::string& type,\n const std::string& method,\n const base::ListValue& arguments,\n base::ListValue* result) {\n DLOG(INFO) << \"OnCallStaticMethodSync: \"\n << \" type:\" << type\n << \" method:\" << method\n << \" arguments:\" << arguments;\n\n if (type == \"App\") {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n api::App::Call(shell, method, arguments, result);\n return;\n }\n\n NOTREACHED() << \"Calling unknown method \" << method << \" of class \" << type;\n}\n\nvoid DispatcherHost::OnUncaughtException(const std::string& err) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n shell->PrintCriticalError(\"Uncaught node.js Error\", err);\n}\n\nvoid DispatcherHost::OnGetShellId(int* id) {\n content::Shell* shell = \n content::Shell::FromRenderViewHost(render_view_host());\n *id = shell->id();\n}\n\nvoid DispatcherHost::OnCreateShell(const std::string& url,\n const base::DictionaryValue& manifest,\n int* routing_id) {\n WebContents* base_web_contents =\n content::Shell::FromRenderViewHost(render_view_host())->web_contents();\n ShellBrowserContext* browser_context =\n static_cast(base_web_contents->GetBrowserContext());\n scoped_ptr new_manifest(manifest.DeepCopy());\n bool new_renderer = false;\n if (new_manifest->GetBoolean(switches::kmNewInstance,\n &new_renderer) && new_renderer)\n browser_context->set_pinning_renderer(false);\n\n WebContents::CreateParams create_params(browser_context,\n new_renderer ? NULL : base_web_contents->GetSiteInstance());\n\n WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(\n create_params,\n static_cast(base_web_contents));\n new content::Shell(web_contents, new_manifest.get());\n web_contents->GetController().LoadURL(\n GURL(url),\n content::Referrer(),\n content::PAGE_TRANSITION_TYPED,\n std::string());\n\n if (new_renderer)\n browser_context->set_pinning_renderer(true);\n\n *routing_id = web_contents->GetRoutingID();\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_host.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0009437474072910845, 0.00032384289079345763, 0.00016712619981262833, 0.00020028557628393173, 0.00023286388022825122]} {"hunk": {"id": 11, "code_window": [" scoped_ptr\n", " resource_dispatcher_host_delegate_;\n", "\n", " ShellBrowserMainParts* shell_browser_main_parts_;\n", "};\n", "\n", "} // namespace content\n", "\n", "#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::RenderProcessHost* master_rph_;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 98}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/api/dispatcher_bindings.h\"\n\n#include \"base/files/file_path.h\"\n#include \"base/file_util.h\"\n#include \"base/logging.h\"\n#include \"base/values.h\"\n#include \"base/command_line.h\"\n#include \"chrome/renderer/static_v8_external_string_resource.h\"\n#include \"content/nw/src/api/api_messages.h\"\n#include \"content/nw/src/api/bindings_common.h\"\n#include \"content/public/renderer/render_view.h\"\n#include \"content/public/renderer/render_thread.h\"\n#include \"content/public/renderer/v8_value_converter.h\"\n#include \"grit/nw_resources.h\"\n\nusing content::RenderView;\nusing content::V8ValueConverter;\nusing base::FilePath;\n\nnamespace api {\n\nnamespace {\n\nv8::Handle WrapSource(v8::Handle source) {\n v8::HandleScope handle_scope;\n v8::Handle left =\n v8::String::New(\"(function(nw, exports) {\");\n v8::Handle right = v8::String::New(\"\\n})\");\n return handle_scope.Close(\n v8::String::Concat(left, v8::String::Concat(source, right)));\n}\n\n// Similar to node's `require` function, save functions in `exports`.\nvoid RequireFromResource(v8::Handle root,\n v8::Handle gui,\n v8::Handle name,\n int resource_id) {\n v8::HandleScope scope;\n\n v8::Handle source = v8::String::NewExternal(\n new StaticV8ExternalAsciiStringResource(\n GetStringResource(resource_id)));\n v8::Handle wrapped_source = WrapSource(source);\n\n v8::Handle script(v8::Script::New(wrapped_source, name));\n v8::Handle func = v8::Handle::Cast(script->Run());\n v8::Handle args[] = { root, gui };\n func->Call(root, 2, args);\n}\n\nbool MakePathAbsolute(FilePath* file_path) {\n DCHECK(file_path);\n\n FilePath current_directory;\n if (!file_util::GetCurrentDirectory(¤t_directory))\n return false;\n\n if (file_path->IsAbsolute())\n return true;\n\n if (current_directory.empty())\n return file_util::AbsolutePath(file_path);\n\n if (!current_directory.IsAbsolute())\n return false;\n\n *file_path = current_directory.Append(*file_path);\n return true;\n}\n\n} // namespace\n\nDispatcherBindings::DispatcherBindings()\n : v8::Extension(\"dispatcher_bindings.js\",\n GetStringResource(\n IDR_NW_API_DISPATCHER_BINDINGS_JS).data(),\n 0, // num dependencies.\n NULL, // dependencies array.\n GetStringResource(\n IDR_NW_API_DISPATCHER_BINDINGS_JS).size()) {\n}\n\nDispatcherBindings::~DispatcherBindings() {\n}\n\nv8::Handle\nDispatcherBindings::GetNativeFunction(v8::Handle name) {\n if (name->Equals(v8::String::New(\"RequireNwGui\")))\n return v8::FunctionTemplate::New(RequireNwGui);\n else if (name->Equals(v8::String::New(\"GetAbsolutePath\")))\n return v8::FunctionTemplate::New(GetAbsolutePath);\n else if (name->Equals(v8::String::New(\"GetShellIdForCurrentContext\")))\n return v8::FunctionTemplate::New(GetShellIdForCurrentContext);\n else if (name->Equals(v8::String::New(\"GetRoutingIDForCurrentContext\")))\n return v8::FunctionTemplate::New(GetRoutingIDForCurrentContext);\n else if (name->Equals(v8::String::New(\"CreateShell\")))\n return v8::FunctionTemplate::New(CreateShell);\n else if (name->Equals(v8::String::New(\"AllocateObject\")))\n return v8::FunctionTemplate::New(AllocateObject);\n else if (name->Equals(v8::String::New(\"DeallocateObject\")))\n return v8::FunctionTemplate::New(DeallocateObject);\n else if (name->Equals(v8::String::New(\"CallObjectMethod\")))\n return v8::FunctionTemplate::New(CallObjectMethod);\n else if (name->Equals(v8::String::New(\"CallObjectMethodSync\")))\n return v8::FunctionTemplate::New(CallObjectMethodSync);\n else if (name->Equals(v8::String::New(\"CallStaticMethod\")))\n return v8::FunctionTemplate::New(CallStaticMethod);\n else if (name->Equals(v8::String::New(\"CallStaticMethodSync\")))\n return v8::FunctionTemplate::New(CallStaticMethodSync);\n\n NOTREACHED() << \"Trying to get an non-exist function in DispatcherBindings:\"\n << *v8::String::Utf8Value(name);\n return v8::FunctionTemplate::New();\n}\n\n// static\nv8::Handle\nDispatcherBindings::RequireNwGui(const v8::Arguments& args) {\n v8::HandleScope scope;\n\n // Initialize lazily\n v8::Local NwGuiSymbol = v8::String::NewSymbol(\"nwGui\");\n v8::Local NwGuiHidden = args.This()->Get(NwGuiSymbol);\n if (NwGuiHidden->IsObject())\n return scope.Close(NwGuiHidden);\n\n v8::Local NwGui = v8::Object::New();\n args.This()->Set(NwGuiSymbol, NwGui);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"base.js\"), IDR_NW_API_BASE_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"menuitem.js\"), IDR_NW_API_MENUITEM_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"menu.js\"), IDR_NW_API_MENU_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"tray.js\"), IDR_NW_API_TRAY_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"clipboard.js\"), IDR_NW_API_CLIPBOARD_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"window.js\"), IDR_NW_API_WINDOW_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"shell.js\"), IDR_NW_API_SHELL_JS);\n RequireFromResource(args.This(),\n NwGui, v8::String::New(\"app.js\"), IDR_NW_API_APP_JS);\n\n return scope.Close(NwGui);\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {\n FilePath path = FilePath::FromUTF8Unsafe(*v8::String::Utf8Value(args[0]));\n MakePathAbsolute(&path);\n#if defined(OS_POSIX)\n return v8::String::New(path.value().c_str());\n#else\n return v8::String::New(path.AsUTF8Unsafe().c_str());\n#endif\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetShellIdForCurrentContext(const v8::Arguments& args) {\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethodSync\")));\n }\n\n int id = -1;\n render_view->Send(new ShellViewHostMsg_GetShellId(MSG_ROUTING_NONE, &id));\n return v8::Integer::New(id);\n}\n\n// static\nv8::Handle\nDispatcherBindings::GetRoutingIDForCurrentContext(const v8::Arguments& args) {\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in GetRoutingIDForCurrentContext\")));\n }\n\n return v8::Integer::New(render_view->GetRoutingID());\n}\n\n// static\nv8::Handle\nDispatcherBindings::CreateShell(const v8::Arguments& args) {\n if (args.Length() < 2)\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CreateShell requries 2 arguments\")));\n\n std::string url = *v8::String::Utf8Value(args[0]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_manifest(\n converter->FromV8Value(args[1], v8::Context::GetCurrent()));\n if (!value_manifest.get() ||\n !value_manifest->IsType(base::Value::TYPE_DICTIONARY)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'options' passed to CreateShell\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethod\")));\n }\n\n int routing_id = -1;\n render_view->Send(new ShellViewHostMsg_CreateShell(\n render_view->GetRoutingID(),\n url,\n *static_cast(value_manifest.get()),\n &routing_id));\n\n return v8::Integer::New(routing_id);\n}\n\n// static\nv8::Handle\nDispatcherBindings::AllocateObject(const v8::Arguments& args) {\n if (args.Length() < 3)\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"AllocateObject requries 3 arguments\")));\n\n int object_id = args[0]->Int32Value();\n std::string name = *v8::String::Utf8Value(args[1]);\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in AllocateObject\")));\n }\n\n return remote::AllocateObject(\n render_view->GetRoutingID(), object_id, name, args[2]);\n}\n\n// static\nv8::Handle\nDispatcherBindings::DeallocateObject(const v8::Arguments& args) {\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in DeallocateObject\")));\n }\n\n if (args.Length() < 1)\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"DeallocateObject requries 1 arguments\")));\n\n return remote::DeallocateObject(render_view->GetRoutingID(),\n args[0]->Int32Value());\n}\n\n// static\nv8::Handle\nDispatcherBindings::CallObjectMethod(const v8::Arguments& args) {\n if (args.Length() < 4)\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallObjectMethod requries 4 arguments\")));\n\n int object_id = args[0]->Int32Value();\n std::string type = *v8::String::Utf8Value(args[1]);\n std::string method = *v8::String::Utf8Value(args[2]);\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallObjectMethod\")));\n }\n\n return remote::CallObjectMethod(\n render_view->GetRoutingID(), object_id, type, method, args[3]);\n}\n\n// static\nv8::Handle DispatcherBindings::CallObjectMethodSync(\n const v8::Arguments& args) {\n if (args.Length() < 4)\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallObjectMethodSync requries 4 arguments\")));\n\n int object_id = args[0]->Int32Value();\n std::string type = *v8::String::Utf8Value(args[1]);\n std::string method = *v8::String::Utf8Value(args[2]);\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallObjectMethod\")));\n }\n\n return remote::CallObjectMethodSync(\n render_view->GetRoutingID(), object_id, type, method, args[3]);\n}\n\n// static\nv8::Handle DispatcherBindings::CallStaticMethod(\n const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallStaticMethod requries 3 arguments\")));\n }\n\n std::string type = *v8::String::Utf8Value(args[0]);\n std::string method = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallStaticMethod\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethod\")));\n }\n\n render_view->Send(new ShellViewHostMsg_Call_Static_Method(\n render_view->GetRoutingID(),\n type,\n method,\n *static_cast(value_args.get())));\n return v8::Undefined();\n}\n\n// static\nv8::Handle DispatcherBindings::CallStaticMethodSync(\n const v8::Arguments& args) {\n if (args.Length() < 3) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"CallStaticMethodSync requries 3 arguments\")));\n }\n\n std::string type = *v8::String::Utf8Value(args[0]);\n std::string method = *v8::String::Utf8Value(args[1]);\n\n scoped_ptr converter(V8ValueConverter::create());\n\n scoped_ptr value_args(\n converter->FromV8Value(args[2], v8::Context::GetCurrent()));\n if (!value_args.get() ||\n !value_args->IsType(base::Value::TYPE_LIST)) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to convert 'args' passed to CallStaticMethodSync\")));\n }\n\n RenderView* render_view = GetCurrentRenderView();\n if (!render_view) {\n return v8::ThrowException(v8::Exception::Error(v8::String::New(\n \"Unable to get render view in CallStaticMethodSync\")));\n }\n\n base::ListValue result;\n render_view->Send(new ShellViewHostMsg_Call_Static_Method_Sync(\n MSG_ROUTING_NONE,\n type,\n method,\n *static_cast(value_args.get()),\n &result));\n return converter->ToV8Value(&result, v8::Context::GetCurrent());\n}\n\n} // namespace api\n", "file_path": "src/api/dispatcher_bindings.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0011611682130023837, 0.0002191932435380295, 0.00016421238251496106, 0.00017240174929611385, 0.00017019640654325485]} {"hunk": {"id": 11, "code_window": [" scoped_ptr\n", " resource_dispatcher_host_delegate_;\n", "\n", " ShellBrowserMainParts* shell_browser_main_parts_;\n", "};\n", "\n", "} // namespace content\n", "\n", "#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::RenderProcessHost* master_rph_;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 98}, "file": "\n\n\n\n\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleDisplayName\n\t${EXECUTABLE_NAME}\n\tCFBundleExecutable\n\t${EXECUTABLE_NAME}\n\tCFBundleIdentifier\n\tcom.intel.nw.helper\n\tCFBundleInfoDictionaryVersion\n\t6.0\n\tCFBundleName\n\t${PRODUCT_NAME}\n\tCFBundlePackageType\n\tAPPL\n\tCFBundleSignature\n\t????\n\tLSFileQuarantineEnabled\n\t\n\tLSMinimumSystemVersion\n\t${MACOSX_DEPLOYMENT_TARGET}.0\n\tLSUIElement\n\t1\n\tNSSupportsAutomaticGraphicsSwitching\n\t\n\n\n", "file_path": "src/mac/helper-Info.plist", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.00017349103291053325, 0.0001711727090878412, 0.00016874684661161155, 0.0001712264638626948, 1.6829387732286705e-06]} {"hunk": {"id": 11, "code_window": [" scoped_ptr\n", " resource_dispatcher_host_delegate_;\n", "\n", " ShellBrowserMainParts* shell_browser_main_parts_;\n", "};\n", "\n", "} // namespace content\n", "\n", "#endif // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" content::RenderProcessHost* master_rph_;\n"], "file_path": "src/shell_content_browser_client.h", "type": "add", "edit_start_line_idx": 98}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// Get basic type definitions.\n#define IPC_MESSAGE_IMPL\n#include \"content/nw/src/renderer/common/render_messages.h\"\n\n// Generate constructors.\n#include \"ipc/struct_constructor_macros.h\"\n#include \"content/nw/src/renderer/common/render_messages.h\"\n\n// Generate destructors.\n#include \"ipc/struct_destructor_macros.h\"\n#include \"content/nw/src/renderer/common/render_messages.h\"\n\n// Generate param traits write methods.\n#include \"ipc/param_traits_write_macros.h\"\nnamespace IPC {\n#include \"content/nw/src/renderer/common/render_messages.h\"\n} // namespace IPC\n\n// Generate param traits read methods.\n#include \"ipc/param_traits_read_macros.h\"\nnamespace IPC {\n#include \"content/nw/src/renderer/common/render_messages.h\"\n} // namespace IPC\n\n// Generate param traits log methods.\n#include \"ipc/param_traits_log_macros.h\"\nnamespace IPC {\n#include \"content/nw/src/renderer/common/render_messages.h\"\n} // namespace IPC\n", "file_path": "src/renderer/common/render_messages.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/17d6746409ee3e788bb22701c5d5ec8ed85d0421", "dependency_score": [0.0006491318927146494, 0.0002657144796103239, 0.00016540229262318462, 0.00017096665396820754, 0.00019173363398294896]} {"hunk": {"id": 0, "code_window": ["\n", "/******************************************************************************/\n", "\n", "vAPI.DOMFilterer = class {\n", " constructor() {\n", " this.commitTimer = new vAPI.SafeAnimationFrame(( ) => this.commitNow);\n", " this.domIsReady = document.readyState !== 'loading';\n", " this.disabled = false;\n", " this.listeners = [];\n", " this.filterset = new Set();\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" this.commitTimer = new vAPI.SafeAnimationFrame(this.commitNow.bind(this));\n"], "file_path": "platform/chromium/vapi-usercss.real.js", "type": "replace", "edit_start_line_idx": 61}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2017-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n// Packaging this file is optional: it is not necessary to package it if the\n// platform is known to not support user stylesheets.\n\n// >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && vAPI.supportsUserStylesheets ) {\n\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.userStylesheet = {\n added: new Set(),\n removed: new Set(),\n apply: function(callback) {\n if ( this.added.size === 0 && this.removed.size === 0 ) { return; }\n vAPI.messaging.send('vapi', {\n what: 'userCSS',\n add: Array.from(this.added),\n remove: Array.from(this.removed)\n }, callback);\n this.added.clear();\n this.removed.clear();\n },\n add: function(cssText, now) {\n if ( cssText === '' ) { return; }\n this.added.add(cssText);\n if ( now ) { this.apply(); }\n },\n remove: function(cssText, now) {\n if ( cssText === '' ) { return; }\n this.removed.add(cssText);\n if ( now ) { this.apply(); }\n }\n};\n\n/******************************************************************************/\n\nvAPI.DOMFilterer = class {\n constructor() {\n this.commitTimer = new vAPI.SafeAnimationFrame(( ) => this.commitNow);\n this.domIsReady = document.readyState !== 'loading';\n this.disabled = false;\n this.listeners = [];\n this.filterset = new Set();\n this.excludedNodeSet = new WeakSet();\n this.addedCSSRules = new Set();\n this.exceptedCSSRules = [];\n this.reOnlySelectors = /\\n\\{[^\\n]+/g;\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/167\n // By the time the DOMContentLoaded is fired, the content script might\n // have been disconnected from the background page. Unclear why this\n // would happen, so far seems to be a Chromium-specific behavior at\n // launch time.\n if ( this.domIsReady !== true ) {\n document.addEventListener('DOMContentLoaded', ( ) => {\n if ( vAPI instanceof Object === false ) { return; }\n this.domIsReady = true;\n this.commit();\n });\n }\n }\n\n // Here we will deal with:\n // - Injecting low priority user styles;\n // - Notifying listeners about changed filterset.\n // https://www.reddit.com/r/uBlockOrigin/comments/9jj0y1/no_longer_blocking_ads/\n // Ensure vAPI is still valid -- it can go away by the time we are\n // called, since the port could be force-disconnected from the main\n // process. Another approach would be to have vAPI.SafeAnimationFrame\n // register a shutdown job: to evaluate. For now I will keep the fix\n // trivial.\n commitNow() {\n this.commitTimer.clear();\n if ( vAPI instanceof Object === false ) { return; }\n const userStylesheet = vAPI.userStylesheet;\n for ( const entry of this.addedCSSRules ) {\n if (\n this.disabled === false &&\n entry.lazy &&\n entry.injected === false\n ) {\n userStylesheet.add(\n entry.selectors + '\\n{' + entry.declarations + '}'\n );\n }\n }\n this.addedCSSRules.clear();\n userStylesheet.apply();\n }\n\n commit(commitNow) {\n if ( commitNow ) {\n this.commitTimer.clear();\n this.commitNow();\n } else {\n this.commitTimer.start();\n }\n }\n\n addCSSRule(selectors, declarations, details) {\n if ( selectors === undefined ) { return; }\n const selectorsStr = Array.isArray(selectors)\n ? selectors.join(',\\n')\n : selectors;\n if ( selectorsStr.length === 0 ) { return; }\n if ( details === undefined ) { details = {}; }\n const entry = {\n selectors: selectorsStr,\n declarations,\n lazy: details.lazy === true,\n injected: details.injected === true\n };\n this.addedCSSRules.add(entry);\n this.filterset.add(entry);\n if (\n this.disabled === false &&\n entry.lazy !== true &&\n entry.injected !== true\n ) {\n vAPI.userStylesheet.add(selectorsStr + '\\n{' + declarations + '}');\n }\n this.commit();\n if ( this.hasListeners() ) {\n this.triggerListeners({\n declarative: [ [ selectorsStr, declarations ] ]\n });\n }\n }\n\n exceptCSSRules(exceptions) {\n if ( exceptions.length === 0 ) { return; }\n this.exceptedCSSRules.push(...exceptions);\n if ( this.hasListeners() ) {\n this.triggerListeners({ exceptions });\n }\n }\n\n addListener(listener) {\n if ( this.listeners.indexOf(listener) !== -1 ) { return; }\n this.listeners.push(listener);\n }\n\n removeListener(listener) {\n const pos = this.listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n this.listeners.splice(pos, 1);\n }\n\n hasListeners() {\n return this.listeners.length !== 0;\n }\n\n triggerListeners(changes) {\n for ( const listener of this.listeners ) {\n listener.onFiltersetChanged(changes);\n }\n }\n\n excludeNode(node) {\n this.excludedNodeSet.add(node);\n this.unhideNode(node);\n }\n\n unexcludeNode(node) {\n this.excludedNodeSet.delete(node);\n }\n\n hideNode(node) {\n if ( this.excludedNodeSet.has(node) ) { return; }\n if ( this.hideNodeAttr === undefined ) { return; }\n node.setAttribute(this.hideNodeAttr, '');\n if ( this.hideNodeStyleSheetInjected === false ) {\n this.hideNodeStyleSheetInjected = true;\n this.addCSSRule(\n `[${this.hideNodeAttr}]`,\n 'display:none!important;'\n );\n }\n }\n\n unhideNode(node) {\n if ( this.hideNodeAttr === undefined ) { return; }\n node.removeAttribute(this.hideNodeAttr);\n }\n\n toggle(state, callback) {\n if ( state === undefined ) { state = this.disabled; }\n if ( state !== this.disabled ) { return; }\n this.disabled = !state;\n const userStylesheet = vAPI.userStylesheet;\n for ( const entry of this.filterset ) {\n const rule = `${entry.selectors}\\n{${entry.declarations}}`;\n if ( this.disabled ) {\n userStylesheet.remove(rule);\n } else {\n userStylesheet.add(rule);\n }\n }\n userStylesheet.apply(callback);\n }\n\n getAllSelectors_(all) {\n const out = {\n declarative: [],\n exceptions: this.exceptedCSSRules,\n };\n for ( const entry of this.filterset ) {\n let selectors = entry.selectors;\n if ( all !== true && this.hideNodeAttr !== undefined ) {\n selectors = selectors\n .replace(`[${this.hideNodeAttr}]`, '')\n .replace(/^,\\n|,\\n$/gm, '');\n if ( selectors === '' ) { continue; }\n }\n out.declarative.push([ selectors, entry.declarations ]);\n }\n return out;\n }\n\n getFilteredElementCount() {\n const details = this.getAllSelectors_(true);\n if ( Array.isArray(details.declarative) === false ) { return 0; }\n const selectors = details.declarative.map(entry => entry[0]);\n if ( selectors.length === 0 ) { return 0; }\n return document.querySelectorAll(selectors.join(',\\n')).length;\n }\n\n getAllSelectors() {\n return this.getAllSelectors_(false);\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n\n\n\n\n\n\n\n\n/*******************************************************************************\n\n DO NOT:\n - Remove the following code\n - Add code beyond the following code\n Reason:\n - https://github.com/gorhill/uBlock/pull/3721\n - uBO never uses the return value from injected content scripts\n\n**/\n\nvoid 0;\n", "file_path": "platform/chromium/vapi-usercss.real.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.996857762336731, 0.07262609899044037, 0.0001694020174909383, 0.00041474131285212934, 0.24052046239376068]} {"hunk": {"id": 0, "code_window": ["\n", "/******************************************************************************/\n", "\n", "vAPI.DOMFilterer = class {\n", " constructor() {\n", " this.commitTimer = new vAPI.SafeAnimationFrame(( ) => this.commitNow);\n", " this.domIsReady = document.readyState !== 'loading';\n", " this.disabled = false;\n", " this.listeners = [];\n", " this.filterset = new Set();\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" this.commitTimer = new vAPI.SafeAnimationFrame(this.commitNow.bind(this));\n"], "file_path": "platform/chromium/vapi-usercss.real.js", "type": "replace", "edit_start_line_idx": 61}, "file": "{\n \"extName\": {\n \"message\": \"uBlock₀\",\n \"description\": \"extension name.\"\n },\n \"extShortDesc\": {\n \"message\": \"Më në fund, një bllokues efikas që nuk e rëndon procesorin dhe memorjen.\",\n \"description\": \"this will be in the Chrome web store: must be 132 characters or less\"\n },\n \"dashboardName\": {\n \"message\": \"uBlock₀ — Paneli i kontrollit\",\n \"description\": \"English: uBlock₀ — Dashboard\"\n },\n \"settingsPageName\": {\n \"message\": \"Parametrat\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"3pPageName\": {\n \"message\": \"Listat e filtrave\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"1pPageName\": {\n \"message\": \"Filtrat e mi\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"rulesPageName\": {\n \"message\": \"Rregullat e mia\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"whitelistPageName\": {\n \"message\": \"Lista e bardhë\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"shortcutsPageName\": {\n \"message\": \"Shkurtoret\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"statsPageName\": {\n \"message\": \"uBlock₀ — Regjistri i kërkesave\",\n \"description\": \"Title for the logger window\"\n },\n \"aboutPageName\": {\n \"message\": \"Info\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"assetViewerPageName\": {\n \"message\": \"uBlock₀ — Ilustruesi i aseteve\",\n \"description\": \"Title for the asset viewer page\"\n },\n \"advancedSettingsPageName\": {\n \"message\": \"Parametra të avancuar\",\n \"description\": \"Title for the advanced settings page\"\n },\n \"popupPowerSwitchInfo\": {\n \"message\": \"Kliko: uBlock₀ bëhet joaktiv\\/aktiv te ky uebsajti.\\n\\nKliko+Ctrl: uBlock₀ bëhet joaktiv vetëm te kjo faqja.\",\n \"description\": \"English: Click: disable\\/enable uBlock₀ for this site.\\n\\nCtrl+click: disable uBlock₀ only on this page.\"\n },\n \"popupPowerSwitchInfo1\": {\n \"message\": \"Çaktivizoj uBlock₀ te ky uebsajti.\\n\\nKlikimi+Ctrl do të çaktivizojë uBlock₀ vetëm te kjo faqja.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupPowerSwitchInfo2\": {\n \"message\": \"Aktivizoj uBlock₀ te ky uebsajti.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupBlockedRequestPrompt\": {\n \"message\": \"kërkesa të refuzuara\",\n \"description\": \"English: requests blocked\"\n },\n \"popupBlockedOnThisPagePrompt\": {\n \"message\": \"te kjo faqja\",\n \"description\": \"English: on this page\"\n },\n \"popupBlockedStats\": {\n \"message\": \"{{count}} ose {{percent}}%\",\n \"description\": \"Example: 15 or 13%\"\n },\n \"popupBlockedSinceInstallPrompt\": {\n \"message\": \"që prej instalimit\",\n \"description\": \"English: since install\"\n },\n \"popupOr\": {\n \"message\": \"ose\",\n \"description\": \"English: or\"\n },\n \"popupTipDashboard\": {\n \"message\": \"Hap panelin e kontrollit\",\n \"description\": \"English: Click to open the dashboard\"\n },\n \"popupTipZapper\": {\n \"message\": \"Asgjësuesi i elementeve\",\n \"description\": \"Tooltip for the element-zapper icon in the popup panel\"\n },\n \"popupTipPicker\": {\n \"message\": \"Përzgjedhësi i elementeve\",\n \"description\": \"English: Enter element picker mode\"\n },\n \"popupTipLog\": {\n \"message\": \"Regjistri i kërkesave\",\n \"description\": \"Tooltip used for the logger icon in the panel\"\n },\n \"popupTipNoPopups\": {\n \"message\": \"Bllokoj të gjitha dritaret automatike që hap faqja\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups1\": {\n \"message\": \"Bllokoj të gjitha dritaret automatike të faqes\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups2\": {\n \"message\": \"Zhbllokoj të gjitha dritaret automatike të faqes\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoLargeMedia\": {\n \"message\": \"Bllokoj elementet e mëdha multimediale te faqja\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia1\": {\n \"message\": \"Bllokoj elementet e mëdha multimediale te faqja\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia2\": {\n \"message\": \"Zbllokoj elementet e mëdha multimediale te faqja\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoCosmeticFiltering\": {\n \"message\": \"Përdor filtrat kozmetikë te faqja\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering1\": {\n \"message\": \"Çaktivizoj filtrat kozmetikë të faqes\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering2\": {\n \"message\": \"Aktivizoj filtrat kozmetikë të faqes\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoRemoteFonts\": {\n \"message\": \"Bllokoj sistemin e shkronjave jashtë faqes\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts1\": {\n \"message\": \"Bllokoj sistemin e shkronjave jashtë faqes\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts2\": {\n \"message\": \"Zhbllokoj sistemin e shkronjave jashtë faqes\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoScripting1\": {\n \"message\": \"Çaktivizoj JavaScript-in te ky uebsajti\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipNoScripting2\": {\n \"message\": \"Nuk e çaktivizoj më JavaScript-in te ky uebsajti\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipGlobalRules\": {\n \"message\": \"Rregullat globale: rregullat në këtë shtyllë aplikohen për të gjitha faqet.\",\n \"description\": \"Tooltip when hovering the top-most cell of the global-rules column.\"\n },\n \"popupTipLocalRules\": {\n \"message\": \"Rregullat lokale: rregullat në këtë shtyllë aplikohen vetëm për këtë faqen dhe kanë përparësi mbi rregullat globale.\",\n \"description\": \"Tooltip when hovering the top-most cell of the local-rules column.\"\n },\n \"popupTipSaveRules\": {\n \"message\": \"Ruaj ndryshimet përherë.\",\n \"description\": \"Tooltip when hovering over the padlock in the dynamic filtering pane.\"\n },\n \"popupTipRevertRules\": {\n \"message\": \"Kthej ndryshimet.\",\n \"description\": \"Tooltip when hovering over the eraser in the dynamic filtering pane.\"\n },\n \"popupAnyRulePrompt\": {\n \"message\": \"të gjitha\",\n \"description\": \"\"\n },\n \"popupImageRulePrompt\": {\n \"message\": \"imazhet\",\n \"description\": \"\"\n },\n \"popup3pAnyRulePrompt\": {\n \"message\": \"palët e treta\",\n \"description\": \"\"\n },\n \"popup3pPassiveRulePrompt\": {\n \"message\": \"CSS\\/imazhet nga palët e treta\",\n \"description\": \"\"\n },\n \"popupInlineScriptRulePrompt\": {\n \"message\": \"skriptet e integruara\",\n \"description\": \"\"\n },\n \"popup1pScriptRulePrompt\": {\n \"message\": \"skriptet nga pala kryesore\",\n \"description\": \"\"\n },\n \"popup3pScriptRulePrompt\": {\n \"message\": \"skriptet nga palët e treta\",\n \"description\": \"\"\n },\n \"popup3pFrameRulePrompt\": {\n \"message\": \"kuadrot nga palët e treta\",\n \"description\": \"\"\n },\n \"popupHitDomainCountPrompt\": {\n \"message\": \"faqe të kontaktuara\",\n \"description\": \"appears in popup\"\n },\n \"popupHitDomainCount\": {\n \"message\": \"{{count}} nga {{total}}\",\n \"description\": \"appears in popup\"\n },\n \"pickerCreate\": {\n \"message\": \"Krijoj\",\n \"description\": \"English: Create\"\n },\n \"pickerPick\": {\n \"message\": \"Përzgjedh\",\n \"description\": \"English: Pick\"\n },\n \"pickerQuit\": {\n \"message\": \"Mbyll\",\n \"description\": \"English: Quit\"\n },\n \"pickerPreview\": {\n \"message\": \"Parashikoj\",\n \"description\": \"Element picker preview mode: will cause the elements matching the current filter to be removed from the page\"\n },\n \"pickerNetFilters\": {\n \"message\": \"Filtrat e rrjetit\",\n \"description\": \"English: header for a type of filter in the element picker dialog\"\n },\n \"pickerCosmeticFilters\": {\n \"message\": \"Filtrat kozmetikë\",\n \"description\": \"English: Cosmetic filters\"\n },\n \"pickerCosmeticFiltersHint\": {\n \"message\": \"Kliko, Kliko me Ctrl\",\n \"description\": \"English: Click, Ctrl-click\"\n },\n \"pickerContextMenuEntry\": {\n \"message\": \"Bllokoj elementin\",\n \"description\": \"English: Block element\"\n },\n \"settingsCollapseBlockedPrompt\": {\n \"message\": \"Fsheh treguesin e elementeve të bllokuara\",\n \"description\": \"English: Hide placeholders of blocked elements\"\n },\n \"settingsIconBadgePrompt\": {\n \"message\": \"Tregoj te ikona numrin e kërkesave të refuzuara\",\n \"description\": \"English: Show the number of blocked requests on the icon\"\n },\n \"settingsTooltipsPrompt\": {\n \"message\": \"Çaktivizoj përshkrimet e shkurtra\",\n \"description\": \"A checkbox in the Settings pane\"\n },\n \"settingsContextMenuPrompt\": {\n \"message\": \"Përdor menunë kontekstuale sipas rrethanave\",\n \"description\": \"English: Make use of context menu where appropriate\"\n },\n \"settingsColorBlindPrompt\": {\n \"message\": \"Përshtat ngjyrat për daltonikët\",\n \"description\": \"English: Color-blind friendly\"\n },\n \"settingsCloudStorageEnabledPrompt\": {\n \"message\": \"Aktivizoj renë informatike\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserPrompt\": {\n \"message\": \"Kam njohuri të avancuara (Lexim i detyruar<\\/a>)\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserSettings\": {\n \"message\": \"parametra të avancuar\",\n \"description\": \"For the tooltip of a link which gives access to advanced settings\"\n },\n \"settingsPrefetchingDisabledPrompt\": {\n \"message\": \"Çaktivizoj kërkesat paraprake (për të evituar çdo lidhje me kërkesat e refuzuara)\",\n \"description\": \"English: \"\n },\n \"settingsHyperlinkAuditingDisabledPrompt\": {\n \"message\": \"Çaktivizoj analizën e lidhjeve hipertekstuale\",\n \"description\": \"English: \"\n },\n \"settingsWebRTCIPAddressHiddenPrompt\": {\n \"message\": \"Nuk lejoj WebRTC-në që të zbulojë adresat IP lokale\",\n \"description\": \"English: \"\n },\n \"settingPerSiteSwitchGroup\": {\n \"message\": \"Vlerat standarde\",\n \"description\": \"\"\n },\n \"settingPerSiteSwitchGroupSynopsis\": {\n \"message\": \"Këto vlera mund të ndryshohen në bazë të faqeve\",\n \"description\": \"\"\n },\n \"settingsNoCosmeticFilteringPrompt\": {\n \"message\": \"Çaktivizoj filtrat kozmetikë\",\n \"description\": \"\"\n },\n \"settingsNoLargeMediaPrompt\": {\n \"message\": \"Bllokoj elementet multimediale më të mëdha se {{input:number}} kB\",\n \"description\": \"\"\n },\n \"settingsNoRemoteFontsPrompt\": {\n \"message\": \"Bllokoj sistemin e shkronjave jashtë faqes\",\n \"description\": \"\"\n },\n \"settingsNoScriptingPrompt\": {\n \"message\": \"Çaktivizoj JavaScript-in\",\n \"description\": \"The default state for the per-site no-scripting switch\"\n },\n \"settingsNoCSPReportsPrompt\": {\n \"message\": \"Bllokoj raportet e CSP-së\",\n \"description\": \"background information: https:\\/\\/github.com\\/gorhill\\/uBlock\\/issues\\/3150\"\n },\n \"settingsStorageUsed\": {\n \"message\": \"Hapësira e përdorur: {{value}} bajt\",\n \"description\": \"English: Storage used: {{}} bytes\"\n },\n \"settingsLastRestorePrompt\": {\n \"message\": \"Rindërtimi i fundit:\",\n \"description\": \"English: Last restore:\"\n },\n \"settingsLastBackupPrompt\": {\n \"message\": \"Kopja e fundit:\",\n \"description\": \"English: Last backup:\"\n },\n \"3pListsOfBlockedHostsPrompt\": {\n \"message\": \"{{netFilterCount}} filtra të rrjetit + {{cosmeticFilterCount}} filtra kozmetikë nga:\",\n \"description\": \"Appears at the top of the _3rd-party filters_ pane\"\n },\n \"3pListsOfBlockedHostsPerListStats\": {\n \"message\": \"përdor {{used}} nga {{total}}\",\n \"description\": \"Appears aside each filter list in the _3rd-party filters_ pane\"\n },\n \"3pAutoUpdatePrompt1\": {\n \"message\": \"Përditësoj filtrat automatikisht\",\n \"description\": \"A checkbox in the _3rd-party filters_ pane\"\n },\n \"3pUpdateNow\": {\n \"message\": \"Përditësoj tani\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pPurgeAll\": {\n \"message\": \"Heq të gjitha stoqet\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pParseAllABPHideFiltersPrompt1\": {\n \"message\": \"Analizoj dhe zbatoj filtrat kozmetikë\",\n \"description\": \"English: Parse and enforce Adblock+ element hiding filters.\"\n },\n \"3pParseAllABPHideFiltersInfo\": {\n \"message\": \"

Ky opsion lejon analizimin dhe zbatimin e filtrave “eliminues” njësoj si në Adblock Plus<\\/a>. Këta filtra kozmetikë shërbejnë kryesisht për të fshehur nga ana vizive elementet e padëshirueshme të cilat nuk bllokohen me metodën standarde të filtrimit.<\\/p>

Aktivizimi i kësaj veçorie rrit impaktin e uBlock₀<\\/i> te memorja e kompjuterit.<\\/p>\",\n \"description\": \"Describes the purpose of the 'Parse and enforce cosmetic filters' feature.\"\n },\n \"3pIgnoreGenericCosmeticFilters\": {\n \"message\": \"Nuk marr parasysh filtrat kozmetikë jospecifikë\",\n \"description\": \"This will cause uBO to ignore all generic cosmetic filters.\"\n },\n \"3pIgnoreGenericCosmeticFiltersInfo\": {\n \"message\": \"

Filtrat kozmetikë jospecifikë janë filtra kozmetikë të cilët aplikohen për të gjitha faqet e internetit.

Megjithëse uBlock₀ i përdor ata me efikasitet, filtrat kozmetikë jospecifikë përsëri mund të rëndojnë memorjen dhe procesorin e kompjuterit në faqet e gjata.

Aktivizimi i këtij opsioni eliminon peshën e tepërt te memorja dhe procesori, dhe zvogëlon impaktin e uBlock₀ te memorja e kompjuterit.

Rekomandohet që ky opsion të aktivizohet për aparatet jo shumë të shpejta.\",\n \"description\": \"Describes the purpose of the 'Ignore generic cosmetic filters' feature.\"\n },\n \"3pListsOfBlockedHostsHeader\": {\n \"message\": \"Lista e hosteve të bllokuara\",\n \"description\": \"English: Lists of blocked hosts\"\n },\n \"3pApplyChanges\": {\n \"message\": \"Ruaj ndryshimet\",\n \"description\": \"English: Apply changes\"\n },\n \"3pGroupDefault\": {\n \"message\": \"Lokalë\",\n \"description\": \"Header for the uBlock filters section in 'Filter lists pane'\"\n },\n \"3pGroupAds\": {\n \"message\": \"Reklamat\",\n \"description\": \"English: Ads\"\n },\n \"3pGroupPrivacy\": {\n \"message\": \"Privatësia\",\n \"description\": \"English: Privacy\"\n },\n \"3pGroupMalware\": {\n \"message\": \"Domenet e dëmshme\",\n \"description\": \"English: Malware domains\"\n },\n \"3pGroupAnnoyances\": {\n \"message\": \"Elementet e bezdisshme\",\n \"description\": \"The header identifying the filter lists in the category 'annoyances'\"\n },\n \"3pGroupMultipurpose\": {\n \"message\": \"Për qëllime të ndryshme\",\n \"description\": \"English: Multipurpose\"\n },\n \"3pGroupRegions\": {\n \"message\": \"Sipas rajonit, gjuhës\",\n \"description\": \"English: Regions, languages\"\n },\n \"3pGroupCustom\": {\n \"message\": \"Personalizoj\",\n \"description\": \"English: Custom\"\n },\n \"3pImport\": {\n \"message\": \"Importoj...\",\n \"description\": \"The label for the checkbox used to import external filter lists\"\n },\n \"3pExternalListsHint\": {\n \"message\": \"Një URL për rresht. Nuk do të merren parasysh adresat e pasakta.\",\n \"description\": \"Short information about how to use the textarea to import external filter lists by URL\"\n },\n \"3pExternalListObsolete\": {\n \"message\": \"E vjetër.\",\n \"description\": \"used as a tooltip for the out-of-date icon beside a list\"\n },\n \"3pLastUpdate\": {\n \"message\": \"Përditësimi i fundit: {{ago}}.\\nKlikoni për ta kryer vetë përditësimin.\",\n \"description\": \"used as a tooltip for the clock icon beside a list\"\n },\n \"3pUpdating\": {\n \"message\": \"Po përditësohet...\",\n \"description\": \"used as a tooltip for the spinner icon beside a list\"\n },\n \"3pNetworkError\": {\n \"message\": \"Një problem me rrjetin pengoi përditësimin e informacionit.\",\n \"description\": \"used as a tooltip for error icon beside a list\"\n },\n \"1pFormatHint\": {\n \"message\": \"Një filtër për rresht. Filtri mund të jetë thjesht emri i një hosti ose i ngjashëm me ata që përdor Adblock Plus. Nuk do të merren parasysh rreshtat që fillojnë me !<\\/code>.\",\n \"description\": \"Short information about how to create custom filters\"\n },\n \"1pImport\": {\n \"message\": \"Importoj dhe shtoj\",\n \"description\": \"English: Import and append\"\n },\n \"1pExport\": {\n \"message\": \"Eksportoj\",\n \"description\": \"English: Export\"\n },\n \"1pExportFilename\": {\n \"message\": \"my-ublock-static-filters_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-static-filters_{{datetime}}.txt\"\n },\n \"1pApplyChanges\": {\n \"message\": \"Ruaj ndryshimet\",\n \"description\": \"English: Apply changes\"\n },\n \"rulesPermanentHeader\": {\n \"message\": \"Rregulla të përhershme\",\n \"description\": \"header\"\n },\n \"rulesTemporaryHeader\": {\n \"message\": \"Rregulla të përkohshme\",\n \"description\": \"header\"\n },\n \"rulesRevert\": {\n \"message\": \"Rikthej\",\n \"description\": \"This will remove all temporary rules\"\n },\n \"rulesCommit\": {\n \"message\": \"Aplikoj\",\n \"description\": \"This will persist temporary rules\"\n },\n \"rulesEdit\": {\n \"message\": \"Modifikoj\",\n \"description\": \"Will enable manual-edit mode (textarea)\"\n },\n \"rulesEditSave\": {\n \"message\": \"Regjistroj\",\n \"description\": \"Will save manually-edited content and exit manual-edit mode\"\n },\n \"rulesEditDiscard\": {\n \"message\": \"Anuloj\",\n \"description\": \"Will discard manually-edited content and exit manual-edit mode\"\n },\n \"rulesImport\": {\n \"message\": \"Importoj nga skedari...\",\n \"description\": \"\"\n },\n \"rulesExport\": {\n \"message\": \"Ruaj në skedar\",\n \"description\": \"\"\n },\n \"rulesDefaultFileName\": {\n \"message\": \"my-ublock-dynamic-rules_{{datetime}}.txt\",\n \"description\": \"default file name to use\"\n },\n \"rulesHint\": {\n \"message\": \"Lista e rregullave për filtrimin dinamik.\",\n \"description\": \"English: List of your dynamic filtering rules.\"\n },\n \"rulesFormatHint\": {\n \"message\": \"Rregullat e sintaksës: burimi destinacioni lloji veprimi<\\/code> (dokumentimi i plotë<\\/a>).\",\n \"description\": \"English: dynamic rule syntax and full documentation.\"\n },\n \"whitelistPrompt\": {\n \"message\": \"Lista e bardhë e detyron uBlock Origin të mos veprojë në faqe të caktuara. Një element për rresht. Nuk do të merren parasysh udhëzimet e pasakta.\",\n \"description\": \"English: An overview of the content of the dashboard's Whitelist pane.\"\n },\n \"whitelistImport\": {\n \"message\": \"Importoj dhe shtoj\",\n \"description\": \"English: Import and append\"\n },\n \"whitelistExport\": {\n \"message\": \"Eksportoj\",\n \"description\": \"English: Export\"\n },\n \"whitelistExportFilename\": {\n \"message\": \"my-ublock-whitelist_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-whitelist_{{datetime}}.txt\"\n },\n \"whitelistApply\": {\n \"message\": \"Ruaj ndryshimet\",\n \"description\": \"English: Apply changes\"\n },\n \"logRequestsHeaderType\": {\n \"message\": \"Lloji\",\n \"description\": \"English: Type\"\n },\n \"logRequestsHeaderDomain\": {\n \"message\": \"Domeni\",\n \"description\": \"English: Domain\"\n },\n \"logRequestsHeaderURL\": {\n \"message\": \"URL\",\n \"description\": \"English: URL\"\n },\n \"logRequestsHeaderFilter\": {\n \"message\": \"Filtri\",\n \"description\": \"English: Filter\"\n },\n \"logAll\": {\n \"message\": \"Të gjitha\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"logBehindTheScene\": {\n \"message\": \"Në prapaskenë\",\n \"description\": \"Pretty name for behind-the-scene network requests\"\n },\n \"loggerCurrentTab\": {\n \"message\": \"Skeda aktuale\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"loggerReloadTip\": {\n \"message\": \"Ngarko përmbajten e skedës\",\n \"description\": \"Tooltip for the reload button in the logger page\"\n },\n \"loggerDomInspectorTip\": {\n \"message\": \"Përdor ispektorin DOM\",\n \"description\": \"Tooltip for the DOM inspector button in the logger page\"\n },\n \"loggerPopupPanelTip\": {\n \"message\": \"Përdor panelin e dritareve automatike\",\n \"description\": \"Tooltip for the popup panel button in the logger page\"\n },\n \"loggerInfoTip\": {\n \"message\": \"uBlock Origin wiki: Regjistri\",\n \"description\": \"Tooltip for the top-right info label in the logger page\"\n },\n \"loggerClearTip\": {\n \"message\": \"Pastro regjistrin\",\n \"description\": \"Tooltip for the eraser in the logger page; used to blank the content of the logger\"\n },\n \"loggerPauseTip\": {\n \"message\": \"Ndalo regjistrin (fshin të gjithë të dhënat në hyrje)\",\n \"description\": \"Tooltip for the pause button in the logger page\"\n },\n \"loggerUnpauseTip\": {\n \"message\": \"Nis regjistrin\",\n \"description\": \"Tooltip for the play button in the logger page\"\n },\n \"loggerRowFiltererButtonTip\": {\n \"message\": \"Përdor filtrin e regjistrit\",\n \"description\": \"Tooltip for the row filterer button in the logger page\"\n },\n \"logFilterPrompt\": {\n \"message\": \"filtroni elementet në regjistër\",\n \"description\": \"Placeholder string for logger output filtering input field\"\n },\n \"loggerRowFiltererBuiltinTip\": {\n \"message\": \"Zgjedhni filtrat e regjistrimit\",\n \"description\": \"Tooltip for the button to bring up logger output filtering options\"\n },\n \"loggerRowFiltererBuiltinNot\": {\n \"message\": \"Nuk\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinEventful\": {\n \"message\": \"plot ngjarje\",\n \"description\": \"A keyword in the built-in row filtering expression: all items corresponding to uBO doing something (blocked, allowed, redirected, etc.)\"\n },\n \"loggerRowFiltererBuiltinBlocked\": {\n \"message\": \"të bllokuara\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinAllowed\": {\n \"message\": \"të lejuara\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin1p\": {\n \"message\": \"palët e para\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin3p\": {\n \"message\": \"palët e treta\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerEntryDetailsHeader\": {\n \"message\": \"Detalet\",\n \"description\": \"Small header to identify the 'Details' pane for a specific logger entry\"\n },\n \"loggerEntryDetailsFilter\": {\n \"message\": \"Filtra\",\n \"description\": \"Label to identify a filter field\"\n },\n \"loggerEntryDetailsFilterList\": {\n \"message\": \"Lista e filtrave\",\n \"description\": \"Label to identify a filter list field\"\n },\n \"loggerEntryDetailsRule\": {\n \"message\": \"Rregulla\",\n \"description\": \"Label to identify a rule field\"\n },\n \"loggerEntryDetailsContext\": {\n \"message\": \"Konteksti\",\n \"description\": \"Label to identify a context field (typically a hostname)\"\n },\n \"loggerEntryDetailsRootContext\": {\n \"message\": \"Konteksti kryesor\",\n \"description\": \"Label to identify a root context field (typically a hostname)\"\n },\n \"loggerEntryDetailsPartyness\": {\n \"message\": \"Pjesa e kërkesës\",\n \"description\": \"Label to identify a field providing partyness information\"\n },\n \"loggerEntryDetailsType\": {\n \"message\": \"Tip\",\n \"description\": \"Label to identify the type of an entry\"\n },\n \"loggerEntryDetailsURL\": {\n \"message\": \"URL\",\n \"description\": \"Label to identify the URL of an entry\"\n },\n \"loggerURLFilteringHeader\": {\n \"message\": \"Filtrim dinamik i adresave\",\n \"description\": \"Small header to identify the dynamic URL filtering section\"\n },\n \"loggerURLFilteringContextLabel\": {\n \"message\": \"Konteksti:\",\n \"description\": \"Label for the context selector\"\n },\n \"loggerURLFilteringTypeLabel\": {\n \"message\": \"Lloji:\",\n \"description\": \"Label for the type selector\"\n },\n \"loggerStaticFilteringHeader\": {\n \"message\": \"Filtrim statik\",\n \"description\": \"Small header to identify the static filtering section\"\n },\n \"loggerStaticFilteringSentence\": {\n \"message\": \"{{action}} kërkesat e {{type}} {{br}}adresa e të cilave korrespondon me {{url}} {{br}}dhe që e kanë origjinën {{origin}},{{br}}{{importance}} ekziston një filtër përjashtues i ngjashëm.\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartBlock\": {\n \"message\": \"Bllokoj\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAllow\": {\n \"message\": \"Lejoj\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartType\": {\n \"message\": \"llojit “{{type}}”\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyType\": {\n \"message\": \"çdo lloji\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartOrigin\": {\n \"message\": \"nga “{{origin}}”\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyOrigin\": {\n \"message\": \"ngado\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartNotImportant\": {\n \"message\": \"përveçse kur\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartImportant\": {\n \"message\": \"edhe kur\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringFinderSentence1\": {\n \"message\": \"Filtri statik {{filter}}<\\/code> gjendet në:\",\n \"description\": \"Below this sentence, the filter list(s) in which the filter was found\"\n },\n \"loggerStaticFilteringFinderSentence2\": {\n \"message\": \"Filtri statik {{filter}}<\\/code> nuk gjendet në asnjërën nga listat aktive\",\n \"description\": \"Message to show when a filter cannot be found in any filter lists\"\n },\n \"loggerSettingDiscardPrompt\": {\n \"message\": \"Regjistrimi i regjistrit që nuk plotëson të tri kushtet e mëposhtme automatikisht do të fshihet:\",\n \"description\": \"Logger setting: A sentence to describe the purpose of the settings below\"\n },\n \"loggerSettingPerEntryMaxAge\": {\n \"message\": \"Mbaj shënimet për {{input}} minutat e fundit\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxLoads\": {\n \"message\": \"Mbaje më së shumti {{input}} ngarkime faqe për skedë\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxEntries\": {\n \"message\": \"Mbaje më së shumti {{input}} shënime për kartë\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerEntryLineCount\": {\n \"message\": \"Përdor {{input}} rreshta për artikull në mënyrë të zgjeruar vertikalisht\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingHideColumnsPrompt\": {\n \"message\": \"Fshih kolonat:\",\n \"description\": \"Logger settings: a sentence to describe the purpose of the checkboxes below\"\n },\n \"loggerSettingHideColumnTime\": {\n \"message\": \"{{input}} Koha\",\n \"description\": \"A label for the time column\"\n },\n \"loggerSettingHideColumnFilter\": {\n \"message\": \"{{input}} Filtra\\/rregulla\",\n \"description\": \"A label for the filter or rule column\"\n },\n \"loggerSettingHideColumnContext\": {\n \"message\": \"{{input}} Konteksti\",\n \"description\": \"A label for the context column\"\n },\n \"loggerSettingHideColumnPartyness\": {\n \"message\": \"{{input}} Pjesa e kërkesës\",\n \"description\": \"A label for the partyness column\"\n },\n \"loggerExportFormatList\": {\n \"message\": \"Lista\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportFormatTable\": {\n \"message\": \"Tabella\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportEncodePlain\": {\n \"message\": \"Thjeshtë\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"loggerExportEncodeMarkdown\": {\n \"message\": \"Markdown\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"aboutChangelog\": {\n \"message\": \"Ditari i ndryshimeve\",\n \"description\": \"\"\n },\n \"aboutWiki\": {\n \"message\": \"Wiki\",\n \"description\": \"English: project' wiki on GitHub\"\n },\n \"aboutSupport\": {\n \"message\": \"Mbështetja teknike\",\n \"description\": \"A link for where to get support\"\n },\n \"aboutIssues\": {\n \"message\": \"Lista e problemeve\",\n \"description\": \"Text for a link to official issue tracker\"\n },\n \"aboutCode\": {\n \"message\": \"Materiali burimor (GPLv3)\",\n \"description\": \"English: Source code (GPLv3)\"\n },\n \"aboutContributors\": {\n \"message\": \"Kontribuesit\",\n \"description\": \"English: Contributors\"\n },\n \"aboutDependencies\": {\n \"message\": \"Programe kushtëzuese (përshtatet me GPLv3):\",\n \"description\": \"Shown in the About pane\"\n },\n \"aboutBackupDataButton\": {\n \"message\": \"Kopjoj në skedar\",\n \"description\": \"Text for button to create a backup of all settings\"\n },\n \"aboutBackupFilename\": {\n \"message\": \"my-ublock-backup_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-backup_{{datetime}}.txt\"\n },\n \"aboutRestoreDataButton\": {\n \"message\": \"Rindërtoj sipas skedarit...\",\n \"description\": \"English: Restore from file...\"\n },\n \"aboutResetDataButton\": {\n \"message\": \"Kthej parametrat fillestarë...\",\n \"description\": \"English: Reset to default settings...\"\n },\n \"aboutRestoreDataConfirm\": {\n \"message\": \"Të gjithë parametrat do të mbishkruhen me të dhënat e kopjuara më {{time}}, dhe uBlock₀ do të hapet përsëri.\\n\\nTë mbishkruhen parametrat aktualë?\",\n \"description\": \"Message asking user to confirm restore\"\n },\n \"aboutRestoreDataError\": {\n \"message\": \"Të dhënat nuk lexohen ose mund të jenë dëmtuar\",\n \"description\": \"Message to display when an error occurred during restore\"\n },\n \"aboutResetDataConfirm\": {\n \"message\": \"Të gjithë parametrat do të fshihen dhe uBlock₀ do të hapet përsëri.\\n\\nTë kthehen parametrat origjinalë?\",\n \"description\": \"Message asking user to confirm reset\"\n },\n \"errorCantConnectTo\": {\n \"message\": \"Problem me rrjetin: {{msg}}\",\n \"description\": \"English: Network error: {{msg}}\"\n },\n \"subscriberConfirm\": {\n \"message\": \"uBlock₀: Të shtohet adresa në listën e filtrave tuaj?\\n\\nTitulli: \\\"{{title}}\\\"\\nURL: {{url}}\",\n \"description\": \"English: The message seen by the user to confirm subscription to a ABP filter list\"\n },\n \"elapsedOneMinuteAgo\": {\n \"message\": \"një minutë më parë\",\n \"description\": \"English: a minute ago\"\n },\n \"elapsedManyMinutesAgo\": {\n \"message\": \"{{value}} minuta më parë\",\n \"description\": \"English: {{value}} minutes ago\"\n },\n \"elapsedOneHourAgo\": {\n \"message\": \"një orë më parë\",\n \"description\": \"English: an hour ago\"\n },\n \"elapsedManyHoursAgo\": {\n \"message\": \"{{value}} orë më parë\",\n \"description\": \"English: {{value}} hours ago\"\n },\n \"elapsedOneDayAgo\": {\n \"message\": \"një ditë më parë\",\n \"description\": \"English: a day ago\"\n },\n \"elapsedManyDaysAgo\": {\n \"message\": \"{{value}} ditë më parë\",\n \"description\": \"English: {{value}} days ago\"\n },\n \"showDashboardButton\": {\n \"message\": \"Paneli i kontrollit\",\n \"description\": \"Firefox\\/Fennec-specific: Show Dashboard\"\n },\n \"showNetworkLogButton\": {\n \"message\": \"Regjistri i kërkesave\",\n \"description\": \"Firefox\\/Fennec-specific: Show Logger\"\n },\n \"fennecMenuItemBlockingOff\": {\n \"message\": \"fikur\",\n \"description\": \"Firefox-specific: appears as 'uBlock₀ (off)'\"\n },\n \"docblockedPrompt1\": {\n \"message\": \"uBlock Origin po pengon hapjen e faqes:\",\n \"description\": \"English: uBlock₀ has prevented the following page from loading:\"\n },\n \"docblockedPrompt2\": {\n \"message\": \"Për shkak të filtrit\",\n \"description\": \"English: Because of the following filter\"\n },\n \"docblockedNoParamsPrompt\": {\n \"message\": \"pa parametra\",\n \"description\": \"label to be used for the parameter-less URL: https:\\/\\/cloud.githubusercontent.com\\/assets\\/585534\\/9832014\\/bfb1b8f0-593b-11e5-8a27-fba472a5529a.png\"\n },\n \"docblockedFoundIn\": {\n \"message\": \"Gjendet në:\",\n \"description\": \"English: List of filter list names follows\"\n },\n \"docblockedBack\": {\n \"message\": \"Kthehem\",\n \"description\": \"English: Go back\"\n },\n \"docblockedClose\": {\n \"message\": \"Mbyll dritaren\",\n \"description\": \"English: Close this window\"\n },\n \"docblockedProceed\": {\n \"message\": \"Zhbllokoj mënyrën strikte për {{hostname}}\",\n \"description\": \"English: Disable strict blocking for {{hostname}} ...\"\n },\n \"docblockedDisableTemporary\": {\n \"message\": \"Përkohësisht\",\n \"description\": \"English: Temporarily\"\n },\n \"docblockedDisablePermanent\": {\n \"message\": \"Gjithmonë\",\n \"description\": \"English: Permanently\"\n },\n \"cloudPush\": {\n \"message\": \"Eksportoj në renë informatike\",\n \"description\": \"tooltip\"\n },\n \"cloudPull\": {\n \"message\": \"Importoj nga reja informatike\",\n \"description\": \"tooltip\"\n },\n \"cloudPullAndMerge\": {\n \"message\": \"Importoj nga reja informatike dhe bashkoj me parametrat aktualë\",\n \"description\": \"tooltip\"\n },\n \"cloudNoData\": {\n \"message\": \"...\\n...\",\n \"description\": \"\"\n },\n \"cloudDeviceNamePrompt\": {\n \"message\": \"Emri i aparatit:\",\n \"description\": \"used as a prompt for the user to provide a custom device name\"\n },\n \"advancedSettingsWarning\": {\n \"message\": \"Kujdes! Përgjegjësia për ndryshimin e këtyre parametrave bie mbi ju.\",\n \"description\": \"A warning to users at the top of 'Advanced settings' page\"\n },\n \"genericSubmit\": {\n \"message\": \"Parashtroj\",\n \"description\": \"for generic 'Submit' buttons\"\n },\n \"genericApplyChanges\": {\n \"message\": \"Ruaj ndryshimet\",\n \"description\": \"for generic 'Apply changes' buttons\"\n },\n \"genericRevert\": {\n \"message\": \"Rikthej\",\n \"description\": \"for generic 'Revert' buttons\"\n },\n \"genericBytes\": {\n \"message\": \"bajt\",\n \"description\": \"\"\n },\n \"contextMenuTemporarilyAllowLargeMediaElements\": {\n \"message\": \"Lejoj përkohësisht elementet multimediale me përmasa të mëdha\",\n \"description\": \"A context menu entry, present when large media elements have been blocked on the current site\"\n },\n \"shortcutCapturePlaceholder\": {\n \"message\": \"Vendosni kombinimin\",\n \"description\": \"Placeholder string for input field used to capture a keyboard shortcut\"\n },\n \"genericMergeViewScrollLock\": {\n \"message\": \"Bllokoj shiritin e lëvizjes\",\n \"description\": \"Tooltip for the button used to lock scrolling between the views in the 'My rules' pane\"\n },\n \"genericCopyToClipboard\": {\n \"message\": \"Kopjo në kujtesën\",\n \"description\": \"Label for buttons used to copy something to the clipboard\"\n },\n \"dummy\": {\n \"message\": \"This entry must be the last one\",\n \"description\": \"so we dont need to deal with comma for last entry\"\n }\n}", "file_path": "src/_locales/sq/messages.json", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001760038430802524, 0.0001714962418191135, 0.00016592150495853275, 0.00017206385382451117, 2.2393205654225312e-06]} {"hunk": {"id": 0, "code_window": ["\n", "/******************************************************************************/\n", "\n", "vAPI.DOMFilterer = class {\n", " constructor() {\n", " this.commitTimer = new vAPI.SafeAnimationFrame(( ) => this.commitNow);\n", " this.domIsReady = document.readyState !== 'loading';\n", " this.disabled = false;\n", " this.listeners = [];\n", " this.filterset = new Set();\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" this.commitTimer = new vAPI.SafeAnimationFrame(this.commitNow.bind(this));\n"], "file_path": "platform/chromium/vapi-usercss.real.js", "type": "replace", "edit_start_line_idx": 61}, "file": "Действащ блокер: щадящ паметта и процесора, но и способен да зареди и наложи хиляди филтри в сравнение с други популярни блокери.\n\nИлюстрация на неговата ефикасност: https://github.com/gorhill/uBlock/wiki/uBlock-vs.-ABP:-efficiency-compared\n\nИзползване: големият бутон за включване в изскачащия прозорец забранява/разрешава uBlock в текущия сайт. Приложим само за текущия сайт, не действа глобално.\n\n***\n\nГъвкав, нещо повече от „блокер на реклами“: чете и създава филтри на базата на файлове с хостове.\n\nПървоначално са заредени и наложени следните филтри:\n\n- EasyList\n- списък с рекламни сървъри от Peter Lowe\n- EasyPrivacy\n- вредоносни домейни\n\nAко желаете, на разположение са допълнителни списъци, които да изберете:\n\n- разширен проследяващ списък от Fanboy\n- файл с хостове от Dan Pollock\n- рекламни и проследяващи сървъри от hpHosts\n- MVPS HOSTS\n- Spam404\n- и много други\n\nРазбира се, колкото повече списъци включите, толкова по-голямо е използването на паметта. Въпреки това, дори и след добавяне на двата допълнителни списъка от Fanboy, рекламните и проследяващи сървъри от hpHosts, uBlock₀ използва по-малко памет в сравнение с други много популярни блокери.\n\nИмайте също така предвид, че избирането на определени допълнителни списъци може да доведе с голяма степен на вероятност до неправилно функциониране на сайтовете — особено тези, които по принцип се ползват като файл с хостове.\n\n***\n\nБез предварително зададените списъци с филтри, това разширение е нищо. Така че, ако някога наистина искате да допринесете с нещо, помислете за хората, работещи усилено по поддържането на списъците с филтри, предоставени ви за безплатно използване от всички.\n\n***\n\nБезплатно.\nОтворен код с публичен лиценз (GPLv3)\nЗа потребители от потребители.\n\nСътрудници @ Github: https://github.com/gorhill/uBlock/graphs/contributors\nСътрудници @ Crowdin: https://crowdin.net/project/ublock\n\n***\n\nТова е доста ранна версия, имайте го предвид, когато я разглеждате.\n\nСписък с промени на проекта:\nhttps://github.com/gorhill/uBlock/releases\n", "file_path": "dist/description/description-bg.txt", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0006685723201371729, 0.0002975276729557663, 0.0001655657688388601, 0.00018749987066257745, 0.0001911306317197159]} {"hunk": {"id": 0, "code_window": ["\n", "/******************************************************************************/\n", "\n", "vAPI.DOMFilterer = class {\n", " constructor() {\n", " this.commitTimer = new vAPI.SafeAnimationFrame(( ) => this.commitNow);\n", " this.domIsReady = document.readyState !== 'loading';\n", " this.disabled = false;\n", " this.listeners = [];\n", " this.filterset = new Set();\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" this.commitTimer = new vAPI.SafeAnimationFrame(this.commitNow.bind(this));\n"], "file_path": "platform/chromium/vapi-usercss.real.js", "type": "replace", "edit_start_line_idx": 61}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2018-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n(function() {\n\n // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/commands#Shortcut_values\n let validStatus0Keys = new Map([\n [ 'alt', 'Alt' ],\n [ 'control', 'Ctrl' ],\n ]);\n let validStatus1Keys = new Map([\n [ 'a', 'A' ],\n [ 'b', 'B' ],\n [ 'c', 'C' ],\n [ 'd', 'D' ],\n [ 'e', 'E' ],\n [ 'f', 'F' ],\n [ 'g', 'G' ],\n [ 'h', 'H' ],\n [ 'i', 'I' ],\n [ 'j', 'J' ],\n [ 'k', 'K' ],\n [ 'l', 'L' ],\n [ 'm', 'M' ],\n [ 'n', 'N' ],\n [ 'o', 'O' ],\n [ 'p', 'P' ],\n [ 'q', 'Q' ],\n [ 'r', 'R' ],\n [ 's', 'S' ],\n [ 't', 'T' ],\n [ 'u', 'U' ],\n [ 'v', 'V' ],\n [ 'w', 'W' ],\n [ 'x', 'X' ],\n [ 'y', 'Y' ],\n [ 'z', 'Z' ],\n [ '0', '0' ],\n [ '1', '1' ],\n [ '2', '2' ],\n [ '3', '3' ],\n [ '4', '4' ],\n [ '5', '5' ],\n [ '6', '6' ],\n [ '7', '7' ],\n [ '8', '8' ],\n [ '9', '9' ],\n [ 'f1', 'F1' ],\n [ 'f2', 'F2' ],\n [ 'f3', 'F3' ],\n [ 'f4', 'F4' ],\n [ 'f5', 'F5' ],\n [ 'f6', 'F6' ],\n [ 'f7', 'F7' ],\n [ 'f8', 'F8' ],\n [ 'f9', 'F9' ],\n [ 'f10', 'F10' ],\n [ 'f11', 'F11' ],\n [ 'f12', 'F12' ],\n [ ' ', 'Space' ],\n [ ',', 'Comma' ],\n [ '.', 'Period' ],\n [ 'home', 'Home' ],\n [ 'end', 'End' ],\n [ 'pageup', 'PageUp' ],\n [ 'pagedown', 'PageDown' ],\n [ 'insert', 'Insert' ],\n [ 'delete', 'Delete' ],\n [ 'arrowup', 'Up' ],\n [ 'arrowdown', 'Down' ],\n [ 'arrowleft', 'Left' ],\n [ 'arrowright', 'Right' ],\n [ 'shift', 'Shift' ],\n ]);\n\n let commandNameFromElement = function(elem) {\n while ( elem !== null ) {\n let name = elem.getAttribute('data-name');\n if ( typeof name === 'string' && name !== '' ) { return name; }\n elem = elem.parentElement;\n }\n };\n\n let captureShortcut = function(ev) {\n let input = ev.target;\n let name = commandNameFromElement(input);\n if ( name === undefined ) { return; }\n\n let before = input.value;\n let after = new Set();\n let status = 0;\n\n let updateCapturedShortcut = function() {\n return (input.value = Array.from(after).join('+'));\n };\n\n let blurHandler = function() {\n input.removeEventListener('blur', blurHandler, true);\n input.removeEventListener('keydown', keydownHandler, true);\n input.removeEventListener('keyup', keyupHandler, true);\n if ( status === 2 ) {\n vAPI.messaging.send(\n 'dashboard',\n { what: 'setShortcut', name: name, shortcut: updateCapturedShortcut() }\n );\n } else {\n input.value = before;\n }\n };\n\n let keydownHandler = function(ev) {\n ev.preventDefault();\n ev.stopImmediatePropagation();\n if ( ev.code === 'Escape' ) {\n input.blur();\n return;\n }\n if ( status === 0 ) {\n let keyName = validStatus0Keys.get(ev.key.toLowerCase());\n if ( keyName !== undefined ) {\n after.add(keyName);\n updateCapturedShortcut();\n status = 1;\n }\n return;\n }\n if ( status === 1 ) {\n if ( ev.key === 'Shift' ) {\n after.add('Shift');\n updateCapturedShortcut();\n return;\n }\n let keyName = validStatus1Keys.get(ev.key.toLowerCase());\n if ( keyName !== undefined ) {\n after.add(keyName);\n updateCapturedShortcut();\n status = 2;\n input.blur();\n return;\n }\n }\n };\n\n let keyupHandler = function(ev) {\n ev.preventDefault();\n ev.stopImmediatePropagation();\n if ( status !== 1 ) { return; }\n let keyName = validStatus0Keys.get(ev.key.toLowerCase());\n if ( keyName !== undefined && after.has(keyName) ) {\n after.clear();\n updateCapturedShortcut();\n status = 0;\n return;\n }\n if ( ev.key === 'Shift' ) {\n after.delete('Shift');\n updateCapturedShortcut();\n return;\n }\n };\n\n input.value = '';\n input.addEventListener('blur', blurHandler, true);\n input.addEventListener('keydown', keydownHandler, true);\n input.addEventListener('keyup', keyupHandler, true);\n };\n\n let resetShortcut = function(ev) {\n let name = commandNameFromElement(ev.target);\n if ( name === undefined ) { return; }\n\n let input = document.querySelector('[data-name=\"' + name + '\"] input');\n if ( input === null ) { return; }\n input.value = '';\n vAPI.messaging.send(\n 'dashboard',\n { what: 'setShortcut', name: name }\n );\n };\n\n let onShortcutsReady = function(commands) {\n if ( Array.isArray(commands) === false ) { return; }\n let template = document.querySelector('#templates .commandEntry');\n let tbody = document.querySelector('.commandEntries tbody');\n for ( let command of commands ) {\n if ( command.description === '' ) { continue; }\n let tr = template.cloneNode(true);\n tr.setAttribute('data-name', command.name);\n tr.querySelector('.commandDesc').textContent = command.description;\n let input = tr.querySelector('.commandShortcut input');\n input.setAttribute('data-name', command.name);\n input.value = command.shortcut;\n input.addEventListener('focus', captureShortcut);\n tr.querySelector('.commandReset').addEventListener('click', resetShortcut);\n tbody.appendChild(tr);\n }\n };\n\n vAPI.messaging.send('dashboard', { what: 'getShortcuts' }, onShortcutsReady);\n\n})();\n", "file_path": "src/js/shortcuts.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00035739794839173555, 0.0001862729841377586, 0.00016186930588446558, 0.0001707765186438337, 4.506425102590583e-05]} {"hunk": {"id": 1, "code_window": [" }\n", " };\n", " PSelector.prototype.operatorToTaskMap = undefined;\n", "\n", " const DOMProceduralFilterer = function(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " };\n", "\n", " DOMProceduralFilterer.prototype = {\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" const DOMProceduralFilterer = class {\n", " constructor(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 711}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9975419044494629, 0.07949253916740417, 0.00016421613690908998, 0.00017331229173578322, 0.24946388602256775]} {"hunk": {"id": 1, "code_window": [" }\n", " };\n", " PSelector.prototype.operatorToTaskMap = undefined;\n", "\n", " const DOMProceduralFilterer = function(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " };\n", "\n", " DOMProceduralFilterer.prototype = {\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" const DOMProceduralFilterer = class {\n", " constructor(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 711}, "file": "#!/usr/bin/env bash\n#\n# This script assumes a linux environment\n\necho \"*** uBlock: Cleaning.\"\nrm -R dist/build\necho \"*** uBlock: Cleaned.\"\n", "file_path": "tools/make-clean.sh", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00016923282237257808, 0.00016923282237257808, 0.00016923282237257808, 0.00016923282237257808, 0.0]} {"hunk": {"id": 1, "code_window": [" }\n", " };\n", " PSelector.prototype.operatorToTaskMap = undefined;\n", "\n", " const DOMProceduralFilterer = function(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " };\n", "\n", " DOMProceduralFilterer.prototype = {\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" const DOMProceduralFilterer = class {\n", " constructor(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 711}, "file": "\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n image/svg+xml\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n contextwhitelisted?\n local dynamicfiltering rule?\n \n allow\n \n no\n noop\n \n no\n \n \n global dynamicfiltering rule?\n \n allow\n noop\n \n no\n \n \n static filtering?\n \n \n \n advanced usermode?\n yes\n \n \n no\n \n \n \n \n no filter\n context\n URL ofresource\n URL of page\n \n block\n \n block\n \n exception filter\n \n block filter\n remote server\n yes\n \n \n your browser\n \n \n url filtering rule?\n \n allow\n \n block\n no\n \n \n noop\n \n \n\n", "file_path": "doc/img/filtering-overview-plain.svg", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001771392417140305, 0.0001738693827064708, 0.00016983870591502637, 0.00017380852659698576, 1.5259116707966314e-06]} {"hunk": {"id": 1, "code_window": [" }\n", " };\n", " PSelector.prototype.operatorToTaskMap = undefined;\n", "\n", " const DOMProceduralFilterer = function(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " };\n", "\n", " DOMProceduralFilterer.prototype = {\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" const DOMProceduralFilterer = class {\n", " constructor(domFilterer) {\n", " this.domFilterer = domFilterer;\n", " this.domIsReady = false;\n", " this.domIsWatched = false;\n", " this.mustApplySelectors = false;\n", " this.selectors = new Map();\n", " this.hiddenNodes = new Set();\n", " }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 711}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n/* global DOMTokenList */\n/* exported uDom */\n\n'use strict';\n\n/******************************************************************************/\n\n// It's just a silly, minimalist DOM framework: this allows me to not rely\n// on jQuery. jQuery contains way too much stuff than I need, and as per\n// Opera rules, I am not allowed to use a cut-down version of jQuery. So\n// the code here does *only* what I need, and nothing more, and with a lot\n// of assumption on passed parameters, etc. I grow it on a per-need-basis only.\n\nconst uDom = (function() {\n\n/******************************************************************************/\n\nconst DOMList = function() {\n this.nodes = [];\n};\n\n/******************************************************************************/\n\nObject.defineProperty(\n DOMList.prototype,\n 'length',\n {\n get: function() {\n return this.nodes.length;\n }\n }\n);\n\n/******************************************************************************/\n\nconst DOMListFactory = function(selector, context) {\n var r = new DOMList();\n if ( typeof selector === 'string' ) {\n selector = selector.trim();\n if ( selector !== '' ) {\n return addSelectorToList(r, selector, context);\n }\n }\n if ( selector instanceof Node ) {\n return addNodeToList(r, selector);\n }\n if ( selector instanceof NodeList ) {\n return addNodeListToList(r, selector);\n }\n if ( selector instanceof DOMList ) {\n return addListToList(r, selector);\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMListFactory.onLoad = function(callback) {\n window.addEventListener('load', callback);\n};\n\n/******************************************************************************/\n\nDOMListFactory.nodeFromId = function(id) {\n return document.getElementById(id);\n};\n\nDOMListFactory.nodeFromSelector = function(selector) {\n return document.querySelector(selector);\n};\n\n/******************************************************************************/\n\nconst addNodeToList = function(list, node) {\n if ( node ) {\n list.nodes.push(node);\n }\n return list;\n};\n\n/******************************************************************************/\n\nconst addNodeListToList = function(list, nodelist) {\n if ( nodelist ) {\n var n = nodelist.length;\n for ( var i = 0; i < n; i++ ) {\n list.nodes.push(nodelist[i]);\n }\n }\n return list;\n};\n\n/******************************************************************************/\n\nconst addListToList = function(list, other) {\n list.nodes = list.nodes.concat(other.nodes);\n return list;\n};\n\n/******************************************************************************/\n\nconst addSelectorToList = function(list, selector, context) {\n var p = context || document;\n var r = p.querySelectorAll(selector);\n var n = r.length;\n for ( var i = 0; i < n; i++ ) {\n list.nodes.push(r[i]);\n }\n return list;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.nodeAt = function(i) {\n return this.nodes[i] || null;\n};\n\nDOMList.prototype.at = function(i) {\n return addNodeToList(new DOMList(), this.nodes[i]);\n};\n\n/******************************************************************************/\n\nDOMList.prototype.toArray = function() {\n return this.nodes.slice();\n};\n\n/******************************************************************************/\n\nDOMList.prototype.pop = function() {\n return addNodeToList(new DOMList(), this.nodes.pop());\n};\n\n/******************************************************************************/\n\nDOMList.prototype.forEach = function(fn) {\n var n = this.nodes.length;\n for ( var i = 0; i < n; i++ ) {\n fn(this.at(i), i);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.subset = function(i, l) {\n var r = new DOMList();\n var n = l !== undefined ? l : this.nodes.length;\n var j = Math.min(i + n, this.nodes.length);\n if ( i < j ) {\n r.nodes = this.nodes.slice(i, j);\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.first = function() {\n return this.subset(0, 1);\n};\n\n/******************************************************************************/\n\nDOMList.prototype.next = function(selector) {\n var r = new DOMList();\n var n = this.nodes.length;\n var node;\n for ( var i = 0; i < n; i++ ) {\n node = this.nodes[i];\n while ( node.nextSibling !== null ) {\n node = node.nextSibling;\n if ( node.nodeType !== 1 ) { continue; }\n if ( node.matches(selector) === false ) { continue; }\n addNodeToList(r, node);\n break;\n }\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.parent = function() {\n var r = new DOMList();\n if ( this.nodes.length ) {\n addNodeToList(r, this.nodes[0].parentNode);\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.filter = function(filter) {\n var r = new DOMList();\n var filterFunc;\n if ( typeof filter === 'string' ) {\n filterFunc = function() {\n return this.matches(filter);\n };\n } else if ( typeof filter === 'function' ) {\n filterFunc = filter;\n } else {\n filterFunc = function(){\n return true;\n };\n }\n var n = this.nodes.length;\n var node;\n for ( var i = 0; i < n; i++ ) {\n node = this.nodes[i];\n if ( filterFunc.apply(node) ) {\n addNodeToList(r, node);\n }\n }\n return r;\n};\n\n/******************************************************************************/\n\n// TODO: Avoid possible duplicates\n\nDOMList.prototype.ancestors = function(selector) {\n var r = new DOMList();\n for ( var i = 0, n = this.nodes.length; i < n; i++ ) {\n var node = this.nodes[i].parentNode;\n while ( node ) {\n if (\n node instanceof Element &&\n node.matches(selector)\n ) {\n addNodeToList(r, node);\n }\n node = node.parentNode;\n }\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.descendants = function(selector) {\n var r = new DOMList();\n var n = this.nodes.length;\n var nl;\n for ( var i = 0; i < n; i++ ) {\n nl = this.nodes[i].querySelectorAll(selector);\n addNodeListToList(r, nl);\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.contents = function() {\n var r = new DOMList();\n var cnodes, cn, ci;\n var n = this.nodes.length;\n for ( var i = 0; i < n; i++ ) {\n cnodes = this.nodes[i].childNodes;\n cn = cnodes.length;\n for ( ci = 0; ci < cn; ci++ ) {\n addNodeToList(r, cnodes.item(ci));\n }\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.remove = function() {\n var cn, p;\n var i = this.nodes.length;\n while ( i-- ) {\n cn = this.nodes[i];\n if ( (p = cn.parentNode) ) {\n p.removeChild(cn);\n }\n }\n return this;\n};\n\nDOMList.prototype.detach = DOMList.prototype.remove;\n\n/******************************************************************************/\n\nDOMList.prototype.empty = function() {\n var node;\n var i = this.nodes.length;\n while ( i-- ) {\n node = this.nodes[i];\n while ( node.firstChild ) {\n node.removeChild(node.firstChild);\n }\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.append = function(selector, context) {\n var p = this.nodes[0];\n if ( p ) {\n var c = DOMListFactory(selector, context);\n var n = c.nodes.length;\n for ( var i = 0; i < n; i++ ) {\n p.appendChild(c.nodes[i]);\n }\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.prepend = function(selector, context) {\n var p = this.nodes[0];\n if ( p ) {\n var c = DOMListFactory(selector, context);\n var i = c.nodes.length;\n while ( i-- ) {\n p.insertBefore(c.nodes[i], p.firstChild);\n }\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.appendTo = function(selector, context) {\n var p = selector instanceof DOMListFactory ? selector : DOMListFactory(selector, context);\n var n = p.length;\n for ( var i = 0; i < n; i++ ) {\n p.nodes[0].appendChild(this.nodes[i]);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.insertAfter = function(selector, context) {\n if ( this.nodes.length === 0 ) {\n return this;\n }\n var p = this.nodes[0].parentNode;\n if ( !p ) {\n return this;\n }\n var c = DOMListFactory(selector, context);\n var n = c.nodes.length;\n for ( var i = 0; i < n; i++ ) {\n p.appendChild(c.nodes[i]);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.insertBefore = function(selector, context) {\n if ( this.nodes.length === 0 ) {\n return this;\n }\n var referenceNodes = DOMListFactory(selector, context);\n if ( referenceNodes.nodes.length === 0 ) {\n return this;\n }\n var referenceNode = referenceNodes.nodes[0];\n var parentNode = referenceNode.parentNode;\n if ( !parentNode ) {\n return this;\n }\n var n = this.nodes.length;\n for ( var i = 0; i < n; i++ ) {\n parentNode.insertBefore(this.nodes[i], referenceNode);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.clone = function(notDeep) {\n var r = new DOMList();\n var n = this.nodes.length;\n for ( var i = 0; i < n; i++ ) {\n addNodeToList(r, this.nodes[i].cloneNode(!notDeep));\n }\n return r;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.nthOfType = function() {\n if ( this.nodes.length === 0 ) {\n return 0;\n }\n var node = this.nodes[0];\n var tagName = node.tagName;\n var i = 1;\n while ( node.previousElementSibling !== null ) {\n node = node.previousElementSibling;\n if ( typeof node.tagName !== 'string' ) {\n continue;\n }\n if ( node.tagName !== tagName ) {\n continue;\n }\n i++;\n }\n return i;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.attr = function(attr, value) {\n var i = this.nodes.length;\n if ( value === undefined && typeof attr !== 'object' ) {\n return i ? this.nodes[0].getAttribute(attr) : undefined;\n }\n if ( typeof attr === 'object' ) {\n var attrNames = Object.keys(attr);\n var node, j, attrName;\n while ( i-- ) {\n node = this.nodes[i];\n j = attrNames.length;\n while ( j-- ) {\n attrName = attrNames[j];\n node.setAttribute(attrName, attr[attrName]);\n }\n }\n } else {\n while ( i-- ) {\n this.nodes[i].setAttribute(attr, value);\n }\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.removeAttr = function(attr) {\n var i = this.nodes.length;\n while ( i-- ) {\n this.nodes[i].removeAttribute(attr);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.prop = function(prop, value) {\n var i = this.nodes.length;\n if ( value === undefined ) {\n return i !== 0 ? this.nodes[0][prop] : undefined;\n }\n while ( i-- ) {\n this.nodes[i][prop] = value;\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.css = function(prop, value) {\n var i = this.nodes.length;\n if ( value === undefined ) {\n return i ? this.nodes[0].style[prop] : undefined;\n }\n if ( value !== '' ) {\n while ( i-- ) {\n this.nodes[i].style.setProperty(prop, value);\n }\n return this;\n }\n while ( i-- ) {\n this.nodes[i].style.removeProperty(prop);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.val = function(value) {\n return this.prop('value', value);\n};\n\n/******************************************************************************/\n\nDOMList.prototype.text = function(text) {\n var i = this.nodes.length;\n if ( text === undefined ) {\n return i ? this.nodes[0].textContent : '';\n }\n while ( i-- ) {\n this.nodes[i].textContent = text;\n }\n return this;\n};\n\n/******************************************************************************/\n\nconst toggleClass = function(node, className, targetState) {\n var tokenList = node.classList;\n if ( tokenList instanceof DOMTokenList === false ) {\n return;\n }\n var currentState = tokenList.contains(className);\n var newState = targetState;\n if ( newState === undefined ) {\n newState = !currentState;\n }\n if ( newState === currentState ) {\n return;\n }\n tokenList.toggle(className, newState);\n};\n\n/******************************************************************************/\n\nDOMList.prototype.hasClass = function(className) {\n if ( !this.nodes.length ) {\n return false;\n }\n var tokenList = this.nodes[0].classList;\n return tokenList instanceof DOMTokenList &&\n tokenList.contains(className);\n};\nDOMList.prototype.hasClassName = DOMList.prototype.hasClass;\n\nDOMList.prototype.addClass = function(className) {\n return this.toggleClass(className, true);\n};\n\nDOMList.prototype.removeClass = function(className) {\n if ( className !== undefined ) {\n return this.toggleClass(className, false);\n }\n var i = this.nodes.length;\n while ( i-- ) {\n this.nodes[i].className = '';\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.toggleClass = function(className, targetState) {\n if ( className.indexOf(' ') !== -1 ) {\n return this.toggleClasses(className, targetState);\n }\n var i = this.nodes.length;\n while ( i-- ) {\n toggleClass(this.nodes[i], className, targetState);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.toggleClasses = function(classNames, targetState) {\n var tokens = classNames.split(/\\s+/);\n var i = this.nodes.length;\n var node, j;\n while ( i-- ) {\n node = this.nodes[i];\n j = tokens.length;\n while ( j-- ) {\n toggleClass(node, tokens[j], targetState);\n }\n }\n return this;\n};\n\n/******************************************************************************/\n\nconst listenerEntries = [];\n\nconst ListenerEntry = function(target, type, capture, callback) {\n this.target = target;\n this.type = type;\n this.capture = capture;\n this.callback = callback;\n target.addEventListener(type, callback, capture);\n};\n\nListenerEntry.prototype.dispose = function() {\n this.target.removeEventListener(this.type, this.callback, this.capture);\n this.target = null;\n this.callback = null;\n};\n\n/******************************************************************************/\n\nconst makeEventHandler = function(selector, callback) {\n return function(event) {\n const dispatcher = event.currentTarget;\n if (\n dispatcher instanceof HTMLElement === false ||\n typeof dispatcher.querySelectorAll !== 'function'\n ) {\n return;\n }\n const receiver = event.target;\n const ancestor = receiver.closest(selector);\n if (\n ancestor === receiver &&\n ancestor !== dispatcher &&\n dispatcher.contains(ancestor)\n ) {\n callback.call(receiver, event);\n }\n };\n};\n\nDOMList.prototype.on = function(etype, selector, callback) {\n if ( typeof selector === 'function' ) {\n callback = selector;\n selector = undefined;\n } else {\n callback = makeEventHandler(selector, callback);\n }\n\n for ( const node of this.nodes ) {\n listenerEntries.push(\n new ListenerEntry(node, etype, selector !== undefined, callback)\n );\n }\n return this;\n};\n\n/******************************************************************************/\n\n// TODO: Won't work for delegated handlers. Need to figure\n// what needs to be done.\n\nDOMList.prototype.off = function(evtype, callback) {\n var i = this.nodes.length;\n while ( i-- ) {\n this.nodes[i].removeEventListener(evtype, callback);\n }\n return this;\n};\n\n/******************************************************************************/\n\nDOMList.prototype.trigger = function(etype) {\n var ev = new CustomEvent(etype);\n var i = this.nodes.length;\n while ( i-- ) {\n this.nodes[i].dispatchEvent(ev);\n }\n return this;\n};\n\n/******************************************************************************/\n\nreturn DOMListFactory;\n\n})();\n", "file_path": "src/js/udom.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00032572634518146515, 0.000183792770258151, 0.00016215414507314563, 0.00016999804938677698, 3.1303035939345136e-05]} {"hunk": {"id": 2, "code_window": ["\n", " addProceduralSelectors: function(aa) {\n", " const addedSelectors = [];\n", " let mustCommit = this.domIsWatched;\n", " for ( let i = 0, n = aa.length; i < n; i++ ) {\n", " const raw = aa[i];\n", " const o = JSON.parse(raw);\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" addProceduralSelectors(aa) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 722}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2017-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n// Packaging this file is optional: it is not necessary to package it if the\n// platform is known to not support user stylesheets.\n\n// >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && vAPI.supportsUserStylesheets ) {\n\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.userStylesheet = {\n added: new Set(),\n removed: new Set(),\n apply: function(callback) {\n if ( this.added.size === 0 && this.removed.size === 0 ) { return; }\n vAPI.messaging.send('vapi', {\n what: 'userCSS',\n add: Array.from(this.added),\n remove: Array.from(this.removed)\n }, callback);\n this.added.clear();\n this.removed.clear();\n },\n add: function(cssText, now) {\n if ( cssText === '' ) { return; }\n this.added.add(cssText);\n if ( now ) { this.apply(); }\n },\n remove: function(cssText, now) {\n if ( cssText === '' ) { return; }\n this.removed.add(cssText);\n if ( now ) { this.apply(); }\n }\n};\n\n/******************************************************************************/\n\nvAPI.DOMFilterer = class {\n constructor() {\n this.commitTimer = new vAPI.SafeAnimationFrame(( ) => this.commitNow);\n this.domIsReady = document.readyState !== 'loading';\n this.disabled = false;\n this.listeners = [];\n this.filterset = new Set();\n this.excludedNodeSet = new WeakSet();\n this.addedCSSRules = new Set();\n this.exceptedCSSRules = [];\n this.reOnlySelectors = /\\n\\{[^\\n]+/g;\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/167\n // By the time the DOMContentLoaded is fired, the content script might\n // have been disconnected from the background page. Unclear why this\n // would happen, so far seems to be a Chromium-specific behavior at\n // launch time.\n if ( this.domIsReady !== true ) {\n document.addEventListener('DOMContentLoaded', ( ) => {\n if ( vAPI instanceof Object === false ) { return; }\n this.domIsReady = true;\n this.commit();\n });\n }\n }\n\n // Here we will deal with:\n // - Injecting low priority user styles;\n // - Notifying listeners about changed filterset.\n // https://www.reddit.com/r/uBlockOrigin/comments/9jj0y1/no_longer_blocking_ads/\n // Ensure vAPI is still valid -- it can go away by the time we are\n // called, since the port could be force-disconnected from the main\n // process. Another approach would be to have vAPI.SafeAnimationFrame\n // register a shutdown job: to evaluate. For now I will keep the fix\n // trivial.\n commitNow() {\n this.commitTimer.clear();\n if ( vAPI instanceof Object === false ) { return; }\n const userStylesheet = vAPI.userStylesheet;\n for ( const entry of this.addedCSSRules ) {\n if (\n this.disabled === false &&\n entry.lazy &&\n entry.injected === false\n ) {\n userStylesheet.add(\n entry.selectors + '\\n{' + entry.declarations + '}'\n );\n }\n }\n this.addedCSSRules.clear();\n userStylesheet.apply();\n }\n\n commit(commitNow) {\n if ( commitNow ) {\n this.commitTimer.clear();\n this.commitNow();\n } else {\n this.commitTimer.start();\n }\n }\n\n addCSSRule(selectors, declarations, details) {\n if ( selectors === undefined ) { return; }\n const selectorsStr = Array.isArray(selectors)\n ? selectors.join(',\\n')\n : selectors;\n if ( selectorsStr.length === 0 ) { return; }\n if ( details === undefined ) { details = {}; }\n const entry = {\n selectors: selectorsStr,\n declarations,\n lazy: details.lazy === true,\n injected: details.injected === true\n };\n this.addedCSSRules.add(entry);\n this.filterset.add(entry);\n if (\n this.disabled === false &&\n entry.lazy !== true &&\n entry.injected !== true\n ) {\n vAPI.userStylesheet.add(selectorsStr + '\\n{' + declarations + '}');\n }\n this.commit();\n if ( this.hasListeners() ) {\n this.triggerListeners({\n declarative: [ [ selectorsStr, declarations ] ]\n });\n }\n }\n\n exceptCSSRules(exceptions) {\n if ( exceptions.length === 0 ) { return; }\n this.exceptedCSSRules.push(...exceptions);\n if ( this.hasListeners() ) {\n this.triggerListeners({ exceptions });\n }\n }\n\n addListener(listener) {\n if ( this.listeners.indexOf(listener) !== -1 ) { return; }\n this.listeners.push(listener);\n }\n\n removeListener(listener) {\n const pos = this.listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n this.listeners.splice(pos, 1);\n }\n\n hasListeners() {\n return this.listeners.length !== 0;\n }\n\n triggerListeners(changes) {\n for ( const listener of this.listeners ) {\n listener.onFiltersetChanged(changes);\n }\n }\n\n excludeNode(node) {\n this.excludedNodeSet.add(node);\n this.unhideNode(node);\n }\n\n unexcludeNode(node) {\n this.excludedNodeSet.delete(node);\n }\n\n hideNode(node) {\n if ( this.excludedNodeSet.has(node) ) { return; }\n if ( this.hideNodeAttr === undefined ) { return; }\n node.setAttribute(this.hideNodeAttr, '');\n if ( this.hideNodeStyleSheetInjected === false ) {\n this.hideNodeStyleSheetInjected = true;\n this.addCSSRule(\n `[${this.hideNodeAttr}]`,\n 'display:none!important;'\n );\n }\n }\n\n unhideNode(node) {\n if ( this.hideNodeAttr === undefined ) { return; }\n node.removeAttribute(this.hideNodeAttr);\n }\n\n toggle(state, callback) {\n if ( state === undefined ) { state = this.disabled; }\n if ( state !== this.disabled ) { return; }\n this.disabled = !state;\n const userStylesheet = vAPI.userStylesheet;\n for ( const entry of this.filterset ) {\n const rule = `${entry.selectors}\\n{${entry.declarations}}`;\n if ( this.disabled ) {\n userStylesheet.remove(rule);\n } else {\n userStylesheet.add(rule);\n }\n }\n userStylesheet.apply(callback);\n }\n\n getAllSelectors_(all) {\n const out = {\n declarative: [],\n exceptions: this.exceptedCSSRules,\n };\n for ( const entry of this.filterset ) {\n let selectors = entry.selectors;\n if ( all !== true && this.hideNodeAttr !== undefined ) {\n selectors = selectors\n .replace(`[${this.hideNodeAttr}]`, '')\n .replace(/^,\\n|,\\n$/gm, '');\n if ( selectors === '' ) { continue; }\n }\n out.declarative.push([ selectors, entry.declarations ]);\n }\n return out;\n }\n\n getFilteredElementCount() {\n const details = this.getAllSelectors_(true);\n if ( Array.isArray(details.declarative) === false ) { return 0; }\n const selectors = details.declarative.map(entry => entry[0]);\n if ( selectors.length === 0 ) { return 0; }\n return document.querySelectorAll(selectors.join(',\\n')).length;\n }\n\n getAllSelectors() {\n return this.getAllSelectors_(false);\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n\n\n\n\n\n\n\n\n/*******************************************************************************\n\n DO NOT:\n - Remove the following code\n - Add code beyond the following code\n Reason:\n - https://github.com/gorhill/uBlock/pull/3721\n - uBO never uses the return value from injected content scripts\n\n**/\n\nvoid 0;\n", "file_path": "platform/chromium/vapi-usercss.real.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0032260289881378412, 0.0002914830984082073, 0.00016580731607973576, 0.00017086087609641254, 0.0005571806686930358]} {"hunk": {"id": 2, "code_window": ["\n", " addProceduralSelectors: function(aa) {\n", " const addedSelectors = [];\n", " let mustCommit = this.domIsWatched;\n", " for ( let i = 0, n = aa.length; i < n; i++ ) {\n", " const raw = aa[i];\n", " const o = JSON.parse(raw);\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" addProceduralSelectors(aa) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 722}, "file": "{\n \"addons\": {\n \"uBlock0@raymondhill.net\": {\n \"updates\": [\n {\n \"version\": \"$ext_version\",\n \"browser_specific_settings\": { \"gecko\": { \"strict_min_version\": \"55\" } },\n \"update_info_url\": \"https://github.com/gorhill/uBlock/releases/tag/$tag_version\",\n \"update_link\": \"https://github.com/gorhill/uBlock/releases/download/$tag_version/uBlock0_$tag_version.firefox.signed.xpi\"\n }\n ]\n }\n }\n}\n", "file_path": "dist/firefox/updates.template.json", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017350954294670373, 0.00017227396892849356, 0.0001710383949102834, 0.00017227396892849356, 1.2355740182101727e-06]} {"hunk": {"id": 2, "code_window": ["\n", " addProceduralSelectors: function(aa) {\n", " const addedSelectors = [];\n", " let mustCommit = this.domIsWatched;\n", " for ( let i = 0, n = aa.length; i < n; i++ ) {\n", " const raw = aa[i];\n", " const o = JSON.parse(raw);\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" addProceduralSelectors(aa) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 722}, "file": ";;\n;; uBlock Origin - a browser extension to block requests.\n;; Copyright (C) 2019-present Raymond Hill\n;;\n;; License: pick the one which suits you:\n;; GPL v3 see \n;; APL v2 see \n;;\n;; Home: https://github.com/gorhill/publicsuffixlist.js\n;; File: publicsuffixlist.wat\n;;\n;; Description: WebAssembly implementation for core lookup method in\n;; publicsuffixlist.js\n;;\n;; How to compile:\n;;\n;; wat2wasm publicsuffixlist.wat -o publicsuffixlist.wasm\n;;\n;; The `wat2wasm` tool can be downloaded from an official WebAssembly\n;; project:\n;; https://github.com/WebAssembly/wabt/releases\n\n\n(module\n;;\n;; module start\n;;\n\n(memory (import \"imports\" \"memory\") 1)\n\n;;\n;; Tree encoding in array buffer:\n;;\n;; Node:\n;; + u8: length of char data\n;; + u8: flags => bit 0: is_publicsuffix, bit 1: is_exception\n;; + u16: length of array of children\n;; + u32: char data or offset to char data\n;; + u32: offset to array of children\n;; = 12 bytes\n;;\n;; // i32 / i8\n;; const HOSTNAME_SLOT = 0; // jshint ignore:line\n;; const LABEL_INDICES_SLOT = 256; // -- / 256\n;; const RULES_PTR_SLOT = 100; // 100 / 400\n;; const CHARDATA_PTR_SLOT = 101; // 101 / 404\n;; const EMPTY_STRING = '';\n;; const SELFIE_MAGIC = 2;\n;;\n\n;;\n;; Public functions\n;;\n\n;;\n;; unsigned int getPublicSuffixPos()\n;;\n;; Returns an offset to the start of the public suffix.\n;;\n(func (export \"getPublicSuffixPos\")\n (result i32) ;; result = match index, -1 = miss\n (local $iCharData i32) ;; offset to start of character data\n (local $iNode i32) ;; offset to current node\n (local $iLabel i32) ;; offset to label indices\n (local $cursorPos i32) ;; position of cursor within hostname argument\n (local $labelBeg i32)\n (local $labelLen i32)\n (local $nCandidates i32)\n (local $iCandidates i32)\n (local $iFound i32)\n (local $l i32)\n (local $r i32)\n (local $d i32)\n (local $iCandidate i32)\n (local $iCandidateNode i32)\n (local $candidateLen i32)\n (local $iCandidateChar i32)\n (local $_1 i32)\n (local $_2 i32)\n (local $_3 i32)\n ;;\n ;; const iCharData = buf32[CHARDATA_PTR_SLOT];\n i32.const 404\n i32.load\n set_local $iCharData\n ;; let iNode = pslBuffer32[RULES_PTR_SLOT];\n i32.const 400\n i32.load\n i32.const 2\n i32.shl\n set_local $iNode\n ;; let iLabel = LABEL_INDICES_SLOT;\n i32.const 256\n set_local $iLabel\n ;; let cursorPos = -1;\n i32.const -1\n set_local $cursorPos\n ;; label-lookup loop\n ;; for (;;) {\n block $labelLookupDone loop $labelLookup\n ;; // Extract label indices\n ;; const labelBeg = buf8[iLabel+1];\n ;; const labelLen = buf8[iLabel+0] - labelBeg;\n get_local $iLabel\n i32.load8_u\n get_local $iLabel\n i32.load8_u offset=1\n tee_local $labelBeg\n i32.sub\n set_local $labelLen\n ;; // Match-lookup loop: binary search\n ;; let r = buf32[iNode+0] >>> 16;\n ;; if ( r === 0 ) { break; }\n get_local $iNode\n i32.load16_u offset=2\n tee_local $r\n i32.eqz\n br_if $labelLookupDone\n ;; const iCandidates = buf32[iNode+2];\n get_local $iNode\n i32.load offset=8\n i32.const 2\n i32.shl\n set_local $iCandidates\n ;; let l = 0;\n ;; let iFound = 0;\n i32.const 0\n tee_local $l\n set_local $iFound\n ;; while ( l < r ) {\n block $binarySearchDone loop $binarySearch\n get_local $l\n get_local $r\n i32.ge_u\n br_if $binarySearchDone\n ;; const iCandidate = l + r >>> 1;\n get_local $l\n get_local $r\n i32.add\n i32.const 1\n i32.shr_u\n tee_local $iCandidate\n ;; const iCandidateNode = iCandidates + iCandidate + (iCandidate << 1);\n i32.const 2\n i32.shl\n tee_local $_1\n get_local $_1\n i32.const 1\n i32.shl\n i32.add\n get_local $iCandidates\n i32.add\n tee_local $iCandidateNode\n ;; const candidateLen = buf32[iCandidateNode+0] & 0x000000FF;\n i32.load8_u\n set_local $candidateLen\n ;; let d = labelLen - candidateLen;\n get_local $labelLen\n get_local $candidateLen\n i32.sub\n tee_local $d\n ;; if ( d === 0 ) {\n i32.eqz\n if\n ;; const iCandidateChar = candidateLen <= 4\n get_local $candidateLen\n i32.const 4\n i32.le_u\n if\n ;; ? iCandidateNode + 1 << 2\n get_local $iCandidateNode\n i32.const 4\n i32.add\n set_local $iCandidateChar\n else\n ;; : buf32[CHARDATA_PTR_SLOT] + buf32[iCandidateNode+1];\n get_local $iCharData\n get_local $iCandidateNode\n i32.load offset=4\n i32.add\n set_local $iCandidateChar\n end\n ;; for ( let i = 0; i < labelLen; i++ ) {\n get_local $labelBeg\n tee_local $_1\n get_local $labelLen\n i32.add\n set_local $_3\n get_local $iCandidateChar\n set_local $_2\n block $findDiffDone loop $findDiff\n ;; d = buf8[labelBeg+i] - buf8[iCandidateChar+i];\n ;; if ( d !== 0 ) { break; }\n get_local $_1\n i32.load8_u\n get_local $_2\n i32.load8_u\n i32.sub\n tee_local $d\n br_if $findDiffDone\n get_local $_1\n i32.const 1\n i32.add\n tee_local $_1\n get_local $_3\n i32.eq\n br_if $findDiffDone\n get_local $_2\n i32.const 1\n i32.add\n set_local $_2\n br $findDiff\n ;; }\n end end\n ;; }\n end\n ;; if ( d < 0 ) {\n ;; r = iCandidate;\n get_local $d\n i32.const 0\n i32.lt_s\n if\n get_local $iCandidate\n set_local $r\n br $binarySearch\n end\n ;; } else if ( d > 0 ) {\n ;; l = iCandidate + 1;\n get_local $d\n i32.const 0\n i32.gt_s\n if\n get_local $iCandidate\n i32.const 1\n i32.add\n set_local $l\n br $binarySearch\n end\n ;; } else /* if ( d === 0 ) */ {\n ;; iFound = iCandidateNode;\n ;; break;\n ;; }\n get_local $iCandidateNode\n set_local $iFound\n end end\n ;; }\n ;; // 2. If no rules match, the prevailing rule is \"*\".\n ;; if ( iFound === 0 ) {\n ;; if ( buf8[iCandidates + 1 << 2] !== 0x2A /* '*' */ ) { break; }\n ;; iFound = iCandidates;\n ;; }\n get_local $iFound\n i32.eqz\n if\n get_local $iCandidates\n i32.load8_u offset=4\n i32.const 0x2A\n i32.ne\n br_if $labelLookupDone\n get_local $iCandidates\n set_local $iFound\n end\n ;; iNode = iFound;\n get_local $iFound\n tee_local $iNode\n ;; // 5. If the prevailing rule is a exception rule, modify it by\n ;; // removing the leftmost label.\n ;; if ( (buf32[iNode+0] & 0x00000200) !== 0 ) {\n ;; if ( iLabel > LABEL_INDICES_SLOT ) {\n ;; return iLabel - 2;\n ;; }\n ;; break;\n ;; }\n i32.load8_u offset=1\n tee_local $_1\n i32.const 0x02\n i32.and\n if\n get_local $iLabel\n i32.const 256\n i32.gt_u\n if\n get_local $iLabel\n i32.const -2\n i32.add\n return\n end\n br $labelLookupDone\n end\n ;; if ( (buf32[iNode+0] & 0x00000100) !== 0 ) {\n ;; cursorPos = labelBeg;\n ;; }\n get_local $_1\n i32.const 0x01\n i32.and\n if\n get_local $iLabel\n set_local $cursorPos\n end\n ;; if ( labelBeg === 0 ) { break; }\n get_local $labelBeg\n i32.eqz\n br_if $labelLookupDone\n ;; iLabel += 2;\n get_local $iLabel\n i32.const 2\n i32.add\n set_local $iLabel\n br $labelLookup\n end end\n get_local $cursorPos\n)\n\n;;\n;; module end\n;;\n)\n", "file_path": "src/lib/publicsuffixlist/wasm/publicsuffixlist.wat", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.010084372013807297, 0.0004914210294373333, 0.0001669761404627934, 0.00017460764502175152, 0.0017234401311725378]} {"hunk": {"id": 2, "code_window": ["\n", " addProceduralSelectors: function(aa) {\n", " const addedSelectors = [];\n", " let mustCommit = this.domIsWatched;\n", " for ( let i = 0, n = aa.length; i < n; i++ ) {\n", " const raw = aa[i];\n", " const o = JSON.parse(raw);\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" addProceduralSelectors(aa) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 722}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n/* global publicSuffixList */\n\n'use strict';\n\n/*******************************************************************************\n\nRFC 3986 as reference: http://tools.ietf.org/html/rfc3986#appendix-A\n\nNaming convention from https://en.wikipedia.org/wiki/URI_scheme#Examples\n\n*/\n\n/******************************************************************************/\n\nµBlock.URI = (function() {\n\n/******************************************************************************/\n\nconst punycode = self.punycode;\n\n// Favorite regex tool: http://regex101.com/\n\n// Ref: \n// I removed redundant capture groups: capture less = peform faster. See\n// \n// Performance improvements welcomed.\n// jsperf: \nconst reRFC3986 = /^([^:\\/?#]+:)?(\\/\\/[^\\/?#]*)?([^?#]*)(\\?[^#]*)?(#.*)?/;\n\n// Derived\nconst reSchemeFromURI = /^[^:\\/?#]+:/;\nconst reAuthorityFromURI = /^(?:[^:\\/?#]+:)?(\\/\\/[^\\/?#]+)/;\nconst reOriginFromURI = /^(?:[^:\\/?#]+:)\\/\\/[^\\/?#]+/;\nconst reCommonHostnameFromURL = /^https?:\\/\\/([0-9a-z_][0-9a-z._-]*[0-9a-z])\\//;\nconst rePathFromURI = /^(?:[^:\\/?#]+:)?(?:\\/\\/[^\\/?#]*)?([^?#]*)/;\nconst reMustNormalizeHostname = /[^0-9a-z._-]/;\n\n// These are to parse authority field, not parsed by above official regex\n// IPv6 is seen as an exception: a non-compatible IPv6 is first tried, and\n// if it fails, the IPv6 compatible regex istr used. This helps\n// peformance by avoiding the use of a too complicated regex first.\n\n// https://github.com/gorhill/httpswitchboard/issues/211\n// \"While a hostname may not contain other characters, such as the\n// \"underscore character (_), other DNS names may contain the underscore\"\nconst reHostPortFromAuthority = /^(?:[^@]*@)?([^:]*)(:\\d*)?$/;\nconst reIPv6PortFromAuthority = /^(?:[^@]*@)?(\\[[0-9a-f:]*\\])(:\\d*)?$/i;\n\nconst reHostFromNakedAuthority = /^[0-9a-z._-]+[0-9a-z]$/i;\nconst reHostFromAuthority = /^(?:[^@]*@)?([^:]+)(?::\\d*)?$/;\nconst reIPv6FromAuthority = /^(?:[^@]*@)?(\\[[0-9a-f:]+\\])(?::\\d*)?$/i;\n\n// Coarse (but fast) tests\nconst reValidHostname = /^([a-z\\d]+(-*[a-z\\d]+)*)(\\.[a-z\\d]+(-*[a-z\\d])*)*$/;\nconst reIPAddressNaive = /^\\d+\\.\\d+\\.\\d+\\.\\d+$|^\\[[\\da-zA-Z:]+\\]$/;\n\n/******************************************************************************/\n\nconst reset = function(o) {\n o.scheme = '';\n o.hostname = '';\n o._ipv4 = undefined;\n o._ipv6 = undefined;\n o.port = '';\n o.path = '';\n o.query = '';\n o.fragment = '';\n return o;\n};\n\nconst resetAuthority = function(o) {\n o.hostname = '';\n o._ipv4 = undefined;\n o._ipv6 = undefined;\n o.port = '';\n return o;\n};\n\n/******************************************************************************/\n\n// This will be exported\n\nconst URI = {\n scheme: '',\n authority: '',\n hostname: '',\n _ipv4: undefined,\n _ipv6: undefined,\n port: '',\n domain: undefined,\n path: '',\n query: '',\n fragment: '',\n schemeBit: (1 << 0),\n userBit: (1 << 1),\n passwordBit: (1 << 2),\n hostnameBit: (1 << 3),\n portBit: (1 << 4),\n pathBit: (1 << 5),\n queryBit: (1 << 6),\n fragmentBit: (1 << 7),\n allBits: (0xFFFF)\n};\n\nURI.authorityBit = (URI.userBit | URI.passwordBit | URI.hostnameBit | URI.portBit);\nURI.normalizeBits = (URI.schemeBit | URI.hostnameBit | URI.pathBit | URI.queryBit);\n\n/******************************************************************************/\n\n// See: https://en.wikipedia.org/wiki/URI_scheme#Examples\n// URI = scheme \":\" hier-part [ \"?\" query ] [ \"#\" fragment ]\n//\n// foo://example.com:8042/over/there?name=ferret#nose\n// \\_/ \\______________/\\_________/ \\_________/ \\__/\n// | | | | |\n// scheme authority path query fragment\n// | _____________________|__\n// / \\ / \\\n// urn:example:animal:ferret:nose\n\nURI.set = function(uri) {\n if ( uri === undefined ) {\n return reset(URI);\n }\n let matches = reRFC3986.exec(uri);\n if ( !matches ) {\n return reset(URI);\n }\n this.scheme = matches[1] !== undefined ? matches[1].slice(0, -1) : '';\n this.authority = matches[2] !== undefined ? matches[2].slice(2).toLowerCase() : '';\n this.path = matches[3] !== undefined ? matches[3] : '';\n\n // \n // \"In general, a URI that uses the generic syntax for authority\n // \"with an empty path should be normalized to a path of '/'.\"\n if ( this.authority !== '' && this.path === '' ) {\n this.path = '/';\n }\n this.query = matches[4] !== undefined ? matches[4].slice(1) : '';\n this.fragment = matches[5] !== undefined ? matches[5].slice(1) : '';\n\n // Assume very simple authority, i.e. just a hostname (highest likelihood\n // case for µBlock)\n if ( reHostFromNakedAuthority.test(this.authority) ) {\n this.hostname = this.authority;\n this.port = '';\n return this;\n }\n // Authority contains more than just a hostname\n matches = reHostPortFromAuthority.exec(this.authority);\n if ( !matches ) {\n matches = reIPv6PortFromAuthority.exec(this.authority);\n if ( !matches ) {\n return resetAuthority(URI);\n }\n }\n this.hostname = matches[1] !== undefined ? matches[1] : '';\n // http://en.wikipedia.org/wiki/FQDN\n if ( this.hostname.endsWith('.') ) {\n this.hostname = this.hostname.slice(0, -1);\n }\n this.port = matches[2] !== undefined ? matches[2].slice(1) : '';\n return this;\n};\n\n/******************************************************************************/\n\n// URI = scheme \":\" hier-part [ \"?\" query ] [ \"#\" fragment ]\n//\n// foo://example.com:8042/over/there?name=ferret#nose\n// \\_/ \\______________/\\_________/ \\_________/ \\__/\n// | | | | |\n// scheme authority path query fragment\n// | _____________________|__\n// / \\ / \\\n// urn:example:animal:ferret:nose\n\nURI.assemble = function(bits) {\n if ( bits === undefined ) {\n bits = this.allBits;\n }\n const s = [];\n if ( this.scheme && (bits & this.schemeBit) ) {\n s.push(this.scheme, ':');\n }\n if ( this.hostname && (bits & this.hostnameBit) ) {\n s.push('//', this.hostname);\n }\n if ( this.port && (bits & this.portBit) ) {\n s.push(':', this.port);\n }\n if ( this.path && (bits & this.pathBit) ) {\n s.push(this.path);\n }\n if ( this.query && (bits & this.queryBit) ) {\n s.push('?', this.query);\n }\n if ( this.fragment && (bits & this.fragmentBit) ) {\n s.push('#', this.fragment);\n }\n return s.join('');\n};\n\n/******************************************************************************/\n\nURI.originFromURI = function(uri) {\n const matches = reOriginFromURI.exec(uri);\n return matches !== null ? matches[0].toLowerCase() : '';\n};\n\n/******************************************************************************/\n\nURI.schemeFromURI = function(uri) {\n const matches = reSchemeFromURI.exec(uri);\n if ( !matches ) { return ''; }\n return matches[0].slice(0, -1).toLowerCase();\n};\n\n/******************************************************************************/\n\nURI.authorityFromURI = function(uri) {\n const matches = reAuthorityFromURI.exec(uri);\n if ( !matches ) { return ''; }\n return matches[1].slice(2).toLowerCase();\n};\n\n/******************************************************************************/\n\n// The most used function, so it better be fast.\n\n// https://github.com/gorhill/uBlock/issues/1559\n// See http://en.wikipedia.org/wiki/FQDN\n// https://bugzilla.mozilla.org/show_bug.cgi?id=1360285\n// Revisit punycode dependency when above issue is fixed in Firefox.\n\nURI.hostnameFromURI = function(uri) {\n let matches = reCommonHostnameFromURL.exec(uri);\n if ( matches !== null ) { return matches[1]; }\n matches = reAuthorityFromURI.exec(uri);\n if ( matches === null ) { return ''; }\n const authority = matches[1].slice(2);\n // Assume very simple authority (most common case for µBlock)\n if ( reHostFromNakedAuthority.test(authority) ) {\n return authority.toLowerCase();\n }\n matches = reHostFromAuthority.exec(authority);\n if ( matches === null ) {\n matches = reIPv6FromAuthority.exec(authority);\n if ( matches === null ) { return ''; }\n }\n let hostname = matches[1];\n while ( hostname.endsWith('.') ) {\n hostname = hostname.slice(0, -1);\n }\n if ( reMustNormalizeHostname.test(hostname) ) {\n hostname = punycode.toASCII(hostname.toLowerCase());\n }\n return hostname;\n};\n\n/******************************************************************************/\n\nURI.domainFromHostname = function(hostname) {\n return reIPAddressNaive.test(hostname) ? hostname : psl.getDomain(hostname);\n};\n\nURI.domain = function() {\n return this.domainFromHostname(this.hostname);\n};\n\n// It is expected that there is higher-scoped `publicSuffixList` lingering\n// somewhere. Cache it. See .\nconst psl = publicSuffixList;\n\n/******************************************************************************/\n\nURI.entityFromDomain = function(domain) {\n const pos = domain.indexOf('.');\n return pos !== -1 ? domain.slice(0, pos) + '.*' : '';\n};\n\n/******************************************************************************/\n\nURI.pathFromURI = function(uri) {\n const matches = rePathFromURI.exec(uri);\n return matches !== null ? matches[1] : '';\n};\n\n/******************************************************************************/\n\nURI.domainFromURI = function(uri) {\n if ( !uri ) { return ''; }\n return this.domainFromHostname(this.hostnameFromURI(uri));\n};\n\n/******************************************************************************/\n\nURI.isNetworkURI = function(uri) {\n return reNetworkURI.test(uri);\n};\n\nconst reNetworkURI = /^(?:ftps?|https?|wss?):\\/\\//;\n\n/******************************************************************************/\n\nURI.isNetworkScheme = function(scheme) {\n return reNetworkScheme.test(scheme);\n};\n\nconst reNetworkScheme = /^(?:ftps?|https?|wss?)$/;\n\n/******************************************************************************/\n\n// Normalize the way µBlock expects it\n\nURI.normalizedURI = function() {\n // Will be removed:\n // - port\n // - user id/password\n // - fragment\n return this.assemble(this.normalizeBits);\n};\n\n/******************************************************************************/\n\nURI.rootURL = function() {\n if ( !this.hostname ) { return ''; }\n return this.assemble(this.schemeBit | this.hostnameBit);\n};\n\n/******************************************************************************/\n\nURI.isValidHostname = function(hostname) {\n try {\n return reValidHostname.test(hostname);\n }\n catch (e) {\n }\n return false;\n};\n\n/******************************************************************************/\n\n// Return the parent domain. For IP address, there is no parent domain.\n\nURI.parentHostnameFromHostname = function(hostname) {\n // `locahost` => ``\n // `example.org` => `example.org`\n // `www.example.org` => `example.org`\n // `tomato.www.example.org` => `example.org`\n const domain = this.domainFromHostname(hostname);\n\n // `locahost` === `` => bye\n // `example.org` === `example.org` => bye\n // `www.example.org` !== `example.org` => stay\n // `tomato.www.example.org` !== `example.org` => stay\n if ( domain === '' || domain === hostname ) { return; }\n\n // Parent is hostname minus first label\n return hostname.slice(hostname.indexOf('.') + 1);\n};\n\n/******************************************************************************/\n\n// Return all possible parent hostnames which can be derived from `hostname`,\n// ordered from direct parent up to domain inclusively.\n\nURI.parentHostnamesFromHostname = function(hostname) {\n // TODO: I should create an object which is optimized to receive\n // the list of hostnames by making it reusable (junkyard etc.) and which\n // has its own element counter property in order to avoid memory\n // alloc/dealloc.\n const domain = this.domainFromHostname(hostname);\n if ( domain === '' || domain === hostname ) {\n return [];\n }\n const nodes = [];\n for (;;) {\n const pos = hostname.indexOf('.');\n if ( pos < 0 ) { break; }\n hostname = hostname.slice(pos + 1);\n nodes.push(hostname);\n if ( hostname === domain ) { break; }\n }\n return nodes;\n};\n\n/******************************************************************************/\n\n// Return all possible hostnames which can be derived from `hostname`,\n// ordered from self up to domain inclusively.\n\nURI.allHostnamesFromHostname = function(hostname) {\n const nodes = this.parentHostnamesFromHostname(hostname);\n nodes.unshift(hostname);\n return nodes;\n};\n\n/******************************************************************************/\n\nURI.toString = function() {\n return this.assemble();\n};\n\n/******************************************************************************/\n\n// Export\n\nreturn URI;\n\n/******************************************************************************/\n\n})();\n\n/******************************************************************************/\n\n", "file_path": "src/js/uritools.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.77937912940979, 0.01802230067551136, 0.00016240683908108622, 0.00017105683218687773, 0.11610767245292664]} {"hunk": {"id": 3, "code_window": [" this.domFilterer.triggerListeners({\n", " procedural: addedSelectors\n", " });\n", " }\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 759}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9477527737617493, 0.007219510152935982, 0.0001623083808226511, 0.0001715841208351776, 0.0752784013748169]} {"hunk": {"id": 3, "code_window": [" this.domFilterer.triggerListeners({\n", " procedural: addedSelectors\n", " });\n", " }\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 759}, "file": "Ein effizienter Blocker: Geringer Speicherbedarf und niedrige CPU-Belastung - und dennoch werden Tausende an Filtern mehr angewendet als bei anderen populären Blockern.\n\nEin illustrierter Überblick über seine Effizienz: https://github.com/gorhill/uBlock/wiki/uBlock-vs.-ABP:-efficiency-compared\n\nBenutzung: Der An-/Ausschaltknopf beim Klicken des Erweiterungssymbols dient zum An-/Ausschalten von uBlock auf der aktuellen Webseite. Dies wirkt sich also nur auf die aktuelle Webseite aus und nicht global.\n\n \n\nuBlock ist flexibel, denn es ist mehr als ein „Werbeblocker“: Es verarbeitet auch Filter aus mehreren hosts-Dateien.\n\nStandardmäßig werden folgende Filterlisten geladen und angewandt:\n\n- EasyList\n- Peter Lowe’s Ad server list\n- EasyPrivacy\n- Malware domains\n\nAuf Wunsch können zusätzliche Listen ausgewählt werden:\n\n- Fanboy’s Enhanced Tracking List\n- Dan Pollock’s hosts file\n- hpHosts’s Ad and tracking servers\n- MVPS HOSTS\n- Spam404\n- etc.\n\nNatürlich ist der Speicherbedarf umso höher, desto mehr Filter angewandt werden. Aber selbst mit den zwei zusätzlichen Listen von Fanboy und hpHosts’s Ad and tracking servers ist der Speicherbedarf von uBlock₀ geringer als bei anderen sehr populären Blockern.\n\nBedenke allerdings, dass durch die Wahl zusätzlicher Listen die Wahrscheinlichkeit größer wird, dass bestimmte Webseiten nicht richtig geladen werden - vor allem bei Listen, die normalerweise als hosts-Dateien verwendet werden.\n\n \n\n Wenn du etwas beitragen möchtest, dann denke an die Menschen, die hart dafür arbeiten, die von dir benutzten Filterlisten zu pflegen, und diese für uns alle frei verfügbar gemacht haben.\n\n \n\nFrei.\nOpen-Source-Software unter der General Public License (GPLv3)\nFür Benutzer von Benutzern.\n\nMitwirkende @ Github: https://github.com/gorhill/uBlock/graphs/contributors\nMitwirkende @ Crowdin: https://crowdin.net/project/ublock\n\n \n\n \n\nÄnderungsprotokoll:\nhttps://github.com/gorhill/uBlock/releases\n", "file_path": "dist/description/description-de.txt", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017321811174042523, 0.0001700220600469038, 0.00016753512318246067, 0.0001700553548289463, 1.8909158825408667e-06]} {"hunk": {"id": 3, "code_window": [" this.domFilterer.triggerListeners({\n", " procedural: addedSelectors\n", " });\n", " }\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 759}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2019-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n/* exported STrieContainer */\n\n'use strict';\n\n/*******************************************************************************\n\n A STrieContainer is mostly a large buffer in which distinct but related\n tries are stored. The memory layout of the buffer is as follow:\n\n 0-255: reserved\n 256-259: offset to start of trie data section (=> trie0)\n 260-263: offset to end of trie data section (=> trie1)\n 264-267: offset to start of character data section (=> char0)\n 268-271: offset to end of character data section (=> char1)\n 272: start of trie data section\n\n*/\n\nconst STRIE_PAGE_SIZE = 65536;\n // i32 / i8\nconst STRIE_TRIE0_SLOT = 256 >>> 2; // 64 / 256\nconst STRIE_TRIE1_SLOT = STRIE_TRIE0_SLOT + 1; // 65 / 260\nconst STRIE_CHAR0_SLOT = STRIE_TRIE0_SLOT + 2; // 66 / 264\nconst STRIE_CHAR1_SLOT = STRIE_TRIE0_SLOT + 3; // 67 / 268\nconst STRIE_TRIE0_START = STRIE_TRIE0_SLOT + 4 << 2; // 272\n\n\nconst STrieContainer = class {\n\n constructor(details) {\n if ( details instanceof Object === false ) { details = {}; }\n const len = (details.byteLength || 0) + STRIE_PAGE_SIZE-1 & ~(STRIE_PAGE_SIZE-1);\n this.buf = new Uint8Array(Math.max(len, 131072));\n this.buf32 = new Uint32Array(this.buf.buffer);\n this.buf32[STRIE_TRIE0_SLOT] = STRIE_TRIE0_START;\n this.buf32[STRIE_TRIE1_SLOT] = this.buf32[STRIE_TRIE0_SLOT];\n this.buf32[STRIE_CHAR0_SLOT] = details.char0 || 65536;\n this.buf32[STRIE_CHAR1_SLOT] = this.buf32[STRIE_CHAR0_SLOT];\n }\n\n //--------------------------------------------------------------------------\n // Public methods\n //--------------------------------------------------------------------------\n\n reset() {\n this.buf32[STRIE_TRIE1_SLOT] = this.buf32[STRIE_TRIE0_SLOT];\n this.buf32[STRIE_CHAR1_SLOT] = this.buf32[STRIE_CHAR0_SLOT];\n }\n\n matches(iroot, a, al) {\n const ar = a.length;\n const char0 = this.buf32[STRIE_CHAR0_SLOT];\n let icell = iroot;\n for (;;) {\n let c = a.charCodeAt(al);\n al += 1;\n let v, bl;\n // find first segment with a first-character match\n for (;;) {\n v = this.buf32[icell+2];\n bl = char0 + (v & 0x00FFFFFF);\n if ( this.buf[bl] === c ) { break; }\n icell = this.buf32[icell+0];\n if ( icell === 0 ) { return -1; }\n }\n // all characters in segment must match\n let n = v >>> 24;\n if ( n > 1 ) {\n n -= 1;\n if ( (al + n) > ar ) { return -1; }\n bl += 1;\n const br = bl + n;\n do {\n if ( a.charCodeAt(al) !== this.buf[bl] ) { return -1; }\n al += 1;\n bl += 1;\n } while ( bl < br );\n }\n // next segment\n icell = this.buf32[icell+1];\n if ( icell === 0 || this.buf32[icell+2] === 0 ) { return al; }\n if ( al === ar ) { return -1; }\n }\n }\n\n createOne(args) {\n if ( Array.isArray(args) ) {\n return new this.STrieRef(this, args[0], args[1]);\n }\n // grow buffer if needed\n if ( (this.buf32[STRIE_CHAR0_SLOT] - this.buf32[STRIE_TRIE1_SLOT]) < 12 ) {\n this.growBuf(12, 0);\n }\n const iroot = this.buf32[STRIE_TRIE1_SLOT] >>> 2;\n this.buf32[STRIE_TRIE1_SLOT] += 12;\n this.buf32[iroot+0] = 0;\n this.buf32[iroot+1] = 0;\n this.buf32[iroot+2] = 0;\n return new this.STrieRef(this, iroot, 0);\n }\n\n compileOne(trieRef) {\n return [ trieRef.iroot, trieRef.size ];\n }\n\n add(iroot, s) {\n const lschar = s.length;\n if ( lschar === 0 ) { return 0; }\n let ischar = 0;\n let icell = iroot;\n // special case: first node in trie\n if ( this.buf32[icell+2] === 0 ) {\n this.buf32[icell+2] = this.addSegment(s.slice(ischar));\n return 1;\n }\n // grow buffer if needed\n if (\n (this.buf32[STRIE_CHAR0_SLOT] - this.buf32[STRIE_TRIE1_SLOT]) < 24 ||\n (this.buf.length - this.buf32[STRIE_CHAR1_SLOT]) < 256\n ) {\n this.growBuf(24, 256);\n }\n //\n const char0 = this.buf32[STRIE_CHAR0_SLOT];\n let inext;\n // find a matching cell: move down\n for (;;) {\n const vseg = this.buf32[icell+2];\n // skip boundary cells\n if ( vseg === 0 ) {\n icell = this.buf32[icell+1];\n continue;\n }\n let isegchar0 = char0 + (vseg & 0x00FFFFFF);\n // if first character is no match, move to next descendant\n if ( this.buf[isegchar0] !== s.charCodeAt(ischar) ) {\n inext = this.buf32[icell+0];\n if ( inext === 0 ) {\n this.buf32[icell+0] = this.addCell(0, 0, this.addSegment(s.slice(ischar)));\n return 1;\n }\n icell = inext;\n continue;\n }\n // 1st character was tested\n let isegchar = 1;\n ischar += 1;\n // find 1st mismatch in rest of segment\n const lsegchar = vseg >>> 24;\n if ( lsegchar !== 1 ) {\n for (;;) {\n if ( isegchar === lsegchar ) { break; }\n if ( ischar === lschar ) { break; }\n if ( this.buf[isegchar0+isegchar] !== s.charCodeAt(ischar) ) { break; }\n isegchar += 1;\n ischar += 1;\n }\n }\n // all segment characters matched\n if ( isegchar === lsegchar ) {\n inext = this.buf32[icell+1];\n // needle remainder: no\n if ( ischar === lschar ) {\n // boundary cell already present\n if ( inext === 0 || this.buf32[inext+2] === 0 ) { return 0; }\n // need boundary cell\n this.buf32[icell+1] = this.addCell(0, inext, 0);\n }\n // needle remainder: yes\n else {\n if ( inext !== 0 ) {\n icell = inext;\n continue;\n }\n // boundary cell + needle remainder\n inext = this.addCell(0, 0, 0);\n this.buf32[icell+1] = inext;\n this.buf32[inext+1] = this.addCell(0, 0, this.addSegment(s.slice(ischar)));\n }\n }\n // some segment characters matched\n else {\n // split current cell\n isegchar0 -= char0;\n this.buf32[icell+2] = isegchar << 24 | isegchar0;\n inext = this.addCell(\n 0,\n this.buf32[icell+1],\n lsegchar - isegchar << 24 | isegchar0 + isegchar\n );\n this.buf32[icell+1] = inext;\n // needle remainder: no = need boundary cell\n if ( ischar === lschar ) {\n this.buf32[icell+1] = this.addCell(0, inext, 0);\n }\n // needle remainder: yes = need new cell for remaining characters\n else {\n this.buf32[inext+0] = this.addCell(0, 0, this.addSegment(s.slice(ischar)));\n }\n }\n return 1;\n }\n }\n\n optimize() {\n this.shrinkBuf();\n return {\n byteLength: this.buf.byteLength,\n char0: this.buf32[STRIE_CHAR0_SLOT],\n };\n }\n\n serialize(encoder) {\n if ( encoder instanceof Object ) {\n return encoder.encode(\n this.buf32.buffer,\n this.buf32[STRIE_CHAR1_SLOT]\n );\n }\n return Array.from(\n new Uint32Array(\n this.buf32.buffer,\n 0,\n this.buf32[STRIE_CHAR1_SLOT] + 3 >>> 2\n )\n );\n }\n\n unserialize(selfie, decoder) {\n const shouldDecode = typeof selfie === 'string';\n let byteLength = shouldDecode\n ? decoder.decodeSize(selfie)\n : selfie.length << 2;\n if ( byteLength === 0 ) { return false; }\n byteLength = byteLength + STRIE_PAGE_SIZE-1 & ~(STRIE_PAGE_SIZE-1);\n if ( byteLength > this.buf.length ) {\n this.buf = new Uint8Array(byteLength);\n this.buf32 = new Uint32Array(this.buf.buffer);\n }\n if ( shouldDecode ) {\n decoder.decode(selfie, this.buf.buffer);\n } else {\n this.buf32.set(selfie);\n }\n return true;\n }\n\n //--------------------------------------------------------------------------\n // Private methods\n //--------------------------------------------------------------------------\n\n addCell(idown, iright, v) {\n let icell = this.buf32[STRIE_TRIE1_SLOT];\n this.buf32[STRIE_TRIE1_SLOT] = icell + 12;\n icell >>>= 2;\n this.buf32[icell+0] = idown;\n this.buf32[icell+1] = iright;\n this.buf32[icell+2] = v;\n return icell;\n }\n\n addSegment(segment) {\n const lsegchar = segment.length;\n if ( lsegchar === 0 ) { return 0; }\n let char1 = this.buf32[STRIE_CHAR1_SLOT];\n const isegchar = char1 - this.buf32[STRIE_CHAR0_SLOT];\n let i = 0;\n do {\n this.buf[char1++] = segment.charCodeAt(i++);\n } while ( i !== lsegchar );\n this.buf32[STRIE_CHAR1_SLOT] = char1;\n return (lsegchar << 24) | isegchar;\n }\n\n growBuf(trieGrow, charGrow) {\n const char0 = Math.max(\n (this.buf32[STRIE_TRIE1_SLOT] + trieGrow + STRIE_PAGE_SIZE-1) & ~(STRIE_PAGE_SIZE-1),\n this.buf32[STRIE_CHAR0_SLOT]\n );\n const char1 = char0 + this.buf32[STRIE_CHAR1_SLOT] - this.buf32[STRIE_CHAR0_SLOT];\n const bufLen = Math.max(\n (char1 + charGrow + STRIE_PAGE_SIZE-1) & ~(STRIE_PAGE_SIZE-1),\n this.buf.length\n );\n this.resizeBuf(bufLen, char0);\n }\n\n shrinkBuf() {\n const char0 = this.buf32[STRIE_TRIE1_SLOT] + 24;\n const char1 = char0 + this.buf32[STRIE_CHAR1_SLOT] - this.buf32[STRIE_CHAR0_SLOT];\n const bufLen = char1 + 256;\n this.resizeBuf(bufLen, char0);\n }\n\n resizeBuf(bufLen, char0) {\n bufLen = bufLen + STRIE_PAGE_SIZE-1 & ~(STRIE_PAGE_SIZE-1);\n if (\n bufLen === this.buf.length &&\n char0 === this.buf32[STRIE_CHAR0_SLOT]\n ) {\n return;\n }\n const charDataLen = this.buf32[STRIE_CHAR1_SLOT] - this.buf32[STRIE_CHAR0_SLOT];\n if ( bufLen !== this.buf.length ) {\n const newBuf = new Uint8Array(bufLen);\n newBuf.set(\n new Uint8Array(\n this.buf.buffer,\n 0,\n this.buf32[STRIE_TRIE1_SLOT]\n ),\n 0\n );\n newBuf.set(\n new Uint8Array(\n this.buf.buffer,\n this.buf32[STRIE_CHAR0_SLOT],\n charDataLen\n ),\n char0\n );\n this.buf = newBuf;\n this.buf32 = new Uint32Array(this.buf.buffer);\n this.buf32[STRIE_CHAR0_SLOT] = char0;\n this.buf32[STRIE_CHAR1_SLOT] = char0 + charDataLen;\n }\n if ( char0 !== this.buf32[STRIE_CHAR0_SLOT] ) {\n this.buf.set(\n new Uint8Array(\n this.buf.buffer,\n this.buf32[STRIE_CHAR0_SLOT],\n charDataLen\n ),\n char0\n );\n this.buf32[STRIE_CHAR0_SLOT] = char0;\n this.buf32[STRIE_CHAR1_SLOT] = char0 + charDataLen;\n }\n }\n};\n\n/*******************************************************************************\n\n Class to hold reference to a specific trie\n\n*/\n\nSTrieContainer.prototype.STrieRef = class {\n constructor(container, iroot, size) {\n this.container = container;\n this.iroot = iroot;\n this.size = size;\n }\n\n add(pattern) {\n if ( this.container.add(this.iroot, pattern) === 1 ) {\n this.size += 1;\n return true;\n }\n return false;\n }\n\n matches(a, al) {\n return this.container.matches(this.iroot, a, al);\n }\n\n dump() {\n for ( const s of this ) {\n console.log(s);\n }\n }\n\n [Symbol.iterator]() {\n return {\n value: undefined,\n done: false,\n next: function() {\n if ( this.icell === 0 ) {\n if ( this.forks.length === 0 ) {\n this.value = undefined;\n this.done = true;\n return this;\n }\n this.charPtr = this.forks.pop();\n this.icell = this.forks.pop();\n }\n for (;;) {\n const idown = this.container.buf32[this.icell+0];\n if ( idown !== 0 ) {\n this.forks.push(idown, this.charPtr);\n }\n const v = this.container.buf32[this.icell+2];\n let i0 = this.container.buf32[STRIE_CHAR0_SLOT] + (v & 0x00FFFFFF);\n const i1 = i0 + (v >>> 24);\n while ( i0 < i1 ) {\n this.charBuf[this.charPtr] = this.container.buf[i0];\n this.charPtr += 1;\n i0 += 1;\n }\n this.icell = this.container.buf32[this.icell+1];\n if ( this.icell === 0 ) {\n return this.toPattern();\n }\n if ( this.container.buf32[this.icell+2] === 0 ) {\n this.icell = this.container.buf32[this.icell+1];\n return this.toPattern();\n }\n }\n },\n toPattern: function() {\n this.value = this.textDecoder.decode(\n new Uint8Array(this.charBuf.buffer, 0, this.charPtr)\n );\n return this;\n },\n container: this.container,\n icell: this.iroot,\n charBuf: new Uint8Array(256),\n charPtr: 0,\n forks: [],\n textDecoder: new TextDecoder()\n };\n }\n};\n", "file_path": "src/js/strie.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001759957813192159, 0.00016983399109449238, 0.00016208490706048906, 0.00016991466691251844, 2.8141998882347252e-06]} {"hunk": {"id": 3, "code_window": [" this.domFilterer.triggerListeners({\n", " procedural: addedSelectors\n", " });\n", " }\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 759}, "file": "@font-face {\n font-family: 'FontAwesome';\n font-weight: normal;\n font-style: normal;\n src: url('fonts/fontawesome-webfont.ttf') format('truetype');\n }\n.fa {\n display: inline-block;\n font-family: FontAwesome;\n font-style: normal;\n font-weight: normal;\n line-height: 1;\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n }\nbody {\n background-color: white;\n color: black;\n font: 14px sans-serif;\n }\ncode {\n background-color: #eee;\n padding: 0 0.25em;\n }\ntextarea {\n font-size: 90%;\n }\n/* I designed the button with: http://charliepark.org/bootstrap_buttons/ */\nbutton.custom {\n padding: 0.6em 1em;\n border: 1px solid transparent;\n border-color: #ccc #ccc #bbb #bbb;\n border-radius: 3px;\n background-color: hsl(216, 0%, 75%);\n background-image: linear-gradient(#f2f2f2, #dddddd);\n background-repeat: repeat-x;\n color: #000;\n opacity: 0.8;\n }\nbutton.custom:hover {\n opacity: 1.0;\n }\nbutton.custom.important {\n border-color: #ffcc7f #ffcc7f hsl(36, 100%, 73%);\n background-color: hsl(36, 100%, 75%);\n background-image: linear-gradient(#ffdca8, #ffcc7f);\n }\nbutton.custom.disabled,\nbutton.custom[disabled],\nbutton.custom.important.disabled,\nbutton.custom.important[disabled] {\n border-color: #ddd #ddd hsl(36, 0%, 85%);\n background-color: hsl(36, 0%, 72%);\n background-image: linear-gradient(#f2f2f2, #dddddd);\n color: #666;\n opacity: 0.6;\n pointer-events: none;\n }\nbutton.custom.iconifiable > .fa {\n padding-right: 0.5em;\n }\nbody[dir=\"rtl\"] button.custom.iconifiable > .fa {\n padding-left: 0.5em;\n }\n.hidden {\n display: none;\n height: 0;\n visibility: hidden;\n width: 0;\n }\n\n@media (max-width: 640px) {\n button.custom.iconifiable > .fa {\n font-size: 150%;\n padding: 0;\n }\n button.custom.iconifiable > [data-i18n] {\n display: none;\n }\n }\n\n.ubo-icon {\n align-items: center;\n background-color: transparent;\n border: 0;\n display: inline-flex;\n justify-content: center;\n margin: 0;\n padding: 0.1em;\n position: relative;\n }\n.ubo-icon > * {\n pointer-events: none;\n }\n.ubo-icon.disabled,\n.disabled > .ubo-icon,\n.ubo-icon[disabled],\n[disabled] > .ubo-icon {\n color: #000;\n fill: #000;\n opacity: 0.25;\n stroke: #888;\n pointer-events: none;\n }\n.ubo-icon > svg {\n height: 1em;\n width: 1em;\n }\n", "file_path": "src/css/common.css", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017691271204967052, 0.0001745041663525626, 0.0001714454556349665, 0.00017538883548695594, 1.9768708625633735e-06]} {"hunk": {"id": 4, "code_window": ["\n", " commitNow: function() {\n", " if ( this.selectors.size === 0 || this.domIsReady === false ) {\n", " return;\n", " }\n", "\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" commitNow() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 761}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9935634136199951, 0.024908116087317467, 0.00016151067393366247, 0.00017086771549656987, 0.15014731884002686]} {"hunk": {"id": 4, "code_window": ["\n", " commitNow: function() {\n", " if ( this.selectors.size === 0 || this.domIsReady === false ) {\n", " return;\n", " }\n", "\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" commitNow() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 761}, "file": "#!/usr/bin/env python3\n\nimport datetime\nimport json\nimport jwt\nimport os\nimport re\nimport requests\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport time\nimport zipfile\n\nfrom distutils.version import StrictVersion\nfrom string import Template\n\n# - Download target (raw) uBlock0.chromium.zip from GitHub\n# - This is referred to as \"raw\" package\n# - This will fail if not a dev build\n# - Upload uBlock0.chromium.zip to Chrome store\n# - Publish uBlock0.chromium.zip to Chrome store\n\n# Find path to project root\nprojdir = os.path.split(os.path.abspath(__file__))[0]\nwhile not os.path.isdir(os.path.join(projdir, '.git')):\n projdir = os.path.normpath(os.path.join(projdir, '..'))\n\n# We need a version string to work with\nif len(sys.argv) >= 2 and sys.argv[1]:\n version = sys.argv[1]\nelse:\n version = input('Github release version: ')\nversion.strip()\nif not re.search('^\\d+\\.\\d+\\.\\d+(b|rc)\\d+$', version):\n print('Error: Invalid version string.')\n exit(1)\n\ncs_extension_id = 'cgbcahbpdhpcegmbfconppldiemgcoii'\ntmpdir = tempfile.TemporaryDirectory()\nraw_zip_filename = 'uBlock0_' + version + '.chromium.zip'\nraw_zip_filepath = os.path.join(tmpdir.name, raw_zip_filename)\ngithub_owner = 'gorhill'\ngithub_repo = 'uBlock'\n\n# Load/save auth secrets\n# The build directory is excluded from git\nubo_secrets = dict()\nubo_secrets_filename = os.path.join(projdir, 'dist', 'build', 'ubo_secrets')\nif os.path.isfile(ubo_secrets_filename):\n with open(ubo_secrets_filename) as f:\n ubo_secrets = json.load(f)\n\ndef input_secret(prompt, token):\n if token in ubo_secrets:\n prompt += ' ✔'\n prompt += ': '\n value = input(prompt).strip()\n if len(value) == 0:\n if token not in ubo_secrets:\n print('Token error:', token)\n exit(1)\n value = ubo_secrets[token]\n elif token not in ubo_secrets or value != ubo_secrets[token]:\n ubo_secrets[token] = value\n exists = os.path.isfile(ubo_secrets_filename)\n with open(ubo_secrets_filename, 'w') as f:\n json.dump(ubo_secrets, f, indent=2)\n if not exists:\n os.chmod(ubo_secrets_filename, 0o600)\n return value\n\n\n# GitHub API token\ngithub_token = input_secret('Github token', 'github_token')\ngithub_auth = 'token ' + github_token\n\n#\n# Get metadata from GitHub about the release\n#\n\n# https://developer.github.com/v3/repos/releases/#get-a-single-release\nprint('Downloading release info from GitHub...')\nrelease_info_url = 'https://api.github.com/repos/{0}/{1}/releases/tags/{2}'.format(github_owner, github_repo, version)\nheaders = { 'Authorization': github_auth, }\nresponse = requests.get(release_info_url, headers=headers)\nif response.status_code != 200:\n print('Error: Release not found: {0}'.format(response.status_code))\n exit(1)\nrelease_info = response.json()\n\n#\n# Extract URL to raw package from metadata\n#\n\n# Find url for uBlock0.chromium.zip\nraw_zip_url = ''\nfor asset in release_info['assets']:\n if asset['name'] == raw_zip_filename:\n raw_zip_url = asset['url']\nif len(raw_zip_url) == 0:\n print('Error: Release asset URL not found')\n exit(1)\n\n#\n# Download raw package from GitHub\n#\n\n# https://developer.github.com/v3/repos/releases/#get-a-single-release-asset\nprint('Downloading raw zip package from GitHub...')\nheaders = {\n 'Authorization': github_auth,\n 'Accept': 'application/octet-stream',\n}\nresponse = requests.get(raw_zip_url, headers=headers)\n# Redirections are transparently handled:\n# http://docs.python-requests.org/en/master/user/quickstart/#redirection-and-history\nif response.status_code != 200:\n print('Error: Downloading raw package failed -- server error {0}'.format(response.status_code))\n exit(1)\nwith open(raw_zip_filepath, 'wb') as f:\n f.write(response.content)\nprint('Downloaded raw package saved as {0}'.format(raw_zip_filepath))\n\n#\n# Upload to Chrome store\n#\n\n# Auth tokens\ncs_id = input_secret('Chrome store id', 'cs_id')\ncs_secret = input_secret('Chrome store secret', 'cs_secret')\ncs_refresh = input_secret('Chrome store refresh token', 'cs_refresh')\n\nprint('Uploading to Chrome store...')\nwith open(raw_zip_filepath, 'rb') as f:\n print('Generating access token...')\n auth_url = 'https://accounts.google.com/o/oauth2/token'\n auth_payload = {\n 'client_id': cs_id,\n 'client_secret': cs_secret,\n 'grant_type': 'refresh_token',\n 'refresh_token': cs_refresh,\n }\n auth_response = requests.post(auth_url, data=auth_payload)\n if auth_response.status_code != 200:\n print('Error: Auth failed -- server error {0}'.format(auth_response.status_code))\n print(auth_response.text)\n exit(1)\n response_dict = auth_response.json()\n if 'access_token' not in response_dict:\n print('Error: Auth failed -- no access token')\n exit(1)\n # Prepare access token\n cs_auth = 'Bearer ' + response_dict['access_token']\n headers = {\n 'Authorization': cs_auth,\n 'x-goog-api-version': '2',\n }\n # Upload\n print('Uploading package...')\n upload_url = 'https://www.googleapis.com/upload/chromewebstore/v1.1/items/{0}'.format(cs_extension_id)\n upload_response = requests.put(upload_url, headers=headers, data=f)\n f.close()\n if upload_response.status_code != 200:\n print('Upload failed -- server error {0}'.format(upload_response.status_code))\n print(upload_response.text)\n exit(1)\n response_dict = upload_response.json();\n if 'uploadState' not in response_dict or response_dict['uploadState'] != 'SUCCESS':\n print('Upload failed -- server error {0}'.format(response_dict['uploadState']))\n exit(1)\n print('Upload succeeded.')\n # Publish\n print('Publishing package...')\n publish_url = 'https://www.googleapis.com/chromewebstore/v1.1/items/{0}/publish'.format(cs_extension_id)\n headers = {\n 'Authorization': cs_auth,\n 'x-goog-api-version': '2',\n 'Content-Length': '0',\n }\n publish_response = requests.post(publish_url, headers=headers)\n if publish_response.status_code != 200:\n print('Error: Chrome store publishing failed -- server error {0}'.format(publish_response.status_code))\n exit(1)\n response_dict = publish_response.json();\n if 'status' not in response_dict or response_dict['status'][0] != 'OK':\n print('Publishing failed -- server error {0}'.format(response_dict['status']))\n exit(1)\n print('Publishing succeeded.')\n\nprint('All done.')\n", "file_path": "dist/chromium/publish-beta.py", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001761112653184682, 0.00017102535639423877, 0.00016508637054357678, 0.00017115307855419815, 2.8572039809660055e-06]} {"hunk": {"id": 4, "code_window": ["\n", " commitNow: function() {\n", " if ( this.selectors.size === 0 || this.domIsReady === false ) {\n", " return;\n", " }\n", "\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" commitNow() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 761}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2017-2018 Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n// Packaging this file is optional: it is not necessary to package it if the\n// platform is known to support user stylesheets.\n\n// >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && vAPI.userStylesheet === undefined ) {\n\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.userStylesheet = {\n style: null,\n styleFixCount: 0,\n css: new Map(),\n disabled: false,\n apply: function() {\n },\n inject: function() {\n this.style = document.createElement('style');\n this.style.disabled = this.disabled;\n const parent = document.head || document.documentElement;\n if ( parent === null ) { return; }\n parent.appendChild(this.style);\n const observer = new MutationObserver(function() {\n if ( this.style === null ) { return; }\n if ( this.style.sheet !== null ) { return; }\n this.styleFixCount += 1;\n if ( this.styleFixCount < 32 ) {\n parent.appendChild(this.style);\n } else {\n observer.disconnect();\n }\n }.bind(this));\n observer.observe(parent, { childList: true });\n },\n add: function(cssText) {\n if ( cssText === '' || this.css.has(cssText) ) { return; }\n if ( this.style === null ) { this.inject(); }\n const sheet = this.style.sheet;\n if ( !sheet ) { return; }\n const i = sheet.cssRules.length;\n sheet.insertRule(cssText, i);\n this.css.set(cssText, sheet.cssRules[i]);\n },\n remove: function(cssText) {\n if ( cssText === '' ) { return; }\n const cssRule = this.css.get(cssText);\n if ( cssRule === undefined ) { return; }\n this.css.delete(cssText);\n if ( this.style === null ) { return; }\n const sheet = this.style.sheet;\n if ( !sheet ) { return; }\n const rules = sheet.cssRules;\n let i = rules.length;\n while ( i-- ) {\n if ( rules[i] !== cssRule ) { continue; }\n sheet.deleteRule(i);\n break;\n }\n if ( rules.length !== 0 ) { return; }\n const style = this.style;\n this.style = null;\n const parent = style.parentNode;\n if ( parent !== null ) {\n parent.removeChild(style);\n }\n },\n toggle: function(state) {\n if ( state === undefined ) { state = this.disabled; }\n if ( state !== this.disabled ) { return; }\n this.disabled = !state;\n if ( this.style !== null ) {\n this.style.disabled = this.disabled;\n }\n }\n};\n\n/******************************************************************************/\n\nvAPI.DOMFilterer = class {\n constructor() {\n this.commitTimer = new vAPI.SafeAnimationFrame(this.commitNow.bind(this));\n this.domIsReady = document.readyState !== 'loading';\n this.listeners = [];\n this.excludedNodeSet = new WeakSet();\n this.addedNodes = new Set();\n this.removedNodes = false;\n\n this.specificSimpleHide = new Set();\n this.specificSimpleHideAggregated = undefined;\n this.addedSpecificSimpleHide = [];\n this.specificComplexHide = new Set();\n this.specificComplexHideAggregated = undefined;\n this.addedSpecificComplexHide = [];\n this.specificOthers = [];\n this.genericSimpleHide = new Set();\n this.genericComplexHide = new Set();\n this.exceptedCSSRules = [];\n\n this.hideNodeExpando = undefined;\n this.hideNodeBatchProcessTimer = undefined;\n this.hiddenNodeObserver = undefined;\n this.hiddenNodesetToProcess = new Set();\n this.hiddenNodeset = new WeakSet();\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n\n // https://www.w3.org/community/webed/wiki/CSS/Selectors#Combinators\n this.reCSSCombinators = /[ >+~]/;\n }\n\n commitNow() {\n this.commitTimer.clear();\n\n if ( this.domIsReady !== true || vAPI.userStylesheet.disabled ) {\n return;\n }\n\n // Filterset changed.\n\n if ( this.addedSpecificSimpleHide.length !== 0 ) {\n //console.time('specific simple filterset changed');\n //console.log('added %d specific simple selectors', this.addedSpecificSimpleHide.length);\n const nodes = document.querySelectorAll(this.addedSpecificSimpleHide.join(','));\n for ( const node of nodes ) {\n this.hideNode(node);\n }\n this.addedSpecificSimpleHide = [];\n this.specificSimpleHideAggregated = undefined;\n //console.timeEnd('specific simple filterset changed');\n }\n\n if ( this.addedSpecificComplexHide.length !== 0 ) {\n //console.time('specific complex filterset changed');\n //console.log('added %d specific complex selectors', this.addedSpecificComplexHide.length);\n const nodes = document.querySelectorAll(this.addedSpecificComplexHide.join(','));\n for ( const node of nodes ) {\n this.hideNode(node);\n }\n this.addedSpecificComplexHide = [];\n this.specificComplexHideAggregated = undefined;\n //console.timeEnd('specific complex filterset changed');\n }\n\n // DOM layout changed.\n\n const domNodesAdded = this.addedNodes.size !== 0;\n const domLayoutChanged = domNodesAdded || this.removedNodes;\n\n if ( domNodesAdded === false || domLayoutChanged === false ) {\n return;\n }\n\n //console.log('%d nodes added', this.addedNodes.size);\n\n if ( this.specificSimpleHide.size !== 0 && domNodesAdded ) {\n //console.time('dom layout changed/specific simple selectors');\n if ( this.specificSimpleHideAggregated === undefined ) {\n this.specificSimpleHideAggregated =\n Array.from(this.specificSimpleHide).join(',\\n');\n }\n for ( const node of this.addedNodes ) {\n if ( node[vAPI.matchesProp](this.specificSimpleHideAggregated) ) {\n this.hideNode(node);\n }\n const nodes = node.querySelectorAll(this.specificSimpleHideAggregated);\n for ( const node of nodes ) {\n this.hideNode(node);\n }\n }\n //console.timeEnd('dom layout changed/specific simple selectors');\n }\n\n if ( this.specificComplexHide.size !== 0 && domLayoutChanged ) {\n //console.time('dom layout changed/specific complex selectors');\n if ( this.specificComplexHideAggregated === undefined ) {\n this.specificComplexHideAggregated =\n Array.from(this.specificComplexHide).join(',\\n');\n }\n const nodes = document.querySelectorAll(this.specificComplexHideAggregated);\n for ( const node of nodes ) {\n this.hideNode(node);\n }\n //console.timeEnd('dom layout changed/specific complex selectors');\n }\n\n this.addedNodes.clear();\n this.removedNodes = false;\n }\n\n commit(now) {\n if ( now ) {\n this.commitTimer.clear();\n this.commitNow();\n } else {\n this.commitTimer.start();\n }\n }\n\n addCSSRule(selectors, declarations, details) {\n if ( selectors === undefined ) { return; }\n\n if ( details === undefined ) { details = {}; }\n\n const selectorsStr = Array.isArray(selectors) ?\n selectors.join(',\\n') :\n selectors;\n if ( selectorsStr.length === 0 ) { return; }\n\n vAPI.userStylesheet.add(selectorsStr + '\\n{' + declarations + '}');\n this.commit();\n if ( this.hasListeners() ) {\n this.triggerListeners({\n declarative: [ [ selectorsStr, declarations ] ]\n });\n }\n\n if ( declarations !== 'display:none!important;' ) {\n this.specificOthers.push({\n selectors: selectorsStr,\n declarations: declarations\n });\n return;\n }\n\n // Do not strongly enforce internal CSS rules.\n if ( details.internal ) { return; }\n\n const isGeneric= details.lazy === true;\n const isSimple = details.type === 'simple';\n const isComplex = details.type === 'complex';\n\n if ( isGeneric ) {\n if ( isSimple ) {\n this.genericSimpleHide.add(selectorsStr);\n return;\n }\n if ( isComplex ) {\n this.genericComplexHide.add(selectorsStr);\n return;\n }\n }\n\n const selectorsArr = Array.isArray(selectors) ?\n selectors :\n selectors.split(',\\n');\n\n if ( isGeneric ) {\n for ( const selector of selectorsArr ) {\n if ( this.reCSSCombinators.test(selector) ) {\n this.genericComplexHide.add(selector);\n } else {\n this.genericSimpleHide.add(selector);\n }\n }\n return;\n }\n\n // Specific cosmetic filters.\n for ( const selector of selectorsArr ) {\n if (\n isComplex ||\n isSimple === false && this.reCSSCombinators.test(selector)\n ) {\n if ( this.specificComplexHide.has(selector) === false ) {\n this.specificComplexHide.add(selector);\n this.addedSpecificComplexHide.push(selector);\n }\n } else if ( this.specificSimpleHide.has(selector) === false ) {\n this.specificSimpleHide.add(selector);\n this.addedSpecificSimpleHide.push(selector);\n }\n }\n }\n\n exceptCSSRules(exceptions) {\n if ( exceptions.length === 0 ) { return; }\n this.exceptedCSSRules.push(...exceptions);\n if ( this.hasListeners() ) {\n this.triggerListeners({ exceptions });\n }\n }\n\n onDOMCreated() {\n this.domIsReady = true;\n this.addedNodes.clear();\n this.removedNodes = false;\n this.commit();\n }\n\n onDOMChanged(addedNodes, removedNodes) {\n for ( const node of addedNodes ) {\n this.addedNodes.add(node);\n }\n this.removedNodes = this.removedNodes || removedNodes;\n this.commit();\n }\n\n addListener(listener) {\n if ( this.listeners.indexOf(listener) !== -1 ) { return; }\n this.listeners.push(listener);\n }\n\n removeListener(listener) {\n const pos = this.listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n this.listeners.splice(pos, 1);\n }\n\n hasListeners() {\n return this.listeners.length !== 0;\n }\n\n triggerListeners(changes) {\n for ( const listener of this.listeners ) {\n listener.onFiltersetChanged(changes);\n }\n }\n\n // https://jsperf.com/clientheight-and-clientwidth-vs-getcomputedstyle\n // Avoid getComputedStyle(), detecting whether a node is visible can be\n // achieved with clientWidth/clientHeight.\n // https://gist.github.com/paulirish/5d52fb081b3570c81e3a\n // Do not interleave read-from/write-to the DOM. Write-to DOM\n // operations would cause the first read-from to be expensive, and\n // interleaving means that potentially all single read-from operation\n // would be expensive rather than just the 1st one.\n // Benchmarking toggling off/on cosmetic filtering confirms quite an\n // improvement when:\n // - batching as much as possible handling of all nodes;\n // - avoiding to interleave read-from/write-to operations.\n // However, toggling off/on cosmetic filtering repeatedly is not\n // a real use case, but this shows this will help performance\n // on sites which try to use inline styles to bypass blockers.\n hideNodeBatchProcess() {\n this.hideNodeBatchProcessTimer.clear();\n const expando = this.hideNodeExpando;\n for ( const node of this.hiddenNodesetToProcess ) {\n if (\n this.hiddenNodeset.has(node) === false ||\n node[expando] === undefined ||\n node.clientHeight === 0 || node.clientWidth === 0\n ) {\n continue;\n }\n let attr = node.getAttribute('style');\n if ( attr === null ) {\n attr = '';\n } else if (\n attr.length !== 0 &&\n attr.charCodeAt(attr.length - 1) !== 0x3B /* ';' */\n ) {\n attr += ';';\n }\n node.setAttribute('style', attr + 'display:none!important;');\n }\n this.hiddenNodesetToProcess.clear();\n }\n\n hideNodeObserverHandler(mutations) {\n if ( vAPI.userStylesheet.disabled ) { return; }\n const stagedNodes = this.hiddenNodesetToProcess;\n for ( const mutation of mutations ) {\n stagedNodes.add(mutation.target);\n }\n this.hideNodeBatchProcessTimer.start();\n }\n\n hideNodeInit() {\n this.hideNodeExpando = vAPI.randomToken();\n this.hideNodeBatchProcessTimer =\n new vAPI.SafeAnimationFrame(this.hideNodeBatchProcess.bind(this));\n this.hiddenNodeObserver =\n new MutationObserver(this.hideNodeObserverHandler.bind(this));\n if ( this.hideNodeStyleSheetInjected === false ) {\n this.hideNodeStyleSheetInjected = true;\n vAPI.userStylesheet.add(\n `[${this.hideNodeAttr}]\\n{display:none!important;}`\n );\n }\n }\n\n excludeNode(node) {\n this.excludedNodeSet.add(node);\n this.unhideNode(node);\n }\n\n unexcludeNode(node) {\n this.excludedNodeSet.delete(node);\n }\n\n hideNode(node) {\n if ( this.excludedNodeSet.has(node) ) { return; }\n if ( this.hideNodeAttr === undefined ) { return; }\n if ( this.hiddenNodeset.has(node) ) { return; }\n node.hidden = true;\n this.hiddenNodeset.add(node);\n if ( this.hideNodeExpando === undefined ) { this.hideNodeInit(); }\n node.setAttribute(this.hideNodeAttr, '');\n if ( node[this.hideNodeExpando] === undefined ) {\n node[this.hideNodeExpando] =\n node.hasAttribute('style') &&\n (node.getAttribute('style') || '');\n }\n this.hiddenNodesetToProcess.add(node);\n this.hideNodeBatchProcessTimer.start();\n this.hiddenNodeObserver.observe(node, this.hiddenNodeObserverOptions);\n }\n\n unhideNode(node) {\n if ( this.hiddenNodeset.has(node) === false ) { return; }\n node.hidden = false;\n node.removeAttribute(this.hideNodeAttr);\n this.hiddenNodesetToProcess.delete(node);\n if ( this.hideNodeExpando === undefined ) { return; }\n const attr = node[this.hideNodeExpando];\n if ( attr === false ) {\n node.removeAttribute('style');\n } else if ( typeof attr === 'string' ) {\n node.setAttribute('style', attr);\n }\n node[this.hideNodeExpando] = undefined;\n this.hiddenNodeset.delete(node);\n }\n\n showNode(node) {\n node.hidden = false;\n const attr = node[this.hideNodeExpando];\n if ( attr === false ) {\n node.removeAttribute('style');\n } else if ( typeof attr === 'string' ) {\n node.setAttribute('style', attr);\n }\n }\n\n unshowNode(node) {\n node.hidden = true;\n this.hiddenNodesetToProcess.add(node);\n }\n\n toggle(state, callback) {\n vAPI.userStylesheet.toggle(state);\n const disabled = vAPI.userStylesheet.disabled;\n const nodes = document.querySelectorAll(`[${this.hideNodeAttr}]`);\n for ( const node of nodes ) {\n if ( disabled ) {\n this.showNode(node);\n } else {\n this.unshowNode(node);\n }\n }\n if ( disabled === false && this.hideNodeExpando !== undefined ) {\n this.hideNodeBatchProcessTimer.start();\n }\n if ( typeof callback === 'function' ) {\n callback();\n }\n }\n\n getAllSelectors_(all) {\n const out = {\n declarative: [],\n exceptions: this.exceptedCSSRules,\n };\n if ( this.specificSimpleHide.size !== 0 ) {\n out.declarative.push([\n Array.from(this.specificSimpleHide).join(',\\n'),\n 'display:none!important;'\n ]);\n }\n if ( this.specificComplexHide.size !== 0 ) {\n out.declarative.push([\n Array.from(this.specificComplexHide).join(',\\n'),\n 'display:none!important;'\n ]);\n }\n if ( this.genericSimpleHide.size !== 0 ) {\n out.declarative.push([\n Array.from(this.genericSimpleHide).join(',\\n'),\n 'display:none!important;'\n ]);\n }\n if ( this.genericComplexHide.size !== 0 ) {\n out.declarative.push([\n Array.from(this.genericComplexHide).join(',\\n'),\n 'display:none!important;'\n ]);\n }\n if ( all ) {\n out.declarative.push([\n '[' + this.hideNodeAttr + ']',\n 'display:none!important;'\n ]);\n }\n for ( const entry of this.specificOthers ) {\n out.declarative.push([ entry.selectors, entry.declarations ]);\n }\n return out;\n }\n\n getFilteredElementCount() {\n const details = this.getAllSelectors_(true);\n if ( Array.isArray(details.declarative) === false ) { return 0; }\n const selectors = details.declarative.map(entry => entry[0]);\n if ( selectors.length === 0 ) { return 0; }\n return document.querySelectorAll(selectors.join(',\\n')).length;\n }\n\n getAllSelectors() {\n return this.getAllSelectors_(false);\n }\n};\n\nvAPI.DOMFilterer.prototype.hiddenNodeObserverOptions = {\n attributes: true,\n attributeFilter: [ 'style' ]\n};\n\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n\n\n\n\n\n\n\n\n/*******************************************************************************\n\n DO NOT:\n - Remove the following code\n - Add code beyond the following code\n Reason:\n - https://github.com/gorhill/uBlock/pull/3721\n - uBO never uses the return value from injected content scripts\n\n**/\n\nvoid 0;\n", "file_path": "platform/chromium/vapi-usercss.pseudo.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9943521022796631, 0.03312355652451515, 0.00016294057422783226, 0.0001756959973135963, 0.17063836753368378]} {"hunk": {"id": 4, "code_window": ["\n", " commitNow: function() {\n", " if ( this.selectors.size === 0 || this.domIsReady === false ) {\n", " return;\n", " }\n", "\n"], "labels": ["keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" commitNow() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 761}, "file": "\n\n\n \n \n \n\n", "file_path": "src/img/ublock-defs.svg", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001770227390807122, 0.00017338585166726261, 0.0001697663392405957, 0.00017336849123239517, 2.9624382023030194e-06]} {"hunk": {"id": 5, "code_window": [" for ( const node of toRemove ) {\n", " if ( this.hiddenNodes.has(node) ) { continue; }\n", " this.domFilterer.unhideNode(node);\n", " }\n", " //console.timeEnd('procedural selectors/dom layout changed');\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 806}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9976733326911926, 0.00737460982054472, 0.0001610017498023808, 0.0001730626099742949, 0.07896503806114197]} {"hunk": {"id": 5, "code_window": [" for ( const node of toRemove ) {\n", " if ( this.hiddenNodes.has(node) ) { continue; }\n", " this.domFilterer.unhideNode(node);\n", " }\n", " //console.timeEnd('procedural selectors/dom layout changed');\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 806}, "file": "## INSTALL\n\n### Chromium\n\n- Download and unzip `ublock0.chromium.zip` ([latest release desirable](https://github.com/gorhill/uBlock/releases)).\n- Rename the unzipped directory to `ublock`\n - When you later update manually, replace the **content** of the `ublock` folder with the **content** of the latest zipped version.\n - This will ensure that all the extension settings will be preserved\n - As long as the extension loads **from same folder path from which it was originally installed**, all your settings will be preserved.\n- Go to chromium/chrome *Extensions*.\n- Click to check *Developer mode*.\n- Click *Load unpacked extension...*.\n- In the file selector dialog:\n - Select the directory `ublock` which was created above.\n - Click *Open*.\n\nThe extension will now be available in your chromium/chromium-based browser.\n\nRemember that you have to update manually also. For some users, updating manually is actually an advantage because:\n- You can update when **you** want\n- If ever a new version sucks, you can easily just re-install the previous one\n\n### Firefox\n\nCompatible with Firefox 52 and beyond. \n\n#### For stable release version\n\nThis works only if you set `xpinstall.signatures.required` to `false` in `about:config`.[see \"Add-on signing in Firefox\"](https://support.mozilla.org/en-US/kb/add-on-signing-in-firefox)\n\n- Download `ublock0.firefox.xpi` ([latest release desirable](https://github.com/gorhill/uBlock/releases)).\n - Right-click and choose _\"Save As...\"_.\n- Drag and drop the previously downloaded `ublock0.firefox.xpi` into Firefox\n\n#### For beta version\n\n- Click on `ublock0.firefox.signed.xpi` ([latest release desirable](https://github.com/gorhill/uBlock/releases)).\n\n#### Location of uBO settings\n\nOn Linux, the settings are saved in a JSON file located at `~/.mozilla/firefox/[profile name]/browser-extension-data/uBlock0@raymondhill.net/storage.js`.\n\nWhen you uninstall the extension, Firefox deletes that file, so all your settings are lost when you uninstall.\n\n### Firefox legacy\n\nCompatible with Firefox 24 to Firefox 56.\n\n- Download `ublock0.firefox-legacy.xpi` ([latest release desirable](https://github.com/gorhill/uBlock/releases)).\n - Right-click and select \"Save Link As...\"\n- Drag and drop the previously downloaded `ublock0.firefox-legacy.xpi` into Firefox\n\nWith Firefox 43 and beyond, you may need to toggle the setting `xpinstall.signatures.required` to `false` in `about:config`.[see \"Add-on signing in Firefox\"](https://support.mozilla.org/en-US/kb/add-on-signing-in-firefox)\n\nYour uBlock Origin settings are kept intact even after you uninstall the addon.\n\nOn Linux, the settings are saved in a SQlite file located at `~/.mozilla/firefox/[profile name]/extension-data/ublock0.sqlite`.\n\nOn Windows, the settings are saved in a SQlite file located at `%APPDATA%\\Mozilla\\Firefox\\Profiles\\[profile name]\\extension-data\\ublock0.sqlite`.\n\n### Build instructions (for developers)\n\n- Clone [uBlock](https://github.com/gorhill/uBlock) and [uAssets](https://github.com/uBlockOrigin/uAssets) repositories in the same parent directory\n - `git clone https://github.com/gorhill/uBlock.git`\n - `git clone https://github.com/uBlockOrigin/uAssets.git`\n- Set path to uBlock: `cd uBlock`\n- The official version of uBO is in the `master` branch\n - `git checkout master`\n- Build the plugin:\n - Chromium: `./tools/make-chromium.sh`\n - Firefox webext: `./tools/make-firefox.sh all`\n - Firefox legacy:\n - `git checkout firefox-legacy`\n - `./tools/make-firefox-legacy.sh all`\n- Load the result of the build into your browser:\n - Chromium: load the unpacked extension folder `/uBlock/dist/build/uBlock0.chromium/` in Chromium to use the extension.\n - Firefox: drag-and-drop `/uBlock/dist/build/uBlock0.firefox.xpi` or `/uBlock/dist/build/uBlock0.firefox-legacy.xpi` into Firefox.\n \n", "file_path": "dist/README.md", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017418571223970503, 0.00017057164222933352, 0.00016575262998230755, 0.00017058673256542534, 2.8639981337619247e-06]} {"hunk": {"id": 5, "code_window": [" for ( const node of toRemove ) {\n", " if ( this.hiddenNodes.has(node) ) { continue; }\n", " this.domFilterer.unhideNode(node);\n", " }\n", " //console.timeEnd('procedural selectors/dom layout changed');\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 806}, "file": "{\n \"extName\": {\n \"message\": \"uBlock Origin\",\n \"description\": \"extension name.\"\n },\n \"extShortDesc\": {\n \"message\": \"Nareszcie skuteczny bloker charakteryzujący się niskim użyciem procesora i pamięci.\",\n \"description\": \"this will be in the Chrome web store: must be 132 characters or less\"\n },\n \"dashboardName\": {\n \"message\": \"uBlock₀ – Panel sterowania\",\n \"description\": \"English: uBlock₀ — Dashboard\"\n },\n \"settingsPageName\": {\n \"message\": \"Ustawienia\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"3pPageName\": {\n \"message\": \"Listy filtrów\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"1pPageName\": {\n \"message\": \"Moje filtry\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"rulesPageName\": {\n \"message\": \"Moje reguły\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"whitelistPageName\": {\n \"message\": \"Biała lista\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"shortcutsPageName\": {\n \"message\": \"Skróty\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"statsPageName\": {\n \"message\": \"uBlock₀ – Rejestrator\",\n \"description\": \"Title for the logger window\"\n },\n \"aboutPageName\": {\n \"message\": \"O rozszerzeniu\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"assetViewerPageName\": {\n \"message\": \"uBlock₀ – Podgląd zasobu\",\n \"description\": \"Title for the asset viewer page\"\n },\n \"advancedSettingsPageName\": {\n \"message\": \"Ustawienia zaawansowane\",\n \"description\": \"Title for the advanced settings page\"\n },\n \"popupPowerSwitchInfo\": {\n \"message\": \"Kliknij, aby włączyć\\/wyłączyć uBlock₀ na tej witrynie.\\n\\nKliknij z wciśniętym klawiszem Ctrl, aby włączyć\\/wyłączyć uBlock₀ tylko na tej stronie.\",\n \"description\": \"English: Click: disable\\/enable uBlock₀ for this site.\\n\\nCtrl+click: disable uBlock₀ only on this page.\"\n },\n \"popupPowerSwitchInfo1\": {\n \"message\": \"Kliknij, aby wyłączyć uBlock₀ dla tej witryny.\\n\\nKliknij z wciśniętym klawiszem Ctrl, aby wyłączyć uBlock₀ tylko dla tej strony.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupPowerSwitchInfo2\": {\n \"message\": \"Kliknij, aby włączyć uBlock₀ dla tej witryny.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupBlockedRequestPrompt\": {\n \"message\": \"zablokowane żądania\",\n \"description\": \"English: requests blocked\"\n },\n \"popupBlockedOnThisPagePrompt\": {\n \"message\": \"na tej stronie\",\n \"description\": \"English: on this page\"\n },\n \"popupBlockedStats\": {\n \"message\": \"{{count}} ({{percent}}%)\",\n \"description\": \"Example: 15 or 13%\"\n },\n \"popupBlockedSinceInstallPrompt\": {\n \"message\": \"od instalacji\",\n \"description\": \"English: since install\"\n },\n \"popupOr\": {\n \"message\": \"lub\",\n \"description\": \"English: or\"\n },\n \"popupTipDashboard\": {\n \"message\": \"Otwórz panel sterowania\",\n \"description\": \"English: Click to open the dashboard\"\n },\n \"popupTipZapper\": {\n \"message\": \"Przejdź do trybu usuwania elementów\",\n \"description\": \"Tooltip for the element-zapper icon in the popup panel\"\n },\n \"popupTipPicker\": {\n \"message\": \"Przejdź do trybu zaznaczania elementów\",\n \"description\": \"English: Enter element picker mode\"\n },\n \"popupTipLog\": {\n \"message\": \"Otwórz rejestrator\",\n \"description\": \"Tooltip used for the logger icon in the panel\"\n },\n \"popupTipNoPopups\": {\n \"message\": \"Włącz\\/wyłącz blokowanie wyskakujących okien na tej witrynie\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups1\": {\n \"message\": \"Kliknij, aby zablokować wszystkie wyskakujące okna na tej witrynie\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups2\": {\n \"message\": \"Kliknij, aby nie blokować wyskakujących okien na tej witrynie\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoLargeMedia\": {\n \"message\": \"Włącz\\/wyłącz blokowanie dużych elementów multimedialnych na tej witrynie\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia1\": {\n \"message\": \"Kliknij, aby zablokować duże elementy multimedialne na tej witrynie\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia2\": {\n \"message\": \"Kliknij, aby nie blokować dużych elementów multimedialnych na tej witrynie\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoCosmeticFiltering\": {\n \"message\": \"Włącz\\/wyłącz kosmetyczne filtrowanie na tej witrynie\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering1\": {\n \"message\": \"Kliknij, aby wyłączyć filtrowanie kosmetyczne na tej witrynie\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering2\": {\n \"message\": \"Kliknij, aby włączyć filtrowanie kosmetyczne na tej witrynie\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoRemoteFonts\": {\n \"message\": \"Włącz\\/wyłącz blokowanie zdalnych czcionek na tej witrynie\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts1\": {\n \"message\": \"Kliknij, aby zablokować zdalne czcionki na tej witrynie\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts2\": {\n \"message\": \"Kliknij, aby nie blokować zdalnych czcionek na tej witrynie\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoScripting1\": {\n \"message\": \"Kliknij, aby wyłączyć JavaScript na tej witrynie\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipNoScripting2\": {\n \"message\": \"Kliknij, aby JavaScript nie był już wyłączony na tej witrynie\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipGlobalRules\": {\n \"message\": \"Reguły globalne. W tej kolumnie znajdują się reguły stosowane na wszystkich witrynach.\",\n \"description\": \"Tooltip when hovering the top-most cell of the global-rules column.\"\n },\n \"popupTipLocalRules\": {\n \"message\": \"Reguły lokalne. W tej kolumnie znajdują się reguły stosowane tylko na bieżącej witrynie.\\nReguły lokalne zastępują reguły globalne.\",\n \"description\": \"Tooltip when hovering the top-most cell of the local-rules column.\"\n },\n \"popupTipSaveRules\": {\n \"message\": \"Kliknij, aby zastosować zmiany na stałe.\",\n \"description\": \"Tooltip when hovering over the padlock in the dynamic filtering pane.\"\n },\n \"popupTipRevertRules\": {\n \"message\": \"Kliknij, aby odrzucić zmiany.\",\n \"description\": \"Tooltip when hovering over the eraser in the dynamic filtering pane.\"\n },\n \"popupAnyRulePrompt\": {\n \"message\": \"wszystko\",\n \"description\": \"\"\n },\n \"popupImageRulePrompt\": {\n \"message\": \"obrazki\",\n \"description\": \"\"\n },\n \"popup3pAnyRulePrompt\": {\n \"message\": \"domeny zewnętrzne\",\n \"description\": \"\"\n },\n \"popup3pPassiveRulePrompt\": {\n \"message\": \"zewnętrzne CSS\\/obrazki\",\n \"description\": \"\"\n },\n \"popupInlineScriptRulePrompt\": {\n \"message\": \"zagnieżdżone skrypty\",\n \"description\": \"\"\n },\n \"popup1pScriptRulePrompt\": {\n \"message\": \"skrypty z tej domeny\",\n \"description\": \"\"\n },\n \"popup3pScriptRulePrompt\": {\n \"message\": \"skrypty z domen zewnętrznych\",\n \"description\": \"\"\n },\n \"popup3pFrameRulePrompt\": {\n \"message\": \"ramki z domen zewnętrznych\",\n \"description\": \"\"\n },\n \"popupHitDomainCountPrompt\": {\n \"message\": \"podłączone domeny\",\n \"description\": \"appears in popup\"\n },\n \"popupHitDomainCount\": {\n \"message\": \"{{count}} z {{total}}\",\n \"description\": \"appears in popup\"\n },\n \"pickerCreate\": {\n \"message\": \"Utwórz\",\n \"description\": \"English: Create\"\n },\n \"pickerPick\": {\n \"message\": \"Wybierz\",\n \"description\": \"English: Pick\"\n },\n \"pickerQuit\": {\n \"message\": \"Zamknij\",\n \"description\": \"English: Quit\"\n },\n \"pickerPreview\": {\n \"message\": \"Podgląd\",\n \"description\": \"Element picker preview mode: will cause the elements matching the current filter to be removed from the page\"\n },\n \"pickerNetFilters\": {\n \"message\": \"Filtry sieciowe\",\n \"description\": \"English: header for a type of filter in the element picker dialog\"\n },\n \"pickerCosmeticFilters\": {\n \"message\": \"Filtry kosmetyczne\",\n \"description\": \"English: Cosmetic filters\"\n },\n \"pickerCosmeticFiltersHint\": {\n \"message\": \"Klik, Ctrl + klik\",\n \"description\": \"English: Click, Ctrl-click\"\n },\n \"pickerContextMenuEntry\": {\n \"message\": \"Zablokuj element\",\n \"description\": \"English: Block element\"\n },\n \"settingsCollapseBlockedPrompt\": {\n \"message\": \"Ukrywaj symbole zastępcze zablokowanych elementów\",\n \"description\": \"English: Hide placeholders of blocked elements\"\n },\n \"settingsIconBadgePrompt\": {\n \"message\": \"Wyświetlaj liczbę zablokowanych żądań na ikonie rozszerzenia\",\n \"description\": \"English: Show the number of blocked requests on the icon\"\n },\n \"settingsTooltipsPrompt\": {\n \"message\": \"Nie wyświetlaj dymków podpowiedzi\",\n \"description\": \"A checkbox in the Settings pane\"\n },\n \"settingsContextMenuPrompt\": {\n \"message\": \"Używaj menu kontekstowego, gdzie to możliwe\",\n \"description\": \"English: Make use of context menu where appropriate\"\n },\n \"settingsColorBlindPrompt\": {\n \"message\": \"Interfejs przyjazny osobom z zaburzeniami widzenia kolorów\",\n \"description\": \"English: Color-blind friendly\"\n },\n \"settingsCloudStorageEnabledPrompt\": {\n \"message\": \"Włącz obsługę zapisu ustawień w chmurze\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserPrompt\": {\n \"message\": \"Jestem zaawansowanym użytkownikiem (Wymagana lektura<\\/a>)\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserSettings\": {\n \"message\": \"Ustawienia zaawansowane\",\n \"description\": \"For the tooltip of a link which gives access to advanced settings\"\n },\n \"settingsPrefetchingDisabledPrompt\": {\n \"message\": \"Wyłącz wstępne pobieranie (by uniknąć połączeń z zablokowanymi zapytaniami sieciowymi)\",\n \"description\": \"English: \"\n },\n \"settingsHyperlinkAuditingDisabledPrompt\": {\n \"message\": \"Wyłącz śledzenie kliknięć odnośników\",\n \"description\": \"English: \"\n },\n \"settingsWebRTCIPAddressHiddenPrompt\": {\n \"message\": \"Zapobiegaj ujawnianiu lokalnego adresu IP poprzez interfejs WebRTC\",\n \"description\": \"English: \"\n },\n \"settingPerSiteSwitchGroup\": {\n \"message\": \"Działanie domyślne\",\n \"description\": \"\"\n },\n \"settingPerSiteSwitchGroupSynopsis\": {\n \"message\": \"Te ustawienia mogą być zastąpione przez ustawienia danej witryny\",\n \"description\": \"\"\n },\n \"settingsNoCosmeticFilteringPrompt\": {\n \"message\": \"Wyłącz filtrowanie kosmetyczne\",\n \"description\": \"\"\n },\n \"settingsNoLargeMediaPrompt\": {\n \"message\": \"Blokuj elementy multimedialne większe niż {{input}} KiB\",\n \"description\": \"\"\n },\n \"settingsNoRemoteFontsPrompt\": {\n \"message\": \"Blokuj zdalne czcionki\",\n \"description\": \"\"\n },\n \"settingsNoScriptingPrompt\": {\n \"message\": \"Wyłącz JavaScript\",\n \"description\": \"The default state for the per-site no-scripting switch\"\n },\n \"settingsNoCSPReportsPrompt\": {\n \"message\": \"Blokuj raporty CSP\",\n \"description\": \"background information: https:\\/\\/github.com\\/gorhill\\/uBlock\\/issues\\/3150\"\n },\n \"settingsStorageUsed\": {\n \"message\": \"Użycie pamięci masowej: {{value}} bajtów\",\n \"description\": \"English: Storage used: {{}} bytes\"\n },\n \"settingsLastRestorePrompt\": {\n \"message\": \"Ostatnie przywrócenie wykonano:\",\n \"description\": \"English: Last restore:\"\n },\n \"settingsLastBackupPrompt\": {\n \"message\": \"Ostatnią kopię zapasową wykonano:\",\n \"description\": \"English: Last backup:\"\n },\n \"3pListsOfBlockedHostsPrompt\": {\n \"message\": \"Filtry sieciowe: {{netFilterCount}} + filtry kosmetyczne: {{cosmeticFilterCount}} z:\",\n \"description\": \"Appears at the top of the _3rd-party filters_ pane\"\n },\n \"3pListsOfBlockedHostsPerListStats\": {\n \"message\": \"użytych {{used}} z {{total}}\",\n \"description\": \"Appears aside each filter list in the _3rd-party filters_ pane\"\n },\n \"3pAutoUpdatePrompt1\": {\n \"message\": \"Automatycznie aktualizuj listy filtrów\",\n \"description\": \"A checkbox in the _3rd-party filters_ pane\"\n },\n \"3pUpdateNow\": {\n \"message\": \"Aktualizuj teraz\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pPurgeAll\": {\n \"message\": \"Wyczyść całą pamięć podręczną\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pParseAllABPHideFiltersPrompt1\": {\n \"message\": \"Przetwarzaj i stosuj filtry kosmetyczne\",\n \"description\": \"English: Parse and enforce Adblock+ element hiding filters.\"\n },\n \"3pParseAllABPHideFiltersInfo\": {\n \"message\": \"

Włączenie tej funkcji skutkuje przetwarzaniem i używaniem filtrów kompatybilnych z dodatkiem Adblock Plus służących do ukrywania elementów<\\/a>. Są to filtry kosmetyczne i służą do ukrycia elementów uważanych za wizualnie uciążliwe, których nie można zablokować przez filtry sieciowe.<\\/p>

Włączenie tej funkcji powoduje zwiększenie użycia pamięci przez uBlock₀.<\\/p>\",\n \"description\": \"Describes the purpose of the 'Parse and enforce cosmetic filters' feature.\"\n },\n \"3pIgnoreGenericCosmeticFilters\": {\n \"message\": \"Ignoruj ogólne filtry kosmetyczne\",\n \"description\": \"This will cause uBO to ignore all generic cosmetic filters.\"\n },\n \"3pIgnoreGenericCosmeticFiltersInfo\": {\n \"message\": \"

Ogólne filtry kosmetyczne, to filtry które mają być zastosowane na wszystkich stronach internetowych.

Choć dobrze obsługiwane przez uBlock₀ mogą na niektórych stronach, szczególnie dużych i otwartych przez dłuższy czas, przyczyniać się do obciążenia procesora i pamięci operacyjnej.

Włącznie tej funkcji wyeliminuje obciążenie procesora i pamięci operacyjnej powodowane stosowaniem ogólnych filtrów kosmetycznych, a także zmniejszy zapotrzebowanie na pamięć samego uBlocka₀.

Zaleca się włączenie tej funkcji na mniej wydajnych urządzeniach.\",\n \"description\": \"Describes the purpose of the 'Ignore generic cosmetic filters' feature.\"\n },\n \"3pListsOfBlockedHostsHeader\": {\n \"message\": \"Listy zablokowanych hostów\",\n \"description\": \"English: Lists of blocked hosts\"\n },\n \"3pApplyChanges\": {\n \"message\": \"Zastosuj zmiany\",\n \"description\": \"English: Apply changes\"\n },\n \"3pGroupDefault\": {\n \"message\": \"Wbudowane\",\n \"description\": \"Header for the uBlock filters section in 'Filter lists pane'\"\n },\n \"3pGroupAds\": {\n \"message\": \"Reklamy\",\n \"description\": \"English: Ads\"\n },\n \"3pGroupPrivacy\": {\n \"message\": \"Prywatność\",\n \"description\": \"English: Privacy\"\n },\n \"3pGroupMalware\": {\n \"message\": \"Domeny ze złośliwym oprogramowaniem\",\n \"description\": \"English: Malware domains\"\n },\n \"3pGroupAnnoyances\": {\n \"message\": \"Elementy irytujące\",\n \"description\": \"The header identifying the filter lists in the category 'annoyances'\"\n },\n \"3pGroupMultipurpose\": {\n \"message\": \"Wielofunkcyjne\",\n \"description\": \"English: Multipurpose\"\n },\n \"3pGroupRegions\": {\n \"message\": \"Regiony, języki\",\n \"description\": \"English: Regions, languages\"\n },\n \"3pGroupCustom\": {\n \"message\": \"Własne\",\n \"description\": \"English: Custom\"\n },\n \"3pImport\": {\n \"message\": \"Importuj...\",\n \"description\": \"The label for the checkbox used to import external filter lists\"\n },\n \"3pExternalListsHint\": {\n \"message\": \"Jeden adres URL na linię. Błędne adresy URL będą pomijane.\",\n \"description\": \"Short information about how to use the textarea to import external filter lists by URL\"\n },\n \"3pExternalListObsolete\": {\n \"message\": \"Nieaktualna.\",\n \"description\": \"used as a tooltip for the out-of-date icon beside a list\"\n },\n \"3pLastUpdate\": {\n \"message\": \"Zaktualizowano: {{ago}}.\\nKliknij, aby wymusić aktualizację.\",\n \"description\": \"used as a tooltip for the clock icon beside a list\"\n },\n \"3pUpdating\": {\n \"message\": \"Aktualizowanie...\",\n \"description\": \"used as a tooltip for the spinner icon beside a list\"\n },\n \"3pNetworkError\": {\n \"message\": \"Błąd sieci uniemożliwił aktualizację zasobów.\",\n \"description\": \"used as a tooltip for error icon beside a list\"\n },\n \"1pFormatHint\": {\n \"message\": \"Jeden filtr na linię. Filtrem może być nazwa hosta lub filtr kompatybilny z dodatkiem Adblock Plus. Wiersze poprzedzone !<\\/code> będą pomijane.\",\n \"description\": \"Short information about how to create custom filters\"\n },\n \"1pImport\": {\n \"message\": \"Importuj i dołącz\",\n \"description\": \"English: Import and append\"\n },\n \"1pExport\": {\n \"message\": \"Eksportuj\",\n \"description\": \"English: Export\"\n },\n \"1pExportFilename\": {\n \"message\": \"ublock-statyczne-filtry_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-static-filters_{{datetime}}.txt\"\n },\n \"1pApplyChanges\": {\n \"message\": \"Zastosuj zmiany\",\n \"description\": \"English: Apply changes\"\n },\n \"rulesPermanentHeader\": {\n \"message\": \"Stałe reguły\",\n \"description\": \"header\"\n },\n \"rulesTemporaryHeader\": {\n \"message\": \"Tymczasowe reguły\",\n \"description\": \"header\"\n },\n \"rulesRevert\": {\n \"message\": \"Przywróć\",\n \"description\": \"This will remove all temporary rules\"\n },\n \"rulesCommit\": {\n \"message\": \"Zatwierdź\",\n \"description\": \"This will persist temporary rules\"\n },\n \"rulesEdit\": {\n \"message\": \"Edytuj\",\n \"description\": \"Will enable manual-edit mode (textarea)\"\n },\n \"rulesEditSave\": {\n \"message\": \"Zapisz\",\n \"description\": \"Will save manually-edited content and exit manual-edit mode\"\n },\n \"rulesEditDiscard\": {\n \"message\": \"Odrzuć\",\n \"description\": \"Will discard manually-edited content and exit manual-edit mode\"\n },\n \"rulesImport\": {\n \"message\": \"Importuj z pliku…\",\n \"description\": \"\"\n },\n \"rulesExport\": {\n \"message\": \"Eksportuj do pliku…\",\n \"description\": \"\"\n },\n \"rulesDefaultFileName\": {\n \"message\": \"ublock-dynamiczne-reguly_{{datetime}}.txt\",\n \"description\": \"default file name to use\"\n },\n \"rulesHint\": {\n \"message\": \"Lista reguł dynamicznego filtrowania.\",\n \"description\": \"English: List of your dynamic filtering rules.\"\n },\n \"rulesFormatHint\": {\n \"message\": \"Składnia reguły: źródło cel typ akcja<\\/code> (pełna dokumentacja<\\/a>).\",\n \"description\": \"English: dynamic rule syntax and full documentation.\"\n },\n \"whitelistPrompt\": {\n \"message\": \"Dyrektywy białej listy wskazują, na których stronach uBlock Origin powinien zostać wyłączony. Jeden wpis na linię. Nieprawidłowe wpisy zostaną bez powiadomienia zignorowane i wykomentowane.\",\n \"description\": \"English: An overview of the content of the dashboard's Whitelist pane.\"\n },\n \"whitelistImport\": {\n \"message\": \"Importuj i dołącz\",\n \"description\": \"English: Import and append\"\n },\n \"whitelistExport\": {\n \"message\": \"Eksportuj\",\n \"description\": \"English: Export\"\n },\n \"whitelistExportFilename\": {\n \"message\": \"ublock-biała-lista_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-whitelist_{{datetime}}.txt\"\n },\n \"whitelistApply\": {\n \"message\": \"Zastosuj zmiany\",\n \"description\": \"English: Apply changes\"\n },\n \"logRequestsHeaderType\": {\n \"message\": \"Typ\",\n \"description\": \"English: Type\"\n },\n \"logRequestsHeaderDomain\": {\n \"message\": \"Domena\",\n \"description\": \"English: Domain\"\n },\n \"logRequestsHeaderURL\": {\n \"message\": \"Adres URL\",\n \"description\": \"English: URL\"\n },\n \"logRequestsHeaderFilter\": {\n \"message\": \"Filtr\",\n \"description\": \"English: Filter\"\n },\n \"logAll\": {\n \"message\": \"Wszystkie\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"logBehindTheScene\": {\n \"message\": \"Bez kart\",\n \"description\": \"Pretty name for behind-the-scene network requests\"\n },\n \"loggerCurrentTab\": {\n \"message\": \"Aktywna karta\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"loggerReloadTip\": {\n \"message\": \"Przeładuj zawartość karty\",\n \"description\": \"Tooltip for the reload button in the logger page\"\n },\n \"loggerDomInspectorTip\": {\n \"message\": \"Przełącz inspektor DOM\",\n \"description\": \"Tooltip for the DOM inspector button in the logger page\"\n },\n \"loggerPopupPanelTip\": {\n \"message\": \"Przełącz panel popup\",\n \"description\": \"Tooltip for the popup panel button in the logger page\"\n },\n \"loggerInfoTip\": {\n \"message\": \"uBlock Origin wiki: Rejestrator (ang.)\",\n \"description\": \"Tooltip for the top-right info label in the logger page\"\n },\n \"loggerClearTip\": {\n \"message\": \"Wyczyść rejestr\",\n \"description\": \"Tooltip for the eraser in the logger page; used to blank the content of the logger\"\n },\n \"loggerPauseTip\": {\n \"message\": \"Pauzuj rejestrowanie (porzuć wszystkie przychodzące dane)\",\n \"description\": \"Tooltip for the pause button in the logger page\"\n },\n \"loggerUnpauseTip\": {\n \"message\": \"Wznów rejestrowanie\",\n \"description\": \"Tooltip for the play button in the logger page\"\n },\n \"loggerRowFiltererButtonTip\": {\n \"message\": \"Przełącz filtrowanie rejestru\",\n \"description\": \"Tooltip for the row filterer button in the logger page\"\n },\n \"logFilterPrompt\": {\n \"message\": \"filtruj zawartość rejestru\",\n \"description\": \"Placeholder string for logger output filtering input field\"\n },\n \"loggerRowFiltererBuiltinTip\": {\n \"message\": \"Opcje filtrowania rejestru\",\n \"description\": \"Tooltip for the button to bring up logger output filtering options\"\n },\n \"loggerRowFiltererBuiltinNot\": {\n \"message\": \"Nie\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinEventful\": {\n \"message\": \"akcje\",\n \"description\": \"A keyword in the built-in row filtering expression: all items corresponding to uBO doing something (blocked, allowed, redirected, etc.)\"\n },\n \"loggerRowFiltererBuiltinBlocked\": {\n \"message\": \"zablokowane\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinAllowed\": {\n \"message\": \"dozwolone\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin1p\": {\n \"message\": \"własna domena\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin3p\": {\n \"message\": \"domeny trzecie\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerEntryDetailsHeader\": {\n \"message\": \"Szczegóły\",\n \"description\": \"Small header to identify the 'Details' pane for a specific logger entry\"\n },\n \"loggerEntryDetailsFilter\": {\n \"message\": \"Filtr\",\n \"description\": \"Label to identify a filter field\"\n },\n \"loggerEntryDetailsFilterList\": {\n \"message\": \"Lista filtrów\",\n \"description\": \"Label to identify a filter list field\"\n },\n \"loggerEntryDetailsRule\": {\n \"message\": \"Reguła\",\n \"description\": \"Label to identify a rule field\"\n },\n \"loggerEntryDetailsContext\": {\n \"message\": \"Kontekst\",\n \"description\": \"Label to identify a context field (typically a hostname)\"\n },\n \"loggerEntryDetailsRootContext\": {\n \"message\": \"Kontekst główny\",\n \"description\": \"Label to identify a root context field (typically a hostname)\"\n },\n \"loggerEntryDetailsPartyness\": {\n \"message\": \"Lokalność\",\n \"description\": \"Label to identify a field providing partyness information\"\n },\n \"loggerEntryDetailsType\": {\n \"message\": \"Typ\",\n \"description\": \"Label to identify the type of an entry\"\n },\n \"loggerEntryDetailsURL\": {\n \"message\": \"Adres URL\",\n \"description\": \"Label to identify the URL of an entry\"\n },\n \"loggerURLFilteringHeader\": {\n \"message\": \"Reguła URL\",\n \"description\": \"Small header to identify the dynamic URL filtering section\"\n },\n \"loggerURLFilteringContextLabel\": {\n \"message\": \"Kontekst:\",\n \"description\": \"Label for the context selector\"\n },\n \"loggerURLFilteringTypeLabel\": {\n \"message\": \"Typ:\",\n \"description\": \"Label for the type selector\"\n },\n \"loggerStaticFilteringHeader\": {\n \"message\": \"Filtr statyczny\",\n \"description\": \"Small header to identify the static filtering section\"\n },\n \"loggerStaticFilteringSentence\": {\n \"message\": \"{{action}} żądania sieciowe {{type}}, których adres URL jest zgodny z: {{url}} {{br}}i pochodzi {{origin}}, {{importance}} filtr znajduje się na liście wyjątków.\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartBlock\": {\n \"message\": \"Blokuj\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAllow\": {\n \"message\": \"Zezwalaj na\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartType\": {\n \"message\": \"typu „{{type}}”\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyType\": {\n \"message\": \"każdego typu\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartOrigin\": {\n \"message\": \"z „{{origin}}”\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyOrigin\": {\n \"message\": \"z dowolnego miejsca\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartNotImportant\": {\n \"message\": \"z wyjątkiem, gdy\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartImportant\": {\n \"message\": \"nawet, jeśli\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringFinderSentence1\": {\n \"message\": \"Filtr statyczny {{filter}}<\\/code> znajdujący się w:\",\n \"description\": \"Below this sentence, the filter list(s) in which the filter was found\"\n },\n \"loggerStaticFilteringFinderSentence2\": {\n \"message\": \"Filtr statyczny {{filter}}<\\/code> nie został znaleziony w aktualnie włączonych listach filtrów\",\n \"description\": \"Message to show when a filter cannot be found in any filter lists\"\n },\n \"loggerSettingDiscardPrompt\": {\n \"message\": \"Wpisy rejestru nie spełniające wszystkich trzech warunków będą automatycznie porzucane:\",\n \"description\": \"Logger setting: A sentence to describe the purpose of the settings below\"\n },\n \"loggerSettingPerEntryMaxAge\": {\n \"message\": \"Zachowuj wpisy z ostatnich {{input}} minut\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxLoads\": {\n \"message\": \"Zachowuj nie więcej niż {{input}} przeładowań strony na kartę\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxEntries\": {\n \"message\": \"Zachowuj nie więcej niż {{input}} wpisów na kartę\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerEntryLineCount\": {\n \"message\": \"Użyj {{input}} linie na wpis w widoku poszerzonym\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingHideColumnsPrompt\": {\n \"message\": \"Ukryj kolumny:\",\n \"description\": \"Logger settings: a sentence to describe the purpose of the checkboxes below\"\n },\n \"loggerSettingHideColumnTime\": {\n \"message\": \"{{input}} Czas\",\n \"description\": \"A label for the time column\"\n },\n \"loggerSettingHideColumnFilter\": {\n \"message\": \"{{input}} Filtr\\/reguła\",\n \"description\": \"A label for the filter or rule column\"\n },\n \"loggerSettingHideColumnContext\": {\n \"message\": \"{{input}} Kontekst\",\n \"description\": \"A label for the context column\"\n },\n \"loggerSettingHideColumnPartyness\": {\n \"message\": \"{{input}} Lokalność\",\n \"description\": \"A label for the partyness column\"\n },\n \"loggerExportFormatList\": {\n \"message\": \"Lista\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportFormatTable\": {\n \"message\": \"Tabela\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportEncodePlain\": {\n \"message\": \"Bez formatowania\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"loggerExportEncodeMarkdown\": {\n \"message\": \"Markdown\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"aboutChangelog\": {\n \"message\": \"Informacje o wydaniu\",\n \"description\": \"\"\n },\n \"aboutWiki\": {\n \"message\": \"Instrukcja obsługi\",\n \"description\": \"English: project' wiki on GitHub\"\n },\n \"aboutSupport\": {\n \"message\": \"Pomoc techniczna\",\n \"description\": \"A link for where to get support\"\n },\n \"aboutIssues\": {\n \"message\": \"Zgłaszanie błędów\",\n \"description\": \"Text for a link to official issue tracker\"\n },\n \"aboutCode\": {\n \"message\": \"Kod źródłowy (GPLv3)\",\n \"description\": \"English: Source code (GPLv3)\"\n },\n \"aboutContributors\": {\n \"message\": \"Współtwórcy\",\n \"description\": \"English: Contributors\"\n },\n \"aboutDependencies\": {\n \"message\": \"Zewnętrzne zależności (kompatybilne z GPLv3):\",\n \"description\": \"Shown in the About pane\"\n },\n \"aboutBackupDataButton\": {\n \"message\": \"Utwórz kopię zapasową…\",\n \"description\": \"Text for button to create a backup of all settings\"\n },\n \"aboutBackupFilename\": {\n \"message\": \"ublock-kopia-zapasowa_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-backup_{{datetime}}.txt\"\n },\n \"aboutRestoreDataButton\": {\n \"message\": \"Przywróć z pliku…\",\n \"description\": \"English: Restore from file...\"\n },\n \"aboutResetDataButton\": {\n \"message\": \"Przywróć ustawienia domyślne…\",\n \"description\": \"English: Reset to default settings...\"\n },\n \"aboutRestoreDataConfirm\": {\n \"message\": \"Wszystkie twoje ustawienia zostaną zastąpione ustawieniami z kopii stworzonej {{time}}. Po zakończeniu uBlock₀ zostanie uruchomiony ponownie.\\n\\nPrzywrócić ustawienia z kopii zapasowej?\",\n \"description\": \"Message asking user to confirm restore\"\n },\n \"aboutRestoreDataError\": {\n \"message\": \"Danych nie można odczytać lub są nieprawidłowe\",\n \"description\": \"Message to display when an error occurred during restore\"\n },\n \"aboutResetDataConfirm\": {\n \"message\": \"Wszystkie twoje ustawienia zostaną usunięte i uBlock₀ zostanie ponownie uruchomiony.\\n\\nCzy chcesz przywrócić ustawienia domyślne?\",\n \"description\": \"Message asking user to confirm reset\"\n },\n \"errorCantConnectTo\": {\n \"message\": \"Błąd sieci: {{msg}}\",\n \"description\": \"English: Network error: {{msg}}\"\n },\n \"subscriberConfirm\": {\n \"message\": \"uBlock₀: Dodać następujący URL do twojej listy filtrów?\\n\\nTytuł: \\\"{{title}}\\\"\\nAdres: {{url}}\",\n \"description\": \"English: The message seen by the user to confirm subscription to a ABP filter list\"\n },\n \"elapsedOneMinuteAgo\": {\n \"message\": \"minutę temu\",\n \"description\": \"English: a minute ago\"\n },\n \"elapsedManyMinutesAgo\": {\n \"message\": \"{{value}} min. temu\",\n \"description\": \"English: {{value}} minutes ago\"\n },\n \"elapsedOneHourAgo\": {\n \"message\": \"godzinę temu\",\n \"description\": \"English: an hour ago\"\n },\n \"elapsedManyHoursAgo\": {\n \"message\": \"{{value}} godz. temu\",\n \"description\": \"English: {{value}} hours ago\"\n },\n \"elapsedOneDayAgo\": {\n \"message\": \"wczoraj\",\n \"description\": \"English: a day ago\"\n },\n \"elapsedManyDaysAgo\": {\n \"message\": \"{{value}} dni temu\",\n \"description\": \"English: {{value}} days ago\"\n },\n \"showDashboardButton\": {\n \"message\": \"Panel sterowania\",\n \"description\": \"Firefox\\/Fennec-specific: Show Dashboard\"\n },\n \"showNetworkLogButton\": {\n \"message\": \"Pokaż rejestrator\",\n \"description\": \"Firefox\\/Fennec-specific: Show Logger\"\n },\n \"fennecMenuItemBlockingOff\": {\n \"message\": \"wyłączony\",\n \"description\": \"Firefox-specific: appears as 'uBlock₀ (off)'\"\n },\n \"docblockedPrompt1\": {\n \"message\": \"uBlock Origin zablokował wczytywanie następującej strony:\",\n \"description\": \"English: uBlock₀ has prevented the following page from loading:\"\n },\n \"docblockedPrompt2\": {\n \"message\": \"Powodem zablokowania jest filtr\",\n \"description\": \"English: Because of the following filter\"\n },\n \"docblockedNoParamsPrompt\": {\n \"message\": \"bez parametrów\",\n \"description\": \"label to be used for the parameter-less URL: https:\\/\\/cloud.githubusercontent.com\\/assets\\/585534\\/9832014\\/bfb1b8f0-593b-11e5-8a27-fba472a5529a.png\"\n },\n \"docblockedFoundIn\": {\n \"message\": \"Filtr znajduje się na liście:\",\n \"description\": \"English: List of filter list names follows\"\n },\n \"docblockedBack\": {\n \"message\": \"Wstecz\",\n \"description\": \"English: Go back\"\n },\n \"docblockedClose\": {\n \"message\": \"Zamknij to okno\",\n \"description\": \"English: Close this window\"\n },\n \"docblockedProceed\": {\n \"message\": \"Wyłącz rygorystyczne blokowanie dla {{hostname}}\",\n \"description\": \"English: Disable strict blocking for {{hostname}} ...\"\n },\n \"docblockedDisableTemporary\": {\n \"message\": \"Tymczasowo\",\n \"description\": \"English: Temporarily\"\n },\n \"docblockedDisablePermanent\": {\n \"message\": \"Na stałe\",\n \"description\": \"English: Permanently\"\n },\n \"cloudPush\": {\n \"message\": \"Eksportuj do chmury\",\n \"description\": \"tooltip\"\n },\n \"cloudPull\": {\n \"message\": \"Importuj z chmury\",\n \"description\": \"tooltip\"\n },\n \"cloudPullAndMerge\": {\n \"message\": \"Importuj z chmury i połącz z aktualnymi ustawieniami\",\n \"description\": \"tooltip\"\n },\n \"cloudNoData\": {\n \"message\": \"...\\n...\",\n \"description\": \"\"\n },\n \"cloudDeviceNamePrompt\": {\n \"message\": \"Nazwa urządzenia:\",\n \"description\": \"used as a prompt for the user to provide a custom device name\"\n },\n \"advancedSettingsWarning\": {\n \"message\": \"Uwaga! Te ustawienia zmieniasz na własne ryzyko.\",\n \"description\": \"A warning to users at the top of 'Advanced settings' page\"\n },\n \"genericSubmit\": {\n \"message\": \"Wyślij\",\n \"description\": \"for generic 'Submit' buttons\"\n },\n \"genericApplyChanges\": {\n \"message\": \"Zastosuj zmiany\",\n \"description\": \"for generic 'Apply changes' buttons\"\n },\n \"genericRevert\": {\n \"message\": \"Przywróć\",\n \"description\": \"for generic 'Revert' buttons\"\n },\n \"genericBytes\": {\n \"message\": \"bajty\",\n \"description\": \"\"\n },\n \"contextMenuTemporarilyAllowLargeMediaElements\": {\n \"message\": \"Tymczasowo zezwalaj na wyświetlanie dużych elementów multimedialnych\",\n \"description\": \"A context menu entry, present when large media elements have been blocked on the current site\"\n },\n \"shortcutCapturePlaceholder\": {\n \"message\": \"Wprowadź skrót\",\n \"description\": \"Placeholder string for input field used to capture a keyboard shortcut\"\n },\n \"genericMergeViewScrollLock\": {\n \"message\": \"Przełącz przewijanie synchroniczne\",\n \"description\": \"Tooltip for the button used to lock scrolling between the views in the 'My rules' pane\"\n },\n \"genericCopyToClipboard\": {\n \"message\": \"Kopiuj do schowka\",\n \"description\": \"Label for buttons used to copy something to the clipboard\"\n },\n \"dummy\": {\n \"message\": \"Ten wpis musi być ostatni\",\n \"description\": \"so we dont need to deal with comma for last entry\"\n }\n}", "file_path": "src/_locales/pl/messages.json", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00018691901641432196, 0.000171188497915864, 0.00016301921277772635, 0.00017193150415550917, 3.608223323681159e-06]} {"hunk": {"id": 5, "code_window": [" for ( const node of toRemove ) {\n", " if ( this.hiddenNodes.has(node) ) { continue; }\n", " this.domFilterer.unhideNode(node);\n", " }\n", " //console.timeEnd('procedural selectors/dom layout changed');\n", " },\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 806}, "file": "#!/usr/bin/env bash\n#\n# This script assumes a linux environment\n\necho \"*** uBlock0.thunderbird: Creating web store package\"\necho \"*** uBlock0.thunderbird: Copying files\"\n\nBLDIR=dist/build\nDES=\"$BLDIR\"/uBlock0.thunderbird\nrm -rf $DES\nmkdir -p $DES\n\nbash ./tools/make-assets.sh $DES\n\ncp -R src/css $DES/\ncp -R src/img $DES/\ncp -R src/js $DES/\ncp -R src/lib $DES/\ncp -R src/_locales $DES/\ncp -R $DES/_locales/nb $DES/_locales/no\ncp src/*.html $DES/\ncp platform/chromium/*.js $DES/js/\ncp platform/chromium/*.html $DES/\ncp platform/chromium/*.json $DES/\ncp LICENSE.txt $DES/\n\ncp platform/thunderbird/manifest.json $DES/\ncp platform/thunderbird/vapi-webrequest.js $DES/js/\ncp platform/firefox/vapi-usercss.js $DES/js/\n\necho \"*** uBlock0.thunderbird: concatenating content scripts\"\ncat $DES/js/vapi-usercss.js > /tmp/contentscript.js\necho >> /tmp/contentscript.js\ngrep -v \"^'use strict';$\" $DES/js/vapi-usercss.real.js >> /tmp/contentscript.js\necho >> /tmp/contentscript.js\ngrep -v \"^'use strict';$\" $DES/js/contentscript.js >> /tmp/contentscript.js\nmv /tmp/contentscript.js $DES/js/contentscript.js\nrm $DES/js/vapi-usercss.js\nrm $DES/js/vapi-usercss.real.js\nrm $DES/js/vapi-usercss.pseudo.js\n\n# Firefox/webext-specific\nrm $DES/img/icon_128.png\n\necho \"*** uBlock0.thunderbird: Generating web accessible resources...\"\ncp -R src/web_accessible_resources $DES/\npython3 tools/import-war.py $DES/\n\necho \"*** uBlock0.thunderbird: Generating meta...\"\npython tools/make-firefox-meta.py $DES/\n\nif [ \"$1\" = all ]; then\n echo \"*** uBlock0.thunderbird: Creating package...\"\n pushd $DES > /dev/null\n zip ../$(basename $DES).xpi -qr *\n popd > /dev/null\nelif [ -n \"$1\" ]; then\n echo \"*** uBlock0.thunderbird: Creating versioned package...\"\n pushd $DES > /dev/null\n zip ../$(basename $DES).xpi -qr *\n popd > /dev/null\n mv \"$BLDIR\"/uBlock0.thunderbird.xpi \"$BLDIR\"/uBlock0_\"$1\".thunderbird.xpi\nfi\n\necho \"*** uBlock0.thunderbird: Package done.\"\n", "file_path": "tools/make-thunderbird.sh", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017751699488144368, 0.0001746072230162099, 0.00016899450565688312, 0.0001755057746777311, 2.6166064799326705e-06]} {"hunk": {"id": 6, "code_window": ["\n", " createProceduralFilter: function(o) {\n", " return new PSelector(o);\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" createProceduralFilter(o) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 808}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9980183839797974, 0.029850276187062263, 0.00016132152813952416, 0.00017008779104799032, 0.15776270627975464]} {"hunk": {"id": 6, "code_window": ["\n", " createProceduralFilter: function(o) {\n", " return new PSelector(o);\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" createProceduralFilter(o) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 808}, "file": "Un blocant (paravan) eficient: folosește foarte puțin procesorul și memoria și totuși poate încărca și aplica mii de filtre în plus față de alte paravane populare.\n\nO ilustrare a eficienței poate fi observată la:\nhttps://github.com/gorhill/uBlock/wiki/uBlock-vs.-ABP:-efficiency-compared\n\nUtilizare: Butonul mare de pornire/oprire în fereastra paravanului este pentru a activa/dezactiva uBlock pentru saitul curent. Funcția este valabilă doar pentru saitul curent, nu la nivel global.\n\n***\n\nFlexibil, mai mult decât un „blocant de reclame”: acesta poate citi și crea filtre din fișierele de gazde (hosts).\n\nÎn mod implicit, aceste liste de filtre sunt încărcate și aplicate:\n\n- EasyList\n- Lista serverelor de reclame a lui Peter Lowe\n- EasyPrivacy\n- Domenii malițioase\n\nDe asemenea, mai sunt disponibile și alte liste precum:\n\n- Lista îmbunătățită pentru urmărire a lui Fanboy\n- Lista de gazde a lui Dan Pollock\n- Lista de reclame și urmărire hpHosts\n- Gazdele MVPS\n- Spam404\n- Și multe altele\n\nDesigur, cu cât sunt mai multe filtre active cu atât mai mult este utilizată memoria. Totuși, chiar și după adăugarea în plus a două liste Fanboy și lista de reclame și urmărire hPhosts, uBlock₀ tot folosește mai puțină memorie decât restul paravanelor.\n\nDe ținut minte, că odată cu selectarea în plus a unora dintre liste se poate ajunge la afectarea aspectului saiturilor -- în special listele care sunt în mod normal liste de gazde.\n\n***\n\nFără listele prestabilite de filtre această extensie nu face nimic. Așadar, dacă totuși vreți să contribuiți, gândiți-vă la persoanele care muncesc să întrețină aceste filtre pe care le utilizați, care sunt oferite pentru utilizare gratuită.\n\n***\n\nGratuit.\nCu sursă liberă și licență publică (GPLv3)\nPentru utilizatori de la utilizatori.\n\nContribuitori pe Github: https://github.com/gorhill/uBlock/graphs/contributors\nContribuitori pe Crowdin: https://crowdin.net/project/ublock\n\n***\n\nEste încă o aplicație recentă, gândiți-vă la acest lucru când scrieți o recenzie.\n\nLista de schimbări a proiectului:\nhttps://github.com/gorhill/uBlock/releases\n", "file_path": "dist/description/description-ro.txt", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00018118089064955711, 0.00017085274157579988, 0.0001664542651269585, 0.0001682588190305978, 5.2915520427632146e-06]} {"hunk": {"id": 6, "code_window": ["\n", " createProceduralFilter: function(o) {\n", " return new PSelector(o);\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" createProceduralFilter(o) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 808}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2017-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n/* global punycode */\n\n'use strict';\n\n/*******************************************************************************\n\n All static extended filters are of the form:\n\n field 1: one hostname, or a list of comma-separated hostnames\n field 2: `##` or `#@#`\n field 3: selector\n\n The purpose of the static extended filtering engine is to coarse-parse and\n dispatch to appropriate specialized filtering engines. There are currently\n three specialized filtering engines:\n\n - cosmetic filtering (aka \"element hiding\" in Adblock Plus)\n - scriptlet injection: selector starts with `script:inject`\n - New shorter syntax (1.15.12): `example.com##+js(bab-defuser.js)`\n - html filtering: selector starts with `^`\n\n Depending on the specialized filtering engine, field 1 may or may not be\n optional.\n\n The static extended filtering engine also offers parsing capabilities which\n are available to all other specialized fitlering engines. For example,\n cosmetic and html filtering can ask the extended filtering engine to\n compile/validate selectors.\n\n**/\n\nµBlock.staticExtFilteringEngine = (function() {\n const µb = µBlock;\n const reHasUnicode = /[^\\x00-\\x7F]/;\n const reParseRegexLiteral = /^\\/(.+)\\/([imu]+)?$/;\n const emptyArray = [];\n const parsed = {\n hostnames: [],\n exception: false,\n suffix: ''\n };\n\n // To be called to ensure no big parent string of a string slice is\n // left into memory after parsing filter lists is over.\n const resetParsed = function() {\n parsed.hostnames = [];\n parsed.suffix = '';\n };\n\n const isValidCSSSelector = (function() {\n var div = document.createElement('div'),\n matchesFn;\n // Keep in mind:\n // https://github.com/gorhill/uBlock/issues/693\n // https://github.com/gorhill/uBlock/issues/1955\n if ( div.matches instanceof Function ) {\n matchesFn = div.matches.bind(div);\n } else if ( div.mozMatchesSelector instanceof Function ) {\n matchesFn = div.mozMatchesSelector.bind(div);\n } else if ( div.webkitMatchesSelector instanceof Function ) {\n matchesFn = div.webkitMatchesSelector.bind(div);\n } else if ( div.msMatchesSelector instanceof Function ) {\n matchesFn = div.msMatchesSelector.bind(div);\n } else {\n matchesFn = div.querySelector.bind(div);\n }\n // https://github.com/gorhill/uBlock/issues/3111\n // Workaround until https://bugzilla.mozilla.org/show_bug.cgi?id=1406817\n // is fixed.\n try {\n matchesFn(':scope');\n } catch (ex) {\n matchesFn = div.querySelector.bind(div);\n }\n // Quick regex-based validation -- most cosmetic filters are of the\n // simple form and in such case a regex is much faster.\n var reSimple = /^[#.][\\w-]+$/;\n return function(s) {\n if ( reSimple.test(s) ) { return true; }\n try {\n matchesFn(s + ', ' + s + ':not(#foo)');\n } catch (ex) {\n return false;\n }\n return true;\n };\n })();\n\n\n const isBadRegex = function(s) {\n try {\n void new RegExp(s);\n } catch (ex) {\n isBadRegex.message = ex.toString();\n return true;\n }\n return false;\n };\n\n const translateAdguardCSSInjectionFilter = function(suffix) {\n const matches = /^([^{]+)\\{([^}]+)\\}$/.exec(suffix);\n if ( matches === null ) { return ''; }\n const selector = matches[1].trim();\n const style = matches[2].trim();\n // For some reasons, many of Adguard's plain cosmetic filters are\n // \"disguised\" as style-based cosmetic filters: convert such filters\n // to plain cosmetic filters.\n return /display\\s*:\\s*none\\s*!important;?$/.test(style)\n ? selector\n : selector + ':style(' + style + ')';\n };\n\n const hostnamesFromPrefix = function(s) {\n const hostnames = [];\n const hasUnicode = reHasUnicode.test(s);\n let beg = 0;\n while ( beg < s.length ) {\n let end = s.indexOf(',', beg);\n if ( end === -1 ) { end = s.length; }\n let hostname = s.slice(beg, end).trim();\n if ( hostname.length !== 0 ) {\n if ( hasUnicode ) {\n hostname = hostname.charCodeAt(0) === 0x7E /* '~' */\n ? '~' + punycode.toASCII(hostname.slice(1))\n : punycode.toASCII(hostname);\n }\n hostnames.push(hostname);\n }\n beg = end + 1;\n }\n return hostnames;\n };\n\n const compileProceduralSelector = (function() {\n const reProceduralOperator = new RegExp([\n '^(?:',\n [\n '-abp-contains',\n '-abp-has',\n 'contains',\n 'has',\n 'has-text',\n 'if',\n 'if-not',\n 'matches-css',\n 'matches-css-after',\n 'matches-css-before',\n 'not',\n 'nth-ancestor',\n 'watch-attrs',\n 'xpath'\n ].join('|'),\n ')\\\\('\n ].join(''));\n\n const reEatBackslashes = /\\\\([()])/g;\n const reEscapeRegex = /[.*+?^${}()|[\\]\\\\]/g;\n const reNeedScope = /^\\s*[+>~]/;\n const reIsDanglingSelector = /(?:[+>~]\\s*|\\s+)$/;\n\n const regexToRawValue = new Map();\n let lastProceduralSelector = '',\n lastProceduralSelectorCompiled;\n\n // When dealing with literal text, we must first eat _some_\n // backslash characters.\n const compileText = function(s) {\n const match = reParseRegexLiteral.exec(s);\n let regexDetails;\n if ( match !== null ) {\n regexDetails = match[1];\n if ( isBadRegex(regexDetails) ) { return; }\n if ( match[2] ) {\n regexDetails = [ regexDetails, match[2] ];\n }\n } else {\n regexDetails = s.replace(reEatBackslashes, '$1')\n .replace(reEscapeRegex, '\\\\$&');\n regexToRawValue.set(regexDetails, s);\n }\n return regexDetails;\n };\n\n const compileCSSDeclaration = function(s) {\n const pos = s.indexOf(':');\n if ( pos === -1 ) { return; }\n const name = s.slice(0, pos).trim();\n const value = s.slice(pos + 1).trim();\n const match = reParseRegexLiteral.exec(value);\n let regexDetails;\n if ( match !== null ) {\n regexDetails = match[1];\n if ( isBadRegex(regexDetails) ) { return; }\n if ( match[2] ) {\n regexDetails = [ regexDetails, match[2] ];\n }\n } else {\n regexDetails = '^' + value.replace(reEscapeRegex, '\\\\$&') + '$';\n regexToRawValue.set(regexDetails, value);\n }\n return { name: name, value: regexDetails };\n };\n\n const compileConditionalSelector = function(s) {\n // https://github.com/AdguardTeam/ExtendedCss/issues/31#issuecomment-302391277\n // Prepend `:scope ` if needed.\n if ( reNeedScope.test(s) ) {\n s = ':scope ' + s;\n }\n return compile(s);\n };\n\n const compileNotSelector = function(s) {\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341#issuecomment-447603588\n // Reject instances of :not() filters for which the argument is\n // a valid CSS selector, otherwise we would be adversely\n // changing the behavior of CSS4's :not().\n if ( isValidCSSSelector(s) === false ) {\n return compileConditionalSelector(s);\n }\n };\n\n const compileNthAncestorSelector = function(s) {\n const n = parseInt(s, 10);\n if ( isNaN(n) === false && n >= 1 && n < 256 ) {\n return n;\n }\n };\n\n const compileSpathExpression = function(s) {\n if ( isValidCSSSelector('*' + s) ) {\n return s;\n }\n };\n\n const compileAttrList = function(s) {\n const attrs = s.split('\\s*,\\s*');\n const out = [];\n for ( const attr of attrs ) {\n if ( attr !== '' ) {\n out.push(attr);\n }\n }\n return out;\n };\n\n const compileXpathExpression = function(s) {\n try {\n document.createExpression(s, null);\n } catch (e) {\n return;\n }\n return s;\n };\n\n // https://github.com/gorhill/uBlock/issues/2793\n const normalizedOperators = new Map([\n [ ':-abp-contains', ':has-text' ],\n [ ':-abp-has', ':has' ],\n [ ':contains', ':has-text' ],\n ]);\n\n const compileArgument = new Map([\n [ ':has', compileConditionalSelector ],\n [ ':has-text', compileText ],\n [ ':if', compileConditionalSelector ],\n [ ':if-not', compileConditionalSelector ],\n [ ':matches-css', compileCSSDeclaration ],\n [ ':matches-css-after', compileCSSDeclaration ],\n [ ':matches-css-before', compileCSSDeclaration ],\n [ ':not', compileNotSelector ],\n [ ':nth-ancestor', compileNthAncestorSelector ],\n [ ':spath', compileSpathExpression ],\n [ ':watch-attrs', compileAttrList ],\n [ ':xpath', compileXpathExpression ]\n ]);\n\n // https://github.com/gorhill/uBlock/issues/2793#issuecomment-333269387\n // Normalize (somewhat) the stringified version of procedural\n // cosmetic filters -- this increase the likelihood of detecting\n // duplicates given that uBO is able to understand syntax specific\n // to other blockers.\n // The normalized string version is what is reported in the logger,\n // by design.\n const decompile = function(compiled) {\n const tasks = compiled.tasks;\n if ( Array.isArray(tasks) === false ) {\n return compiled.selector;\n }\n const raw = [ compiled.selector ];\n let value;\n for ( const task of tasks ) {\n switch ( task[0] ) {\n case ':has':\n case ':if':\n raw.push(`:has(${decompile(task[1])})`);\n break;\n case ':has-text':\n if ( Array.isArray(task[1]) ) {\n value = `/${task[1][0]}/${task[1][1]}`;\n } else {\n value = regexToRawValue.get(task[1]);\n if ( value === undefined ) {\n value = `/${task[1]}/`;\n }\n }\n raw.push(`:has-text(${value})`);\n break;\n case ':matches-css':\n case ':matches-css-after':\n case ':matches-css-before':\n if ( Array.isArray(task[1].value) ) {\n value = `/${task[1].value[0]}/${task[1].value[1]}`;\n } else {\n value = regexToRawValue.get(task[1].value);\n if ( value === undefined ) {\n value = `/${task[1].value}/`;\n }\n }\n raw.push(`${task[0]}(${task[1].name}: ${value})`);\n break;\n case ':not':\n case ':if-not':\n raw.push(`:not(${decompile(task[1])})`);\n break;\n case ':nth-ancestor':\n raw.push(`:nth-ancestor(${task[1]})`);\n break;\n case ':spath':\n raw.push(task[1]);\n break;\n case ':watch-attrs':\n case ':xpath':\n raw.push(`${task[0]}(${task[1]})`);\n break;\n }\n }\n return raw.join('');\n };\n\n const compile = function(raw) {\n if ( raw === '' ) { return; }\n let prefix = '',\n tasks = [];\n let i = 0,\n n = raw.length,\n opPrefixBeg = 0;\n for (;;) {\n let c, match;\n // Advance to next operator.\n while ( i < n ) {\n c = raw.charCodeAt(i++);\n if ( c === 0x3A /* ':' */ ) {\n match = reProceduralOperator.exec(raw.slice(i));\n if ( match !== null ) { break; }\n }\n }\n if ( i === n ) { break; }\n const opNameBeg = i - 1;\n const opNameEnd = i + match[0].length - 1;\n i += match[0].length;\n // Find end of argument: first balanced closing parenthesis.\n // Note: unbalanced parenthesis can be used in a regex literal\n // when they are escaped using `\\`.\n // TODO: need to handle quoted parentheses.\n let pcnt = 1;\n while ( i < n ) {\n c = raw.charCodeAt(i++);\n if ( c === 0x5C /* '\\\\' */ ) {\n if ( i < n ) { i += 1; }\n } else if ( c === 0x28 /* '(' */ ) {\n pcnt +=1 ;\n } else if ( c === 0x29 /* ')' */ ) {\n pcnt -= 1;\n if ( pcnt === 0 ) { break; }\n }\n }\n // Unbalanced parenthesis? An unbalanced parenthesis is fine\n // as long as the last character is a closing parenthesis.\n if ( pcnt !== 0 && c !== 0x29 ) { return; }\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341#issuecomment-447603588\n // Maybe that one operator is a valid CSS selector and if so,\n // then consider it to be part of the prefix. If there is\n // at least one task present, then we fail, as we do not\n // support suffix CSS selectors.\n if ( isValidCSSSelector(raw.slice(opNameBeg, i)) ) { continue; }\n // Extract and remember operator details.\n let operator = raw.slice(opNameBeg, opNameEnd);\n operator = normalizedOperators.get(operator) || operator;\n let args = raw.slice(opNameEnd + 1, i - 1);\n args = compileArgument.get(operator)(args);\n if ( args === undefined ) { return; }\n if ( opPrefixBeg === 0 ) {\n prefix = raw.slice(0, opNameBeg);\n } else if ( opNameBeg !== opPrefixBeg ) {\n const spath = compileSpathExpression(\n raw.slice(opPrefixBeg, opNameBeg)\n );\n if ( spath === undefined ) { return; }\n tasks.push([ ':spath', spath ]);\n }\n tasks.push([ operator, args ]);\n opPrefixBeg = i;\n if ( i === n ) { break; }\n }\n // No task found: then we have a CSS selector.\n // At least one task found: nothing should be left to parse.\n if ( tasks.length === 0 ) {\n prefix = raw;\n tasks = undefined;\n } else if ( opPrefixBeg < n ) {\n const spath = compileSpathExpression(raw.slice(opPrefixBeg));\n if ( spath === undefined ) { return; }\n tasks.push([ ':spath', spath ]);\n }\n // https://github.com/NanoAdblocker/NanoCore/issues/1#issuecomment-354394894\n if ( prefix !== '' ) {\n if ( reIsDanglingSelector.test(prefix) ) { prefix += '*'; }\n if ( isValidCSSSelector(prefix) === false ) { return; }\n }\n return { selector: prefix, tasks: tasks };\n };\n\n const entryPoint = function(raw) {\n if ( raw === lastProceduralSelector ) {\n return lastProceduralSelectorCompiled;\n }\n lastProceduralSelector = raw;\n let compiled = compile(raw);\n if ( compiled !== undefined ) {\n compiled.raw = decompile(compiled);\n compiled = JSON.stringify(compiled);\n }\n lastProceduralSelectorCompiled = compiled;\n return compiled;\n };\n\n entryPoint.reset = function() {\n regexToRawValue.clear();\n lastProceduralSelector = '';\n lastProceduralSelectorCompiled = undefined;\n };\n\n return entryPoint;\n })();\n\n //--------------------------------------------------------------------------\n // Public API\n //--------------------------------------------------------------------------\n\n const api = {\n get acceptedCount() {\n return µb.cosmeticFilteringEngine.acceptedCount +\n µb.scriptletFilteringEngine.acceptedCount +\n µb.htmlFilteringEngine.acceptedCount;\n },\n get discardedCount() {\n return µb.cosmeticFilteringEngine.discardedCount +\n µb.scriptletFilteringEngine.discardedCount +\n µb.htmlFilteringEngine.discardedCount;\n },\n };\n\n //--------------------------------------------------------------------------\n // Public classes\n //--------------------------------------------------------------------------\n\n api.HostnameBasedDB = class {\n\n constructor(nBits, selfie = undefined) {\n this.nBits = nBits;\n this.timer = undefined;\n this.strToIdMap = new Map();\n if ( selfie !== undefined ) {\n this.fromSelfie(selfie);\n return;\n }\n this.hostnameToSlotIdMap = new Map();\n this.hostnameSlots = [];\n this.strSlots = [];\n this.size = 0;\n }\n\n store(hn, bits, s) {\n this.size += 1;\n let iStr = this.strToIdMap.get(s);\n if ( iStr === undefined ) {\n iStr = this.strSlots.length;\n this.strSlots.push(s);\n this.strToIdMap.set(s, iStr);\n if ( this.timer === undefined ) {\n this.collectGarbage(true);\n }\n }\n const strId = iStr << this.nBits | bits;\n const iHn = this.hostnameToSlotIdMap.get(hn);\n if ( iHn === undefined ) {\n this.hostnameToSlotIdMap.set(hn, this.hostnameSlots.length);\n this.hostnameSlots.push(strId);\n return;\n }\n const bucket = this.hostnameSlots[iHn];\n if ( Array.isArray(bucket) ) {\n bucket.push(strId);\n } else {\n this.hostnameSlots[iHn] = [ bucket, strId ];\n }\n }\n\n clear() {\n this.hostnameToSlotIdMap.clear();\n this.hostnameSlots.length = 0;\n this.strSlots.length = 0;\n this.strToIdMap.clear();\n this.size = 0;\n }\n\n collectGarbage(async = false) {\n if ( async === false ) {\n if ( this.timer !== undefined ) {\n self.cancelIdleCallback(this.timer);\n this.timer = undefined;\n }\n this.strToIdMap.clear();\n return;\n }\n if ( this.timer !== undefined ) { return; }\n this.timer = self.requestIdleCallback(\n ( ) => {\n this.timer = undefined;\n this.strToIdMap.clear();\n },\n { timeout: 10000 }\n );\n }\n\n retrieve(hostname, out) {\n const mask = out.length - 1; // out.length must be power of two\n for (;;) {\n const filterId = this.hostnameToSlotIdMap.get(hostname);\n if ( filterId !== undefined ) {\n const bucket = this.hostnameSlots[filterId];\n if ( Array.isArray(bucket) ) {\n for ( const id of bucket ) {\n out[id & mask].add(this.strSlots[id >>> this.nBits]);\n }\n } else {\n out[bucket & mask].add(this.strSlots[bucket >>> this.nBits]);\n }\n }\n if ( hostname === '' ) { break; }\n const pos = hostname.indexOf('.');\n hostname = pos !== -1 ? hostname.slice(pos + 1) : '';\n }\n }\n\n toSelfie() {\n return {\n hostnameToSlotIdMap: Array.from(this.hostnameToSlotIdMap),\n hostnameSlots: this.hostnameSlots,\n strSlots: this.strSlots,\n size: this.size\n };\n }\n\n fromSelfie(selfie) {\n this.hostnameToSlotIdMap = new Map(selfie.hostnameToSlotIdMap);\n this.hostnameSlots = selfie.hostnameSlots;\n this.strSlots = selfie.strSlots;\n this.size = selfie.size;\n }\n };\n\n //--------------------------------------------------------------------------\n // Public methods\n //--------------------------------------------------------------------------\n\n api.reset = function() {\n compileProceduralSelector.reset();\n µb.cosmeticFilteringEngine.reset();\n µb.scriptletFilteringEngine.reset();\n µb.htmlFilteringEngine.reset();\n resetParsed(parsed);\n };\n\n api.freeze = function() {\n compileProceduralSelector.reset();\n µb.cosmeticFilteringEngine.freeze();\n µb.scriptletFilteringEngine.freeze();\n µb.htmlFilteringEngine.freeze();\n resetParsed(parsed);\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/1004\n // Detect and report invalid CSS selectors.\n\n // Discard new ABP's `-abp-properties` directive until it is\n // implemented (if ever). Unlikely, see:\n // https://github.com/gorhill/uBlock/issues/1752\n\n // https://github.com/gorhill/uBlock/issues/2624\n // Convert Adguard's `-ext-has='...'` into uBO's `:has(...)`.\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/89\n // Do not discard unknown pseudo-elements.\n\n api.compileSelector = (function() {\n const reAfterBeforeSelector = /^(.+?)(::?after|::?before|::[a-z-]+)$/;\n const reStyleSelector = /^(.+?):style\\((.+?)\\)$/;\n const reStyleBad = /url\\(/;\n const reExtendedSyntax = /\\[-(?:abp|ext)-[a-z-]+=(['\"])(?:.+?)(?:\\1)\\]/;\n const reExtendedSyntaxParser = /\\[-(?:abp|ext)-([a-z-]+)=(['\"])(.+?)\\2\\]/;\n const div = document.createElement('div');\n\n const normalizedExtendedSyntaxOperators = new Map([\n [ 'contains', ':has-text' ],\n [ 'has', ':has' ],\n [ 'matches-css', ':matches-css' ],\n [ 'matches-css-after', ':matches-css-after' ],\n [ 'matches-css-before', ':matches-css-before' ],\n ]);\n\n const isValidStyleProperty = function(cssText) {\n if ( reStyleBad.test(cssText) ) { return false; }\n div.style.cssText = cssText;\n if ( div.style.cssText === '' ) { return false; }\n div.style.cssText = '';\n return true;\n };\n\n const entryPoint = function(raw) {\n entryPoint.pseudoclass = false;\n\n const extendedSyntax = reExtendedSyntax.test(raw);\n if ( isValidCSSSelector(raw) && extendedSyntax === false ) {\n return raw;\n }\n\n // We rarely reach this point -- majority of selectors are plain\n // CSS selectors.\n\n let matches;\n\n // Supported Adguard/ABP advanced selector syntax: will translate\n // into uBO's syntax before further processing.\n // Mind unsupported advanced selector syntax, such as ABP's\n // `-abp-properties`.\n // Note: extended selector syntax has been deprecated in ABP, in\n // favor of the procedural one (i.e. `:operator(...)`).\n // See https://issues.adblockplus.org/ticket/5287\n if ( extendedSyntax ) {\n while ( (matches = reExtendedSyntaxParser.exec(raw)) !== null ) {\n const operator = normalizedExtendedSyntaxOperators.get(matches[1]);\n if ( operator === undefined ) { return; }\n raw = raw.slice(0, matches.index) +\n operator + '(' + matches[3] + ')' +\n raw.slice(matches.index + matches[0].length);\n }\n return entryPoint(raw);\n }\n\n let selector = raw, pseudoclass, style;\n\n // `:style` selector?\n if ( (matches = reStyleSelector.exec(selector)) !== null ) {\n selector = matches[1];\n style = matches[2];\n }\n\n // https://github.com/gorhill/uBlock/issues/2448\n // :after- or :before-based selector?\n if ( (matches = reAfterBeforeSelector.exec(selector)) ) {\n selector = matches[1];\n pseudoclass = matches[2];\n }\n\n if ( style !== undefined || pseudoclass !== undefined ) {\n if ( isValidCSSSelector(selector) === false ) { return; }\n if ( pseudoclass !== undefined ) {\n selector += pseudoclass;\n }\n if ( style !== undefined ) {\n if ( isValidStyleProperty(style) === false ) { return; }\n return JSON.stringify({ raw, style: [ selector, style ] });\n }\n entryPoint.pseudoclass = true;\n return JSON.stringify({ raw, pseudoclass: true });\n }\n\n // Procedural selector?\n let compiled;\n if ( (compiled = compileProceduralSelector(raw)) ) {\n return compiled;\n }\n };\n\n entryPoint.pseudoclass = false;\n\n return entryPoint;\n })();\n\n api.compile = function(raw, writer) {\n let lpos = raw.indexOf('#');\n if ( lpos === -1 ) { return false; }\n let rpos = lpos + 1;\n if ( raw.charCodeAt(rpos) !== 0x23 /* '#' */ ) {\n rpos = raw.indexOf('#', rpos + 1);\n if ( rpos === -1 ) { return false; }\n }\n\n // https://github.com/AdguardTeam/AdguardFilters/commit/4fe02d73cee6\n // AdGuard also uses `$?` to force inline-based style rather than\n // stylesheet-based style.\n // Coarse-check that the anchor is valid.\n // `##`: l === 1\n // `#@#`, `#$#`, `#%#`, `#?#`: l === 2\n // `#@$#`, `#@%#`, `#@?#`, `#$?#`: l === 3\n // `#@$?#`: l === 4\n const anchorLen = rpos - lpos;\n if ( anchorLen > 4 ) { return false; }\n if (\n anchorLen > 1 &&\n /^@?(?:\\$\\??|%|\\?)?$/.test(raw.slice(lpos + 1, rpos)) === false\n ) {\n return false;\n }\n\n // Extract the selector.\n let suffix = raw.slice(rpos + 1).trim();\n if ( suffix.length === 0 ) { return false; }\n parsed.suffix = suffix;\n\n // https://github.com/gorhill/uBlock/issues/952\n // Find out whether we are dealing with an Adguard-specific cosmetic\n // filter, and if so, translate it if supported, or discard it if not\n // supported.\n // We have an Adguard/ABP cosmetic filter if and only if the\n // character is `$`, `%` or `?`, otherwise it's not a cosmetic\n // filter.\n let cCode = raw.charCodeAt(rpos - 1);\n if ( cCode !== 0x23 /* '#' */ && cCode !== 0x40 /* '@' */ ) {\n // Adguard's scriptlet injection: not supported.\n if ( cCode === 0x25 /* '%' */ ) { return true; }\n if ( cCode === 0x3F /* '?' */ && anchorLen > 2 ) {\n cCode = raw.charCodeAt(rpos - 2);\n }\n // Adguard's style injection: translate to uBO's format.\n if ( cCode === 0x24 /* '$' */ ) {\n suffix = translateAdguardCSSInjectionFilter(suffix);\n if ( suffix === '' ) { return true; }\n parsed.suffix = suffix;\n }\n }\n\n // Exception filter?\n parsed.exception = raw.charCodeAt(lpos + 1) === 0x40 /* '@' */;\n\n // Extract the hostname(s), punycode if required.\n if ( lpos === 0 ) {\n parsed.hostnames = emptyArray;\n } else {\n parsed.hostnames = hostnamesFromPrefix(raw.slice(0, lpos));\n }\n\n // Backward compatibility with deprecated syntax.\n if ( suffix.startsWith('script:') ) {\n if ( suffix.startsWith('script:inject') ) {\n suffix = parsed.suffix = '+js' + suffix.slice(13);\n } else if ( suffix.startsWith('script:contains') ) {\n suffix = parsed.suffix = '^script:has-text' + suffix.slice(15);\n }\n }\n\n let c0 = suffix.charCodeAt(0);\n\n // New shorter syntax for scriptlet injection engine.\n if ( c0 === 0x2B /* '+' */ && suffix.startsWith('+js') ) {\n µb.scriptletFilteringEngine.compile(parsed, writer);\n return true;\n }\n\n // HTML filtering engine.\n // TODO: evaluate converting Adguard's `$$` syntax into uBO's HTML\n // filtering syntax.\n if ( c0 === 0x5E /* '^' */ ) {\n µb.htmlFilteringEngine.compile(parsed, writer);\n return true;\n }\n\n // Cosmetic filtering engine.\n µb.cosmeticFilteringEngine.compile(parsed, writer);\n return true;\n };\n\n api.fromCompiledContent = function(reader, options) {\n µb.cosmeticFilteringEngine.fromCompiledContent(reader, options);\n µb.scriptletFilteringEngine.fromCompiledContent(reader, options);\n µb.htmlFilteringEngine.fromCompiledContent(reader, options);\n };\n\n api.toSelfie = function(path) {\n return µBlock.assets.put(\n `${path}/main`,\n JSON.stringify({\n cosmetic: µb.cosmeticFilteringEngine.toSelfie(),\n scriptlets: µb.scriptletFilteringEngine.toSelfie(),\n html: µb.htmlFilteringEngine.toSelfie()\n })\n );\n };\n\n api.fromSelfie = function(path) {\n return µBlock.assets.get(`${path}/main`).then(details => {\n let selfie;\n try {\n selfie = JSON.parse(details.content);\n } catch (ex) {\n }\n if ( selfie instanceof Object === false ) { return false; }\n µb.cosmeticFilteringEngine.fromSelfie(selfie.cosmetic);\n µb.scriptletFilteringEngine.fromSelfie(selfie.scriptlets);\n µb.htmlFilteringEngine.fromSelfie(selfie.html);\n return true;\n });\n };\n\n return api;\n})();\n\n/******************************************************************************/\n", "file_path": "src/js/static-ext-filtering.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.02506755106151104, 0.0007755689439363778, 0.00016195019998122007, 0.0001703442248981446, 0.003063891315832734]} {"hunk": {"id": 6, "code_window": ["\n", " createProceduralFilter: function(o) {\n", " return new PSelector(o);\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" createProceduralFilter(o) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 808}, "file": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n

\n

\n

\n  \n

\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "src/advanced-settings.html", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017202104208990932, 0.00016883852367755026, 0.00016679569671396166, 0.00016826868522912264, 2.161114025511779e-06]} {"hunk": {"id": 7, "code_window": [" return new PSelector(o);\n", " },\n", "\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 810}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9830212593078613, 0.01867961324751377, 0.00016319824499078095, 0.00017075387586373836, 0.12163783609867096]} {"hunk": {"id": 7, "code_window": [" return new PSelector(o);\n", " },\n", "\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 810}, "file": "// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n CodeMirror.defineExtension(\"annotateScrollbar\", function(options) {\n if (typeof options == \"string\") options = {className: options};\n return new Annotation(this, options);\n });\n\n CodeMirror.defineOption(\"scrollButtonHeight\", 0);\n\n function Annotation(cm, options) {\n this.cm = cm;\n this.options = options;\n this.buttonHeight = options.scrollButtonHeight || cm.getOption(\"scrollButtonHeight\");\n this.annotations = [];\n this.doRedraw = this.doUpdate = null;\n this.div = cm.getWrapperElement().appendChild(document.createElement(\"div\"));\n this.div.style.cssText = \"position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none\";\n this.computeScale();\n\n function scheduleRedraw(delay) {\n clearTimeout(self.doRedraw);\n self.doRedraw = setTimeout(function() { self.redraw(); }, delay);\n }\n\n var self = this;\n cm.on(\"refresh\", this.resizeHandler = function() {\n clearTimeout(self.doUpdate);\n self.doUpdate = setTimeout(function() {\n if (self.computeScale()) scheduleRedraw(20);\n }, 100);\n });\n cm.on(\"markerAdded\", this.resizeHandler);\n cm.on(\"markerCleared\", this.resizeHandler);\n if (options.listenForChanges !== false)\n cm.on(\"change\", this.changeHandler = function() {\n scheduleRedraw(250);\n });\n }\n\n Annotation.prototype.computeScale = function() {\n var cm = this.cm;\n var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) /\n cm.getScrollerElement().scrollHeight\n if (hScale != this.hScale) {\n this.hScale = hScale;\n return true;\n }\n };\n\n Annotation.prototype.update = function(annotations) {\n this.annotations = annotations;\n this.redraw();\n };\n\n Annotation.prototype.redraw = function(compute) {\n if (compute !== false) this.computeScale();\n var cm = this.cm, hScale = this.hScale;\n\n var frag = document.createDocumentFragment(), anns = this.annotations;\n\n var wrapping = cm.getOption(\"lineWrapping\");\n var singleLineH = wrapping && cm.defaultTextHeight() * 1.5;\n var curLine = null, curLineObj = null;\n function getY(pos, top) {\n if (curLine != pos.line) {\n curLine = pos.line;\n curLineObj = cm.getLineHandle(curLine);\n }\n if ((curLineObj.widgets && curLineObj.widgets.length) ||\n (wrapping && curLineObj.height > singleLineH))\n return cm.charCoords(pos, \"local\")[top ? \"top\" : \"bottom\"];\n var topY = cm.heightAtLine(curLineObj, \"local\");\n return topY + (top ? 0 : curLineObj.height);\n }\n\n var lastLine = cm.lastLine()\n if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) {\n var ann = anns[i];\n if (ann.to.line > lastLine) continue;\n var top = nextTop || getY(ann.from, true) * hScale;\n var bottom = getY(ann.to, false) * hScale;\n while (i < anns.length - 1) {\n if (anns[i + 1].to.line > lastLine) break;\n nextTop = getY(anns[i + 1].from, true) * hScale;\n if (nextTop > bottom + .9) break;\n ann = anns[++i];\n bottom = getY(ann.to, false) * hScale;\n }\n if (bottom == top) continue;\n var height = Math.max(bottom - top, 3);\n\n var elt = frag.appendChild(document.createElement(\"div\"));\n elt.style.cssText = \"position: absolute; right: 0px; width: \" + Math.max(cm.display.barWidth - 1, 2) + \"px; top: \"\n + (top + this.buttonHeight) + \"px; height: \" + height + \"px\";\n elt.className = this.options.className;\n if (ann.id) {\n elt.setAttribute(\"annotation-id\", ann.id);\n }\n }\n this.div.textContent = \"\";\n this.div.appendChild(frag);\n };\n\n Annotation.prototype.clear = function() {\n this.cm.off(\"refresh\", this.resizeHandler);\n this.cm.off(\"markerAdded\", this.resizeHandler);\n this.cm.off(\"markerCleared\", this.resizeHandler);\n if (this.changeHandler) this.cm.off(\"change\", this.changeHandler);\n this.div.parentNode.removeChild(this.div);\n };\n});\n", "file_path": "src/lib/codemirror/addon/scroll/annotatescrollbar.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017765024676918983, 0.00017151398060377687, 0.00016609689919278026, 0.0001720408909022808, 2.9620196073665284e-06]} {"hunk": {"id": 7, "code_window": [" return new PSelector(o);\n", " },\n", "\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 810}, "file": "#!/usr/bin/env bash\n#\n# This script assumes an OS X or *NIX environment\n\necho \"*** uBlock.safariextension: Copying files...\"\n\nDES=dist/build/uBlock.safariextension\nrm -rf $DES\nmkdir -p $DES\n\ncp -R assets $DES/\nrm $DES/assets/*.sh\ncp -R src/css $DES/\ncp -R src/img $DES/\ncp -R src/js $DES/\ncp -R src/lib $DES/\ncp -R src/_locales $DES/\ncp src/*.html $DES/\nmv $DES/img/icon_128.png $DES/Icon.png\ncp platform/safari/*.js $DES/js/\ncp -R platform/safari/img $DES/\ncp platform/safari/Info.plist $DES/\ncp platform/safari/Settings.plist $DES/\ncp LICENSE.txt $DES/\n\necho \"*** uBlock.safariextension: Generating Info.plist...\"\npython tools/make-safari-meta.py $DES/\n\nif [ \"$1\" = all ]; then\n echo \"*** Use Safari's Extension Builder to create the signed uBlock extension package -- can't automate it.\"\nfi\n\necho \"*** uBlock.safariextension: Done.\"\n", "file_path": "tools/make-safari.sh", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017642724560573697, 0.0001693811937002465, 0.00016410546959377825, 0.00016849602980073541, 5.244196927378653e-06]} {"hunk": {"id": 7, "code_window": [" return new PSelector(o);\n", " },\n", "\n"], "labels": ["keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 810}, "file": "\n\n\n\n\n\n\n
\n \n \n \n \n
\n

\n\n
\n
\n

\n

\n

\n
\n\n\n", "file_path": "src/cloud-ui.html", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017731433035805821, 0.00017390162975061685, 0.00017183955060318112, 0.00017255099373869598, 2.430563199595781e-06]} {"hunk": {"id": 8, "code_window": ["\n", " onDOMCreated: function() {\n", " this.domIsReady = true;\n", " this.domFilterer.commitNow();\n"], "labels": ["keep", "replace", "keep", "keep"], "after_edit": [" onDOMCreated() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 812}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9925593137741089, 0.04235377535223961, 0.00016274975496344268, 0.0001715484686428681, 0.1861380785703659]} {"hunk": {"id": 8, "code_window": ["\n", " onDOMCreated: function() {\n", " this.domIsReady = true;\n", " this.domFilterer.commitNow();\n"], "labels": ["keep", "replace", "keep", "keep"], "after_edit": [" onDOMCreated() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 812}, "file": "{\n \"extName\": {\n \"message\": \"uBlock Origin\",\n \"description\": \"extension name.\"\n },\n \"extShortDesc\": {\n \"message\": \"Pagaliau, efektyvus blokatorius, neapkraunantis nei procesoriaus, nei darbinės atminties.\",\n \"description\": \"this will be in the Chrome web store: must be 132 characters or less\"\n },\n \"dashboardName\": {\n \"message\": \"uBlock₀ — Prietaisų skydas\",\n \"description\": \"English: uBlock₀ — Dashboard\"\n },\n \"settingsPageName\": {\n \"message\": \"Nustatymai\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"3pPageName\": {\n \"message\": \"Filtrų sąrašai\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"1pPageName\": {\n \"message\": \"Mano filtrai\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"rulesPageName\": {\n \"message\": \"Mano taisyklės\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"whitelistPageName\": {\n \"message\": \"Išimtys\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"shortcutsPageName\": {\n \"message\": \"Nuorodos\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"statsPageName\": {\n \"message\": \"uBlock₀ — Žurnalas\",\n \"description\": \"Title for the logger window\"\n },\n \"aboutPageName\": {\n \"message\": \"Apie\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"assetViewerPageName\": {\n \"message\": \"uBlock₀ — resursų žiūryklė\",\n \"description\": \"Title for the asset viewer page\"\n },\n \"advancedSettingsPageName\": {\n \"message\": \"Sudėtingesni nustatymai\",\n \"description\": \"Title for the advanced settings page\"\n },\n \"popupPowerSwitchInfo\": {\n \"message\": \"Spustelėjimas: įjungti\\/išjungti uBlock₀ šiam puslapiui.\\n\\nVald+spustelėjimas: išjungti uBlock₀ tik šiam puslapiui.\",\n \"description\": \"English: Click: disable\\/enable uBlock₀ for this site.\\n\\nCtrl+click: disable uBlock₀ only on this page.\"\n },\n \"popupPowerSwitchInfo1\": {\n \"message\": \"Spustelėkite, kad išjungtumėte uBlock₀ šiai svetainei.\\n\\nVald+spustelėkite, kad išjungtumėte uBlock₀ tik šiam puslapiui.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupPowerSwitchInfo2\": {\n \"message\": \"Spustelėkite, kad įjungtumėte uBlock₀ šiai svetainei.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupBlockedRequestPrompt\": {\n \"message\": \"blokuotos užklausos\",\n \"description\": \"English: requests blocked\"\n },\n \"popupBlockedOnThisPagePrompt\": {\n \"message\": \"šiame puslapyje\",\n \"description\": \"English: on this page\"\n },\n \"popupBlockedStats\": {\n \"message\": \"{{count}} arba {{percent}} %\",\n \"description\": \"Example: 15 or 13%\"\n },\n \"popupBlockedSinceInstallPrompt\": {\n \"message\": \"nuo įdiegimo\",\n \"description\": \"English: since install\"\n },\n \"popupOr\": {\n \"message\": \"arba\",\n \"description\": \"English: or\"\n },\n \"popupTipDashboard\": {\n \"message\": \"Atverti prietaisų skydą\",\n \"description\": \"English: Click to open the dashboard\"\n },\n \"popupTipZapper\": {\n \"message\": \"Atverti elementų trynimo veikseną\",\n \"description\": \"Tooltip for the element-zapper icon in the popup panel\"\n },\n \"popupTipPicker\": {\n \"message\": \"Atverti elementų parinkimo veikseną\",\n \"description\": \"English: Enter element picker mode\"\n },\n \"popupTipLog\": {\n \"message\": \"Atverti žurnalą\",\n \"description\": \"Tooltip used for the logger icon in the panel\"\n },\n \"popupTipNoPopups\": {\n \"message\": \"Perjungti visų iškylančiųjų langų blokavimą šiame puslapyje\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups1\": {\n \"message\": \"Spustelėkite visų iškylančių langų blokavimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups2\": {\n \"message\": \"Spustelėkite visų iškylančių langų neblokavimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoLargeMedia\": {\n \"message\": \"Perjungti didelių medijos elementų blokavimą šiame puslapyje\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia1\": {\n \"message\": \"Spustelėkite didelių medijos elementų blokavimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia2\": {\n \"message\": \"Spustelėkite didelių medijos elementų neblokavimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoCosmeticFiltering\": {\n \"message\": \"Perjungti kosmetinį filtravimą šiame puslapyje\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering1\": {\n \"message\": \"Spustelėkite kosmetinių filtrų išjungimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering2\": {\n \"message\": \"Spustelėkite kosmetinių filtrų įjungimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoRemoteFonts\": {\n \"message\": \"Perjungti nuotolinių šriftų blokavimą šiame puslapyje\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts1\": {\n \"message\": \"Spustelėkite nutolusių šriftų blokavimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts2\": {\n \"message\": \"Spustelėkite nutolusių šriftų neblokavimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoScripting1\": {\n \"message\": \"Spustelėkite JavaScript išjungimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipNoScripting2\": {\n \"message\": \"Spustelėkite JavaScript įjungimui šioje svetainėje\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipGlobalRules\": {\n \"message\": \"Globalios taisyklės: ši skiltis skirta visiems puslapiams taikomoms taisyklėms.\",\n \"description\": \"Tooltip when hovering the top-most cell of the global-rules column.\"\n },\n \"popupTipLocalRules\": {\n \"message\": \"Vietinės taisyklės: ši skiltis skirta dabartiniam puslapiui taikomoms taisyklėms.\\nVietinės taisyklės nustelbia globalias.\",\n \"description\": \"Tooltip when hovering the top-most cell of the local-rules column.\"\n },\n \"popupTipSaveRules\": {\n \"message\": \"Spauskite pakeitimams padaryti pastoviais.\",\n \"description\": \"Tooltip when hovering over the padlock in the dynamic filtering pane.\"\n },\n \"popupTipRevertRules\": {\n \"message\": \"Spauskite pakeitimams atstatyti.\",\n \"description\": \"Tooltip when hovering over the eraser in the dynamic filtering pane.\"\n },\n \"popupAnyRulePrompt\": {\n \"message\": \"visi\",\n \"description\": \"\"\n },\n \"popupImageRulePrompt\": {\n \"message\": \"vaizdai\",\n \"description\": \"\"\n },\n \"popup3pAnyRulePrompt\": {\n \"message\": \"trečios šalies\",\n \"description\": \"\"\n },\n \"popup3pPassiveRulePrompt\": {\n \"message\": \"3-ios šalies CSS\\/paveikslai\",\n \"description\": \"\"\n },\n \"popupInlineScriptRulePrompt\": {\n \"message\": \"įterptieji scenarijai\",\n \"description\": \"\"\n },\n \"popup1pScriptRulePrompt\": {\n \"message\": \"1-os šalies scenarijai\",\n \"description\": \"\"\n },\n \"popup3pScriptRulePrompt\": {\n \"message\": \"3-ios šalies scenarijai\",\n \"description\": \"\"\n },\n \"popup3pFrameRulePrompt\": {\n \"message\": \"3-ios šalies rėmeliai\",\n \"description\": \"\"\n },\n \"popupHitDomainCountPrompt\": {\n \"message\": \"jungtasi prie sričių\",\n \"description\": \"appears in popup\"\n },\n \"popupHitDomainCount\": {\n \"message\": \"{{count}} iš {{total}}\",\n \"description\": \"appears in popup\"\n },\n \"pickerCreate\": {\n \"message\": \"Sukurti\",\n \"description\": \"English: Create\"\n },\n \"pickerPick\": {\n \"message\": \"Parinkti\",\n \"description\": \"English: Pick\"\n },\n \"pickerQuit\": {\n \"message\": \"Baigti\",\n \"description\": \"English: Quit\"\n },\n \"pickerPreview\": {\n \"message\": \"Peržiūra\",\n \"description\": \"Element picker preview mode: will cause the elements matching the current filter to be removed from the page\"\n },\n \"pickerNetFilters\": {\n \"message\": \"Tinklo filtrai\",\n \"description\": \"English: header for a type of filter in the element picker dialog\"\n },\n \"pickerCosmeticFilters\": {\n \"message\": \"Kosmetiniai filtrai\",\n \"description\": \"English: Cosmetic filters\"\n },\n \"pickerCosmeticFiltersHint\": {\n \"message\": \"Spustelėjimas, Vald-spustelėjimas\",\n \"description\": \"English: Click, Ctrl-click\"\n },\n \"pickerContextMenuEntry\": {\n \"message\": \"Blokuoti elementą\",\n \"description\": \"English: Block element\"\n },\n \"settingsCollapseBlockedPrompt\": {\n \"message\": \"Slėpti blokuotų elementų rezervuotą vietą\",\n \"description\": \"English: Hide placeholders of blocked elements\"\n },\n \"settingsIconBadgePrompt\": {\n \"message\": \"Rodyti blokuotų užklausų skaičių piktogramoje\",\n \"description\": \"English: Show the number of blocked requests on the icon\"\n },\n \"settingsTooltipsPrompt\": {\n \"message\": \"Išjungti paaiškinimus\",\n \"description\": \"A checkbox in the Settings pane\"\n },\n \"settingsContextMenuPrompt\": {\n \"message\": \"Kur tinka, naudoti kontekstinį meniu\",\n \"description\": \"English: Make use of context menu where appropriate\"\n },\n \"settingsColorBlindPrompt\": {\n \"message\": \"Draugiškas neskiriantiems spalvų\",\n \"description\": \"English: Color-blind friendly\"\n },\n \"settingsCloudStorageEnabledPrompt\": {\n \"message\": \"Įjungti nuotolinės saugyklos palaikymą\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserPrompt\": {\n \"message\": \"Aš esu patyręs naudotojas (privaloma perskaityti<\\/a>)\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserSettings\": {\n \"message\": \"sudėtingesni nustatymai\",\n \"description\": \"For the tooltip of a link which gives access to advanced settings\"\n },\n \"settingsPrefetchingDisabledPrompt\": {\n \"message\": \"Išjungti išankstinį gavimą (visiems blokuotų tinklo užklausų prisijungimams išvengti)\",\n \"description\": \"English: \"\n },\n \"settingsHyperlinkAuditingDisabledPrompt\": {\n \"message\": \"Išjungti saitų auditą\",\n \"description\": \"English: \"\n },\n \"settingsWebRTCIPAddressHiddenPrompt\": {\n \"message\": \"Neleisti WebRTC atskleisti vietinio IP adreso\",\n \"description\": \"English: \"\n },\n \"settingPerSiteSwitchGroup\": {\n \"message\": \"Numatytoji elgsena\",\n \"description\": \"\"\n },\n \"settingPerSiteSwitchGroupSynopsis\": {\n \"message\": \"Šios numatytosios elgsenos gali būti nustelbtos kiekvienam puslapiui atskirai\",\n \"description\": \"\"\n },\n \"settingsNoCosmeticFilteringPrompt\": {\n \"message\": \"Išjungti kosmetinius filtrus\",\n \"description\": \"\"\n },\n \"settingsNoLargeMediaPrompt\": {\n \"message\": \"Blokuoti medijos elementus didesnius nei {{input}} kB\",\n \"description\": \"\"\n },\n \"settingsNoRemoteFontsPrompt\": {\n \"message\": \"Blokuoti nuotolinius šriftus\",\n \"description\": \"\"\n },\n \"settingsNoScriptingPrompt\": {\n \"message\": \"Išjungti JavaScript\",\n \"description\": \"The default state for the per-site no-scripting switch\"\n },\n \"settingsNoCSPReportsPrompt\": {\n \"message\": \"Blokuoti CSP ataskaitas\",\n \"description\": \"background information: https:\\/\\/github.com\\/gorhill\\/uBlock\\/issues\\/3150\"\n },\n \"settingsStorageUsed\": {\n \"message\": \"Naudojama vietos: {{value}} baitų\",\n \"description\": \"English: Storage used: {{}} bytes\"\n },\n \"settingsLastRestorePrompt\": {\n \"message\": \"Paskutinis atkūrimas:\",\n \"description\": \"English: Last restore:\"\n },\n \"settingsLastBackupPrompt\": {\n \"message\": \"Paskutinė atsarginė kopija:\",\n \"description\": \"English: Last backup:\"\n },\n \"3pListsOfBlockedHostsPrompt\": {\n \"message\": \"Tinklo filtrų ({{netFilterCount}}) + kosmetinių filtrų ({{cosmeticFilterCount}}) iš:\",\n \"description\": \"Appears at the top of the _3rd-party filters_ pane\"\n },\n \"3pListsOfBlockedHostsPerListStats\": {\n \"message\": \"naudojama {{used}} iš {{total}}\",\n \"description\": \"Appears aside each filter list in the _3rd-party filters_ pane\"\n },\n \"3pAutoUpdatePrompt1\": {\n \"message\": \"Automatiškai atnaujinti filtrų sąrašus.\",\n \"description\": \"A checkbox in the _3rd-party filters_ pane\"\n },\n \"3pUpdateNow\": {\n \"message\": \"Atnaujinti dabar\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pPurgeAll\": {\n \"message\": \"Valyti visus podėlius\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pParseAllABPHideFiltersPrompt1\": {\n \"message\": \"Analizuoti ir taikyti kosmetinius filtrus.\",\n \"description\": \"English: Parse and enforce Adblock+ element hiding filters.\"\n },\n \"3pParseAllABPHideFiltersInfo\": {\n \"message\": \"

Ši nuostata įjungia Su Adblock Plus suderinamų „elementų slėpimo“ filtrų<\\/a> analizę ir taikymą. Šie filtrai iš esmės yra kosmetiniai, jie naudojami tinklalapio elementams, kurie yra laikomi vaizdiniais nepatogumais ir kurių negalima užblokuoti tinklo užklausomis paremtais filtrais, paslėpti.<\\/p>

Šios nuostatos įjungimas padidina uBlock₀ atminties naudojimą.<\\/p>\",\n \"description\": \"Describes the purpose of the 'Parse and enforce cosmetic filters' feature.\"\n },\n \"3pIgnoreGenericCosmeticFilters\": {\n \"message\": \"Ignoruoti daugybinius kosmetinius filtrus.\",\n \"description\": \"This will cause uBO to ignore all generic cosmetic filters.\"\n },\n \"3pIgnoreGenericCosmeticFiltersInfo\": {\n \"message\": \"

Daugybiniai kosmetiniai filtrai yra tokie kosmetiniai filtrai, kurie taikomi visoms svetainėms.

Nors uBlock₀ juos apdoroja efektyviai, daugybiniai kosmetiniai filtrai vis tiek gali prisidėti prie pamatuojamo atminties ir procesoriaus panaudojimo kai kuriose svetainėse, ypač didelėse ir ilgai gyvuojančiose.

Šio nustatymo įjungimas sumažins atminties ir procesoriaus naudojimą, kurį sukelia svetainės dėl daugybinių kosmetinių filtrų apdorojimo, bei sumažins bendrą uBlock₀ atminties naudojimą.

Rekomenduojama įjungti šį nustatymą mažiau galinguose įrenginiuose.\",\n \"description\": \"Describes the purpose of the 'Ignore generic cosmetic filters' feature.\"\n },\n \"3pListsOfBlockedHostsHeader\": {\n \"message\": \"Blokuotų serverių sąrašas\",\n \"description\": \"English: Lists of blocked hosts\"\n },\n \"3pApplyChanges\": {\n \"message\": \"Taikyti pakeitimus\",\n \"description\": \"English: Apply changes\"\n },\n \"3pGroupDefault\": {\n \"message\": \"Įtaisyti\",\n \"description\": \"Header for the uBlock filters section in 'Filter lists pane'\"\n },\n \"3pGroupAds\": {\n \"message\": \"Reklamos\",\n \"description\": \"English: Ads\"\n },\n \"3pGroupPrivacy\": {\n \"message\": \"Privatumas\",\n \"description\": \"English: Privacy\"\n },\n \"3pGroupMalware\": {\n \"message\": \"Kenksmingos sritys\",\n \"description\": \"English: Malware domains\"\n },\n \"3pGroupAnnoyances\": {\n \"message\": \"Erzinimas\",\n \"description\": \"The header identifying the filter lists in the category 'annoyances'\"\n },\n \"3pGroupMultipurpose\": {\n \"message\": \"Univarsalūs\",\n \"description\": \"English: Multipurpose\"\n },\n \"3pGroupRegions\": {\n \"message\": \"Regionai, kalbos\",\n \"description\": \"English: Regions, languages\"\n },\n \"3pGroupCustom\": {\n \"message\": \"Adaptuoti\",\n \"description\": \"English: Custom\"\n },\n \"3pImport\": {\n \"message\": \"Importuoti...\",\n \"description\": \"The label for the checkbox used to import external filter lists\"\n },\n \"3pExternalListsHint\": {\n \"message\": \"Vienas URL eilutėje. Neteisingi URL bus tyliai ignoruoti.\",\n \"description\": \"Short information about how to use the textarea to import external filter lists by URL\"\n },\n \"3pExternalListObsolete\": {\n \"message\": \"Pasenęs.\",\n \"description\": \"used as a tooltip for the out-of-date icon beside a list\"\n },\n \"3pLastUpdate\": {\n \"message\": \"Paskutinis atnaujinimas: {{ago}}.\\nIeškoti atnaujinimo.\",\n \"description\": \"used as a tooltip for the clock icon beside a list\"\n },\n \"3pUpdating\": {\n \"message\": \"Atnaujinama...\",\n \"description\": \"used as a tooltip for the spinner icon beside a list\"\n },\n \"3pNetworkError\": {\n \"message\": \"Tinklo klaida sutrukdė atnaujinti resursą.\",\n \"description\": \"used as a tooltip for error icon beside a list\"\n },\n \"1pFormatHint\": {\n \"message\": \"Vienas filtras eilutėje. Filtras gali būti paprastas serverio adresas, arba su Adblock Plus suderinamas filtras. Eilutės pradėtos !<\\/code> bus ignoruotos.\",\n \"description\": \"Short information about how to create custom filters\"\n },\n \"1pImport\": {\n \"message\": \"Importuoti ir papildyti\",\n \"description\": \"English: Import and append\"\n },\n \"1pExport\": {\n \"message\": \"Eksportuoti\",\n \"description\": \"English: Export\"\n },\n \"1pExportFilename\": {\n \"message\": \"mano-ublock-statiniai-filtrai_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-static-filters_{{datetime}}.txt\"\n },\n \"1pApplyChanges\": {\n \"message\": \"Taikyti pakeitimus\",\n \"description\": \"English: Apply changes\"\n },\n \"rulesPermanentHeader\": {\n \"message\": \"Pastovios taisyklės\",\n \"description\": \"header\"\n },\n \"rulesTemporaryHeader\": {\n \"message\": \"Laikinos taisyklės\",\n \"description\": \"header\"\n },\n \"rulesRevert\": {\n \"message\": \"Atstatyti\",\n \"description\": \"This will remove all temporary rules\"\n },\n \"rulesCommit\": {\n \"message\": \"Pritaikyti\",\n \"description\": \"This will persist temporary rules\"\n },\n \"rulesEdit\": {\n \"message\": \"Redaguoti\",\n \"description\": \"Will enable manual-edit mode (textarea)\"\n },\n \"rulesEditSave\": {\n \"message\": \"Įrašyti\",\n \"description\": \"Will save manually-edited content and exit manual-edit mode\"\n },\n \"rulesEditDiscard\": {\n \"message\": \"Atmesti\",\n \"description\": \"Will discard manually-edited content and exit manual-edit mode\"\n },\n \"rulesImport\": {\n \"message\": \"Importuoti iš failo...\",\n \"description\": \"\"\n },\n \"rulesExport\": {\n \"message\": \"Eksportuoti į failą\",\n \"description\": \"\"\n },\n \"rulesDefaultFileName\": {\n \"message\": \"mano-ublock-dinaminės-taisyklės_{{datetime}}.txt\",\n \"description\": \"default file name to use\"\n },\n \"rulesHint\": {\n \"message\": \"Dinaminių filtravimo taisyklių sąrašas.\",\n \"description\": \"English: List of your dynamic filtering rules.\"\n },\n \"rulesFormatHint\": {\n \"message\": \"Taisyklės sintaksė: šaltinis paskirtis tipas veiksmas<\\/code> (dokumentacija<\\/a>).\",\n \"description\": \"English: dynamic rule syntax and full documentation.\"\n },\n \"whitelistPrompt\": {\n \"message\": \"Baltojo sąrašo direktyvos nurodo, kurioms svetainėms uBlock Origin turėtų būti išjungtas. Vienas įrašas eilutėje. Neteisingos direktyvos bus tyliai ignoruotos ir užkomentuotos.\",\n \"description\": \"English: An overview of the content of the dashboard's Whitelist pane.\"\n },\n \"whitelistImport\": {\n \"message\": \"Importuoti ir papildyti\",\n \"description\": \"English: Import and append\"\n },\n \"whitelistExport\": {\n \"message\": \"Eksportuoti\",\n \"description\": \"English: Export\"\n },\n \"whitelistExportFilename\": {\n \"message\": \"mano-ublock-išimtys_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-whitelist_{{datetime}}.txt\"\n },\n \"whitelistApply\": {\n \"message\": \"Taikyti pakeitimus\",\n \"description\": \"English: Apply changes\"\n },\n \"logRequestsHeaderType\": {\n \"message\": \"Tipas\",\n \"description\": \"English: Type\"\n },\n \"logRequestsHeaderDomain\": {\n \"message\": \"Sritis\",\n \"description\": \"English: Domain\"\n },\n \"logRequestsHeaderURL\": {\n \"message\": \"URL\",\n \"description\": \"English: URL\"\n },\n \"logRequestsHeaderFilter\": {\n \"message\": \"Filtras\",\n \"description\": \"English: Filter\"\n },\n \"logAll\": {\n \"message\": \"Visos\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"logBehindTheScene\": {\n \"message\": \"Užkulisiai\",\n \"description\": \"Pretty name for behind-the-scene network requests\"\n },\n \"loggerCurrentTab\": {\n \"message\": \"Dabartinė kortelė\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"loggerReloadTip\": {\n \"message\": \"Įkelti kortelės turinį iš naujo\",\n \"description\": \"Tooltip for the reload button in the logger page\"\n },\n \"loggerDomInspectorTip\": {\n \"message\": \"Įjungti \\/ išjungti DOM tyriklį\",\n \"description\": \"Tooltip for the DOM inspector button in the logger page\"\n },\n \"loggerPopupPanelTip\": {\n \"message\": \"Toggle the popup panel\",\n \"description\": \"Tooltip for the popup panel button in the logger page\"\n },\n \"loggerInfoTip\": {\n \"message\": \"„uBlock Origin“ vikis: žurnalas\",\n \"description\": \"Tooltip for the top-right info label in the logger page\"\n },\n \"loggerClearTip\": {\n \"message\": \"Valyti žurnalą\",\n \"description\": \"Tooltip for the eraser in the logger page; used to blank the content of the logger\"\n },\n \"loggerPauseTip\": {\n \"message\": \"Pristabdyti žurnalą (atmesti visus gaunamus duomenis)\",\n \"description\": \"Tooltip for the pause button in the logger page\"\n },\n \"loggerUnpauseTip\": {\n \"message\": \"Tęsti žurnalą\",\n \"description\": \"Tooltip for the play button in the logger page\"\n },\n \"loggerRowFiltererButtonTip\": {\n \"message\": \"Įjungti \\/ išjungti žurnalo filtravimą\",\n \"description\": \"Tooltip for the row filterer button in the logger page\"\n },\n \"logFilterPrompt\": {\n \"message\": \"filtruoti žurnalo įrašus\",\n \"description\": \"Placeholder string for logger output filtering input field\"\n },\n \"loggerRowFiltererBuiltinTip\": {\n \"message\": \"Žurnalo filtravimo nuostatos\",\n \"description\": \"Tooltip for the button to bring up logger output filtering options\"\n },\n \"loggerRowFiltererBuiltinNot\": {\n \"message\": \"Ne\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinEventful\": {\n \"message\": \"eventful\",\n \"description\": \"A keyword in the built-in row filtering expression: all items corresponding to uBO doing something (blocked, allowed, redirected, etc.)\"\n },\n \"loggerRowFiltererBuiltinBlocked\": {\n \"message\": \"užblokuota\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinAllowed\": {\n \"message\": \"leidžiama\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin1p\": {\n \"message\": \"1-oji šalis\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin3p\": {\n \"message\": \"3-ioji šalis\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerEntryDetailsHeader\": {\n \"message\": \"Išsamiau\",\n \"description\": \"Small header to identify the 'Details' pane for a specific logger entry\"\n },\n \"loggerEntryDetailsFilter\": {\n \"message\": \"Filtras\",\n \"description\": \"Label to identify a filter field\"\n },\n \"loggerEntryDetailsFilterList\": {\n \"message\": \"Filtrų sąrašas\",\n \"description\": \"Label to identify a filter list field\"\n },\n \"loggerEntryDetailsRule\": {\n \"message\": \"Taisyklė\",\n \"description\": \"Label to identify a rule field\"\n },\n \"loggerEntryDetailsContext\": {\n \"message\": \"Kontekstas\",\n \"description\": \"Label to identify a context field (typically a hostname)\"\n },\n \"loggerEntryDetailsRootContext\": {\n \"message\": \"Šakninis kontekstas\",\n \"description\": \"Label to identify a root context field (typically a hostname)\"\n },\n \"loggerEntryDetailsPartyness\": {\n \"message\": \"Partyness\",\n \"description\": \"Label to identify a field providing partyness information\"\n },\n \"loggerEntryDetailsType\": {\n \"message\": \"Tipas\",\n \"description\": \"Label to identify the type of an entry\"\n },\n \"loggerEntryDetailsURL\": {\n \"message\": \"URL\",\n \"description\": \"Label to identify the URL of an entry\"\n },\n \"loggerURLFilteringHeader\": {\n \"message\": \"URL taisyklė\",\n \"description\": \"Small header to identify the dynamic URL filtering section\"\n },\n \"loggerURLFilteringContextLabel\": {\n \"message\": \"Kontekstas:\",\n \"description\": \"Label for the context selector\"\n },\n \"loggerURLFilteringTypeLabel\": {\n \"message\": \"Tipas:\",\n \"description\": \"Label for the type selector\"\n },\n \"loggerStaticFilteringHeader\": {\n \"message\": \"Statinis filtravimas\",\n \"description\": \"Small header to identify the static filtering section\"\n },\n \"loggerStaticFilteringSentence\": {\n \"message\": \"{{action}} {{type}} tinklo užklausas, {{br}}kur URL adresas atitinka {{url}} {{br}}ir kurios kyla {{origin}},{{br}}{{importance}} yra atitinkantis išimties filtras.\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartBlock\": {\n \"message\": \"Blokuoti\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAllow\": {\n \"message\": \"Leisti\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartType\": {\n \"message\": \"„{{type}}“ tipo\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyType\": {\n \"message\": \"bet kokio tipo\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartOrigin\": {\n \"message\": \"iš „{{origin}}“\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyOrigin\": {\n \"message\": \"bet kur\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartNotImportant\": {\n \"message\": \"išskyrus kai\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartImportant\": {\n \"message\": \"net jei\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringFinderSentence1\": {\n \"message\": \"Statinis filtras {{filter}}<\\/code> rastas:\",\n \"description\": \"Below this sentence, the filter list(s) in which the filter was found\"\n },\n \"loggerStaticFilteringFinderSentence2\": {\n \"message\": \"Statinis filtras {{filter}}<\\/code> nerastas jokiame dabar įjungtame filtrų sąraše\",\n \"description\": \"Message to show when a filter cannot be found in any filter lists\"\n },\n \"loggerSettingDiscardPrompt\": {\n \"message\": \"Logger entries which do not fulfill all three conditions below will be automatically discarded:\",\n \"description\": \"Logger setting: A sentence to describe the purpose of the settings below\"\n },\n \"loggerSettingPerEntryMaxAge\": {\n \"message\": \"Preserve entries from the last {{input}} minutes\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxLoads\": {\n \"message\": \"Preserve at most {{input}} page loads per tab\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxEntries\": {\n \"message\": \"Preserve at most {{input}} entries per tab\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerEntryLineCount\": {\n \"message\": \"Use {{input}} lines per entry in vertically expanded mode\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingHideColumnsPrompt\": {\n \"message\": \"Hide columns:\",\n \"description\": \"Logger settings: a sentence to describe the purpose of the checkboxes below\"\n },\n \"loggerSettingHideColumnTime\": {\n \"message\": \"{{input}} Time\",\n \"description\": \"A label for the time column\"\n },\n \"loggerSettingHideColumnFilter\": {\n \"message\": \"{{input}} Filter\\/rule\",\n \"description\": \"A label for the filter or rule column\"\n },\n \"loggerSettingHideColumnContext\": {\n \"message\": \"{{input}} Context\",\n \"description\": \"A label for the context column\"\n },\n \"loggerSettingHideColumnPartyness\": {\n \"message\": \"{{input}} Partyness\",\n \"description\": \"A label for the partyness column\"\n },\n \"loggerExportFormatList\": {\n \"message\": \"Sąrašas\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportFormatTable\": {\n \"message\": \"Lentelė\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportEncodePlain\": {\n \"message\": \"Neformatuotas\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"loggerExportEncodeMarkdown\": {\n \"message\": \"Markdown\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"aboutChangelog\": {\n \"message\": \"Pakeitimų žurnalas\",\n \"description\": \"\"\n },\n \"aboutWiki\": {\n \"message\": \"Viki\",\n \"description\": \"English: project' wiki on GitHub\"\n },\n \"aboutSupport\": {\n \"message\": \"Palaikymas\",\n \"description\": \"A link for where to get support\"\n },\n \"aboutIssues\": {\n \"message\": \"Klaidų sekimo sistema\",\n \"description\": \"Text for a link to official issue tracker\"\n },\n \"aboutCode\": {\n \"message\": \"Pirminis tekstas (GPLv3)\",\n \"description\": \"English: Source code (GPLv3)\"\n },\n \"aboutContributors\": {\n \"message\": \"Talkininkai\",\n \"description\": \"English: Contributors\"\n },\n \"aboutDependencies\": {\n \"message\": \"Išorinės priklausomybės (suderinamos su „GPLv3“):\",\n \"description\": \"Shown in the About pane\"\n },\n \"aboutBackupDataButton\": {\n \"message\": \"Padaryti atsarginę kopiją į failą\",\n \"description\": \"Text for button to create a backup of all settings\"\n },\n \"aboutBackupFilename\": {\n \"message\": \"mano-ublock-atsarginė_kopija_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-backup_{{datetime}}.txt\"\n },\n \"aboutRestoreDataButton\": {\n \"message\": \"Atkurti iš failo...\",\n \"description\": \"English: Restore from file...\"\n },\n \"aboutResetDataButton\": {\n \"message\": \"Atkurti numatytuosius nustatymus...\",\n \"description\": \"English: Reset to default settings...\"\n },\n \"aboutRestoreDataConfirm\": {\n \"message\": \"Visi jūsų nustatymai bus perrašyti naudojant duomenis iš {{time}} atsarginės kopijos, o uBlock₀ bus perleistas.\\n\\nPerrašyti visus nustatymus naudojant atsarginės kopijos duomenis?\",\n \"description\": \"Message asking user to confirm restore\"\n },\n \"aboutRestoreDataError\": {\n \"message\": \"Nepavyko nuskaityti duomenų arba jie neteisingi\",\n \"description\": \"Message to display when an error occurred during restore\"\n },\n \"aboutResetDataConfirm\": {\n \"message\": \"Visi jūsų nustatymai bus pašalinti, o uBlock₀ bus perleistas.\\n\\nAtkurti uBlock₀ pradinius nustatymus?\",\n \"description\": \"Message asking user to confirm reset\"\n },\n \"errorCantConnectTo\": {\n \"message\": \"Tinklo klaida: {{msg}}\",\n \"description\": \"English: Network error: {{msg}}\"\n },\n \"subscriberConfirm\": {\n \"message\": \"uBlock₀: Pridėti šį URL į jūsų adaptuotų filtrų sąrašą?\\n\\nPavadinimas: „{{title}}“\\nURL: {{url}}\",\n \"description\": \"English: The message seen by the user to confirm subscription to a ABP filter list\"\n },\n \"elapsedOneMinuteAgo\": {\n \"message\": \"prieš minutę\",\n \"description\": \"English: a minute ago\"\n },\n \"elapsedManyMinutesAgo\": {\n \"message\": \"prieš {{value}} min.\",\n \"description\": \"English: {{value}} minutes ago\"\n },\n \"elapsedOneHourAgo\": {\n \"message\": \"prieš valandą\",\n \"description\": \"English: an hour ago\"\n },\n \"elapsedManyHoursAgo\": {\n \"message\": \"prieš {{value}} val.\",\n \"description\": \"English: {{value}} hours ago\"\n },\n \"elapsedOneDayAgo\": {\n \"message\": \"prieš dieną\",\n \"description\": \"English: a day ago\"\n },\n \"elapsedManyDaysAgo\": {\n \"message\": \"prieš {{value}} d.\",\n \"description\": \"English: {{value}} days ago\"\n },\n \"showDashboardButton\": {\n \"message\": \"Rodyti prietaisų skydą\",\n \"description\": \"Firefox\\/Fennec-specific: Show Dashboard\"\n },\n \"showNetworkLogButton\": {\n \"message\": \"Rodyti žurnalą\",\n \"description\": \"Firefox\\/Fennec-specific: Show Logger\"\n },\n \"fennecMenuItemBlockingOff\": {\n \"message\": \"išjungta\",\n \"description\": \"Firefox-specific: appears as 'uBlock₀ (off)'\"\n },\n \"docblockedPrompt1\": {\n \"message\": \"uBlock Origin neleido įkelti šio puslapio:\",\n \"description\": \"English: uBlock₀ has prevented the following page from loading:\"\n },\n \"docblockedPrompt2\": {\n \"message\": \"Dėl šio filtro\",\n \"description\": \"English: Because of the following filter\"\n },\n \"docblockedNoParamsPrompt\": {\n \"message\": \"be parametrų\",\n \"description\": \"label to be used for the parameter-less URL: https:\\/\\/cloud.githubusercontent.com\\/assets\\/585534\\/9832014\\/bfb1b8f0-593b-11e5-8a27-fba472a5529a.png\"\n },\n \"docblockedFoundIn\": {\n \"message\": \"Rasta:\",\n \"description\": \"English: List of filter list names follows\"\n },\n \"docblockedBack\": {\n \"message\": \"Grįžti\",\n \"description\": \"English: Go back\"\n },\n \"docblockedClose\": {\n \"message\": \"Užverti langą\",\n \"description\": \"English: Close this window\"\n },\n \"docblockedProceed\": {\n \"message\": \"Išjungti griežtą {{hostname}} blokavimą\",\n \"description\": \"English: Disable strict blocking for {{hostname}} ...\"\n },\n \"docblockedDisableTemporary\": {\n \"message\": \"Laikinai\",\n \"description\": \"English: Temporarily\"\n },\n \"docblockedDisablePermanent\": {\n \"message\": \"Negrįžtamai\",\n \"description\": \"English: Permanently\"\n },\n \"cloudPush\": {\n \"message\": \"Eksportuoti į nuotolinę saugyklą\",\n \"description\": \"tooltip\"\n },\n \"cloudPull\": {\n \"message\": \"Importuoti iš nuotolinės saugyklos\",\n \"description\": \"tooltip\"\n },\n \"cloudPullAndMerge\": {\n \"message\": \"Importuoti iš nuotolinės saugyklos ir sulieti su dabartiniais nustatymais\",\n \"description\": \"tooltip\"\n },\n \"cloudNoData\": {\n \"message\": \"...\\n...\",\n \"description\": \"\"\n },\n \"cloudDeviceNamePrompt\": {\n \"message\": \"Šio įrenginio vardas:\",\n \"description\": \"used as a prompt for the user to provide a custom device name\"\n },\n \"advancedSettingsWarning\": {\n \"message\": \"Įspėjimas! Keiskite šiuos sudėtingesnius nustatymus savo rizika.\",\n \"description\": \"A warning to users at the top of 'Advanced settings' page\"\n },\n \"genericSubmit\": {\n \"message\": \"Pateikti\",\n \"description\": \"for generic 'Submit' buttons\"\n },\n \"genericApplyChanges\": {\n \"message\": \"Taikyti pakeitimus\",\n \"description\": \"for generic 'Apply changes' buttons\"\n },\n \"genericRevert\": {\n \"message\": \"Atstatyti\",\n \"description\": \"for generic 'Revert' buttons\"\n },\n \"genericBytes\": {\n \"message\": \"baitai\",\n \"description\": \"\"\n },\n \"contextMenuTemporarilyAllowLargeMediaElements\": {\n \"message\": \"Laikinai leisti didelius medijos elementus\",\n \"description\": \"A context menu entry, present when large media elements have been blocked on the current site\"\n },\n \"shortcutCapturePlaceholder\": {\n \"message\": \"Įveskite nuorodą\",\n \"description\": \"Placeholder string for input field used to capture a keyboard shortcut\"\n },\n \"genericMergeViewScrollLock\": {\n \"message\": \"Toggle locked scrolling\",\n \"description\": \"Tooltip for the button used to lock scrolling between the views in the 'My rules' pane\"\n },\n \"genericCopyToClipboard\": {\n \"message\": \"Kopijuoti į iškarpinę\",\n \"description\": \"Label for buttons used to copy something to the clipboard\"\n },\n \"dummy\": {\n \"message\": \"This entry must be the last one\",\n \"description\": \"so we dont need to deal with comma for last entry\"\n }\n}", "file_path": "src/_locales/lt/messages.json", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0002726636594161391, 0.00017121869313996285, 0.00016475943266414106, 0.00016932401922531426, 1.347382476524217e-05]} {"hunk": {"id": 8, "code_window": ["\n", " onDOMCreated: function() {\n", " this.domIsReady = true;\n", " this.domFilterer.commitNow();\n"], "labels": ["keep", "replace", "keep", "keep"], "after_edit": [" onDOMCreated() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 812}, "file": "#!/usr/bin/env bash\n#\n# This script assumes a linux environment\n\necho \"*** uBlock0.chromium: Creating web store package\"\necho \"*** uBlock0.chromium: Copying files\"\n\nDES=dist/build/uBlock0.chromium\nrm -rf $DES\nmkdir -p $DES\n\nbash ./tools/make-assets.sh $DES\n\ncp -R src/css $DES/\ncp -R src/img $DES/\ncp -R src/js $DES/\ncp -R src/lib $DES/\ncp -R src/_locales $DES/\ncp src/*.html $DES/\ncp platform/chromium/*.js $DES/js/\ncp platform/chromium/*.html $DES/\ncp platform/chromium/*.json $DES/\ncp LICENSE.txt $DES/\n\necho \"*** uBlock0.chromium: concatenating content scripts\"\ncat $DES/js/vapi-usercss.js > /tmp/contentscript.js\necho >> /tmp/contentscript.js\ngrep -v \"^'use strict';$\" $DES/js/vapi-usercss.real.js >> /tmp/contentscript.js\necho >> /tmp/contentscript.js\ngrep -v \"^'use strict';$\" $DES/js/vapi-usercss.pseudo.js >> /tmp/contentscript.js\necho >> /tmp/contentscript.js\ngrep -v \"^'use strict';$\" $DES/js/contentscript.js >> /tmp/contentscript.js\nmv /tmp/contentscript.js $DES/js/contentscript.js\nrm $DES/js/vapi-usercss.js\nrm $DES/js/vapi-usercss.real.js\nrm $DES/js/vapi-usercss.pseudo.js\n\n# Chrome store-specific\ncp -R $DES/_locales/nb $DES/_locales/no\n\necho \"*** uBlock0.chromium: Generating web accessible resources...\"\ncp -R src/web_accessible_resources $DES/\npython3 tools/import-war.py $DES/\n\necho \"*** uBlock0.chromium: Generating meta...\"\npython tools/make-chromium-meta.py $DES/\n\nif [ \"$1\" = all ]; then\n echo \"*** uBlock0.chromium: Creating plain package...\"\n pushd $(dirname $DES/) > /dev/null\n zip uBlock0.chromium.zip -qr $(basename $DES/)/*\n popd > /dev/null\nelif [ -n \"$1\" ]; then\n echo \"*** uBlock0.chromium: Creating versioned package...\"\n pushd $(dirname $DES/) > /dev/null\n zip uBlock0_\"$1\".chromium.zip -qr $(basename $DES/)/*\n popd > /dev/null\nfi\n\necho \"*** uBlock0.chromium: Package done.\"\n", "file_path": "tools/make-chromium.sh", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001773045223671943, 0.00017220500740222633, 0.0001658617111388594, 0.00017186987679451704, 3.3702674500091234e-06]} {"hunk": {"id": 8, "code_window": ["\n", " onDOMCreated: function() {\n", " this.domIsReady = true;\n", " this.domFilterer.commitNow();\n"], "labels": ["keep", "replace", "keep", "keep"], "after_edit": [" onDOMCreated() {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 812}, "file": "{\n \"extName\": {\n \"message\": \"uBlock₀\",\n \"description\": \"extension name.\"\n },\n \"extShortDesc\": {\n \"message\": \"終於出現了,一個高效率的阻擋器,使用不多的 CPU 及記憶體資源。\",\n \"description\": \"this will be in the Chrome web store: must be 132 characters or less\"\n },\n \"dashboardName\": {\n \"message\": \"uBlock₀ — 控制台\",\n \"description\": \"English: uBlock₀ — Dashboard\"\n },\n \"settingsPageName\": {\n \"message\": \"設定\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"3pPageName\": {\n \"message\": \"過濾規則清單\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"1pPageName\": {\n \"message\": \"自訂靜態過濾規則\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"rulesPageName\": {\n \"message\": \"自訂動態過濾規則\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"whitelistPageName\": {\n \"message\": \"白名單\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"shortcutsPageName\": {\n \"message\": \"快速鍵\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"statsPageName\": {\n \"message\": \"uBlock₀ — 記錄器\",\n \"description\": \"Title for the logger window\"\n },\n \"aboutPageName\": {\n \"message\": \"關於\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"assetViewerPageName\": {\n \"message\": \"uBlock₀ — 資源檢視器\",\n \"description\": \"Title for the asset viewer page\"\n },\n \"advancedSettingsPageName\": {\n \"message\": \"進階設定\",\n \"description\": \"Title for the advanced settings page\"\n },\n \"popupPowerSwitchInfo\": {\n \"message\": \"點擊:對此網站 停用\\/啟用 uBlock₀ 。\\n\\nCtrl + 點擊:僅在此頁面停用 uBlock₀ 。\",\n \"description\": \"English: Click: disable\\/enable uBlock₀ for this site.\\n\\nCtrl+click: disable uBlock₀ only on this page.\"\n },\n \"popupPowerSwitchInfo1\": {\n \"message\": \"點擊:對此網站停用 uBlock₀ 。\\n\\nCtrl + 點擊:僅在此頁面停用 uBlock₀ 。\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupPowerSwitchInfo2\": {\n \"message\": \"點擊以在此網站啟用 uBlock₀ 。\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupBlockedRequestPrompt\": {\n \"message\": \"已阻擋連線請求\",\n \"description\": \"English: requests blocked\"\n },\n \"popupBlockedOnThisPagePrompt\": {\n \"message\": \"在此頁面\",\n \"description\": \"English: on this page\"\n },\n \"popupBlockedStats\": {\n \"message\": \"{{count}} 或 {{percent}}%\",\n \"description\": \"Example: 15 or 13%\"\n },\n \"popupBlockedSinceInstallPrompt\": {\n \"message\": \"自安裝後\",\n \"description\": \"English: since install\"\n },\n \"popupOr\": {\n \"message\": \"或\",\n \"description\": \"English: or\"\n },\n \"popupTipDashboard\": {\n \"message\": \"開啟控制台\",\n \"description\": \"English: Click to open the dashboard\"\n },\n \"popupTipZapper\": {\n \"message\": \"進入元素臨時移除模式\",\n \"description\": \"Tooltip for the element-zapper icon in the popup panel\"\n },\n \"popupTipPicker\": {\n \"message\": \"進入元素選擇器模式\",\n \"description\": \"English: Enter element picker mode\"\n },\n \"popupTipLog\": {\n \"message\": \"開啟記錄器\",\n \"description\": \"Tooltip used for the logger icon in the panel\"\n },\n \"popupTipNoPopups\": {\n \"message\": \"切換是否阻擋此網站的所有彈出型視窗\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups1\": {\n \"message\": \"點擊以封鎖此網站所有彈窗\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups2\": {\n \"message\": \"點擊以停止封鎖此網站所有彈窗\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoLargeMedia\": {\n \"message\": \"切換是否封鎖此網站的大型媒體元素\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia1\": {\n \"message\": \"點擊以封鎖此網站的大型媒體元素\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia2\": {\n \"message\": \"點擊以停止封鎖此網站的大型媒體元素\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoCosmeticFiltering\": {\n \"message\": \"切換是否在此網站過濾網頁元素\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering1\": {\n \"message\": \"點擊以停用此網站的網頁元素過濾\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering2\": {\n \"message\": \"點擊以啟用此網站的網頁元素過濾\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoRemoteFonts\": {\n \"message\": \"切換是否封鎖此網站的遠端字體\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts1\": {\n \"message\": \"點擊以封鎖此網站的遠端字體\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts2\": {\n \"message\": \"點擊以停止封鎖此網站的遠端字體\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoScripting1\": {\n \"message\": \"點擊以禁用此網站的所有腳本\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipNoScripting2\": {\n \"message\": \"點擊以停止禁用此網站的所有腳本\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipGlobalRules\": {\n \"message\": \"全域規則:此欄位的規則會套用至所有網站。\",\n \"description\": \"Tooltip when hovering the top-most cell of the global-rules column.\"\n },\n \"popupTipLocalRules\": {\n \"message\": \"區域規則:此欄位的規則僅會套用至目前網站。\\n區域規則會覆蓋過全域規則。\",\n \"description\": \"Tooltip when hovering the top-most cell of the local-rules column.\"\n },\n \"popupTipSaveRules\": {\n \"message\": \"點擊此處讓變更永久生效。\",\n \"description\": \"Tooltip when hovering over the padlock in the dynamic filtering pane.\"\n },\n \"popupTipRevertRules\": {\n \"message\": \"點擊以撤銷變更。\",\n \"description\": \"Tooltip when hovering over the eraser in the dynamic filtering pane.\"\n },\n \"popupAnyRulePrompt\": {\n \"message\": \"全部\",\n \"description\": \"\"\n },\n \"popupImageRulePrompt\": {\n \"message\": \"圖片\",\n \"description\": \"\"\n },\n \"popup3pAnyRulePrompt\": {\n \"message\": \"第三方\",\n \"description\": \"\"\n },\n \"popup3pPassiveRulePrompt\": {\n \"message\": \"第三方階層式樣式表 (CSS)/圖片\",\n \"description\": \"\"\n },\n \"popupInlineScriptRulePrompt\": {\n \"message\": \"內聯腳本\",\n \"description\": \"\"\n },\n \"popup1pScriptRulePrompt\": {\n \"message\": \"第一方腳本\",\n \"description\": \"\"\n },\n \"popup3pScriptRulePrompt\": {\n \"message\": \"第三方腳本\",\n \"description\": \"\"\n },\n \"popup3pFrameRulePrompt\": {\n \"message\": \"第三方框架\",\n \"description\": \"\"\n },\n \"popupHitDomainCountPrompt\": {\n \"message\": \"已連結域名\",\n \"description\": \"appears in popup\"\n },\n \"popupHitDomainCount\": {\n \"message\": \"{{count}} \\/ {{total}}\",\n \"description\": \"appears in popup\"\n },\n \"pickerCreate\": {\n \"message\": \"建立\",\n \"description\": \"English: Create\"\n },\n \"pickerPick\": {\n \"message\": \"選擇\",\n \"description\": \"English: Pick\"\n },\n \"pickerQuit\": {\n \"message\": \"放棄\",\n \"description\": \"English: Quit\"\n },\n \"pickerPreview\": {\n \"message\": \"預覽\",\n \"description\": \"Element picker preview mode: will cause the elements matching the current filter to be removed from the page\"\n },\n \"pickerNetFilters\": {\n \"message\": \"網址過濾規則\",\n \"description\": \"English: header for a type of filter in the element picker dialog\"\n },\n \"pickerCosmeticFilters\": {\n \"message\": \"元素隱藏過濾規則\",\n \"description\": \"English: Cosmetic filters\"\n },\n \"pickerCosmeticFiltersHint\": {\n \"message\": \"點擊,按住 Ctrl 鍵點擊\",\n \"description\": \"English: Click, Ctrl-click\"\n },\n \"pickerContextMenuEntry\": {\n \"message\": \"阻擋元素\",\n \"description\": \"English: Block element\"\n },\n \"settingsCollapseBlockedPrompt\": {\n \"message\": \"隱藏已阻擋元素的佔位元素\",\n \"description\": \"English: Hide placeholders of blocked elements\"\n },\n \"settingsIconBadgePrompt\": {\n \"message\": \"在圖示上顯示被阻擋的連線請求的數量\",\n \"description\": \"English: Show the number of blocked requests on the icon\"\n },\n \"settingsTooltipsPrompt\": {\n \"message\": \"關閉提示文字功能\",\n \"description\": \"A checkbox in the Settings pane\"\n },\n \"settingsContextMenuPrompt\": {\n \"message\": \"當適用時改進右鍵選單\",\n \"description\": \"English: Make use of context menu where appropriate\"\n },\n \"settingsColorBlindPrompt\": {\n \"message\": \"使用對色盲友善的色彩\",\n \"description\": \"English: Color-blind friendly\"\n },\n \"settingsCloudStorageEnabledPrompt\": {\n \"message\": \"啟用雲端儲存空間的支援\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserPrompt\": {\n \"message\": \"我是進階使用者(必讀資訊<\\/a>)\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserSettings\": {\n \"message\": \"進階設定\",\n \"description\": \"For the tooltip of a link which gives access to advanced settings\"\n },\n \"settingsPrefetchingDisabledPrompt\": {\n \"message\": \"關閉預讀功能(避免連線至被阻擋的網域)\",\n \"description\": \"English: \"\n },\n \"settingsHyperlinkAuditingDisabledPrompt\": {\n \"message\": \"停用超連結監測\",\n \"description\": \"English: \"\n },\n \"settingsWebRTCIPAddressHiddenPrompt\": {\n \"message\": \"預防 WebRTC 洩漏本地 IP 地址\",\n \"description\": \"English: \"\n },\n \"settingPerSiteSwitchGroup\": {\n \"message\": \"預設行為\",\n \"description\": \"\"\n },\n \"settingPerSiteSwitchGroupSynopsis\": {\n \"message\": \"這些預設行為可再依各網站調整\",\n \"description\": \"\"\n },\n \"settingsNoCosmeticFilteringPrompt\": {\n \"message\": \"停用元素隱藏過濾規則\",\n \"description\": \"\"\n },\n \"settingsNoLargeMediaPrompt\": {\n \"message\": \"封鎖超過 {{input}} KB 的媒體元素\",\n \"description\": \"\"\n },\n \"settingsNoRemoteFontsPrompt\": {\n \"message\": \"封鎖遠端字體\",\n \"description\": \"\"\n },\n \"settingsNoScriptingPrompt\": {\n \"message\": \"禁用網頁腳本\",\n \"description\": \"The default state for the per-site no-scripting switch\"\n },\n \"settingsNoCSPReportsPrompt\": {\n \"message\": \"封鎖 CSP 報告\",\n \"description\": \"background information: https:\\/\\/github.com\\/gorhill\\/uBlock\\/issues\\/3150\"\n },\n \"settingsStorageUsed\": {\n \"message\": \"儲存空間:已使用 {{value}} 位元組\",\n \"description\": \"English: Storage used: {{}} bytes\"\n },\n \"settingsLastRestorePrompt\": {\n \"message\": \"上次還原:\",\n \"description\": \"English: Last restore:\"\n },\n \"settingsLastBackupPrompt\": {\n \"message\": \"上次備份:\",\n \"description\": \"English: Last backup:\"\n },\n \"3pListsOfBlockedHostsPrompt\": {\n \"message\": \"目前已使用 {{netFilterCount}} 個網址過濾規則 + {{cosmeticFilterCount}} 個元素隱藏過濾規則:\",\n \"description\": \"Appears at the top of the _3rd-party filters_ pane\"\n },\n \"3pListsOfBlockedHostsPerListStats\": {\n \"message\": \"在 {{total}} 個中,已使用 {{used}} 個\",\n \"description\": \"Appears aside each filter list in the _3rd-party filters_ pane\"\n },\n \"3pAutoUpdatePrompt1\": {\n \"message\": \"自動更新過濾規則\",\n \"description\": \"A checkbox in the _3rd-party filters_ pane\"\n },\n \"3pUpdateNow\": {\n \"message\": \"立即更新\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pPurgeAll\": {\n \"message\": \"清除所有快取\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pParseAllABPHideFiltersPrompt1\": {\n \"message\": \"解析並套用元素隱藏過濾規則\",\n \"description\": \"English: Parse and enforce Adblock+ element hiding filters.\"\n },\n \"3pParseAllABPHideFiltersInfo\": {\n \"message\": \"

啟用此選項後,您就可以使用 與 Adblock Plus 相容的「元素隱藏」過濾規則<\\/a>。這些過濾規則可用來隱藏網頁中礙眼,卻又不能被網路請求的過濾引擎所阻擋的元素。<\\/p>

啟用這項功能後將增加 uBlock₀ <\\/i> 的記憶體使用量。<\\/p>\",\n \"description\": \"Describes the purpose of the 'Parse and enforce cosmetic filters' feature.\"\n },\n \"3pIgnoreGenericCosmeticFilters\": {\n \"message\": \"忽略通用元素隱藏過濾規則\",\n \"description\": \"This will cause uBO to ignore all generic cosmetic filters.\"\n },\n \"3pIgnoreGenericCosmeticFiltersInfo\": {\n \"message\": \"

一般元素過濾規則是指會套用於所有網站的規則。

雖然 uBlock₀ 會有效率地處理這些規則,但這些規則還是可能會在某些網頁中造成許多多餘的記憶體與 CPU 使用率,尤其是在較長又較舊的網頁。

開啟此選項後將可避免處理一般元素過濾規則時,所造成多餘的記憶體與 CPU 使用率,也能降低 uBlock₀ 本身的記憶體用量。

建議您在效能較差的裝置中開啟此選項。\",\n \"description\": \"Describes the purpose of the 'Ignore generic cosmetic filters' feature.\"\n },\n \"3pListsOfBlockedHostsHeader\": {\n \"message\": \"已阻擋域名的列表\",\n \"description\": \"English: Lists of blocked hosts\"\n },\n \"3pApplyChanges\": {\n \"message\": \"套用變更\",\n \"description\": \"English: Apply changes\"\n },\n \"3pGroupDefault\": {\n \"message\": \"內建\",\n \"description\": \"Header for the uBlock filters section in 'Filter lists pane'\"\n },\n \"3pGroupAds\": {\n \"message\": \"廣告\",\n \"description\": \"English: Ads\"\n },\n \"3pGroupPrivacy\": {\n \"message\": \"隱私\",\n \"description\": \"English: Privacy\"\n },\n \"3pGroupMalware\": {\n \"message\": \"惡意域名\",\n \"description\": \"English: Malware domains\"\n },\n \"3pGroupAnnoyances\": {\n \"message\": \"惱人的\",\n \"description\": \"The header identifying the filter lists in the category 'annoyances'\"\n },\n \"3pGroupMultipurpose\": {\n \"message\": \"多用途\",\n \"description\": \"English: Multipurpose\"\n },\n \"3pGroupRegions\": {\n \"message\": \"地區、語言\",\n \"description\": \"English: Regions, languages\"\n },\n \"3pGroupCustom\": {\n \"message\": \"自訂\",\n \"description\": \"English: Custom\"\n },\n \"3pImport\": {\n \"message\": \"匯入⋯\",\n \"description\": \"The label for the checkbox used to import external filter lists\"\n },\n \"3pExternalListsHint\": {\n \"message\": \"每行一個網址。無效網址將被忽略。\",\n \"description\": \"Short information about how to use the textarea to import external filter lists by URL\"\n },\n \"3pExternalListObsolete\": {\n \"message\": \"过久未更新。\",\n \"description\": \"used as a tooltip for the out-of-date icon beside a list\"\n },\n \"3pLastUpdate\": {\n \"message\": \"最後更新:{{ago}}。\\n點擊此處以要求更新。\",\n \"description\": \"used as a tooltip for the clock icon beside a list\"\n },\n \"3pUpdating\": {\n \"message\": \"更新中…\",\n \"description\": \"used as a tooltip for the spinner icon beside a list\"\n },\n \"3pNetworkError\": {\n \"message\": \"因網路錯誤無法更新資源。\",\n \"description\": \"used as a tooltip for error icon beside a list\"\n },\n \"1pFormatHint\": {\n \"message\": \"每行一個過濾規則。規則可以單純是主機名稱,或是 Adblock Plus 相容格式的過濾規則,以 !<\\/code> 開頭的行將被忽略。\",\n \"description\": \"Short information about how to create custom filters\"\n },\n \"1pImport\": {\n \"message\": \"匯入並加入\",\n \"description\": \"English: Import and append\"\n },\n \"1pExport\": {\n \"message\": \"匯出\",\n \"description\": \"English: Export\"\n },\n \"1pExportFilename\": {\n \"message\": \"my-ublock-static-filters_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-static-filters_{{datetime}}.txt\"\n },\n \"1pApplyChanges\": {\n \"message\": \"套用變更\",\n \"description\": \"English: Apply changes\"\n },\n \"rulesPermanentHeader\": {\n \"message\": \"永久規則\",\n \"description\": \"header\"\n },\n \"rulesTemporaryHeader\": {\n \"message\": \"臨時規則\",\n \"description\": \"header\"\n },\n \"rulesRevert\": {\n \"message\": \"還原\",\n \"description\": \"This will remove all temporary rules\"\n },\n \"rulesCommit\": {\n \"message\": \"提交\",\n \"description\": \"This will persist temporary rules\"\n },\n \"rulesEdit\": {\n \"message\": \"編輯\",\n \"description\": \"Will enable manual-edit mode (textarea)\"\n },\n \"rulesEditSave\": {\n \"message\": \"儲存\",\n \"description\": \"Will save manually-edited content and exit manual-edit mode\"\n },\n \"rulesEditDiscard\": {\n \"message\": \"捨棄\",\n \"description\": \"Will discard manually-edited content and exit manual-edit mode\"\n },\n \"rulesImport\": {\n \"message\": \"從檔案匯入…\",\n \"description\": \"\"\n },\n \"rulesExport\": {\n \"message\": \"匯出至檔案…\",\n \"description\": \"\"\n },\n \"rulesDefaultFileName\": {\n \"message\": \"my-ublock-dynamic-rules_{{datetime}}.txt\",\n \"description\": \"default file name to use\"\n },\n \"rulesHint\": {\n \"message\": \"您的動態過濾規則清單。\",\n \"description\": \"English: List of your dynamic filtering rules.\"\n },\n \"rulesFormatHint\": {\n \"message\": \"規則語法:來源主機名稱 目標主機名稱 連線請求類型 操作<\\/code>(完整說明<\\/a>)。\",\n \"description\": \"English: dynamic rule syntax and full documentation.\"\n },\n \"whitelistPrompt\": {\n \"message\": \"白名單中的規則適用的頁面不會被 uBlock₀ 過濾或阻擋。每行一個規則。無效的規則將被忽略。\",\n \"description\": \"English: An overview of the content of the dashboard's Whitelist pane.\"\n },\n \"whitelistImport\": {\n \"message\": \"匯入並加入\",\n \"description\": \"English: Import and append\"\n },\n \"whitelistExport\": {\n \"message\": \"匯出\",\n \"description\": \"English: Export\"\n },\n \"whitelistExportFilename\": {\n \"message\": \"my-ublock-whitelist_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-whitelist_{{datetime}}.txt\"\n },\n \"whitelistApply\": {\n \"message\": \"套用變更\",\n \"description\": \"English: Apply changes\"\n },\n \"logRequestsHeaderType\": {\n \"message\": \"類型\",\n \"description\": \"English: Type\"\n },\n \"logRequestsHeaderDomain\": {\n \"message\": \"域名\",\n \"description\": \"English: Domain\"\n },\n \"logRequestsHeaderURL\": {\n \"message\": \"網址\",\n \"description\": \"English: URL\"\n },\n \"logRequestsHeaderFilter\": {\n \"message\": \"過濾規則\",\n \"description\": \"English: Filter\"\n },\n \"logAll\": {\n \"message\": \"全部\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"logBehindTheScene\": {\n \"message\": \"背景網路連線請求\",\n \"description\": \"Pretty name for behind-the-scene network requests\"\n },\n \"loggerCurrentTab\": {\n \"message\": \"目前分頁\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"loggerReloadTip\": {\n \"message\": \"重新載入分頁內容\",\n \"description\": \"Tooltip for the reload button in the logger page\"\n },\n \"loggerDomInspectorTip\": {\n \"message\": \"切換 DOM 檢測器\",\n \"description\": \"Tooltip for the DOM inspector button in the logger page\"\n },\n \"loggerPopupPanelTip\": {\n \"message\": \"開閉彈出式面板\",\n \"description\": \"Tooltip for the popup panel button in the logger page\"\n },\n \"loggerInfoTip\": {\n \"message\": \"uBlock Origin wiki:記錄器\",\n \"description\": \"Tooltip for the top-right info label in the logger page\"\n },\n \"loggerClearTip\": {\n \"message\": \"清除記錄\",\n \"description\": \"Tooltip for the eraser in the logger page; used to blank the content of the logger\"\n },\n \"loggerPauseTip\": {\n \"message\": \"暫停記錄(丟棄所有傳入資料)\",\n \"description\": \"Tooltip for the pause button in the logger page\"\n },\n \"loggerUnpauseTip\": {\n \"message\": \"取消暫停記錄\",\n \"description\": \"Tooltip for the play button in the logger page\"\n },\n \"loggerRowFiltererButtonTip\": {\n \"message\": \"開閉記錄篩選\",\n \"description\": \"Tooltip for the row filterer button in the logger page\"\n },\n \"logFilterPrompt\": {\n \"message\": \"篩選記錄條目\",\n \"description\": \"Placeholder string for logger output filtering input field\"\n },\n \"loggerRowFiltererBuiltinTip\": {\n \"message\": \"記錄篩選設定\",\n \"description\": \"Tooltip for the button to bring up logger output filtering options\"\n },\n \"loggerRowFiltererBuiltinNot\": {\n \"message\": \"非\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinEventful\": {\n \"message\": \"已套用規則\",\n \"description\": \"A keyword in the built-in row filtering expression: all items corresponding to uBO doing something (blocked, allowed, redirected, etc.)\"\n },\n \"loggerRowFiltererBuiltinBlocked\": {\n \"message\": \"已封鎖\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinAllowed\": {\n \"message\": \"已允許\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin1p\": {\n \"message\": \"第一方\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin3p\": {\n \"message\": \"第三方\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerEntryDetailsHeader\": {\n \"message\": \"詳細資料\",\n \"description\": \"Small header to identify the 'Details' pane for a specific logger entry\"\n },\n \"loggerEntryDetailsFilter\": {\n \"message\": \"過濾規則\",\n \"description\": \"Label to identify a filter field\"\n },\n \"loggerEntryDetailsFilterList\": {\n \"message\": \"過濾規則清單\",\n \"description\": \"Label to identify a filter list field\"\n },\n \"loggerEntryDetailsRule\": {\n \"message\": \"規則\",\n \"description\": \"Label to identify a rule field\"\n },\n \"loggerEntryDetailsContext\": {\n \"message\": \"上下文\",\n \"description\": \"Label to identify a context field (typically a hostname)\"\n },\n \"loggerEntryDetailsRootContext\": {\n \"message\": \"根上下文\",\n \"description\": \"Label to identify a root context field (typically a hostname)\"\n },\n \"loggerEntryDetailsPartyness\": {\n \"message\": \"第一方\\/第三方\",\n \"description\": \"Label to identify a field providing partyness information\"\n },\n \"loggerEntryDetailsType\": {\n \"message\": \"類型\",\n \"description\": \"Label to identify the type of an entry\"\n },\n \"loggerEntryDetailsURL\": {\n \"message\": \"網址\",\n \"description\": \"Label to identify the URL of an entry\"\n },\n \"loggerURLFilteringHeader\": {\n \"message\": \"網址規則\",\n \"description\": \"Small header to identify the dynamic URL filtering section\"\n },\n \"loggerURLFilteringContextLabel\": {\n \"message\": \"上下文:\",\n \"description\": \"Label for the context selector\"\n },\n \"loggerURLFilteringTypeLabel\": {\n \"message\": \"類型:\",\n \"description\": \"Label for the type selector\"\n },\n \"loggerStaticFilteringHeader\": {\n \"message\": \"靜態過濾規則\",\n \"description\": \"Small header to identify the static filtering section\"\n },\n \"loggerStaticFilteringSentence\": {\n \"message\": \"當網址符合 {{url}},{{br}}並且來自 {{origin}} 時,{{br}}{{action}} {{type}} 的網路請求,{{br}}{{importance}} 已有符合的過濾例外規則。\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartBlock\": {\n \"message\": \"封鎖\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAllow\": {\n \"message\": \"允許\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartType\": {\n \"message\": \"{{type}} 類型\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyType\": {\n \"message\": \"任何類型\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartOrigin\": {\n \"message\": \"來自「{{origin}}」\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyOrigin\": {\n \"message\": \"來自任何地方\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartNotImportant\": {\n \"message\": \"除非\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartImportant\": {\n \"message\": \"就算\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringFinderSentence1\": {\n \"message\": \"在下列清單中找到靜態過濾規則 {{filter}}<\\/code>:\",\n \"description\": \"Below this sentence, the filter list(s) in which the filter was found\"\n },\n \"loggerStaticFilteringFinderSentence2\": {\n \"message\": \"無法在任何啟用的過濾清單中,找到靜態過濾規則 {{filter}}<\\/code>\",\n \"description\": \"Message to show when a filter cannot be found in any filter lists\"\n },\n \"loggerSettingDiscardPrompt\": {\n \"message\": \"不符合以下任一狀況的記錄將會被自動清除:\",\n \"description\": \"Logger setting: A sentence to describe the purpose of the settings below\"\n },\n \"loggerSettingPerEntryMaxAge\": {\n \"message\": \"最多保留 {{input}} 分鐘以內的記錄\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxLoads\": {\n \"message\": \"每個分頁最多保留 {{input}} 次內容加載產生的記錄\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxEntries\": {\n \"message\": \"每個分頁最多保留 {{input}} 條記錄\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerEntryLineCount\": {\n \"message\": \"在垂直延展模式中每條記錄顯示 {{input}} 行\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingHideColumnsPrompt\": {\n \"message\": \"隱藏欄位:\",\n \"description\": \"Logger settings: a sentence to describe the purpose of the checkboxes below\"\n },\n \"loggerSettingHideColumnTime\": {\n \"message\": \"{{input}} 時間\",\n \"description\": \"A label for the time column\"\n },\n \"loggerSettingHideColumnFilter\": {\n \"message\": \"{{input}} 過濾規則\",\n \"description\": \"A label for the filter or rule column\"\n },\n \"loggerSettingHideColumnContext\": {\n \"message\": \"{{input}} 上下文\",\n \"description\": \"A label for the context column\"\n },\n \"loggerSettingHideColumnPartyness\": {\n \"message\": \"{{input}} 第一方\\/第三方\",\n \"description\": \"A label for the partyness column\"\n },\n \"loggerExportFormatList\": {\n \"message\": \"清單\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportFormatTable\": {\n \"message\": \"表格\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportEncodePlain\": {\n \"message\": \"純文字\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"loggerExportEncodeMarkdown\": {\n \"message\": \"Markdown\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"aboutChangelog\": {\n \"message\": \"更新日誌\",\n \"description\": \"\"\n },\n \"aboutWiki\": {\n \"message\": \"Wiki\",\n \"description\": \"English: project' wiki on GitHub\"\n },\n \"aboutSupport\": {\n \"message\": \"支援網站\",\n \"description\": \"A link for where to get support\"\n },\n \"aboutIssues\": {\n \"message\": \"問題報告\",\n \"description\": \"Text for a link to official issue tracker\"\n },\n \"aboutCode\": {\n \"message\": \"程式原始碼(GPLv3)\",\n \"description\": \"English: Source code (GPLv3)\"\n },\n \"aboutContributors\": {\n \"message\": \"貢獻者\",\n \"description\": \"English: Contributors\"\n },\n \"aboutDependencies\": {\n \"message\": \"外部相依套件(與 GPLv3 相容):\",\n \"description\": \"Shown in the About pane\"\n },\n \"aboutBackupDataButton\": {\n \"message\": \"備份到檔案…\",\n \"description\": \"Text for button to create a backup of all settings\"\n },\n \"aboutBackupFilename\": {\n \"message\": \"my-ublock-backup_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-backup_{{datetime}}.txt\"\n },\n \"aboutRestoreDataButton\": {\n \"message\": \"從檔案還原…\",\n \"description\": \"English: Restore from file...\"\n },\n \"aboutResetDataButton\": {\n \"message\": \"重設為預設設定…\",\n \"description\": \"English: Reset to default settings...\"\n },\n \"aboutRestoreDataConfirm\": {\n \"message\": \"您所有的設定將會被 {{time}} 的備份資料覆蓋,並將重新啟動 uBlock₀。\\n\\n您確定要用備份資料蓋過目前的所有設定嗎?\",\n \"description\": \"Message asking user to confirm restore\"\n },\n \"aboutRestoreDataError\": {\n \"message\": \"無法讀取資料,或資料無效\",\n \"description\": \"Message to display when an error occurred during restore\"\n },\n \"aboutResetDataConfirm\": {\n \"message\": \"您所有的設定都將被移除,並將重新啟動 uBlock₀。\\n\\n您確定要將 uBlock₀ 回復為原廠設定?\",\n \"description\": \"Message asking user to confirm reset\"\n },\n \"errorCantConnectTo\": {\n \"message\": \"網路錯誤:{{msg}}\",\n \"description\": \"English: Network error: {{msg}}\"\n },\n \"subscriberConfirm\": {\n \"message\": \"uBlock₀:確定要新增下列網址至自訂過濾規則清單?\\n\\n標題:「{{title}}」\\n網址:{{url}}\",\n \"description\": \"English: The message seen by the user to confirm subscription to a ABP filter list\"\n },\n \"elapsedOneMinuteAgo\": {\n \"message\": \"1 分鐘前\",\n \"description\": \"English: a minute ago\"\n },\n \"elapsedManyMinutesAgo\": {\n \"message\": \"{{value}} 分鐘前\",\n \"description\": \"English: {{value}} minutes ago\"\n },\n \"elapsedOneHourAgo\": {\n \"message\": \"1 小時前\",\n \"description\": \"English: an hour ago\"\n },\n \"elapsedManyHoursAgo\": {\n \"message\": \"{{value}} 小時前\",\n \"description\": \"English: {{value}} hours ago\"\n },\n \"elapsedOneDayAgo\": {\n \"message\": \"1 天前\",\n \"description\": \"English: a day ago\"\n },\n \"elapsedManyDaysAgo\": {\n \"message\": \"{{value}} 天前\",\n \"description\": \"English: {{value}} days ago\"\n },\n \"showDashboardButton\": {\n \"message\": \"顯示控制台\",\n \"description\": \"Firefox\\/Fennec-specific: Show Dashboard\"\n },\n \"showNetworkLogButton\": {\n \"message\": \"顯示記錄器\",\n \"description\": \"Firefox\\/Fennec-specific: Show Logger\"\n },\n \"fennecMenuItemBlockingOff\": {\n \"message\": \"關閉\",\n \"description\": \"Firefox-specific: appears as 'uBlock₀ (off)'\"\n },\n \"docblockedPrompt1\": {\n \"message\": \"uBlock₀ 已防止下列的頁面載入:\",\n \"description\": \"English: uBlock₀ has prevented the following page from loading:\"\n },\n \"docblockedPrompt2\": {\n \"message\": \"因為下列過濾規則\",\n \"description\": \"English: Because of the following filter\"\n },\n \"docblockedNoParamsPrompt\": {\n \"message\": \"不帶參數\",\n \"description\": \"label to be used for the parameter-less URL: https:\\/\\/cloud.githubusercontent.com\\/assets\\/585534\\/9832014\\/bfb1b8f0-593b-11e5-8a27-fba472a5529a.png\"\n },\n \"docblockedFoundIn\": {\n \"message\": \"在下列清單找到:\",\n \"description\": \"English: List of filter list names follows\"\n },\n \"docblockedBack\": {\n \"message\": \"返回\",\n \"description\": \"English: Go back\"\n },\n \"docblockedClose\": {\n \"message\": \"關閉此視窗\",\n \"description\": \"English: Close this window\"\n },\n \"docblockedProceed\": {\n \"message\": \"停止針對 {{hostname}} 的嚴格封鎖\",\n \"description\": \"English: Disable strict blocking for {{hostname}} ...\"\n },\n \"docblockedDisableTemporary\": {\n \"message\": \"暫時\",\n \"description\": \"English: Temporarily\"\n },\n \"docblockedDisablePermanent\": {\n \"message\": \"永久\",\n \"description\": \"English: Permanently\"\n },\n \"cloudPush\": {\n \"message\": \"匯出至雲端儲存空間\",\n \"description\": \"tooltip\"\n },\n \"cloudPull\": {\n \"message\": \"從雲端儲存空間匯入\",\n \"description\": \"tooltip\"\n },\n \"cloudPullAndMerge\": {\n \"message\": \"自雲端匯入,並與目前設定合併\",\n \"description\": \"tooltip\"\n },\n \"cloudNoData\": {\n \"message\": \"…\\n…\",\n \"description\": \"\"\n },\n \"cloudDeviceNamePrompt\": {\n \"message\": \"此裝置的名稱:\",\n \"description\": \"used as a prompt for the user to provide a custom device name\"\n },\n \"advancedSettingsWarning\": {\n \"message\": \"警告!修改進階設定時請自負風險。\",\n \"description\": \"A warning to users at the top of 'Advanced settings' page\"\n },\n \"genericSubmit\": {\n \"message\": \"送出\",\n \"description\": \"for generic 'Submit' buttons\"\n },\n \"genericApplyChanges\": {\n \"message\": \"套用變更\",\n \"description\": \"for generic 'Apply changes' buttons\"\n },\n \"genericRevert\": {\n \"message\": \"還原\",\n \"description\": \"for generic 'Revert' buttons\"\n },\n \"genericBytes\": {\n \"message\": \"位元組\",\n \"description\": \"\"\n },\n \"contextMenuTemporarilyAllowLargeMediaElements\": {\n \"message\": \"暫時允許大型媒體元素\",\n \"description\": \"A context menu entry, present when large media elements have been blocked on the current site\"\n },\n \"shortcutCapturePlaceholder\": {\n \"message\": \"輸入捷徑\",\n \"description\": \"Placeholder string for input field used to capture a keyboard shortcut\"\n },\n \"genericMergeViewScrollLock\": {\n \"message\": \"切換是否啟用同步捲動\",\n \"description\": \"Tooltip for the button used to lock scrolling between the views in the 'My rules' pane\"\n },\n \"genericCopyToClipboard\": {\n \"message\": \"複製到剪貼簿\",\n \"description\": \"Label for buttons used to copy something to the clipboard\"\n },\n \"dummy\": {\n \"message\": \"此條目須為最後一個\",\n \"description\": \"so we dont need to deal with comma for last entry\"\n }\n}", "file_path": "src/_locales/zh_TW/messages.json", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0002842926187440753, 0.00017089718312490731, 0.0001648515317356214, 0.00016866723308339715, 1.3735384527535643e-05]} {"hunk": {"id": 9, "code_window": [" this.domIsReady = true;\n", " this.domFilterer.commitNow();\n", " },\n", "\n"], "labels": ["keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 815}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9813434481620789, 0.01534699834883213, 0.00016383123875129968, 0.00017010692681651562, 0.08750329166650772]} {"hunk": {"id": 9, "code_window": [" this.domIsReady = true;\n", " this.domFilterer.commitNow();\n", " },\n", "\n"], "labels": ["keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 815}, "file": "#domInspector {\n display: none;\n }\n#inspectors.dom #domInspector {\n display: flex;\n }\n#domInspector .permatoolbar .highlightMode.invert {\n transform: rotate(180deg);\n }\n#domInspector .vscrollable {\n overflow-x: auto;\n }\n#domInspector > ul:first-of-type {\n padding-left: 0.5em;\n }\n#domInspector ul {\n background-color: #fff;\n margin: 0;\n padding-left: 1em;\n }\n#domInspector li {\n list-style-type: none;\n white-space: nowrap;\n }\n#domInspector li.isCosmeticHide,\n#domInspector li.isCosmeticHide ul,\n#domInspector li.isCosmeticHide li {\n background-color: #fee;\n }\n#domInspector li > * {\n font-size: 0.8rem;\n display: inline-block;\n line-height: 1.2;\n margin-right: 1em;\n vertical-align: middle;\n }\n#domInspector li > span {\n color: #aaa;\n }\n#domInspector li > span:first-child {\n color: #000;\n cursor: default;\n font-size: 1rem;\n margin-right: 0;\n opacity: 0.5;\n padding: 0 4px 0 1px;\n visibility: hidden;\n }\n#domInspector li > span:first-child:hover {\n opacity: 1;\n }\n#domInspector li > *:last-child {\n margin-right: 0;\n }\n#domInspector li > span:first-child:before {\n content: '\\a0';\n }\n#domInspector li.branch > span:first-child:before {\n content: '\\25b8';\n visibility: visible;\n }\n#domInspector li.branch.show > span:first-child:before {\n content: '\\25be';\n }\n#domInspector li.branch.hasCosmeticHide > span:first-child:before {\n color: red;\n }\n#domInspector li > code {\n cursor: pointer;\n font-family: monospace;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n#domInspector li > code.off {\n text-decoration: line-through;\n }\n#domInspector li > code.filter {\n color: red;\n }\n\n#domInspector li > ul {\n display: block;\n }\n#domInspector li:not(.hasCosmeticHide):not(.isCosmeticHide):not(.show) > ul {\n display: none;\n }\n\n#domInspector:not(.vExpanded) li:not(.hasCosmeticHide):not(.isCosmeticHide) {\n display: none;\n }\n#domInspector #domTree > li {\n display: block;\n }\n#domInspector:not(.vExpanded) ul {\n display: block;\n }\n#domInspector li > ul > li:not(.hasCosmeticHide):not(.isCosmeticHide) {\n display: none;\n }\n#domInspector li.show > ul > li:not(.hasCosmeticHide):not(.isCosmeticHide) {\n display: block;\n }\n#domInspector li:not(.hasCosmeticHide):not(.isCosmeticHide) {\n display: block;\n }\n#domInspector.hCompact li > code:first-of-type {\n max-width: 12em;\n }\n\n#cosmeticFilteringDialog .dialog {\n text-align: center;\n }\n#cosmeticFilteringDialog .dialog textarea {\n height: 40vh;\n white-space: pre;\n word-wrap: normal;\n }\n", "file_path": "src/css/logger-ui-inspector.css", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017757387831807137, 0.00016812440298963338, 0.0001649891200941056, 0.00016760846483521163, 3.1105414564081e-06]} {"hunk": {"id": 9, "code_window": [" this.domIsReady = true;\n", " this.domFilterer.commitNow();\n", " },\n", "\n"], "labels": ["keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 815}, "file": "/*******************************************************************************\n\n lz4-block-codec-any.js\n A wrapper to instanciate a wasm- and/or js-based LZ4 block\n encoder/decoder.\n Copyright (C) 2018 Raymond Hill\n\n BSD-2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following disclaimer\n in the documentation and/or other materials provided with the\n distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n Home: https://github.com/gorhill/lz4-wasm\n\n I used the same license as the one picked by creator of LZ4 out of respect\n for his creation, see https://lz4.github.io/lz4/\n\n*/\n\n'use strict';\n\n/******************************************************************************/\n\n(function(context) { // >>>> Start of private namespace\n\n/******************************************************************************/\n\nconst wd = (function() {\n let url = document.currentScript.src;\n let match = /[^\\/]+$/.exec(url);\n return match !== null ?\n url.slice(0, match.index) :\n '';\n})();\n\nconst removeScript = function(script) {\n if ( !script ) { return; }\n if ( script.parentNode === null ) { return; }\n script.parentNode.removeChild(script);\n};\n\nconst createInstanceWASM = function() {\n if ( context.LZ4BlockWASM instanceof Function ) {\n const instance = new context.LZ4BlockWASM();\n return instance.init().then(ok => ok ? instance : null);\n }\n if ( context.LZ4BlockWASM === null ) {\n return Promise.resolve(null);\n }\n return new Promise(resolve => {\n const script = document.createElement('script');\n script.src = wd + 'lz4-block-codec-wasm.js';\n script.addEventListener('load', ( ) => {\n if ( context.LZ4BlockWASM instanceof Function === false ) {\n context.LZ4BlockWASM = null;\n resolve(null);\n return;\n }\n const instance = new context.LZ4BlockWASM();\n instance.init().then(ok => { resolve(ok ? instance : null); });\n });\n script.addEventListener('error', ( ) => {\n context.LZ4BlockWASM = null;\n resolve(null);\n });\n document.head.appendChild(script);\n removeScript(script);\n });\n};\n\nconst createInstanceJS = function() {\n if ( context.LZ4BlockJS instanceof Function ) {\n const instance = new context.LZ4BlockJS();\n return instance.init().then(ok => ok ? instance : null);\n }\n if ( context.LZ4BlockJS === null ) {\n return Promise.resolve(null);\n }\n return new Promise(resolve => {\n const script = document.createElement('script');\n script.src = wd + 'lz4-block-codec-js.js';\n script.addEventListener('load', ( ) => {\n if ( context.LZ4BlockJS instanceof Function === false ) {\n context.LZ4BlockJS = null;\n resolve(null);\n return;\n }\n const instance = new context.LZ4BlockJS();\n instance.init().then(ok => { resolve(ok ? instance : null); });\n });\n script.addEventListener('error', ( ) => {\n context.LZ4BlockJS = null;\n resolve(null);\n });\n document.head.appendChild(script);\n removeScript(script);\n });\n};\n\n/******************************************************************************/\n\ncontext.lz4BlockCodec = {\n createInstance: function(flavor) {\n let instantiator;\n if ( flavor === 'wasm' ) {\n instantiator = createInstanceWASM;\n } else if ( flavor === 'js' ) {\n instantiator = createInstanceJS;\n } else {\n instantiator = createInstanceWASM || createInstanceJS;\n }\n return (instantiator)().then(instance => {\n if ( instance ) { return instance; }\n if ( flavor === undefined ) {\n return createInstanceJS();\n }\n return null;\n });\n },\n reset: function() {\n context.LZ4BlockWASM = undefined;\n context.LZ4BlockJS = undefined;\n }\n};\n\n/******************************************************************************/\n\n})(this || self); // <<<< End of private namespace\n\n/******************************************************************************/\n", "file_path": "src/lib/lz4/lz4-block-codec-any.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017542346904519945, 0.00016849604435265064, 0.00016248693282250315, 0.00016772841627243906, 3.6992096283938736e-06]} {"hunk": {"id": 9, "code_window": [" this.domIsReady = true;\n", " this.domFilterer.commitNow();\n", " },\n", "\n"], "labels": ["keep", "keep", "replace", "keep"], "after_edit": [" }\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 815}, "file": "An efficient blocker: easy on memory and CPU footprint, and yet can load and enforce thousands more filters than other popular blockers out there.\n\nIllustrated overview of its efficiency: https://github.com/gorhill/uBlock/wiki/uBlock-vs.-ABP:-efficiency-compared\n\nUsage: The big power button in the popup is to permanently disable/enable uBlock for the current web site. It applies to the current web site only, it is not a global power button.\n\n***\n\nFlexible, it's more than an \"ad blocker\": it can also read and create filters from hosts files.\n\nOut of the box, these lists of filters are loaded and enforced:\n\n- EasyList\n- Peter Lowe’s Ad server list\n- EasyPrivacy\n- Malware domains\n\nMore lists are available for you to select if you wish:\n\n- Fanboy’s Enhanced Tracking List\n- Dan Pollock’s hosts file\n- hpHosts’s Ad and tracking servers\n- MVPS HOSTS\n- Spam404\n- And many others\n\nOf course, the more filters enabled, the higher the memory footprint. Yet, even after adding Fanboy's two extra lists, hpHosts’s Ad and tracking servers, uBlock still has a lower memory footprint than other very popular blockers out there.\n\nAlso, be aware that selecting some of these extra lists may lead to higher likelihood of web site breakage -- especially those lists which are normally used as hosts file.\n\n***\n\nWithout the preset lists of filters, this extension is nothing. So if ever you really do want to contribute something, think about the people working hard to maintain the filter lists you are using, which were made available to use by all for free.\n\n***\n\nFree.\nOpen source with public license (GPLv3)\nFor users by users.\n\nContributors @ Github: https://github.com/gorhill/uBlock/graphs/contributors\nContributors @ Crowdin: https://crowdin.net/project/ublock\n\n***\n\nIt's quite an early version, keep this in mind when you review.\n\nProject change log:\nhttps://github.com/gorhill/uBlock/releases\n", "file_path": "dist/description/description-ta.txt", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017443785327486694, 0.00017098399985115975, 0.0001662830909481272, 0.0001716784026939422, 2.6859390800382243e-06]} {"hunk": {"id": 10, "code_window": ["\n", " onDOMChanged: function(addedNodes, removedNodes) {\n", " if ( this.selectors.size === 0 ) { return; }\n", " this.mustApplySelectors =\n", " this.mustApplySelectors ||\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" onDOMChanged(addedNodes, removedNodes) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 817}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9988359808921814, 0.08900986611843109, 0.00015947125211823732, 0.00017284623754676431, 0.26798713207244873]} {"hunk": {"id": 10, "code_window": ["\n", " onDOMChanged: function(addedNodes, removedNodes) {\n", " if ( this.selectors.size === 0 ) { return; }\n", " this.mustApplySelectors =\n", " this.mustApplySelectors ||\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" onDOMChanged(addedNodes, removedNodes) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 817}, "file": "/**\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2018-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n#results {\n font-family: mono;\n font-size: 90%;\n white-space: pre;\n }\n", "file_path": "src/css/benchmarks.css", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017578629194758832, 0.00017524370923638344, 0.00017430965090170503, 0.00017563518485985696, 6.633536600020307e-07]} {"hunk": {"id": 10, "code_window": ["\n", " onDOMChanged: function(addedNodes, removedNodes) {\n", " if ( this.selectors.size === 0 ) { return; }\n", " this.mustApplySelectors =\n", " this.mustApplySelectors ||\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" onDOMChanged(addedNodes, removedNodes) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 817}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2015-2018 Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/******************************************************************************/\n\nif ( typeof vAPI === 'object' && vAPI.domFilterer ) {\n vAPI.domFilterer.toggle(true);\n}\n\n\n\n\n\n\n\n\n/*******************************************************************************\n\n DO NOT:\n - Remove the following code\n - Add code beyond the following code\n Reason:\n - https://github.com/gorhill/uBlock/pull/3721\n - uBO never uses the return value from injected content scripts\n\n**/\n\nvoid 0;\n", "file_path": "src/js/scriptlets/cosmetic-on.js", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.0001752267125993967, 0.0001702650624793023, 0.0001611487241461873, 0.00017334171570837498, 5.17034550284734e-06]} {"hunk": {"id": 10, "code_window": ["\n", " onDOMChanged: function(addedNodes, removedNodes) {\n", " if ( this.selectors.size === 0 ) { return; }\n", " this.mustApplySelectors =\n", " this.mustApplySelectors ||\n"], "labels": ["keep", "replace", "keep", "keep", "keep"], "after_edit": [" onDOMChanged(addedNodes, removedNodes) {\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 817}, "file": "{\n \"extName\": {\n \"message\": \"uBlock Origin\",\n \"description\": \"extension name.\"\n },\n \"extShortDesc\": {\n \"message\": \"Behingoz, blokeatzaile eraginkor bat. PUZ eta memorian arina.\",\n \"description\": \"this will be in the Chrome web store: must be 132 characters or less\"\n },\n \"dashboardName\": {\n \"message\": \"uBlock₀ — Kontrol panela\",\n \"description\": \"English: uBlock₀ — Dashboard\"\n },\n \"settingsPageName\": {\n \"message\": \"Ezarpenak\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"3pPageName\": {\n \"message\": \"Iragazki-zerrendak\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"1pPageName\": {\n \"message\": \"Nire iragazkiak\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"rulesPageName\": {\n \"message\": \"Nire arauak\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"whitelistPageName\": {\n \"message\": \"Zerrenda zuria\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"shortcutsPageName\": {\n \"message\": \"Lasterbideak\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"statsPageName\": {\n \"message\": \"uBlock₀ — Egunkaria\",\n \"description\": \"Title for the logger window\"\n },\n \"aboutPageName\": {\n \"message\": \"Honi buruz\",\n \"description\": \"appears as tab name in dashboard\"\n },\n \"assetViewerPageName\": {\n \"message\": \"uBlock₀ — Aktibo-ikuslea\",\n \"description\": \"Title for the asset viewer page\"\n },\n \"advancedSettingsPageName\": {\n \"message\": \"Ezarpen aurreratuak\",\n \"description\": \"Title for the advanced settings page\"\n },\n \"popupPowerSwitchInfo\": {\n \"message\": \"Klik: gaitu\\/ezgaitu uBlock₀ gune honetan.\\n\\nKtrl+klik: ezgaitu uBlock₀ orri honetan soilik.\",\n \"description\": \"English: Click: disable\\/enable uBlock₀ for this site.\\n\\nCtrl+click: disable uBlock₀ only on this page.\"\n },\n \"popupPowerSwitchInfo1\": {\n \"message\": \"Klik: Gaitu\\/ezgaitu uBlock₀ gune honetan.\\n\\nKtrl+klik: Desgaitu uBlock₀ orri honetan soilik.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupPowerSwitchInfo2\": {\n \"message\": \"Kilk: Gaitu uBlock₀ gune honetan.\",\n \"description\": \"Message to be read by screen readers\"\n },\n \"popupBlockedRequestPrompt\": {\n \"message\": \"blokeatutako eskariak\",\n \"description\": \"English: requests blocked\"\n },\n \"popupBlockedOnThisPagePrompt\": {\n \"message\": \"orri honetan\",\n \"description\": \"English: on this page\"\n },\n \"popupBlockedStats\": {\n \"message\": \"{{count}} edo %{{percent}}\",\n \"description\": \"Example: 15 or 13%\"\n },\n \"popupBlockedSinceInstallPrompt\": {\n \"message\": \"instalaziotik\",\n \"description\": \"English: since install\"\n },\n \"popupOr\": {\n \"message\": \"edo\",\n \"description\": \"English: or\"\n },\n \"popupTipDashboard\": {\n \"message\": \"Ireki kontrol panela\",\n \"description\": \"English: Click to open the dashboard\"\n },\n \"popupTipZapper\": {\n \"message\": \"Elementuak lekuz aldatzeko modua\",\n \"description\": \"Tooltip for the element-zapper icon in the popup panel\"\n },\n \"popupTipPicker\": {\n \"message\": \"Elementuak hautatzeko modua\",\n \"description\": \"English: Enter element picker mode\"\n },\n \"popupTipLog\": {\n \"message\": \"Ireki egunkaria\",\n \"description\": \"Tooltip used for the logger icon in the panel\"\n },\n \"popupTipNoPopups\": {\n \"message\": \"Txandakatu laster-leihoen blokeoa gune honetan\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups1\": {\n \"message\": \"Click: Blokeatu gune honetako laster leiho guztiak\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoPopups2\": {\n \"message\": \"Click: Utzi gune honetako laster-leihoak blokeatzeari\",\n \"description\": \"Tooltip for the no-popups per-site switch\"\n },\n \"popupTipNoLargeMedia\": {\n \"message\": \"Txandakatu multimedia elementu handiak blokeatzea gune honetan\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia1\": {\n \"message\": \"Klik: Blokeatu gune honetako tamaina handiko elementuak\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoLargeMedia2\": {\n \"message\": \"Klik: Utzi gune honetako tamaina handiko elementuak blokeatzeari\",\n \"description\": \"Tooltip for the no-large-media per-site switch\"\n },\n \"popupTipNoCosmeticFiltering\": {\n \"message\": \"Txandakatu iragazki kosmetikoa gune honetan\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering1\": {\n \"message\": \"Klik: Desgaitu iragazki kosmetikoak gune honetan\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoCosmeticFiltering2\": {\n \"message\": \"Klik: Gaitu iragazki kosmetikoak gune honetan\",\n \"description\": \"Tooltip for the no-cosmetic-filtering per-site switch\"\n },\n \"popupTipNoRemoteFonts\": {\n \"message\": \"Txandakatu urruneko letra tipoen blokeoa gune honetan\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts1\": {\n \"message\": \"Klik: Blokeatu urruneko letra-tipoak gune honetan\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoRemoteFonts2\": {\n \"message\": \"Klik: Utzi urruneko letra-tipoak gune honetan blokeatzeari\",\n \"description\": \"Tooltip for the no-remote-fonts per-site switch\"\n },\n \"popupTipNoScripting1\": {\n \"message\": \"Egin klik gune honetan JavaScript desgaitzeko\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipNoScripting2\": {\n \"message\": \"Egin klik gune honetan JavaScript desgaitzeari uzteko\",\n \"description\": \"Tooltip for the no-scripting per-site switch\"\n },\n \"popupTipGlobalRules\": {\n \"message\": \"Arau orokorrak: Zutabe hau gune guztietan aplikatzen diren arauentzat da.\",\n \"description\": \"Tooltip when hovering the top-most cell of the global-rules column.\"\n },\n \"popupTipLocalRules\": {\n \"message\": \"Tokiko arauak: Zutabe hau soilik uneko gunean aplikatuko diren arauentzat da. Tokiko arauek arau orokorrak gainidazten dituzte.\",\n \"description\": \"Tooltip when hovering the top-most cell of the local-rules column.\"\n },\n \"popupTipSaveRules\": {\n \"message\": \"Sakatu aldaketak gordetzeko.\",\n \"description\": \"Tooltip when hovering over the padlock in the dynamic filtering pane.\"\n },\n \"popupTipRevertRules\": {\n \"message\": \"Sakatu aldaketak desegiteko.\",\n \"description\": \"Tooltip when hovering over the eraser in the dynamic filtering pane.\"\n },\n \"popupAnyRulePrompt\": {\n \"message\": \"guztiak\",\n \"description\": \"\"\n },\n \"popupImageRulePrompt\": {\n \"message\": \"irudiak\",\n \"description\": \"\"\n },\n \"popup3pAnyRulePrompt\": {\n \"message\": \"Hirugarrengoak\",\n \"description\": \"\"\n },\n \"popup3pPassiveRulePrompt\": {\n \"message\": \"Hirugarrengoen CSS\\/Irudiak\",\n \"description\": \"\"\n },\n \"popupInlineScriptRulePrompt\": {\n \"message\": \"barne scriptak\",\n \"description\": \"\"\n },\n \"popup1pScriptRulePrompt\": {\n \"message\": \"bertako scriptak\",\n \"description\": \"\"\n },\n \"popup3pScriptRulePrompt\": {\n \"message\": \"hirugarrengoen scriptak\",\n \"description\": \"\"\n },\n \"popup3pFrameRulePrompt\": {\n \"message\": \"hirugarrengoen markoak\",\n \"description\": \"\"\n },\n \"popupHitDomainCountPrompt\": {\n \"message\": \"konektatutako domeinuak\",\n \"description\": \"appears in popup\"\n },\n \"popupHitDomainCount\": {\n \"message\": \"{{count}} \\/ {{total}}\",\n \"description\": \"appears in popup\"\n },\n \"pickerCreate\": {\n \"message\": \"Sortu\",\n \"description\": \"English: Create\"\n },\n \"pickerPick\": {\n \"message\": \"Hautatu\",\n \"description\": \"English: Pick\"\n },\n \"pickerQuit\": {\n \"message\": \"Irten\",\n \"description\": \"English: Quit\"\n },\n \"pickerPreview\": {\n \"message\": \"Aurreikusi\",\n \"description\": \"Element picker preview mode: will cause the elements matching the current filter to be removed from the page\"\n },\n \"pickerNetFilters\": {\n \"message\": \"Sare iragazkiak\",\n \"description\": \"English: header for a type of filter in the element picker dialog\"\n },\n \"pickerCosmeticFilters\": {\n \"message\": \"Iragazki kosmetikoak\",\n \"description\": \"English: Cosmetic filters\"\n },\n \"pickerCosmeticFiltersHint\": {\n \"message\": \"Klik, Ktrl-klik\",\n \"description\": \"English: Click, Ctrl-click\"\n },\n \"pickerContextMenuEntry\": {\n \"message\": \"Blokeatu elementua\",\n \"description\": \"English: Block element\"\n },\n \"settingsCollapseBlockedPrompt\": {\n \"message\": \"Ezkutatu blokeatutako elementuen hutsuneak\",\n \"description\": \"English: Hide placeholders of blocked elements\"\n },\n \"settingsIconBadgePrompt\": {\n \"message\": \"Bistaratu blokeatutako eskari kopurua ikonoan\",\n \"description\": \"English: Show the number of blocked requests on the icon\"\n },\n \"settingsTooltipsPrompt\": {\n \"message\": \"Desgaitu argibideak\",\n \"description\": \"A checkbox in the Settings pane\"\n },\n \"settingsContextMenuPrompt\": {\n \"message\": \"Erabili laster-menua egokia denean\",\n \"description\": \"English: Make use of context menu where appropriate\"\n },\n \"settingsColorBlindPrompt\": {\n \"message\": \"Kolore-itsuentzat egokia\",\n \"description\": \"English: Color-blind friendly\"\n },\n \"settingsCloudStorageEnabledPrompt\": {\n \"message\": \"Gaitu hodei biltegiratzearen euskarria\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserPrompt\": {\n \"message\": \"Erabiltzaile aurreratua naiz (Irakurri beharrekoa<\\/a>)\",\n \"description\": \"\"\n },\n \"settingsAdvancedUserSettings\": {\n \"message\": \"ezarpen aurreratuak\",\n \"description\": \"For the tooltip of a link which gives access to advanced settings\"\n },\n \"settingsPrefetchingDisabledPrompt\": {\n \"message\": \"Desgaitu aurrez-kargatzea (blokeatutako sare eskaeretako edozein konexio galarazteko)\",\n \"description\": \"English: \"\n },\n \"settingsHyperlinkAuditingDisabledPrompt\": {\n \"message\": \"Desgaitu loturen auditoretza\",\n \"description\": \"English: \"\n },\n \"settingsWebRTCIPAddressHiddenPrompt\": {\n \"message\": \"Galarazi WebRTCk tokiko IP helbidea iragartzea\",\n \"description\": \"English: \"\n },\n \"settingPerSiteSwitchGroup\": {\n \"message\": \"Lehenetsitako portaera\",\n \"description\": \"\"\n },\n \"settingPerSiteSwitchGroupSynopsis\": {\n \"message\": \"Lehenetsitako portaera hauek gunez gune gainidatzi daitezke\",\n \"description\": \"\"\n },\n \"settingsNoCosmeticFilteringPrompt\": {\n \"message\": \"Desgaitu iragazki kosmetikoa\",\n \"description\": \"\"\n },\n \"settingsNoLargeMediaPrompt\": {\n \"message\": \"Blokeatu {{input:number}} kB baino handiagoak diren multimedia elementuak\",\n \"description\": \"\"\n },\n \"settingsNoRemoteFontsPrompt\": {\n \"message\": \"Blokeatu urruneko letra-tipoak\",\n \"description\": \"\"\n },\n \"settingsNoScriptingPrompt\": {\n \"message\": \"Desgaitu JavaScript\",\n \"description\": \"The default state for the per-site no-scripting switch\"\n },\n \"settingsNoCSPReportsPrompt\": {\n \"message\": \"Blokeatu CSP txostenak\",\n \"description\": \"background information: https:\\/\\/github.com\\/gorhill\\/uBlock\\/issues\\/3150\"\n },\n \"settingsStorageUsed\": {\n \"message\": \"Erabilitako biltegiratzea: {{value}} byte\",\n \"description\": \"English: Storage used: {{}} bytes\"\n },\n \"settingsLastRestorePrompt\": {\n \"message\": \"Azken berreskuratzea:\",\n \"description\": \"English: Last restore:\"\n },\n \"settingsLastBackupPrompt\": {\n \"message\": \"Azken babeskopia:\",\n \"description\": \"English: Last backup:\"\n },\n \"3pListsOfBlockedHostsPrompt\": {\n \"message\": \"{{netFilterCount}} sare iragazki + {{cosmeticFilterCount}} iragazki kosmetiko hemendik:\",\n \"description\": \"Appears at the top of the _3rd-party filters_ pane\"\n },\n \"3pListsOfBlockedHostsPerListStats\": {\n \"message\": \"{{used}} erabilita, guztira {{total}}\",\n \"description\": \"Appears aside each filter list in the _3rd-party filters_ pane\"\n },\n \"3pAutoUpdatePrompt1\": {\n \"message\": \"Automatikoki eguneratu iragazkien zerrenda.\",\n \"description\": \"A checkbox in the _3rd-party filters_ pane\"\n },\n \"3pUpdateNow\": {\n \"message\": \"Eguneratu orain\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pPurgeAll\": {\n \"message\": \"Garbitu cache guztiak\",\n \"description\": \"A button in the in the _3rd-party filters_ pane\"\n },\n \"3pParseAllABPHideFiltersPrompt1\": {\n \"message\": \"Prozesatu eta ezarri iragazki kosmetikoak.\",\n \"description\": \"English: Parse and enforce Adblock+ element hiding filters.\"\n },\n \"3pParseAllABPHideFiltersInfo\": {\n \"message\": \"

Aukera honek Adblock Plusekin bateragarriak diren “elementuak ezkutatzeko” iragazkiak<\\/a> prozesatzea eta ezartzea gaitzen du. Iragazki hauek nagusiki kosmetikoak dira, web orri batean itsusitzat jo diren eta sare iragazkien bidez blokeatzerik ez dauden elementuak ezkutatzeko balio dute.<\\/p>

Ezaugarri hau gaitzeak uBlock₀en memoria erabilera handitzen du.<\\/p>\",\n \"description\": \"Describes the purpose of the 'Parse and enforce cosmetic filters' feature.\"\n },\n \"3pIgnoreGenericCosmeticFilters\": {\n \"message\": \"Ezikusi iragazki kosmetiko orokorrak\",\n \"description\": \"This will cause uBO to ignore all generic cosmetic filters.\"\n },\n \"3pIgnoreGenericCosmeticFiltersInfo\": {\n \"message\": \"

Iragazki kosmetiko orokorrak webgune guztietan aplikatzeko sortu diren iragazki kosmetikoak dira.

uBlock₀ aplikazioak ongi kudeatzen baditu ere iragazki kosmetiko orokorrek wegune batzuetan memoria edo PUZ erabilera nabarmena ekar dezakete handiak eta antzinakoak diren horietan gehienbat.

Aukera hau gaituz iragazki kosmetiko orokorren erabileraren ondoriozko memoria eta PUZ erabilera gehigarria sahiestuko da, eta baita uBlock₀ beraren memoria erabilera gutxiagotu.

Ahalmen gutxiagoko gailuetan aukera hau gaitzea aholkatzen da.\",\n \"description\": \"Describes the purpose of the 'Ignore generic cosmetic filters' feature.\"\n },\n \"3pListsOfBlockedHostsHeader\": {\n \"message\": \"Lists of blocked hosts\",\n \"description\": \"English: Lists of blocked hosts\"\n },\n \"3pApplyChanges\": {\n \"message\": \"Aplikatu aldaketak\",\n \"description\": \"English: Apply changes\"\n },\n \"3pGroupDefault\": {\n \"message\": \"Barnekoa\",\n \"description\": \"Header for the uBlock filters section in 'Filter lists pane'\"\n },\n \"3pGroupAds\": {\n \"message\": \"Iragarkiak\",\n \"description\": \"English: Ads\"\n },\n \"3pGroupPrivacy\": {\n \"message\": \"Pribatutasuna\",\n \"description\": \"English: Privacy\"\n },\n \"3pGroupMalware\": {\n \"message\": \"Malware domeinuak\",\n \"description\": \"English: Malware domains\"\n },\n \"3pGroupAnnoyances\": {\n \"message\": \"Eragozpenak\",\n \"description\": \"The header identifying the filter lists in the category 'annoyances'\"\n },\n \"3pGroupMultipurpose\": {\n \"message\": \"Helburu anitzekoak\",\n \"description\": \"English: Multipurpose\"\n },\n \"3pGroupRegions\": {\n \"message\": \"Eskualdeak, hizkuntzak\",\n \"description\": \"English: Regions, languages\"\n },\n \"3pGroupCustom\": {\n \"message\": \"Pertsonala\",\n \"description\": \"English: Custom\"\n },\n \"3pImport\": {\n \"message\": \"Inportatu...\",\n \"description\": \"The label for the checkbox used to import external filter lists\"\n },\n \"3pExternalListsHint\": {\n \"message\": \"URL bat lerroko. Baliogabeko URL-ak ezikusiko dira.\",\n \"description\": \"Short information about how to use the textarea to import external filter lists by URL\"\n },\n \"3pExternalListObsolete\": {\n \"message\": \"Zaharkituta.\",\n \"description\": \"used as a tooltip for the out-of-date icon beside a list\"\n },\n \"3pLastUpdate\": {\n \"message\": \"Azken eguneraketa: {{ago}}.\",\n \"description\": \"used as a tooltip for the clock icon beside a list\"\n },\n \"3pUpdating\": {\n \"message\": \"Eguneratzen...\",\n \"description\": \"used as a tooltip for the spinner icon beside a list\"\n },\n \"3pNetworkError\": {\n \"message\": \"Sare errore batek baliabidea eguneratzea eragotzi du.\",\n \"description\": \"used as a tooltip for error icon beside a list\"\n },\n \"1pFormatHint\": {\n \"message\": \"Iragazki bat lerroko. Iragazkia hostalari izen soila izan daiteke, edo Adblock Plusekin bateragarria den iragazki bat. Hasieran !<\\/code> duten lerroak ezikusiko dira.\",\n \"description\": \"Short information about how to create custom filters\"\n },\n \"1pImport\": {\n \"message\": \"Inportatu eta gehitu\",\n \"description\": \"English: Import and append\"\n },\n \"1pExport\": {\n \"message\": \"Esportatu\",\n \"description\": \"English: Export\"\n },\n \"1pExportFilename\": {\n \"message\": \"nire-ublock-iragazki-estatikoak_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-static-filters_{{datetime}}.txt\"\n },\n \"1pApplyChanges\": {\n \"message\": \"Aplikatu aldaketak\",\n \"description\": \"English: Apply changes\"\n },\n \"rulesPermanentHeader\": {\n \"message\": \"Behin betiko arauak\",\n \"description\": \"header\"\n },\n \"rulesTemporaryHeader\": {\n \"message\": \"Behin behineko arauak\",\n \"description\": \"header\"\n },\n \"rulesRevert\": {\n \"message\": \"Baztertu\",\n \"description\": \"This will remove all temporary rules\"\n },\n \"rulesCommit\": {\n \"message\": \"Behin betiko bihurtu\",\n \"description\": \"This will persist temporary rules\"\n },\n \"rulesEdit\": {\n \"message\": \"Aldatu\",\n \"description\": \"Will enable manual-edit mode (textarea)\"\n },\n \"rulesEditSave\": {\n \"message\": \"Gorde\",\n \"description\": \"Will save manually-edited content and exit manual-edit mode\"\n },\n \"rulesEditDiscard\": {\n \"message\": \"Baztertu\",\n \"description\": \"Will discard manually-edited content and exit manual-edit mode\"\n },\n \"rulesImport\": {\n \"message\": \"Inportatu fitxategitik...\",\n \"description\": \"\"\n },\n \"rulesExport\": {\n \"message\": \"Esportatu fitxategira\",\n \"description\": \"\"\n },\n \"rulesDefaultFileName\": {\n \"message\": \"nire-ublock-arau-dinamikoak_{{datetime}}.txt\",\n \"description\": \"default file name to use\"\n },\n \"rulesHint\": {\n \"message\": \"Zure iragazki dinamikoen arau zerrenda.\",\n \"description\": \"English: List of your dynamic filtering rules.\"\n },\n \"rulesFormatHint\": {\n \"message\": \"Arauen sintaxia: jatorria helburua mota ekintza<\\/code>(Dokumentazio osoa<\\/a>).\",\n \"description\": \"English: dynamic rule syntax and full documentation.\"\n },\n \"whitelistPrompt\": {\n \"message\": \"Zerrenda zuriaren direktibek uBlock zeintzu web orrietan desgaituko den zehazten dute. Sarrera bat lerroko. Baliogabeko ostalari izenak ezikusiko dira.\",\n \"description\": \"English: An overview of the content of the dashboard's Whitelist pane.\"\n },\n \"whitelistImport\": {\n \"message\": \"Inportatu eta gehitu\",\n \"description\": \"English: Import and append\"\n },\n \"whitelistExport\": {\n \"message\": \"Esportatu\",\n \"description\": \"English: Export\"\n },\n \"whitelistExportFilename\": {\n \"message\": \"nire-ublock-zerrendazuria_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-whitelist_{{datetime}}.txt\"\n },\n \"whitelistApply\": {\n \"message\": \"Aplikatu aldaketak\",\n \"description\": \"English: Apply changes\"\n },\n \"logRequestsHeaderType\": {\n \"message\": \"Mota\",\n \"description\": \"English: Type\"\n },\n \"logRequestsHeaderDomain\": {\n \"message\": \"Domeinua\",\n \"description\": \"English: Domain\"\n },\n \"logRequestsHeaderURL\": {\n \"message\": \"URL\",\n \"description\": \"English: URL\"\n },\n \"logRequestsHeaderFilter\": {\n \"message\": \"Iragazkia\",\n \"description\": \"English: Filter\"\n },\n \"logAll\": {\n \"message\": \"Guztiak\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"logBehindTheScene\": {\n \"message\": \"Atzeko planoan\",\n \"description\": \"Pretty name for behind-the-scene network requests\"\n },\n \"loggerCurrentTab\": {\n \"message\": \"Uneko fitxa\",\n \"description\": \"Appears in the logger's tab selector\"\n },\n \"loggerReloadTip\": {\n \"message\": \"Birkargatu fitxako edukia\",\n \"description\": \"Tooltip for the reload button in the logger page\"\n },\n \"loggerDomInspectorTip\": {\n \"message\": \"Txandakatu DOM ikuskatzailea\",\n \"description\": \"Tooltip for the DOM inspector button in the logger page\"\n },\n \"loggerPopupPanelTip\": {\n \"message\": \"Txandakatu laster-leiho panela\",\n \"description\": \"Tooltip for the popup panel button in the logger page\"\n },\n \"loggerInfoTip\": {\n \"message\": \"uBlock Origin wiki: Egunkaria\",\n \"description\": \"Tooltip for the top-right info label in the logger page\"\n },\n \"loggerClearTip\": {\n \"message\": \"Garbitu egunkaria\",\n \"description\": \"Tooltip for the eraser in the logger page; used to blank the content of the logger\"\n },\n \"loggerPauseTip\": {\n \"message\": \"Pausatu egunkaria (baztertu jasotako informazioa)\",\n \"description\": \"Tooltip for the pause button in the logger page\"\n },\n \"loggerUnpauseTip\": {\n \"message\": \"Kendu pausa egunkariari\",\n \"description\": \"Tooltip for the play button in the logger page\"\n },\n \"loggerRowFiltererButtonTip\": {\n \"message\": \"Txandakatu egunkariaren iragazkia\",\n \"description\": \"Tooltip for the row filterer button in the logger page\"\n },\n \"logFilterPrompt\": {\n \"message\": \"iragazi egunkariko sarrerak\",\n \"description\": \"Placeholder string for logger output filtering input field\"\n },\n \"loggerRowFiltererBuiltinTip\": {\n \"message\": \"Egunkaria iragazteko aukerak\",\n \"description\": \"Tooltip for the button to bring up logger output filtering options\"\n },\n \"loggerRowFiltererBuiltinNot\": {\n \"message\": \"Ez\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinEventful\": {\n \"message\": \"eventful\",\n \"description\": \"A keyword in the built-in row filtering expression: all items corresponding to uBO doing something (blocked, allowed, redirected, etc.)\"\n },\n \"loggerRowFiltererBuiltinBlocked\": {\n \"message\": \"blokeatuta\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltinAllowed\": {\n \"message\": \"baimenduta\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin1p\": {\n \"message\": \"1st-party\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerRowFiltererBuiltin3p\": {\n \"message\": \"3rd-party\",\n \"description\": \"A keyword in the built-in row filtering expression\"\n },\n \"loggerEntryDetailsHeader\": {\n \"message\": \"Xehetasunak\",\n \"description\": \"Small header to identify the 'Details' pane for a specific logger entry\"\n },\n \"loggerEntryDetailsFilter\": {\n \"message\": \"Iragazkia\",\n \"description\": \"Label to identify a filter field\"\n },\n \"loggerEntryDetailsFilterList\": {\n \"message\": \"Iragazki-zerrendak\",\n \"description\": \"Label to identify a filter list field\"\n },\n \"loggerEntryDetailsRule\": {\n \"message\": \"Araua\",\n \"description\": \"Label to identify a rule field\"\n },\n \"loggerEntryDetailsContext\": {\n \"message\": \"Testuingurua\",\n \"description\": \"Label to identify a context field (typically a hostname)\"\n },\n \"loggerEntryDetailsRootContext\": {\n \"message\": \"Erro testuingurua\",\n \"description\": \"Label to identify a root context field (typically a hostname)\"\n },\n \"loggerEntryDetailsPartyness\": {\n \"message\": \"Partyness\",\n \"description\": \"Label to identify a field providing partyness information\"\n },\n \"loggerEntryDetailsType\": {\n \"message\": \"Mota\",\n \"description\": \"Label to identify the type of an entry\"\n },\n \"loggerEntryDetailsURL\": {\n \"message\": \"URLa\",\n \"description\": \"Label to identify the URL of an entry\"\n },\n \"loggerURLFilteringHeader\": {\n \"message\": \"URL araua\",\n \"description\": \"Small header to identify the dynamic URL filtering section\"\n },\n \"loggerURLFilteringContextLabel\": {\n \"message\": \"Testuingurua:\",\n \"description\": \"Label for the context selector\"\n },\n \"loggerURLFilteringTypeLabel\": {\n \"message\": \"Mota:\",\n \"description\": \"Label for the type selector\"\n },\n \"loggerStaticFilteringHeader\": {\n \"message\": \"Iragazketa estatikoa\",\n \"description\": \"Small header to identify the static filtering section\"\n },\n \"loggerStaticFilteringSentence\": {\n \"message\": \"{{action}} {{type}} motako sare eskariak {{br}}URL helbidea {{url}} helbidearekin bat datorrenean {{br}}eta jatorria {{origin}} denean,{{br}}{{importance}} bat datorren salbuespen iragazki bat badago.\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartBlock\": {\n \"message\": \"Blokeatu\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAllow\": {\n \"message\": \"Baimendu\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartType\": {\n \"message\": \"mota “{{type}}”\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyType\": {\n \"message\": \"edozein mota\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartOrigin\": {\n \"message\": \"hemendik “{{origin}}”\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartAnyOrigin\": {\n \"message\": \"edonondik\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartNotImportant\": {\n \"message\": \"kenduta\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringSentencePartImportant\": {\n \"message\": \"nahiz eta\",\n \"description\": \"Used in the static filtering wizard\"\n },\n \"loggerStaticFilteringFinderSentence1\": {\n \"message\": \"{{filter}}<\\/code> iragazki estatikoa aurkitu da hemen:\",\n \"description\": \"Below this sentence, the filter list(s) in which the filter was found\"\n },\n \"loggerStaticFilteringFinderSentence2\": {\n \"message\": \"{{filter}}<\\/code> iragazki estatikoa ezin izan da aurkitu orain aktibatutako iragazki zerrendetan\",\n \"description\": \"Message to show when a filter cannot be found in any filter lists\"\n },\n \"loggerSettingDiscardPrompt\": {\n \"message\": \"Logger entries which do not fulfill all three conditions below will be automatically discarded:\",\n \"description\": \"Logger setting: A sentence to describe the purpose of the settings below\"\n },\n \"loggerSettingPerEntryMaxAge\": {\n \"message\": \"Preserve entries from the last {{input}} minutes\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxLoads\": {\n \"message\": \"Preserve at most {{input}} page loads per tab\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerTabMaxEntries\": {\n \"message\": \"Preserve at most {{input}} entries per tab\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingPerEntryLineCount\": {\n \"message\": \"Use {{input}} lines per entry in vertically expanded mode\",\n \"description\": \"A logger setting\"\n },\n \"loggerSettingHideColumnsPrompt\": {\n \"message\": \"Ezkutatu zutabeak:\",\n \"description\": \"Logger settings: a sentence to describe the purpose of the checkboxes below\"\n },\n \"loggerSettingHideColumnTime\": {\n \"message\": \"{{input}} Denbora\",\n \"description\": \"A label for the time column\"\n },\n \"loggerSettingHideColumnFilter\": {\n \"message\": \"{{input}} Iragazkia\\/araua\",\n \"description\": \"A label for the filter or rule column\"\n },\n \"loggerSettingHideColumnContext\": {\n \"message\": \"{{input}} Testuingurua\",\n \"description\": \"A label for the context column\"\n },\n \"loggerSettingHideColumnPartyness\": {\n \"message\": \"{{input}} Partyness\",\n \"description\": \"A label for the partyness column\"\n },\n \"loggerExportFormatList\": {\n \"message\": \"Zerrenda\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportFormatTable\": {\n \"message\": \"Taula\",\n \"description\": \"Label for radio-button to pick export format\"\n },\n \"loggerExportEncodePlain\": {\n \"message\": \"Laua\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"loggerExportEncodeMarkdown\": {\n \"message\": \"Markdown\",\n \"description\": \"Label for radio-button to pick export text format\"\n },\n \"aboutChangelog\": {\n \"message\": \"Aldaketa egunkaria\",\n \"description\": \"\"\n },\n \"aboutWiki\": {\n \"message\": \"Wiki\",\n \"description\": \"English: project' wiki on GitHub\"\n },\n \"aboutSupport\": {\n \"message\": \"Laguntza\",\n \"description\": \"A link for where to get support\"\n },\n \"aboutIssues\": {\n \"message\": \"Akats datu-basea\",\n \"description\": \"Text for a link to official issue tracker\"\n },\n \"aboutCode\": {\n \"message\": \"Iturburu kodea (GPLv3)\",\n \"description\": \"English: Source code (GPLv3)\"\n },\n \"aboutContributors\": {\n \"message\": \"Parte-hartzaileak\",\n \"description\": \"English: Contributors\"\n },\n \"aboutDependencies\": {\n \"message\": \"Kanpo menpekotasunak (GPLv3 lizentziarekin bateragarriak):\",\n \"description\": \"Shown in the About pane\"\n },\n \"aboutBackupDataButton\": {\n \"message\": \"Egin babeskopia fitxategian\",\n \"description\": \"Text for button to create a backup of all settings\"\n },\n \"aboutBackupFilename\": {\n \"message\": \"nire-ublock-babeskopia_{{datetime}}.txt\",\n \"description\": \"English: my-ublock-backup_{{datetime}}.txt\"\n },\n \"aboutRestoreDataButton\": {\n \"message\": \"Berreskuratu fitxategitik...\",\n \"description\": \"English: Restore from file...\"\n },\n \"aboutResetDataButton\": {\n \"message\": \"Leheneratu lehenetsitako ezarpenetara...\",\n \"description\": \"English: Reset to default settings...\"\n },\n \"aboutRestoreDataConfirm\": {\n \"message\": \"Zure ezarpen guztiak gainidatziko dira {{time}}ko datuak erabiliz, eta uBlock₀ berrabiaraziko da.\\n\\nGainidatzi ezarpen guztiak babeskopiako datuekin?\",\n \"description\": \"Message asking user to confirm restore\"\n },\n \"aboutRestoreDataError\": {\n \"message\": \"Datuak ezin dira irakurri edo baliogabeak dira\",\n \"description\": \"Message to display when an error occurred during restore\"\n },\n \"aboutResetDataConfirm\": {\n \"message\": \"Zure ezarpen guztiak ezabatuko dira, eta uBlock₀ berrabiaraziko da.\\n\\nLeheneratu uBlock₀ jatorrizko ezarpenetara?\",\n \"description\": \"Message asking user to confirm reset\"\n },\n \"errorCantConnectTo\": {\n \"message\": \"Sare-errorea: {{msg}}\",\n \"description\": \"English: Network error: {{msg}}\"\n },\n \"subscriberConfirm\": {\n \"message\": \"uBlock₀: Gehitu honako URL hauek zure iragazki pertsonalizatuen zerrendara?\\n\\nIzenburua: \\\"{{title}}\\\"\\nURLa: {{url}}\",\n \"description\": \"English: The message seen by the user to confirm subscription to a ABP filter list\"\n },\n \"elapsedOneMinuteAgo\": {\n \"message\": \"duela minutu bat\",\n \"description\": \"English: a minute ago\"\n },\n \"elapsedManyMinutesAgo\": {\n \"message\": \"duela {{value}} minutu\",\n \"description\": \"English: {{value}} minutes ago\"\n },\n \"elapsedOneHourAgo\": {\n \"message\": \"duela ordu bat\",\n \"description\": \"English: an hour ago\"\n },\n \"elapsedManyHoursAgo\": {\n \"message\": \"duela {{value}} ordu\",\n \"description\": \"English: {{value}} hours ago\"\n },\n \"elapsedOneDayAgo\": {\n \"message\": \"duela egun bat\",\n \"description\": \"English: a day ago\"\n },\n \"elapsedManyDaysAgo\": {\n \"message\": \"duela {{value}} egun\",\n \"description\": \"English: {{value}} days ago\"\n },\n \"showDashboardButton\": {\n \"message\": \"Bistaratu kontrol panela\",\n \"description\": \"Firefox\\/Fennec-specific: Show Dashboard\"\n },\n \"showNetworkLogButton\": {\n \"message\": \"Bistaratu egunkaria\",\n \"description\": \"Firefox\\/Fennec-specific: Show Logger\"\n },\n \"fennecMenuItemBlockingOff\": {\n \"message\": \"itzalita\",\n \"description\": \"Firefox-specific: appears as 'uBlock₀ (off)'\"\n },\n \"docblockedPrompt1\": {\n \"message\": \"uBlock₀ek orri hau kargatzea galarazi du:\",\n \"description\": \"English: uBlock₀ has prevented the following page from loading:\"\n },\n \"docblockedPrompt2\": {\n \"message\": \"Iragazki hau dela eta\",\n \"description\": \"English: Because of the following filter\"\n },\n \"docblockedNoParamsPrompt\": {\n \"message\": \"parametrorik gabe\",\n \"description\": \"label to be used for the parameter-less URL: https:\\/\\/cloud.githubusercontent.com\\/assets\\/585534\\/9832014\\/bfb1b8f0-593b-11e5-8a27-fba472a5529a.png\"\n },\n \"docblockedFoundIn\": {\n \"message\": \"Hemen aurkitua:\",\n \"description\": \"English: List of filter list names follows\"\n },\n \"docblockedBack\": {\n \"message\": \"Atzera\",\n \"description\": \"English: Go back\"\n },\n \"docblockedClose\": {\n \"message\": \"Itxi leiho hau\",\n \"description\": \"English: Close this window\"\n },\n \"docblockedProceed\": {\n \"message\": \"Ezgaitu blokeatze zorrotza {{hostname}} gunean\",\n \"description\": \"English: Disable strict blocking for {{hostname}} ...\"\n },\n \"docblockedDisableTemporary\": {\n \"message\": \"Une batez\",\n \"description\": \"English: Temporarily\"\n },\n \"docblockedDisablePermanent\": {\n \"message\": \"Behin betiko\",\n \"description\": \"English: Permanently\"\n },\n \"cloudPush\": {\n \"message\": \"Esportatu hodei biltegiratzera\",\n \"description\": \"tooltip\"\n },\n \"cloudPull\": {\n \"message\": \"Inportatu hodei biltegiratzetik\",\n \"description\": \"tooltip\"\n },\n \"cloudPullAndMerge\": {\n \"message\": \"Inportatu hodeiko biltegiratzetik eta nahastu oraingo ezarpenekin\",\n \"description\": \"tooltip\"\n },\n \"cloudNoData\": {\n \"message\": \"...\\n...\",\n \"description\": \"\"\n },\n \"cloudDeviceNamePrompt\": {\n \"message\": \"Gailu honen izena:\",\n \"description\": \"used as a prompt for the user to provide a custom device name\"\n },\n \"advancedSettingsWarning\": {\n \"message\": \"Abisua! Ez aldatu ezarpen aurreratu hauek zertan ari zaren ez badakizu.\",\n \"description\": \"A warning to users at the top of 'Advanced settings' page\"\n },\n \"genericSubmit\": {\n \"message\": \"Bidali\",\n \"description\": \"for generic 'Submit' buttons\"\n },\n \"genericApplyChanges\": {\n \"message\": \"Aplikatu aldaketak\",\n \"description\": \"for generic 'Apply changes' buttons\"\n },\n \"genericRevert\": {\n \"message\": \"Baztertu\",\n \"description\": \"for generic 'Revert' buttons\"\n },\n \"genericBytes\": {\n \"message\": \"byte\",\n \"description\": \"\"\n },\n \"contextMenuTemporarilyAllowLargeMediaElements\": {\n \"message\": \"Une batez baimendu multimedia elementu handiak\",\n \"description\": \"A context menu entry, present when large media elements have been blocked on the current site\"\n },\n \"shortcutCapturePlaceholder\": {\n \"message\": \"Idatzi lasterbide bat\",\n \"description\": \"Placeholder string for input field used to capture a keyboard shortcut\"\n },\n \"genericMergeViewScrollLock\": {\n \"message\": \"Txandakatu korritze blokeatua\",\n \"description\": \"Tooltip for the button used to lock scrolling between the views in the 'My rules' pane\"\n },\n \"genericCopyToClipboard\": {\n \"message\": \"Kopiatu arbelera\",\n \"description\": \"Label for buttons used to copy something to the clipboard\"\n },\n \"dummy\": {\n \"message\": \"This entry must be the last one\",\n \"description\": \"so we dont need to deal with comma for last entry\"\n }\n}", "file_path": "src/_locales/eu/messages.json", "label": 0, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.00017722000484354794, 0.00017220039444509894, 0.00016583751130383462, 0.00017217495769727975, 2.3336676804319723e-06]} {"hunk": {"id": 11, "code_window": [" }\n", "\n", " onDOMChanged() {\n", " if ( super.onDOMChanged instanceof Function ) {\n", " super.onDOMChanged(arguments);\n", " }\n", " this.proceduralFilterer.onDOMChanged.apply(\n", " this.proceduralFilterer,\n", " arguments\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" super.onDOMChanged.apply(this, arguments);\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 871}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2014-present Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n'use strict';\n\n/*******************************************************************************\n\n +--> domCollapser\n |\n |\n domWatcher--+\n | +-- domSurveyor\n | |\n +--> domFilterer --+-- domLogger\n |\n +-- domInspector\n\n domWatcher:\n Watches for changes in the DOM, and notify the other components about these\n changes.\n\n domCollapser:\n Enforces the collapsing of DOM elements for which a corresponding\n resource was blocked through network filtering.\n\n domFilterer:\n Enforces the filtering of DOM elements, by feeding it cosmetic filters.\n\n domSurveyor:\n Surveys the DOM to find new cosmetic filters to apply to the current page.\n\n domLogger:\n Surveys the page to find and report the injected cosmetic filters blocking\n actual elements on the current page. This component is dynamically loaded\n IF AND ONLY IF uBO's logger is opened.\n\n If page is whitelisted:\n - domWatcher: off\n - domCollapser: off\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n I verified that the code in this file is completely flushed out of memory\n when a page is whitelisted.\n\n If cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: off\n - domSurveyor: off\n - domLogger: off\n\n If generic cosmetic filtering is disabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: off\n - domLogger: on if uBO logger is opened\n\n If generic cosmetic filtering is enabled:\n - domWatcher: on\n - domCollapser: on\n - domFilterer: on\n - domSurveyor: on\n - domLogger: on if uBO logger is opened\n\n Additionally, the domSurveyor can turn itself off once it decides that\n it has become pointless (repeatedly not finding new cosmetic filters).\n\n The domFilterer makes use of platform-dependent user stylesheets[1].\n\n At time of writing, only modern Firefox provides a custom implementation,\n which makes for solid, reliable and low overhead cosmetic filtering on\n Firefox.\n\n The generic implementation[2] performs as best as can be, but won't ever be\n as reliable and accurate as real user stylesheets.\n\n [1] \"user stylesheets\" refer to local CSS rules which have priority over,\n and can't be overriden by a web page's own CSS rules.\n [2] below, see platformUserCSS / platformHideNode / platformUnhideNode\n\n*/\n\n// Abort execution if our global vAPI object does not exist.\n// https://github.com/chrisaljoudi/uBlock/issues/456\n// https://github.com/gorhill/uBlock/issues/2029\n\n // >>>>>>>> start of HUGE-IF-BLOCK\nif ( typeof vAPI === 'object' && !vAPI.contentScript ) {\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.contentScript = true;\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The purpose of SafeAnimationFrame is to take advantage of the behavior of\n window.requestAnimationFrame[1]. If we use an animation frame as a timer,\n then this timer is described as follow:\n\n - time events are throttled by the browser when the viewport is not visible --\n there is no point for uBO to play with the DOM if the document is not\n visible.\n - time events are micro tasks[2].\n - time events are synchronized to monitor refresh, meaning that they can fire\n at most 1/60 (typically).\n\n If a delay value is provided, a plain timer is first used. Plain timers are\n macro-tasks, so this is good when uBO wants to yield to more important tasks\n on a page. Once the plain timer elapse, an animation frame is used to trigger\n the next time at which to execute the job.\n\n [1] https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\n [2] https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/\n\n*/\n\n// https://github.com/gorhill/uBlock/issues/2147\n\nvAPI.SafeAnimationFrame = function(callback) {\n this.fid = this.tid = undefined;\n this.callback = callback;\n};\n\nvAPI.SafeAnimationFrame.prototype = {\n start: function(delay) {\n if ( delay === undefined ) {\n if ( this.fid === undefined ) {\n this.fid = requestAnimationFrame(( ) => { this.onRAF(); } );\n }\n if ( this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.onSTO(); }, 20000);\n }\n return;\n }\n if ( this.fid === undefined && this.tid === undefined ) {\n this.tid = vAPI.setTimeout(( ) => { this.macroToMicro(); }, delay);\n }\n },\n clear: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n },\n macroToMicro: function() {\n this.tid = undefined;\n this.start();\n },\n onRAF: function() {\n if ( this.tid !== undefined ) {\n clearTimeout(this.tid);\n this.tid = undefined;\n }\n this.fid = undefined;\n this.callback();\n },\n onSTO: function() {\n if ( this.fid !== undefined ) {\n cancelAnimationFrame(this.fid);\n this.fid = undefined;\n }\n this.tid = undefined;\n this.callback();\n },\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// https://github.com/uBlockOrigin/uBlock-issues/issues/552\n// Listen and report CSP violations so that blocked resources through CSP\n// are properly reported in the logger.\n\n{\n const events = new Set();\n let timer;\n\n const send = function() {\n vAPI.messaging.send(\n 'scriptlets',\n {\n what: 'securityPolicyViolation',\n type: 'net',\n docURL: document.location.href,\n violations: Array.from(events),\n },\n response => {\n if ( response === true ) { return; }\n stop();\n }\n );\n events.clear();\n };\n\n const sendAsync = function() {\n if ( timer !== undefined ) { return; }\n timer = self.requestIdleCallback(\n ( ) => { timer = undefined; send(); },\n { timeout: 2000 }\n );\n };\n\n const listener = function(ev) {\n if ( ev.isTrusted !== true ) { return; }\n if ( ev.disposition !== 'enforce' ) { return; }\n events.add(JSON.stringify({\n url: ev.blockedURL || ev.blockedURI,\n policy: ev.originalPolicy,\n directive: ev.effectiveDirective || ev.violatedDirective,\n }));\n sendAsync();\n };\n\n const stop = function() {\n events.clear();\n if ( timer !== undefined ) {\n self.cancelIdleCallback(timer);\n timer = undefined;\n }\n document.removeEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.remove(stop);\n };\n\n document.addEventListener('securitypolicyviolation', listener);\n vAPI.shutdown.add(stop);\n\n // We need to call at least once to find out whether we really need to\n // listen to CSP violations.\n sendAsync();\n}\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domWatcher = (function() {\n\n const addedNodeLists = [];\n const removedNodeLists = [];\n const addedNodes = [];\n const ignoreTags = new Set([ 'br', 'head', 'link', 'meta', 'script', 'style' ]);\n const listeners = [];\n\n let domIsReady = false,\n domLayoutObserver,\n listenerIterator = [], listenerIteratorDirty = false,\n removedNodes = false,\n safeObserverHandlerTimer;\n\n const safeObserverHandler = function() {\n //console.time('dom watcher/safe observer handler');\n let i = addedNodeLists.length,\n j = addedNodes.length;\n while ( i-- ) {\n const nodeList = addedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n const node = nodeList[iNode];\n if ( node.nodeType !== 1 ) { continue; }\n if ( ignoreTags.has(node.localName) ) { continue; }\n if ( node.parentElement === null ) { continue; }\n addedNodes[j++] = node;\n }\n }\n addedNodeLists.length = 0;\n i = removedNodeLists.length;\n while ( i-- && removedNodes === false ) {\n const nodeList = removedNodeLists[i];\n let iNode = nodeList.length;\n while ( iNode-- ) {\n if ( nodeList[iNode].nodeType !== 1 ) { continue; }\n removedNodes = true;\n break;\n }\n }\n removedNodeLists.length = 0;\n //console.timeEnd('dom watcher/safe observer handler');\n if ( addedNodes.length === 0 && removedNodes === false ) { return; }\n for ( const listener of getListenerIterator() ) {\n listener.onDOMChanged(addedNodes, removedNodes);\n }\n addedNodes.length = 0;\n removedNodes = false;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/205\n // Do not handle added node directly from within mutation observer.\n const observerHandler = function(mutations) {\n //console.time('dom watcher/observer handler');\n let i = mutations.length;\n while ( i-- ) {\n const mutation = mutations[i];\n let nodeList = mutation.addedNodes;\n if ( nodeList.length !== 0 ) {\n addedNodeLists.push(nodeList);\n }\n nodeList = mutation.removedNodes;\n if ( nodeList.length !== 0 ) {\n removedNodeLists.push(nodeList);\n }\n }\n if ( addedNodeLists.length !== 0 || removedNodes ) {\n safeObserverHandlerTimer.start(\n addedNodeLists.length < 100 ? 1 : undefined\n );\n }\n //console.timeEnd('dom watcher/observer handler');\n };\n\n const startMutationObserver = function() {\n if ( domLayoutObserver !== undefined || !domIsReady ) { return; }\n domLayoutObserver = new MutationObserver(observerHandler);\n domLayoutObserver.observe(document.documentElement, {\n //attributeFilter: [ 'class', 'id' ],\n //attributes: true,\n childList: true,\n subtree: true\n });\n safeObserverHandlerTimer = new vAPI.SafeAnimationFrame(safeObserverHandler);\n vAPI.shutdown.add(cleanup);\n };\n\n const stopMutationObserver = function() {\n if ( domLayoutObserver === undefined ) { return; }\n cleanup();\n vAPI.shutdown.remove(cleanup);\n };\n\n const getListenerIterator = function() {\n if ( listenerIteratorDirty ) {\n listenerIterator = listeners.slice();\n listenerIteratorDirty = false;\n }\n return listenerIterator;\n };\n\n const addListener = function(listener) {\n if ( listeners.indexOf(listener) !== -1 ) { return; }\n listeners.push(listener);\n listenerIteratorDirty = true;\n if ( domIsReady !== true ) { return; }\n listener.onDOMCreated();\n startMutationObserver();\n };\n\n const removeListener = function(listener) {\n const pos = listeners.indexOf(listener);\n if ( pos === -1 ) { return; }\n listeners.splice(pos, 1);\n listenerIteratorDirty = true;\n if ( listeners.length === 0 ) {\n stopMutationObserver();\n }\n };\n\n const cleanup = function() {\n if ( domLayoutObserver !== undefined ) {\n domLayoutObserver.disconnect();\n domLayoutObserver = null;\n }\n if ( safeObserverHandlerTimer !== undefined ) {\n safeObserverHandlerTimer.clear();\n safeObserverHandlerTimer = undefined;\n }\n };\n\n const start = function() {\n domIsReady = true;\n for ( const listener of getListenerIterator() ) {\n listener.onDOMCreated();\n }\n startMutationObserver();\n };\n\n return { start, addListener, removeListener };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.matchesProp = (( ) => {\n const docElem = document.documentElement;\n if ( typeof docElem.matches !== 'function' ) {\n if ( typeof docElem.mozMatchesSelector === 'function' ) {\n return 'mozMatchesSelector';\n } else if ( typeof docElem.webkitMatchesSelector === 'function' ) {\n return 'webkitMatchesSelector';\n } else if ( typeof docElem.msMatchesSelector === 'function' ) {\n return 'msMatchesSelector';\n }\n }\n return 'matches';\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.injectScriptlet = function(doc, text) {\n if ( !doc ) { return; }\n let script;\n try {\n script = doc.createElement('script');\n script.appendChild(doc.createTextNode(text));\n (doc.head || doc.documentElement).appendChild(script);\n } catch (ex) {\n }\n if ( script ) {\n if ( script.parentNode ) {\n script.parentNode.removeChild(script);\n }\n script.textContent = '';\n }\n};\n\n/******************************************************************************/\n/******************************************************************************/\n/*******************************************************************************\n\n The DOM filterer is the heart of uBO's cosmetic filtering.\n\n DOMBaseFilterer: platform-specific\n |\n |\n +---- DOMFilterer: adds procedural cosmetic filtering\n\n*/\n\nvAPI.DOMFilterer = (function() {\n\n // 'P' stands for 'Procedural'\n\n const PSelectorHasTextTask = class {\n constructor(task) {\n let arg0 = task[1], arg1;\n if ( Array.isArray(task[1]) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.needle = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.needle.test(node.textContent) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorIfTask = class {\n constructor(task) {\n this.pselector = new PSelector(task[1]);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n if ( this.pselector.test(node) === this.target ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorIfTask.prototype.target = true;\n\n const PSelectorIfNotTask = class extends PSelectorIfTask {\n constructor(task) {\n super(task);\n this.target = false;\n }\n };\n\n const PSelectorMatchesCSSTask = class {\n constructor(task) {\n this.name = task[1].name;\n let arg0 = task[1].value, arg1;\n if ( Array.isArray(arg0) ) {\n arg1 = arg0[1]; arg0 = arg0[0];\n }\n this.value = new RegExp(arg0, arg1);\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n const style = window.getComputedStyle(node, this.pseudo);\n if ( style === null ) { return null; } /* FF */\n if ( this.value.test(style[this.name]) ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n PSelectorMatchesCSSTask.prototype.pseudo = null;\n\n const PSelectorMatchesCSSAfterTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':after';\n }\n };\n\n const PSelectorMatchesCSSBeforeTask = class extends PSelectorMatchesCSSTask {\n constructor(task) {\n super(task);\n this.pseudo = ':before';\n }\n };\n\n const PSelectorNthAncestorTask = class {\n constructor(task) {\n this.nth = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n let nth = this.nth;\n for (;;) {\n node = node.parentElement;\n if ( node === null ) { break; }\n nth -= 1;\n if ( nth !== 0 ) { continue; }\n output.push(node);\n break;\n }\n }\n return output;\n }\n };\n\n const PSelectorSpathTask = class {\n constructor(task) {\n this.spath = task[1];\n }\n exec(input) {\n const output = [];\n for ( let node of input ) {\n const parent = node.parentElement;\n if ( parent === null ) { continue; }\n let pos = 1;\n for (;;) {\n node = node.previousElementSibling;\n if ( node === null ) { break; }\n pos += 1;\n }\n const nodes = parent.querySelectorAll(\n ':scope > :nth-child(' + pos + ')' + this.spath\n );\n for ( const node of nodes ) {\n output.push(node);\n }\n }\n return output;\n }\n };\n\n const PSelectorWatchAttrs = class {\n constructor(task) {\n this.observer = null;\n this.observed = new WeakSet();\n this.observerOptions = {\n attributes: true,\n subtree: true,\n };\n const attrs = task[1];\n if ( Array.isArray(attrs) && attrs.length !== 0 ) {\n this.observerOptions.attributeFilter = task[1];\n }\n }\n // TODO: Is it worth trying to re-apply only the current selector?\n handler() {\n const filterer =\n vAPI.domFilterer && vAPI.domFilterer.proceduralFilterer;\n if ( filterer instanceof Object ) {\n filterer.onDOMChanged([ null ]);\n }\n }\n exec(input) {\n if ( input.length === 0 ) { return input; }\n if ( this.observer === null ) {\n this.observer = new MutationObserver(this.handler);\n }\n for ( const node of input ) {\n if ( this.observed.has(node) ) { continue; }\n this.observer.observe(node, this.observerOptions);\n this.observed.add(node);\n }\n return input;\n }\n };\n\n const PSelectorXpathTask = class {\n constructor(task) {\n this.xpe = document.createExpression(task[1], null);\n this.xpr = null;\n }\n exec(input) {\n const output = [];\n for ( const node of input ) {\n this.xpr = this.xpe.evaluate(\n node,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,\n this.xpr\n );\n let j = this.xpr.snapshotLength;\n while ( j-- ) {\n const node = this.xpr.snapshotItem(j);\n if ( node.nodeType === 1 ) {\n output.push(node);\n }\n }\n }\n return output;\n }\n };\n\n const PSelector = class {\n constructor(o) {\n if ( PSelector.prototype.operatorToTaskMap === undefined ) {\n PSelector.prototype.operatorToTaskMap = new Map([\n [ ':has', PSelectorIfTask ],\n [ ':has-text', PSelectorHasTextTask ],\n [ ':if', PSelectorIfTask ],\n [ ':if-not', PSelectorIfNotTask ],\n [ ':matches-css', PSelectorMatchesCSSTask ],\n [ ':matches-css-after', PSelectorMatchesCSSAfterTask ],\n [ ':matches-css-before', PSelectorMatchesCSSBeforeTask ],\n [ ':not', PSelectorIfNotTask ],\n [ ':nth-ancestor', PSelectorNthAncestorTask ],\n [ ':spath', PSelectorSpathTask ],\n [ ':watch-attrs', PSelectorWatchAttrs ],\n [ ':xpath', PSelectorXpathTask ],\n ]);\n }\n this.budget = 200; // I arbitrary picked a 1/5 second\n this.raw = o.raw;\n this.cost = 0;\n this.lastAllowanceTime = 0;\n this.selector = o.selector;\n this.tasks = [];\n const tasks = o.tasks;\n if ( !tasks ) { return; }\n for ( const task of tasks ) {\n this.tasks.push(new (this.operatorToTaskMap.get(task[0]))(task));\n }\n }\n prime(input) {\n const root = input || document;\n if ( this.selector !== '' ) {\n return root.querySelectorAll(this.selector);\n }\n return [ root ];\n }\n exec(input) {\n let nodes = this.prime(input);\n for ( const task of this.tasks ) {\n if ( nodes.length === 0 ) { break; }\n nodes = task.exec(nodes);\n }\n return nodes;\n }\n test(input) {\n const nodes = this.prime(input);\n const AA = [ null ];\n for ( const node of nodes ) {\n AA[0] = node;\n let aa = AA;\n for ( const task of this.tasks ) {\n aa = task.exec(aa);\n if ( aa.length === 0 ) { break; }\n }\n if ( aa.length !== 0 ) { return true; }\n }\n return false;\n }\n };\n PSelector.prototype.operatorToTaskMap = undefined;\n\n const DOMProceduralFilterer = function(domFilterer) {\n this.domFilterer = domFilterer;\n this.domIsReady = false;\n this.domIsWatched = false;\n this.mustApplySelectors = false;\n this.selectors = new Map();\n this.hiddenNodes = new Set();\n };\n\n DOMProceduralFilterer.prototype = {\n\n addProceduralSelectors: function(aa) {\n const addedSelectors = [];\n let mustCommit = this.domIsWatched;\n for ( let i = 0, n = aa.length; i < n; i++ ) {\n const raw = aa[i];\n const o = JSON.parse(raw);\n if ( o.style ) {\n this.domFilterer.addCSSRule(o.style[0], o.style[1]);\n mustCommit = true;\n continue;\n }\n if ( o.pseudoclass ) {\n this.domFilterer.addCSSRule(\n o.raw,\n 'display:none!important;'\n );\n mustCommit = true;\n continue;\n }\n if ( o.tasks ) {\n if ( this.selectors.has(raw) === false ) {\n const pselector = new PSelector(o);\n this.selectors.set(raw, pselector);\n addedSelectors.push(pselector);\n mustCommit = true;\n }\n continue;\n }\n }\n if ( mustCommit === false ) { return; }\n this.mustApplySelectors = this.selectors.size !== 0;\n this.domFilterer.commit();\n if ( this.domFilterer.hasListeners() ) {\n this.domFilterer.triggerListeners({\n procedural: addedSelectors\n });\n }\n },\n\n commitNow: function() {\n if ( this.selectors.size === 0 || this.domIsReady === false ) {\n return;\n }\n\n this.mustApplySelectors = false;\n\n //console.time('procedural selectors/dom layout changed');\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/341\n // Be ready to unhide nodes which no longer matches any of\n // the procedural selectors.\n const toRemove = this.hiddenNodes;\n this.hiddenNodes = new Set();\n\n let t0 = Date.now();\n\n for ( const entry of this.selectors ) {\n const pselector = entry[1];\n const allowance = Math.floor((t0 - pselector.lastAllowanceTime) / 2000);\n if ( allowance >= 1 ) {\n pselector.budget += allowance * 50;\n if ( pselector.budget > 200 ) { pselector.budget = 200; }\n pselector.lastAllowanceTime = t0;\n }\n if ( pselector.budget <= 0 ) { continue; }\n const nodes = pselector.exec();\n const t1 = Date.now();\n pselector.budget += t0 - t1;\n if ( pselector.budget < -500 ) {\n console.info('uBO: disabling %s', pselector.raw);\n pselector.budget = -0x7FFFFFFF;\n }\n t0 = t1;\n for ( const node of nodes ) {\n this.domFilterer.hideNode(node);\n this.hiddenNodes.add(node);\n }\n }\n\n for ( const node of toRemove ) {\n if ( this.hiddenNodes.has(node) ) { continue; }\n this.domFilterer.unhideNode(node);\n }\n //console.timeEnd('procedural selectors/dom layout changed');\n },\n\n createProceduralFilter: function(o) {\n return new PSelector(o);\n },\n\n onDOMCreated: function() {\n this.domIsReady = true;\n this.domFilterer.commitNow();\n },\n\n onDOMChanged: function(addedNodes, removedNodes) {\n if ( this.selectors.size === 0 ) { return; }\n this.mustApplySelectors =\n this.mustApplySelectors ||\n addedNodes.length !== 0 ||\n removedNodes;\n this.domFilterer.commit();\n }\n };\n\n const DOMFilterer = class extends vAPI.DOMFilterer {\n constructor() {\n super();\n this.exceptions = [];\n this.proceduralFilterer = new DOMProceduralFilterer(this);\n this.hideNodeAttr = undefined;\n this.hideNodeStyleSheetInjected = false;\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(this);\n }\n }\n\n commitNow() {\n super.commitNow();\n this.proceduralFilterer.commitNow();\n }\n\n addProceduralSelectors(aa) {\n this.proceduralFilterer.addProceduralSelectors(aa);\n }\n\n createProceduralFilter(o) {\n return this.proceduralFilterer.createProceduralFilter(o);\n }\n\n getAllSelectors() {\n const out = super.getAllSelectors();\n out.procedural = Array.from(this.proceduralFilterer.selectors.values());\n return out;\n }\n\n getAllExceptionSelectors() {\n return this.exceptions.join(',\\n');\n }\n\n onDOMCreated() {\n if ( super.onDOMCreated instanceof Function ) {\n super.onDOMCreated();\n }\n this.proceduralFilterer.onDOMCreated();\n }\n\n onDOMChanged() {\n if ( super.onDOMChanged instanceof Function ) {\n super.onDOMChanged(arguments);\n }\n this.proceduralFilterer.onDOMChanged.apply(\n this.proceduralFilterer,\n arguments\n );\n }\n };\n\n return DOMFilterer;\n})();\n\nvAPI.domFilterer = new vAPI.DOMFilterer();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domCollapser = (function() {\n const messaging = vAPI.messaging;\n const toCollapse = new Map();\n const src1stProps = {\n embed: 'src',\n iframe: 'src',\n img: 'src',\n object: 'data'\n };\n const src2ndProps = {\n img: 'srcset'\n };\n const tagToTypeMap = {\n embed: 'object',\n iframe: 'sub_frame',\n img: 'image',\n object: 'object'\n };\n\n let resquestIdGenerator = 1,\n processTimer,\n cachedBlockedSet,\n cachedBlockedSetHash,\n cachedBlockedSetTimer,\n toProcess = [],\n toFilter = [],\n netSelectorCacheCount = 0;\n\n const cachedBlockedSetClear = function() {\n cachedBlockedSet =\n cachedBlockedSetHash =\n cachedBlockedSetTimer = undefined;\n };\n\n // https://github.com/chrisaljoudi/uBlock/issues/174\n // Do not remove fragment from src URL\n const onProcessed = function(response) {\n if ( !response ) { // This happens if uBO is disabled or restarted.\n toCollapse.clear();\n return;\n }\n\n const targets = toCollapse.get(response.id);\n if ( targets === undefined ) { return; }\n toCollapse.delete(response.id);\n if ( cachedBlockedSetHash !== response.hash ) {\n cachedBlockedSet = new Set(response.blockedResources);\n cachedBlockedSetHash = response.hash;\n if ( cachedBlockedSetTimer !== undefined ) {\n clearTimeout(cachedBlockedSetTimer);\n }\n cachedBlockedSetTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);\n }\n if ( cachedBlockedSet === undefined || cachedBlockedSet.size === 0 ) {\n return;\n }\n const selectors = [];\n const iframeLoadEventPatch = vAPI.iframeLoadEventPatch;\n let netSelectorCacheCountMax = response.netSelectorCacheCountMax;\n\n for ( const target of targets ) {\n const tag = target.localName;\n let prop = src1stProps[tag];\n if ( prop === undefined ) { continue; }\n let src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) {\n prop = src2ndProps[tag];\n if ( prop === undefined ) { continue; }\n src = target[prop];\n if ( typeof src !== 'string' || src.length === 0 ) { continue; }\n }\n if ( cachedBlockedSet.has(tagToTypeMap[tag] + ' ' + src) === false ) {\n continue;\n }\n // https://github.com/chrisaljoudi/uBlock/issues/399\n // Never remove elements from the DOM, just hide them\n target.style.setProperty('display', 'none', 'important');\n target.hidden = true;\n // https://github.com/chrisaljoudi/uBlock/issues/1048\n // Use attribute to construct CSS rule\n if ( netSelectorCacheCount <= netSelectorCacheCountMax ) {\n const value = target.getAttribute(prop);\n if ( value ) {\n selectors.push(tag + '[' + prop + '=\"' + value + '\"]');\n netSelectorCacheCount += 1;\n }\n }\n if ( iframeLoadEventPatch !== undefined ) {\n iframeLoadEventPatch(target);\n }\n }\n\n if ( selectors.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'cosmeticFiltersInjected',\n type: 'net',\n hostname: window.location.hostname,\n selectors: selectors\n }\n );\n }\n };\n\n const send = function() {\n processTimer = undefined;\n toCollapse.set(resquestIdGenerator, toProcess);\n const msg = {\n what: 'getCollapsibleBlockedRequests',\n id: resquestIdGenerator,\n frameURL: window.location.href,\n resources: toFilter,\n hash: cachedBlockedSetHash\n };\n messaging.send('contentscript', msg, onProcessed);\n toProcess = [];\n toFilter = [];\n resquestIdGenerator += 1;\n };\n\n const process = function(delay) {\n if ( toProcess.length === 0 ) { return; }\n if ( delay === 0 ) {\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n send();\n } else if ( processTimer === undefined ) {\n processTimer = vAPI.setTimeout(send, delay || 20);\n }\n };\n\n const add = function(target) {\n toProcess[toProcess.length] = target;\n };\n\n const addMany = function(targets) {\n for ( const target of targets ) {\n add(target);\n }\n };\n\n const iframeSourceModified = function(mutations) {\n for ( const mutation of mutations ) {\n addIFrame(mutation.target, true);\n }\n process();\n };\n const iframeSourceObserver = new MutationObserver(iframeSourceModified);\n const iframeSourceObserverOptions = {\n attributes: true,\n attributeFilter: [ 'src' ]\n };\n\n // The injected scriptlets are those which were injected in the current\n // document, from within `bootstrapPhase1`, and which scriptlets are\n // selectively looked-up from:\n // https://github.com/uBlockOrigin/uAssets/blob/master/filters/resources.txt\n const primeLocalIFrame = function(iframe) {\n if ( vAPI.injectedScripts ) {\n vAPI.injectScriptlet(iframe.contentDocument, vAPI.injectedScripts);\n }\n };\n\n // https://github.com/gorhill/uBlock/issues/162\n // Be prepared to deal with possible change of src attribute.\n const addIFrame = function(iframe, dontObserve) {\n if ( dontObserve !== true ) {\n iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);\n }\n const src = iframe.src;\n if ( src === '' || typeof src !== 'string' ) {\n primeLocalIFrame(iframe);\n return;\n }\n if ( src.startsWith('http') === false ) { return; }\n toFilter.push({ type: 'sub_frame', url: iframe.src });\n add(iframe);\n };\n\n const addIFrames = function(iframes) {\n for ( const iframe of iframes ) {\n addIFrame(iframe);\n }\n };\n\n const onResourceFailed = function(ev) {\n if ( tagToTypeMap[ev.target.localName] !== undefined ) {\n add(ev.target);\n process();\n }\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if ( vAPI instanceof Object === false ) { return; }\n if ( vAPI.domCollapser instanceof Object === false ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n return;\n }\n // Listener to collapse blocked resources.\n // - Future requests not blocked yet\n // - Elements dynamically added to the page\n // - Elements which resource URL changes\n // https://github.com/chrisaljoudi/uBlock/issues/7\n // Preferring getElementsByTagName over querySelectorAll:\n // http://jsperf.com/queryselectorall-vs-getelementsbytagname/145\n const elems = document.images ||\n document.getElementsByTagName('img');\n for ( const elem of elems ) {\n if ( elem.complete ) {\n add(elem);\n }\n }\n addMany(document.embeds || document.getElementsByTagName('embed'));\n addMany(document.getElementsByTagName('object'));\n addIFrames(document.getElementsByTagName('iframe'));\n process(0);\n\n document.addEventListener('error', onResourceFailed, true);\n\n vAPI.shutdown.add(function() {\n document.removeEventListener('error', onResourceFailed, true);\n if ( processTimer !== undefined ) {\n clearTimeout(processTimer);\n }\n });\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n for ( const node of addedNodes ) {\n if ( node.localName === 'iframe' ) {\n addIFrame(node);\n }\n if ( node.childElementCount === 0 ) { continue; }\n const iframes = node.getElementsByTagName('iframe');\n if ( iframes.length !== 0 ) {\n addIFrames(iframes);\n }\n }\n process();\n }\n };\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.addListener(domWatcherInterface);\n }\n\n return { add, addMany, addIFrame, addIFrames, process };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\nvAPI.domSurveyor = (function() {\n const messaging = vAPI.messaging;\n const queriedIds = new Set();\n const queriedClasses = new Set();\n const maxSurveyNodes = 65536;\n const maxSurveyTimeSlice = 4;\n const maxSurveyBuffer = 64;\n\n let domFilterer,\n hostname = '',\n surveyCost = 0;\n\n const pendingNodes = {\n nodeLists: [],\n buffer: [\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n null, null, null, null, null, null, null, null,\n ],\n j: 0,\n accepted: 0,\n iterated: 0,\n stopped: false,\n add: function(nodes) {\n if ( nodes.length === 0 || this.accepted >= maxSurveyNodes ) {\n return;\n }\n this.nodeLists.push(nodes);\n this.accepted += nodes.length;\n },\n next: function() {\n if ( this.nodeLists.length === 0 || this.stopped ) { return 0; }\n const nodeLists = this.nodeLists;\n let ib = 0;\n do {\n const nodeList = nodeLists[0];\n let j = this.j;\n let n = j + maxSurveyBuffer - ib;\n if ( n > nodeList.length ) {\n n = nodeList.length;\n }\n for ( let i = j; i < n; i++ ) {\n this.buffer[ib++] = nodeList[j++];\n }\n if ( j !== nodeList.length ) {\n this.j = j;\n break;\n }\n this.j = 0;\n this.nodeLists.shift();\n } while ( ib < maxSurveyBuffer && nodeLists.length !== 0 );\n this.iterated += ib;\n if ( this.iterated >= maxSurveyNodes ) {\n this.nodeLists = [];\n this.stopped = true;\n //console.info(`domSurveyor> Surveyed a total of ${this.iterated} nodes. Enough.`);\n }\n return ib;\n },\n hasNodes: function() {\n return this.nodeLists.length !== 0;\n },\n };\n\n // Extract all classes/ids: these will be passed to the cosmetic\n // filtering engine, and in return we will obtain only the relevant\n // CSS selectors.\n const reWhitespace = /\\s/;\n\n // https://github.com/gorhill/uBlock/issues/672\n // http://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#space-separated-tokens\n // http://jsperf.com/enumerate-classes/6\n\n const surveyPhase1 = function() {\n //console.time('dom surveyor/surveying');\n const t0 = performance.now();\n const rews = reWhitespace;\n const ids = [];\n const classes = [];\n const nodes = pendingNodes.buffer;\n const deadline = t0 + maxSurveyTimeSlice;\n let qids = queriedIds;\n let qcls = queriedClasses;\n let processed = 0;\n for (;;) {\n const n = pendingNodes.next();\n if ( n === 0 ) { break; }\n for ( let i = 0; i < n; i++ ) {\n const node = nodes[i]; nodes[i] = null;\n let v = node.id;\n if ( typeof v === 'string' && v.length !== 0 ) {\n v = v.trim();\n if ( qids.has(v) === false && v.length !== 0 ) {\n ids.push(v); qids.add(v);\n }\n }\n let vv = node.className;\n if ( typeof vv === 'string' && vv.length !== 0 ) {\n if ( rews.test(vv) === false ) {\n if ( qcls.has(vv) === false ) {\n classes.push(vv); qcls.add(vv);\n }\n } else {\n vv = node.classList;\n let j = vv.length;\n while ( j-- ) {\n const v = vv[j];\n if ( qcls.has(v) === false ) {\n classes.push(v); qcls.add(v);\n }\n }\n }\n }\n }\n processed += n;\n if ( performance.now() >= deadline ) { break; }\n }\n const t1 = performance.now();\n surveyCost += t1 - t0;\n //console.info(`domSurveyor> Surveyed ${processed} nodes in ${(t1-t0).toFixed(2)} ms`);\n // Phase 2: Ask main process to lookup relevant cosmetic filters.\n if ( ids.length !== 0 || classes.length !== 0 ) {\n messaging.send(\n 'contentscript',\n {\n what: 'retrieveGenericCosmeticSelectors',\n hostname: hostname,\n ids: ids,\n classes: classes,\n exceptions: domFilterer.exceptions,\n cost: surveyCost\n },\n surveyPhase3\n );\n } else {\n surveyPhase3(null);\n }\n //console.timeEnd('dom surveyor/surveying');\n };\n\n const surveyTimer = new vAPI.SafeAnimationFrame(surveyPhase1);\n\n // This is to shutdown the surveyor if result of surveying keeps being\n // fruitless. This is useful on long-lived web page. I arbitrarily\n // picked 5 minutes before the surveyor is allowed to shutdown. I also\n // arbitrarily picked 256 misses before the surveyor is allowed to\n // shutdown.\n let canShutdownAfter = Date.now() + 300000,\n surveyingMissCount = 0;\n\n // Handle main process' response.\n\n const surveyPhase3 = function(response) {\n const result = response && response.result;\n let mustCommit = false;\n\n if ( result ) {\n let selectors = result.simple;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'simple' }\n );\n mustCommit = true;\n }\n selectors = result.complex;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { type: 'complex' }\n );\n mustCommit = true;\n }\n selectors = result.injected;\n if ( typeof selectors === 'string' && selectors.length !== 0 ) {\n domFilterer.addCSSRule(\n selectors,\n 'display:none!important;',\n { injected: true }\n );\n mustCommit = true;\n }\n selectors = result.excepted;\n if ( Array.isArray(selectors) && selectors.length !== 0 ) {\n domFilterer.exceptCSSRules(selectors);\n }\n }\n\n if ( pendingNodes.stopped === false ) {\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n if ( mustCommit ) {\n surveyingMissCount = 0;\n canShutdownAfter = Date.now() + 300000;\n return;\n }\n surveyingMissCount += 1;\n if ( surveyingMissCount < 256 || Date.now() < canShutdownAfter ) {\n return;\n }\n }\n\n //console.info('dom surveyor shutting down: too many misses');\n\n surveyTimer.clear();\n vAPI.domWatcher.removeListener(domWatcherInterface);\n vAPI.domSurveyor = null;\n };\n\n const domWatcherInterface = {\n onDOMCreated: function() {\n if (\n vAPI instanceof Object === false ||\n vAPI.domSurveyor instanceof Object === false ||\n vAPI.domFilterer instanceof Object === false\n ) {\n if ( vAPI instanceof Object ) {\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.removeListener(domWatcherInterface);\n }\n vAPI.domSurveyor = null;\n }\n return;\n }\n //console.time('dom surveyor/dom layout created');\n domFilterer = vAPI.domFilterer;\n pendingNodes.add(document.querySelectorAll('[id],[class]'));\n surveyTimer.start();\n //console.timeEnd('dom surveyor/dom layout created');\n },\n onDOMChanged: function(addedNodes) {\n if ( addedNodes.length === 0 ) { return; }\n //console.time('dom surveyor/dom layout changed');\n let i = addedNodes.length;\n while ( i-- ) {\n const node = addedNodes[i];\n pendingNodes.add([ node ]);\n if ( node.childElementCount === 0 ) { continue; }\n pendingNodes.add(node.querySelectorAll('[id],[class]'));\n }\n if ( pendingNodes.hasNodes() ) {\n surveyTimer.start(1);\n }\n //console.timeEnd('dom surveyor/dom layout changed');\n }\n };\n\n const start = function(details) {\n if ( vAPI.domWatcher instanceof Object === false ) { return; }\n hostname = details.hostname;\n vAPI.domWatcher.addListener(domWatcherInterface);\n };\n\n return { start };\n})();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n// Bootstrapping allows all components of the content script to be launched\n// if/when needed.\n\nvAPI.bootstrap = (function() {\n\n const bootstrapPhase2 = function() {\n // This can happen on Firefox. For instance:\n // https://github.com/gorhill/uBlock/issues/1893\n if ( window.location === null ) { return; }\n if ( vAPI instanceof Object === false ) { return; }\n\n vAPI.messaging.send(\n 'contentscript',\n { what: 'shouldRenderNoscriptTags' }\n );\n\n if ( vAPI.domWatcher instanceof Object ) {\n vAPI.domWatcher.start();\n }\n\n // Element picker works only in top window for now.\n if (\n window !== window.top ||\n vAPI.domFilterer instanceof Object === false\n ) {\n return;\n }\n\n // To send mouse coordinates to main process, as the chrome API fails\n // to provide the mouse position to context menu listeners.\n // https://github.com/chrisaljoudi/uBlock/issues/1143\n // Also, find a link under the mouse, to try to avoid confusing new tabs\n // as nuisance popups.\n // Ref.: https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu\n\n const onMouseClick = function(ev) {\n let elem = ev.target;\n while ( elem !== null && elem.localName !== 'a' ) {\n elem = elem.parentElement;\n }\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'mouseClick',\n x: ev.clientX,\n y: ev.clientY,\n url: elem !== null && ev.isTrusted !== false ? elem.href : ''\n }\n );\n };\n\n document.addEventListener('mousedown', onMouseClick, true);\n\n // https://github.com/gorhill/uMatrix/issues/144\n vAPI.shutdown.add(function() {\n document.removeEventListener('mousedown', onMouseClick, true);\n });\n };\n\n // https://github.com/uBlockOrigin/uBlock-issues/issues/403\n // If there was a spurious port disconnection -- in which case the\n // response is expressly set to `null`, rather than undefined or\n // an object -- let's stay around, we may be given the opportunity\n // to try bootstrapping again later.\n\n const bootstrapPhase1 = function(response) {\n if ( response === null ) { return; }\n vAPI.bootstrap = undefined;\n\n // cosmetic filtering engine aka 'cfe'\n const cfeDetails = response && response.specificCosmeticFilters;\n if ( !cfeDetails || !cfeDetails.ready ) {\n vAPI.domWatcher = vAPI.domCollapser = vAPI.domFilterer =\n vAPI.domSurveyor = vAPI.domIsLoaded = null;\n return;\n }\n\n if ( response.noCosmeticFiltering ) {\n vAPI.domFilterer = null;\n vAPI.domSurveyor = null;\n } else {\n const domFilterer = vAPI.domFilterer;\n if ( response.noGenericCosmeticFiltering || cfeDetails.noDOMSurveying ) {\n vAPI.domSurveyor = null;\n }\n domFilterer.exceptions = cfeDetails.exceptionFilters;\n domFilterer.hideNodeAttr = cfeDetails.hideNodeAttr;\n domFilterer.hideNodeStyleSheetInjected =\n cfeDetails.hideNodeStyleSheetInjected === true;\n domFilterer.addCSSRule(\n cfeDetails.declarativeFilters,\n 'display:none!important;'\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideSimple,\n 'display:none!important;',\n { type: 'simple', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.highGenericHideComplex,\n 'display:none!important;',\n { type: 'complex', lazy: true }\n );\n domFilterer.addCSSRule(\n cfeDetails.injectedHideFilters,\n 'display:none!important;',\n { injected: true }\n );\n domFilterer.addProceduralSelectors(cfeDetails.proceduralFilters);\n domFilterer.exceptCSSRules(cfeDetails.exceptedFilters);\n }\n\n if ( cfeDetails.networkFilters.length !== 0 ) {\n vAPI.userStylesheet.add(\n cfeDetails.networkFilters + '\\n{display:none!important;}');\n }\n\n vAPI.userStylesheet.apply();\n\n // Library of resources is located at:\n // https://github.com/gorhill/uBlock/blob/master/assets/ublock/resources.txt\n if ( response.scriptlets ) {\n vAPI.injectScriptlet(document, response.scriptlets);\n vAPI.injectedScripts = response.scriptlets;\n }\n\n if ( vAPI.domSurveyor instanceof Object ) {\n vAPI.domSurveyor.start(cfeDetails);\n }\n\n // https://github.com/chrisaljoudi/uBlock/issues/587\n // If no filters were found, maybe the script was injected before\n // uBlock's process was fully initialized. When this happens, pages\n // won't be cleaned right after browser launch.\n if (\n typeof document.readyState === 'string' &&\n document.readyState !== 'loading'\n ) {\n bootstrapPhase2();\n } else {\n document.addEventListener(\n 'DOMContentLoaded',\n bootstrapPhase2,\n { once: true }\n );\n }\n };\n\n return function() {\n vAPI.messaging.send(\n 'contentscript',\n {\n what: 'retrieveContentScriptParameters',\n url: window.location.href,\n isRootFrame: window === window.top,\n charset: document.characterSet,\n },\n bootstrapPhase1\n );\n };\n})();\n\n// This starts bootstrap process.\nvAPI.bootstrap();\n\n/******************************************************************************/\n/******************************************************************************/\n/******************************************************************************/\n\n}\n// <<<<<<<< end of HUGE-IF-BLOCK\n", "file_path": "src/js/contentscript.js", "label": 1, "commit_url": "https://github.com/gorhill/uBlock/commit/138642938257928dd18b24d38a8dd82eb5a66a4a", "dependency_score": [0.9988290667533875, 0.02651805989444256, 0.00015994958812370896, 0.00017005778499878943, 0.153080016374588]} {"hunk": {"id": 11, "code_window": [" }\n", "\n", " onDOMChanged() {\n", " if ( super.onDOMChanged instanceof Function ) {\n", " super.onDOMChanged(arguments);\n", " }\n", " this.proceduralFilterer.onDOMChanged.apply(\n", " this.proceduralFilterer,\n", " arguments\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" super.onDOMChanged.apply(this, arguments);\n"], "file_path": "src/js/contentscript.js", "type": "replace", "edit_start_line_idx": 871}, "file": "/*******************************************************************************\n\n uBlock Origin - a browser extension to block requests.\n Copyright (C) 2015-2018 Raymond Hill\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see {http://www.gnu.org/licenses/}.\n\n Home: https://github.com/gorhill/uBlock\n*/\n\n/******************************************************************************/\n\n(function() {\n\n'use strict';\n\n/******************************************************************************/\n\n// For all media resources which have failed to load, trigger a reload.\n\nvar elems, i, elem, src;\n\n//

\n// Header for shell helper functions.\n// \n//-------------------------------------------------------------------------------------------------\n\n#ifndef REFKNOWNFOLDERID\n#define REFKNOWNFOLDERID REFGUID\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef BOOL (STDAPICALLTYPE *PFN_SHELLEXECUTEEXW)(\n __inout LPSHELLEXECUTEINFOW lpExecInfo\n );\n\nvoid DAPI ShelFunctionOverride(\n __in_opt PFN_SHELLEXECUTEEXW pfnShellExecuteExW\n );\nHRESULT DAPI ShelExec(\n __in_z LPCWSTR wzTargetPath,\n __in_opt LPCWSTR wzParameters,\n __in_opt LPCWSTR wzVerb,\n __in_opt LPCWSTR wzWorkingDirectory,\n __in int nShowCmd,\n __in_opt HWND hwndParent,\n __out_opt HANDLE* phProcess\n );\nHRESULT DAPI ShelExecUnelevated(\n __in_z LPCWSTR wzTargetPath,\n __in_z_opt LPCWSTR wzParameters,\n __in_z_opt LPCWSTR wzVerb,\n __in_z_opt LPCWSTR wzWorkingDirectory,\n __in int nShowCmd\n );\nHRESULT DAPI ShelGetFolder(\n __out_z LPWSTR* psczFolderPath,\n __in int csidlFolder\n );\nHRESULT DAPI ShelGetKnownFolder(\n __out_z LPWSTR* psczFolderPath,\n __in REFKNOWNFOLDERID rfidFolder\n );\n\n#ifdef __cplusplus\n}\n#endif\n", "file_path": "scripts/windows/installer/WiXSDK/inc/shelutil.h", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.0009731046739034355, 0.0003898089053109288, 0.00017074916104320437, 0.00026128196623176336, 0.0002714056463446468]} {"hunk": {"id": 7, "code_window": ["export const CORDOVA_PLATFORMS = ['ios', 'android'];\n", "\n", "export const CORDOVA_PLATFORM_VERSIONS = {\n", " 'android': '6.1.1',\n", " 'ios': '4.3.0'\n", "};\n", "\n", "const PLATFORM_TO_DISPLAY_NAME_MAP = {\n", " 'ios': 'iOS',\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" 'android': '6.2.3',\n", " 'ios': '4.4.0'\n"], "file_path": "tools/cordova/index.js", "type": "replace", "edit_start_line_idx": 13}, "file": "// This will execute a shell script, print its output, and process.exit(0).\nNpm.require('meteor-test-executable').doIt();\n", "file_path": "tools/tests/apps/npmtest/packages/npm-test/npmtest.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00018019355775322765, 0.00018019355775322765, 0.00018019355775322765, 0.00018019355775322765, 0.0]} {"hunk": {"id": 7, "code_window": ["export const CORDOVA_PLATFORMS = ['ios', 'android'];\n", "\n", "export const CORDOVA_PLATFORM_VERSIONS = {\n", " 'android': '6.1.1',\n", " 'ios': '4.3.0'\n", "};\n", "\n", "const PLATFORM_TO_DISPLAY_NAME_MAP = {\n", " 'ios': 'iOS',\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" 'android': '6.2.3',\n", " 'ios': '4.4.0'\n"], "file_path": "tools/cordova/index.js", "type": "replace", "edit_start_line_idx": 13}, "file": "# Meteor packages used by this project, one per line.\n#\n# 'meteor add' and 'meteor remove' will edit this file for you,\n# but you can also edit it by hand.\n\nstandard-app-packages\n", "file_path": "examples/other/defer-in-inactive-tab/.meteor/packages", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00020979387045372277, 0.00020979387045372277, 0.00020979387045372277, 0.00020979387045372277, 0.0]} {"hunk": {"id": 8, "code_window": ["// Versions are taken from cordova-lib's package.json and should be updated\n", "// when we update to a newer version of cordova-lib.\n", "const pinnedPluginVersions = {\n", " \"cordova-plugin-battery-status\": \"1.2.2\",\n", " \"cordova-plugin-camera\": \"2.3.1\",\n", " \"cordova-plugin-console\": \"1.0.5\",\n", " \"cordova-plugin-contacts\": \"2.2.1\",\n", " \"cordova-plugin-device\": \"1.1.4\",\n", " \"cordova-plugin-device-motion\": \"1.2.3\",\n", " \"cordova-plugin-device-orientation\": \"1.0.5\",\n", " \"cordova-plugin-dialogs\": \"1.3.1\",\n", " \"cordova-plugin-file\": \"4.3.1\",\n", " \"cordova-plugin-file-transfer\": \"1.6.1\",\n", " \"cordova-plugin-geolocation\": \"2.4.1\",\n", " \"cordova-plugin-globalization\": \"1.0.5\",\n", " \"cordova-plugin-inappbrowser\": \"1.6.1\",\n", " \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" \"cordova-plugin-battery-status\": \"1.2.4\",\n", " \"cordova-plugin-camera\": \"2.4.1\",\n", " \"cordova-plugin-console\": \"1.0.7\",\n", " \"cordova-plugin-contacts\": \"2.3.1\",\n", " \"cordova-plugin-device\": \"1.1.6\",\n", " \"cordova-plugin-device-motion\": \"1.2.5\",\n", " \"cordova-plugin-device-orientation\": \"1.0.7\",\n", " \"cordova-plugin-dialogs\": \"1.3.3\",\n", " \"cordova-plugin-file\": \"4.3.3\",\n", " \"cordova-plugin-file-transfer\": \"1.6.3\",\n", " \"cordova-plugin-geolocation\": \"2.4.3\",\n", " \"cordova-plugin-globalization\": \"1.0.7\",\n", " \"cordova-plugin-inappbrowser\": \"1.7.1\",\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 53}, "file": "Package.describe({\n summary: \"Serves a Meteor app over HTTP\",\n version: '1.3.17'\n});\n\nNpm.depends({connect: \"2.30.2\",\n parseurl: \"1.3.0\",\n send: \"0.13.0\",\n useragent: \"2.0.7\"});\n\nNpm.strip({\n multiparty: [\"test/\"],\n useragent: [\"test/\"]\n});\n\nCordova.depends({\n 'cordova-plugin-whitelist': '1.3.1',\n 'cordova-plugin-wkwebview-engine': '1.1.1',\n 'cordova-plugin-meteor-webapp': '1.4.1'\n});\n\nPackage.onUse(function (api) {\n api.use('ecmascript');\n api.use(['logging', 'underscore', 'routepolicy', 'boilerplate-generator',\n 'webapp-hashing'], 'server');\n api.use(['underscore'], 'client');\n\n // At response serving time, webapp uses browser-policy if it is loaded. If\n // browser-policy is loaded, then it must be loaded after webapp\n // (browser-policy depends on webapp). So we don't explicitly depend in any\n // way on browser-policy here, but we use it when it is loaded, and it can be\n // loaded after webapp.\n api.mainModule('webapp_server.js', 'server');\n api.export('WebApp', 'server');\n api.export('WebAppInternals', 'server');\n api.export('main', 'server');\n\n api.mainModule('webapp_client.js', 'client');\n api.export('WebApp', 'client');\n\n api.mainModule('webapp_cordova.js', 'web.cordova');\n});\n\nPackage.onTest(function (api) {\n api.use(['tinytest', 'ecmascript', 'webapp', 'http', 'underscore']);\n api.addFiles('webapp_tests.js', 'server');\n api.addFiles('webapp_client_tests.js', 'client');\n});\n", "file_path": "packages/webapp/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.0005389921134337783, 0.00024041894357651472, 0.00016440243052784353, 0.00016598480578977615, 0.0001492891024099663]} {"hunk": {"id": 8, "code_window": ["// Versions are taken from cordova-lib's package.json and should be updated\n", "// when we update to a newer version of cordova-lib.\n", "const pinnedPluginVersions = {\n", " \"cordova-plugin-battery-status\": \"1.2.2\",\n", " \"cordova-plugin-camera\": \"2.3.1\",\n", " \"cordova-plugin-console\": \"1.0.5\",\n", " \"cordova-plugin-contacts\": \"2.2.1\",\n", " \"cordova-plugin-device\": \"1.1.4\",\n", " \"cordova-plugin-device-motion\": \"1.2.3\",\n", " \"cordova-plugin-device-orientation\": \"1.0.5\",\n", " \"cordova-plugin-dialogs\": \"1.3.1\",\n", " \"cordova-plugin-file\": \"4.3.1\",\n", " \"cordova-plugin-file-transfer\": \"1.6.1\",\n", " \"cordova-plugin-geolocation\": \"2.4.1\",\n", " \"cordova-plugin-globalization\": \"1.0.5\",\n", " \"cordova-plugin-inappbrowser\": \"1.6.1\",\n", " \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" \"cordova-plugin-battery-status\": \"1.2.4\",\n", " \"cordova-plugin-camera\": \"2.4.1\",\n", " \"cordova-plugin-console\": \"1.0.7\",\n", " \"cordova-plugin-contacts\": \"2.3.1\",\n", " \"cordova-plugin-device\": \"1.1.6\",\n", " \"cordova-plugin-device-motion\": \"1.2.5\",\n", " \"cordova-plugin-device-orientation\": \"1.0.7\",\n", " \"cordova-plugin-dialogs\": \"1.3.3\",\n", " \"cordova-plugin-file\": \"4.3.3\",\n", " \"cordova-plugin-file-transfer\": \"1.6.3\",\n", " \"cordova-plugin-geolocation\": \"2.4.3\",\n", " \"cordova-plugin-globalization\": \"1.0.7\",\n", " \"cordova-plugin-inappbrowser\": \"1.7.1\",\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 53}, "file": "Meteor.call('log', 'all clients');\n", "file_path": "tools/tests/apps/package-tests/packages/say-something-client-targets/all-clients.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00016678503016009927, 0.00016678503016009927, 0.00016678503016009927, 0.00016678503016009927, 0.0]} {"hunk": {"id": 8, "code_window": ["// Versions are taken from cordova-lib's package.json and should be updated\n", "// when we update to a newer version of cordova-lib.\n", "const pinnedPluginVersions = {\n", " \"cordova-plugin-battery-status\": \"1.2.2\",\n", " \"cordova-plugin-camera\": \"2.3.1\",\n", " \"cordova-plugin-console\": \"1.0.5\",\n", " \"cordova-plugin-contacts\": \"2.2.1\",\n", " \"cordova-plugin-device\": \"1.1.4\",\n", " \"cordova-plugin-device-motion\": \"1.2.3\",\n", " \"cordova-plugin-device-orientation\": \"1.0.5\",\n", " \"cordova-plugin-dialogs\": \"1.3.1\",\n", " \"cordova-plugin-file\": \"4.3.1\",\n", " \"cordova-plugin-file-transfer\": \"1.6.1\",\n", " \"cordova-plugin-geolocation\": \"2.4.1\",\n", " \"cordova-plugin-globalization\": \"1.0.5\",\n", " \"cordova-plugin-inappbrowser\": \"1.6.1\",\n", " \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" \"cordova-plugin-battery-status\": \"1.2.4\",\n", " \"cordova-plugin-camera\": \"2.4.1\",\n", " \"cordova-plugin-console\": \"1.0.7\",\n", " \"cordova-plugin-contacts\": \"2.3.1\",\n", " \"cordova-plugin-device\": \"1.1.6\",\n", " \"cordova-plugin-device-motion\": \"1.2.5\",\n", " \"cordova-plugin-device-orientation\": \"1.0.7\",\n", " \"cordova-plugin-dialogs\": \"1.3.3\",\n", " \"cordova-plugin-file\": \"4.3.3\",\n", " \"cordova-plugin-file-transfer\": \"1.6.3\",\n", " \"cordova-plugin-geolocation\": \"2.4.3\",\n", " \"cordova-plugin-globalization\": \"1.0.7\",\n", " \"cordova-plugin-inappbrowser\": \"1.7.1\",\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 53}, "file": "#pragma once\n//-------------------------------------------------------------------------------------------------\n// \n// Copyright (c) 2004, Outercurve Foundation.\n// This software is released under Microsoft Reciprocal License (MS-RL).\n// The license and further copyright text can be found in the file\n// LICENSE.TXT at the root directory of the distribution.\n// \n// \n// \n// Ini/cfg file helper functions.\n// \n//-------------------------------------------------------------------------------------------------\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define ReleaseIni(ih) if (ih) { IniUninitialize(ih); }\n#define ReleaseNullIni(ih) if (ih) { IniUninitialize(ih); ih = NULL; }\n\ntypedef void* INI_HANDLE;\ntypedef const void* C_INI_HANDLE;\n\nextern const int INI_HANDLE_BYTES;\n\nstruct INI_VALUE\n{\n LPCWSTR wzName;\n LPCWSTR wzValue;\n\n DWORD dwLineNumber;\n};\n\nHRESULT DAPI IniInitialize(\n __out_bcount(INI_HANDLE_BYTES) INI_HANDLE* piHandle\n );\nvoid DAPI IniUninitialize(\n __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle\n );\nHRESULT DAPI IniSetOpenTag(\n __inout_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in_z_opt LPCWSTR wzOpenTagPrefix,\n __in_z_opt LPCWSTR wzOpenTagPostfix\n );\nHRESULT DAPI IniSetValueStyle(\n __inout_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in_z_opt LPCWSTR wzValuePrefix,\n __in_z_opt LPCWSTR wzValueSeparator\n );\nHRESULT DAPI IniSetCommentStyle(\n __inout_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in_z_opt LPCWSTR wzLinePrefix\n );\nHRESULT DAPI IniParse(\n __inout_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in LPCWSTR wzPath,\n __out_opt FILE_ENCODING *pfeEncodingFound\n );\nHRESULT DAPI IniGetValueList(\n __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __deref_out_ecount_opt(pcValues) INI_VALUE** prgivValues,\n __out DWORD *pcValues\n );\nHRESULT DAPI IniGetValue(\n __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in LPCWSTR wzValueName,\n __deref_out_z LPWSTR* psczValue\n );\nHRESULT DAPI IniSetValue(\n __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in LPCWSTR wzValueName,\n __in_z_opt LPCWSTR wzValue\n );\nHRESULT DAPI IniWriteFile(\n __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle,\n __in_z_opt LPCWSTR wzPath,\n __in FILE_ENCODING feOverrideEncoding\n );\n\n#ifdef __cplusplus\n}\n#endif\n", "file_path": "scripts/windows/installer/WiXSDK/inc/iniutil.h", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.0001742657768772915, 0.00016675940423738211, 0.00016185324057005346, 0.00016703570145182312, 3.567425210349029e-06]} {"hunk": {"id": 8, "code_window": ["// Versions are taken from cordova-lib's package.json and should be updated\n", "// when we update to a newer version of cordova-lib.\n", "const pinnedPluginVersions = {\n", " \"cordova-plugin-battery-status\": \"1.2.2\",\n", " \"cordova-plugin-camera\": \"2.3.1\",\n", " \"cordova-plugin-console\": \"1.0.5\",\n", " \"cordova-plugin-contacts\": \"2.2.1\",\n", " \"cordova-plugin-device\": \"1.1.4\",\n", " \"cordova-plugin-device-motion\": \"1.2.3\",\n", " \"cordova-plugin-device-orientation\": \"1.0.5\",\n", " \"cordova-plugin-dialogs\": \"1.3.1\",\n", " \"cordova-plugin-file\": \"4.3.1\",\n", " \"cordova-plugin-file-transfer\": \"1.6.1\",\n", " \"cordova-plugin-geolocation\": \"2.4.1\",\n", " \"cordova-plugin-globalization\": \"1.0.5\",\n", " \"cordova-plugin-inappbrowser\": \"1.6.1\",\n", " \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep"], "after_edit": [" \"cordova-plugin-battery-status\": \"1.2.4\",\n", " \"cordova-plugin-camera\": \"2.4.1\",\n", " \"cordova-plugin-console\": \"1.0.7\",\n", " \"cordova-plugin-contacts\": \"2.3.1\",\n", " \"cordova-plugin-device\": \"1.1.6\",\n", " \"cordova-plugin-device-motion\": \"1.2.5\",\n", " \"cordova-plugin-device-orientation\": \"1.0.7\",\n", " \"cordova-plugin-dialogs\": \"1.3.3\",\n", " \"cordova-plugin-file\": \"4.3.3\",\n", " \"cordova-plugin-file-transfer\": \"1.6.3\",\n", " \"cordova-plugin-geolocation\": \"2.4.3\",\n", " \"cordova-plugin-globalization\": \"1.0.7\",\n", " \"cordova-plugin-inappbrowser\": \"1.7.1\",\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 53}, "file": "Package.describe({\n name: 'jshint',\n version: '1.1.7',\n summary: 'Lint all your JavaScript files with JSHint.',\n documentation: 'README.md'\n});\n\nPackage.registerBuildPlugin({\n name: \"lintJshint\",\n sources: [\n 'plugin/lint-jshint.js'\n ],\n npmDependencies: {\n \"jshint\": \"2.7.0\"\n }\n});\n\nPackage.onUse(function(api) {\n api.use('isobuild:linter-plugin@1.0.0');\n});\n\nPackage.onTest(function(api) {\n api.use('tinytest');\n api.use('jshint');\n});\n", "file_path": "packages/jshint/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00016962233348749578, 0.00016810638771858066, 0.00016661988047417253, 0.000168076905538328, 1.2259233699296601e-06]} {"hunk": {"id": 9, "code_window": [" \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n", " \"cordova-plugin-media\": \"2.4.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.1\",\n", " \"cordova-plugin-network-information\": \"1.3.1\",\n", " \"cordova-plugin-splashscreen\": \"4.0.1\",\n", " \"cordova-plugin-statusbar\": \"2.2.1\",\n", " \"cordova-plugin-test-framework\": \"1.1.4\",\n", " \"cordova-plugin-vibration\": \"2.1.3\",\n", " \"cordova-plugin-whitelist\": \"1.3.1\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.1\"\n", "}\n", "\n", "export class CordovaProject {\n", " constructor(projectContext, options = {}) {\n", "\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" \"cordova-plugin-media\": \"3.0.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.3\",\n", " \"cordova-plugin-network-information\": \"1.3.3\",\n", " \"cordova-plugin-splashscreen\": \"4.0.3\",\n", " \"cordova-plugin-statusbar\": \"2.2.3\",\n", " \"cordova-plugin-test-framework\": \"1.1.5\",\n", " \"cordova-plugin-vibration\": \"2.1.5\",\n", " \"cordova-plugin-whitelist\": \"1.3.2\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.3\"\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 67}, "file": "Package.describe({\n // XXX We currently hard-code the \"launch-screen\" package in the\n // build tool. If this package is in your app, we turn off the\n // default splash screen loading behavior (this packages hides it\n // explicitly). In the future, there should be a better interface\n // between such packages and the build tool.\n name: 'launch-screen',\n summary: 'Default and customizable launch screen on mobile.',\n version: '1.1.1'\n});\n\nCordova.depends({\n 'cordova-plugin-splashscreen': '4.0.1'\n});\n\nPackage.onUse(function(api) {\n api.addFiles('mobile-launch-screen.js', 'web');\n api.addFiles('default-behavior.js', 'web');\n api.use(['blaze', 'templating'], 'web', { weak: true });\n\n api.export('LaunchScreen');\n});\n", "file_path": "packages/launch-screen/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00017172489606309682, 0.00016942185175139457, 0.00016818352742120624, 0.00016835711721796542, 1.6300430161209079e-06]} {"hunk": {"id": 9, "code_window": [" \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n", " \"cordova-plugin-media\": \"2.4.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.1\",\n", " \"cordova-plugin-network-information\": \"1.3.1\",\n", " \"cordova-plugin-splashscreen\": \"4.0.1\",\n", " \"cordova-plugin-statusbar\": \"2.2.1\",\n", " \"cordova-plugin-test-framework\": \"1.1.4\",\n", " \"cordova-plugin-vibration\": \"2.1.3\",\n", " \"cordova-plugin-whitelist\": \"1.3.1\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.1\"\n", "}\n", "\n", "export class CordovaProject {\n", " constructor(projectContext, options = {}) {\n", "\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" \"cordova-plugin-media\": \"3.0.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.3\",\n", " \"cordova-plugin-network-information\": \"1.3.3\",\n", " \"cordova-plugin-splashscreen\": \"4.0.3\",\n", " \"cordova-plugin-statusbar\": \"2.2.3\",\n", " \"cordova-plugin-test-framework\": \"1.1.5\",\n", " \"cordova-plugin-vibration\": \"2.1.5\",\n", " \"cordova-plugin-whitelist\": \"1.3.2\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.3\"\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 67}, "file": ".build*\n", "file_path": "packages/accounts-ui/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00017101067351177335, 0.00017101067351177335, 0.00017101067351177335, 0.00017101067351177335, 0.0]} {"hunk": {"id": 9, "code_window": [" \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n", " \"cordova-plugin-media\": \"2.4.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.1\",\n", " \"cordova-plugin-network-information\": \"1.3.1\",\n", " \"cordova-plugin-splashscreen\": \"4.0.1\",\n", " \"cordova-plugin-statusbar\": \"2.2.1\",\n", " \"cordova-plugin-test-framework\": \"1.1.4\",\n", " \"cordova-plugin-vibration\": \"2.1.3\",\n", " \"cordova-plugin-whitelist\": \"1.3.1\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.1\"\n", "}\n", "\n", "export class CordovaProject {\n", " constructor(projectContext, options = {}) {\n", "\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" \"cordova-plugin-media\": \"3.0.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.3\",\n", " \"cordova-plugin-network-information\": \"1.3.3\",\n", " \"cordova-plugin-splashscreen\": \"4.0.3\",\n", " \"cordova-plugin-statusbar\": \"2.2.3\",\n", " \"cordova-plugin-test-framework\": \"1.1.5\",\n", " \"cordova-plugin-vibration\": \"2.1.5\",\n", " \"cordova-plugin-whitelist\": \"1.3.2\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.3\"\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 67}, "file": "import { InputFile } from \"./build-plugin.js\";\n\nexport class LinterPlugin {\n constructor(pluginDefinition, userPlugin) {\n this.pluginDefinition = pluginDefinition;\n this.userPlugin = userPlugin;\n }\n}\n\nexport class LintingFile extends InputFile {\n constructor(source) {\n super();\n this._source = source;\n }\n\n getContentsAsBuffer() {\n return this._source.contents;\n }\n\n getPathInPackage() {\n return this._source.relPath;\n }\n\n getPackageName() {\n return this._source[\"package\"];\n }\n\n getSourceHash() {\n return this._source.hash;\n }\n\n getArch() {\n return this._source.arch;\n }\n\n getFileOptions() {\n return this._source.fileOptions || {};\n }\n}\n", "file_path": "tools/isobuild/linter-plugin.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.0009129898971877992, 0.0003547754604369402, 0.00016022739873733371, 0.000172942309291102, 0.00032232707599177957]} {"hunk": {"id": 9, "code_window": [" \"cordova-plugin-legacy-whitelist\": \"1.1.2\",\n", " \"cordova-plugin-media\": \"2.4.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.1\",\n", " \"cordova-plugin-network-information\": \"1.3.1\",\n", " \"cordova-plugin-splashscreen\": \"4.0.1\",\n", " \"cordova-plugin-statusbar\": \"2.2.1\",\n", " \"cordova-plugin-test-framework\": \"1.1.4\",\n", " \"cordova-plugin-vibration\": \"2.1.3\",\n", " \"cordova-plugin-whitelist\": \"1.3.1\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.1\"\n", "}\n", "\n", "export class CordovaProject {\n", " constructor(projectContext, options = {}) {\n", "\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" \"cordova-plugin-media\": \"3.0.1\",\n", " \"cordova-plugin-media-capture\": \"1.4.3\",\n", " \"cordova-plugin-network-information\": \"1.3.3\",\n", " \"cordova-plugin-splashscreen\": \"4.0.3\",\n", " \"cordova-plugin-statusbar\": \"2.2.3\",\n", " \"cordova-plugin-test-framework\": \"1.1.5\",\n", " \"cordova-plugin-vibration\": \"2.1.5\",\n", " \"cordova-plugin-whitelist\": \"1.3.2\",\n", " \"cordova-plugin-wkwebview-engine\": \"1.1.3\"\n"], "file_path": "tools/cordova/project.js", "type": "replace", "edit_start_line_idx": 67}, "file": "Package.describe({version: '1.0.0'});\n\nNpm.depends({});\n\nPackage.onUse(function (api) { api.addFiles('dummy.js', 'server'); });\n", "file_path": "tools/tests/old/app-with-package/packages/test-package/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/08fdc8a6f00d18f1b46d90633edce49c109ab683", "dependency_score": [0.00017392548033967614, 0.00017392548033967614, 0.00017392548033967614, 0.00017392548033967614, 0.0]} {"hunk": {"id": 0, "code_window": ["Package.on_use(function (api) {\n", " api.use(['check', 'random', 'ejson', 'json', 'underscore', 'deps', 'logging'],\n", " ['client', 'server']);\n", "\n", " // XXX we do NOT require webapp here, because it's OK to use this package on a\n", " // server architecture without making a server (in order to do\n", " // server-to-server DDP as a client). So if you want to provide a DDP server,\n", " // you need to use webapp before you use livedata.\n", "\n", " // Transport\n", " api.use('reload', 'client');\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // XXX we do NOT require webapp or routepolicy here, because it's OK to use\n", " // this package on a server architecture without making a server (in order to\n", " // do server-to-server DDP as a client). So if you want to provide a DDP\n", " // server, you need to use webapp before you use livedata.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 12}, "file": "Meteor._routePolicy.declare('/sockjs/', 'network');\n\n// unique id for this instantiation of the server. If this changes\n// between client reconnects, the client will reload. You can set the\n// environment variable \"SERVER_ID\" to control this. For example, if\n// you want to only force a reload on major changes, you can use a\n// custom serverId which you only change when something worth pushing\n// to clients immediately happens.\n__meteor_runtime_config__.serverId =\n process.env.SERVER_ID ? process.env.SERVER_ID : Random.id();\n\nMeteor._DdpStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n self.server = sockjs.createServer({\n prefix: '/sockjs', log: function(){},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 25000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n jsessionid: false});\n self.server.installHandlers(__meteor_bootstrap__.app);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n\n // Send a welcome message with the serverId. Client uses this to\n // reload if needed.\n socket.send(JSON.stringify({server_id: __meteor_runtime_config__.serverId}));\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\n_.extend(Meteor._DdpStreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n _.each(['request', 'upgrade'], function(event) {\n var app = __meteor_bootstrap__.app;\n var oldAppListeners = app.listeners(event).slice(0);\n app.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n if (request.url === '/websocket' ||\n request.url === '/websocket/')\n request.url = '/sockjs/websocket';\n\n _.each(oldAppListeners, function(oldListener) {\n oldListener.apply(app, args);\n });\n };\n app.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/livedata/stream_server.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00020773349388036877, 0.00017253943951800466, 0.00016432155098300427, 0.00016632574261166155, 1.3695863344764803e-05]} {"hunk": {"id": 0, "code_window": ["Package.on_use(function (api) {\n", " api.use(['check', 'random', 'ejson', 'json', 'underscore', 'deps', 'logging'],\n", " ['client', 'server']);\n", "\n", " // XXX we do NOT require webapp here, because it's OK to use this package on a\n", " // server architecture without making a server (in order to do\n", " // server-to-server DDP as a client). So if you want to provide a DDP server,\n", " // you need to use webapp before you use livedata.\n", "\n", " // Transport\n", " api.use('reload', 'client');\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // XXX we do NOT require webapp or routepolicy here, because it's OK to use\n", " // this package on a server architecture without making a server (in order to\n", " // do server-to-server DDP as a client). So if you want to provide a DDP\n", " // server, you need to use webapp before you use livedata.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 12}, "file": "Package.describe({\n summary: \"Generate and consume reset password and verify account URLs\",\n internal: true\n});\n\nPackage.on_use(function (api) {\n api.add_files('url_client.js', 'client');\n api.add_files('url_server.js', 'server');\n});\n", "file_path": "packages/accounts-urls/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0011827748967334628, 0.0011827748967334628, 0.0011827748967334628, 0.0011827748967334628, 0.0]} {"hunk": {"id": 0, "code_window": ["Package.on_use(function (api) {\n", " api.use(['check', 'random', 'ejson', 'json', 'underscore', 'deps', 'logging'],\n", " ['client', 'server']);\n", "\n", " // XXX we do NOT require webapp here, because it's OK to use this package on a\n", " // server architecture without making a server (in order to do\n", " // server-to-server DDP as a client). So if you want to provide a DDP server,\n", " // you need to use webapp before you use livedata.\n", "\n", " // Transport\n", " api.use('reload', 'client');\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // XXX we do NOT require webapp or routepolicy here, because it's OK to use\n", " // this package on a server architecture without making a server (in order to\n", " // do server-to-server DDP as a client). So if you want to provide a DDP\n", " // server, you need to use webapp before you use livedata.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 12}, "file": "Package.describe({\n summary: \"Easy macros for generating DOM elements in Javascript\"\n});\n\nPackage.on_use(function (api) {\n // Note: html.js will optionally use jquery if it's available\n api.add_files('html.js', 'client');\n});\n\nPackage.on_test(function (api) {\n api.use('htmljs', 'client');\n api.use('tinytest');\n api.add_files('htmljs_test.js', 'client');\n});\n", "file_path": "packages/htmljs/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0004034879384562373, 0.0002864955458790064, 0.00016950316785369068, 0.0002864955458790064, 0.00011699238530127332]} {"hunk": {"id": 0, "code_window": ["Package.on_use(function (api) {\n", " api.use(['check', 'random', 'ejson', 'json', 'underscore', 'deps', 'logging'],\n", " ['client', 'server']);\n", "\n", " // XXX we do NOT require webapp here, because it's OK to use this package on a\n", " // server architecture without making a server (in order to do\n", " // server-to-server DDP as a client). So if you want to provide a DDP server,\n", " // you need to use webapp before you use livedata.\n", "\n", " // Transport\n", " api.use('reload', 'client');\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // XXX we do NOT require webapp or routepolicy here, because it's OK to use\n", " // this package on a server architecture without making a server (in order to\n", " // do server-to-server DDP as a client). So if you want to provide a DDP\n", " // server, you need to use webapp before you use livedata.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 12}, "file": "if (process.env.ROOT_URL &&\n typeof __meteor_runtime_config__ === \"object\")\n __meteor_runtime_config__.ROOT_URL = process.env.ROOT_URL;\n", "file_path": "packages/meteor/url_server.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001670121419010684, 0.0001670121419010684, 0.0001670121419010684, 0.0001670121419010684, 0.0]} {"hunk": {"id": 1, "code_window": ["\n", " // Transport\n", " api.use('reload', 'client');\n", " api.use('routepolicy', 'server');\n", " api.add_files(['sockjs-0.3.4.js',\n", " 'stream_client_sockjs.js'], 'client');\n", " api.add_files('stream_client_nodejs.js', 'server');\n", " api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "Meteor._routePolicy.declare('/sockjs/', 'network');\n\n// unique id for this instantiation of the server. If this changes\n// between client reconnects, the client will reload. You can set the\n// environment variable \"SERVER_ID\" to control this. For example, if\n// you want to only force a reload on major changes, you can use a\n// custom serverId which you only change when something worth pushing\n// to clients immediately happens.\n__meteor_runtime_config__.serverId =\n process.env.SERVER_ID ? process.env.SERVER_ID : Random.id();\n\nMeteor._DdpStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n self.server = sockjs.createServer({\n prefix: '/sockjs', log: function(){},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 25000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n jsessionid: false});\n self.server.installHandlers(__meteor_bootstrap__.app);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n\n // Send a welcome message with the serverId. Client uses this to\n // reload if needed.\n socket.send(JSON.stringify({server_id: __meteor_runtime_config__.serverId}));\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\n_.extend(Meteor._DdpStreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n _.each(['request', 'upgrade'], function(event) {\n var app = __meteor_bootstrap__.app;\n var oldAppListeners = app.listeners(event).slice(0);\n app.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n if (request.url === '/websocket' ||\n request.url === '/websocket/')\n request.url = '/sockjs/websocket';\n\n _.each(oldAppListeners, function(oldListener) {\n oldListener.apply(app, args);\n });\n };\n app.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/livedata/stream_server.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00047962102689780295, 0.00020688680524472147, 0.00016444742504972965, 0.0001698380510788411, 8.974479715107009e-05]} {"hunk": {"id": 1, "code_window": ["\n", " // Transport\n", " api.use('reload', 'client');\n", " api.use('routepolicy', 'server');\n", " api.add_files(['sockjs-0.3.4.js',\n", " 'stream_client_sockjs.js'], 'client');\n", " api.add_files('stream_client_nodejs.js', 'server');\n", " api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "/* CSS declarations go here */\n", "file_path": "examples/unfinished/benchmark/benchmark.css", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00016833400877658278, 0.00016833400877658278, 0.00016833400877658278, 0.00016833400877658278, 0.0]} {"hunk": {"id": 1, "code_window": ["\n", " // Transport\n", " api.use('reload', 'client');\n", " api.use('routepolicy', 'server');\n", " api.add_files(['sockjs-0.3.4.js',\n", " 'stream_client_sockjs.js'], 'client');\n", " api.add_files('stream_client_nodejs.js', 'server');\n", " api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "\n", "file_path": "docs/client/packages/force-ssl.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001715762773528695, 0.0001646201708354056, 0.00015976895519997925, 0.000162515279953368, 5.044874797022203e-06]} {"hunk": {"id": 1, "code_window": ["\n", " // Transport\n", " api.use('reload', 'client');\n", " api.use('routepolicy', 'server');\n", " api.add_files(['sockjs-0.3.4.js',\n", " 'stream_client_sockjs.js'], 'client');\n", " api.add_files('stream_client_nodejs.js', 'server');\n", " api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 19}, "file": "0.6.2.1\n", "file_path": "examples/todos/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001671263453317806, 0.0001671263453317806, 0.0001671263453317806, 0.0001671263453317806, 0.0]} {"hunk": {"id": 2, "code_window": [" api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n", "\n", " // livedata_connection.js uses a Minimongo collection internally to\n", " // manage the current set of subscriptions.\n", " api.use('minimongo', ['client', 'server']);\n", "\n", " api.add_files('writefence.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // we depend on LocalCollection._diffObjects and ._applyChanges.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 26}, "file": "Package.describe({\n summary: \"Meteor's latency-compensated distributed data framework\",\n internal: true\n});\n\nNpm.depends({sockjs: \"0.3.7\",\n websocket: \"1.0.7\"});\n\nPackage.on_use(function (api) {\n api.use(['check', 'random', 'ejson', 'json', 'underscore', 'deps', 'logging'],\n ['client', 'server']);\n\n // XXX we do NOT require webapp here, because it's OK to use this package on a\n // server architecture without making a server (in order to do\n // server-to-server DDP as a client). So if you want to provide a DDP server,\n // you need to use webapp before you use livedata.\n\n // Transport\n api.use('reload', 'client');\n api.use('routepolicy', 'server');\n api.add_files(['sockjs-0.3.4.js',\n 'stream_client_sockjs.js'], 'client');\n api.add_files('stream_client_nodejs.js', 'server');\n api.add_files('stream_client_common.js', ['client', 'server']);\n api.add_files('stream_server.js', 'server');\n\n // livedata_connection.js uses a Minimongo collection internally to\n // manage the current set of subscriptions.\n api.use('minimongo', ['client', 'server']);\n\n api.add_files('writefence.js', 'server');\n api.add_files('crossbar.js', 'server');\n\n api.add_files('livedata_common.js', ['client', 'server']);\n\n api.add_files('livedata_connection.js', ['client', 'server']);\n\n api.add_files('livedata_server.js', 'server');\n\n\n api.add_files('client_convenience.js', 'client');\n api.add_files('server_convenience.js', 'server');\n});\n\nPackage.on_test(function (api) {\n api.use('livedata', ['client', 'server']);\n api.use('mongo-livedata', ['client', 'server']);\n api.use('test-helpers', ['client', 'server']);\n api.use(['underscore', 'tinytest', 'random', 'deps']);\n\n api.add_files('livedata_connection_tests.js', ['client', 'server']);\n api.add_files('livedata_tests.js', ['client', 'server']);\n api.add_files('livedata_test_service.js', ['client', 'server']);\n api.add_files('session_view_tests.js', ['server']);\n api.add_files('crossbar_tests.js', ['server']);\n\n api.use('http', 'client');\n api.add_files(['stream_tests.js'], 'client');\n api.use('check', ['client', 'server']);\n});\n", "file_path": "packages/livedata/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.9943448305130005, 0.14490249752998352, 0.00017000624211505055, 0.001138842198997736, 0.3468037247657776]} {"hunk": {"id": 2, "code_window": [" api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n", "\n", " // livedata_connection.js uses a Minimongo collection internally to\n", " // manage the current set of subscriptions.\n", " api.use('minimongo', ['client', 'server']);\n", "\n", " api.add_files('writefence.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // we depend on LocalCollection._diffObjects and ._applyChanges.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 26}, "file": "// intentionally initialize later so that we can debug tests after\n// they fail without trying to recreate a user with the same email\n// address\nvar email1;\nvar email2;\nvar email3;\nvar email4;\n\nvar resetPasswordToken;\nvar verifyEmailToken;\nvar enrollAccountToken;\n\nAccounts._isolateLoginTokenForTest();\n\ntestAsyncMulti(\"accounts emails - reset password flow\", [\n function (test, expect) {\n email1 = Random.id() + \"-intercept@example.com\";\n Accounts.createUser({email: email1, password: 'foobar'},\n expect(function (error) {\n test.equal(error, undefined);\n }));\n },\n function (test, expect) {\n Accounts.forgotPassword({email: email1}, expect(function (error) {\n test.equal(error, undefined);\n }));\n },\n function (test, expect) {\n Meteor.call(\"getInterceptedEmails\", email1, expect(function (error, result) {\n test.equal(error, undefined);\n test.notEqual(result, undefined);\n test.equal(result.length, 2); // the first is the email verification\n var content = result[1];\n\n var match = content.match(\n new RegExp(Meteor.absoluteUrl() + \"#/reset-password/(\\\\S*)\"));\n test.isTrue(match);\n resetPasswordToken = match[1];\n }));\n },\n function (test, expect) {\n Accounts.resetPassword(resetPasswordToken, \"newPassword\", expect(function(error) {\n test.isFalse(error);\n }));\n },\n function (test, expect) {\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n },\n function (test, expect) {\n Meteor.loginWithPassword(\n {email: email1}, \"newPassword\",\n expect(function (error) {\n test.isFalse(error);\n }));\n },\n function (test, expect) {\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n }\n]);\n\nvar getVerifyEmailToken = function (email, test, expect) {\n Meteor.call(\"getInterceptedEmails\", email, expect(function (error, result) {\n test.equal(error, undefined);\n test.notEqual(result, undefined);\n test.equal(result.length, 1);\n var content = result[0];\n\n var match = content.match(\n new RegExp(Meteor.absoluteUrl() + \"#/verify-email/(\\\\S*)\"));\n test.isTrue(match);\n verifyEmailToken = match[1];\n }));\n};\n\nvar loggedIn = function (test, expect) {\n return expect(function (error) {\n test.equal(error, undefined);\n test.isTrue(Meteor.user());\n });\n};\n\ntestAsyncMulti(\"accounts emails - verify email flow\", [\n function (test, expect) {\n email2 = Random.id() + \"-intercept@example.com\";\n email3 = Random.id() + \"-intercept@example.com\";\n Accounts.createUser(\n {email: email2, password: 'foobar'},\n loggedIn(test, expect));\n },\n function (test, expect) {\n test.equal(Meteor.user().emails.length, 1);\n test.equal(Meteor.user().emails[0].address, email2);\n test.isFalse(Meteor.user().emails[0].verified);\n // We should NOT be publishing things like verification tokens!\n test.isFalse(_.has(Meteor.user(), 'services'));\n },\n function (test, expect) {\n getVerifyEmailToken(email2, test, expect);\n },\n function (test, expect) {\n // Log out, to test that verifyEmail logs us back in.\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n },\n function (test, expect) {\n Accounts.verifyEmail(verifyEmailToken,\n loggedIn(test, expect));\n },\n function (test, expect) {\n test.equal(Meteor.user().emails.length, 1);\n test.equal(Meteor.user().emails[0].address, email2);\n test.isTrue(Meteor.user().emails[0].verified);\n },\n function (test, expect) {\n Meteor.call(\n \"addEmailForTestAndVerify\", email3,\n expect(function (error, result) {\n test.isFalse(error);\n test.equal(Meteor.user().emails.length, 2);\n test.equal(Meteor.user().emails[1].address, email3);\n test.isFalse(Meteor.user().emails[1].verified);\n }));\n },\n function (test, expect) {\n getVerifyEmailToken(email3, test, expect);\n },\n function (test, expect) {\n // Log out, to test that verifyEmail logs us back in. (And if we don't\n // do that, waitUntilLoggedIn won't be able to prevent race conditions.)\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n },\n function (test, expect) {\n Accounts.verifyEmail(verifyEmailToken,\n loggedIn(test, expect));\n },\n function (test, expect) {\n test.equal(Meteor.user().emails[1].address, email3);\n test.isTrue(Meteor.user().emails[1].verified);\n },\n function (test, expect) {\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n }\n]);\n\nvar getEnrollAccountToken = function (email, test, expect) {\n Meteor.call(\"getInterceptedEmails\", email, expect(function (error, result) {\n test.equal(error, undefined);\n test.notEqual(result, undefined);\n test.equal(result.length, 1);\n var content = result[0];\n\n var match = content.match(\n new RegExp(Meteor.absoluteUrl() + \"#/enroll-account/(\\\\S*)\"));\n test.isTrue(match);\n enrollAccountToken = match[1];\n }));\n};\n\ntestAsyncMulti(\"accounts emails - enroll account flow\", [\n function (test, expect) {\n email4 = Random.id() + \"-intercept@example.com\";\n Meteor.call(\"createUserOnServer\", email4,\n expect(function (error, result) {\n test.isFalse(error);\n var user = result;\n test.equal(user.emails.length, 1);\n test.equal(user.emails[0].address, email4);\n test.isFalse(user.emails[0].verified);\n }));\n },\n function (test, expect) {\n getEnrollAccountToken(email4, test, expect);\n },\n function (test, expect) {\n Accounts.resetPassword(enrollAccountToken, 'password',\n loggedIn(test, expect));\n },\n function (test, expect) {\n test.equal(Meteor.user().emails.length, 1);\n test.equal(Meteor.user().emails[0].address, email4);\n test.isTrue(Meteor.user().emails[0].verified);\n },\n function (test, expect) {\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n },\n function (test, expect) {\n Meteor.loginWithPassword({email: email4}, 'password',\n loggedIn(test ,expect));\n },\n function (test, expect) {\n test.equal(Meteor.user().emails.length, 1);\n test.equal(Meteor.user().emails[0].address, email4);\n test.isTrue(Meteor.user().emails[0].verified);\n },\n function (test, expect) {\n Meteor.logout(expect(function (error) {\n test.equal(error, undefined);\n test.equal(Meteor.user(), null);\n }));\n }\n]);\n", "file_path": "packages/accounts-password/email_tests.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001771281094988808, 0.00017409979773219675, 0.00016968316049315035, 0.00017425036639906466, 2.0447184851946076e-06]} {"hunk": {"id": 2, "code_window": [" api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n", "\n", " // livedata_connection.js uses a Minimongo collection internally to\n", " // manage the current set of subscriptions.\n", " api.use('minimongo', ['client', 'server']);\n", "\n", " api.add_files('writefence.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // we depend on LocalCollection._diffObjects and ._applyChanges.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 26}, "file": "\n", "file_path": "docs/client/commandline.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017489401216153055, 0.00016907458484638482, 0.00016331062943208963, 0.0001692498044576496, 3.2077487048809417e-06]} {"hunk": {"id": 2, "code_window": [" api.add_files('stream_client_common.js', ['client', 'server']);\n", " api.add_files('stream_server.js', 'server');\n", "\n", " // livedata_connection.js uses a Minimongo collection internally to\n", " // manage the current set of subscriptions.\n", " api.use('minimongo', ['client', 'server']);\n", "\n", " api.add_files('writefence.js', 'server');\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" // we depend on LocalCollection._diffObjects and ._applyChanges.\n"], "file_path": "packages/livedata/package.js", "type": "replace", "edit_start_line_idx": 26}, "file": ".build*\n", "file_path": "packages/domutils/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017436567577533424, 0.00017436567577533424, 0.00017436567577533424, 0.00017436567577533424, 0.0]} {"hunk": {"id": 3, "code_window": ["Meteor._routePolicy.declare('/sockjs/', 'network');\n", "\n", "// unique id for this instantiation of the server. If this changes\n", "// between client reconnects, the client will reload. You can set the\n", "// environment variable \"SERVER_ID\" to control this. For example, if\n", "// you want to only force a reload on major changes, you can use a\n", "// custom serverId which you only change when something worth pushing\n"], "labels": ["replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 0}, "file": "Meteor._routePolicy.declare('/sockjs/', 'network');\n\n// unique id for this instantiation of the server. If this changes\n// between client reconnects, the client will reload. You can set the\n// environment variable \"SERVER_ID\" to control this. For example, if\n// you want to only force a reload on major changes, you can use a\n// custom serverId which you only change when something worth pushing\n// to clients immediately happens.\n__meteor_runtime_config__.serverId =\n process.env.SERVER_ID ? process.env.SERVER_ID : Random.id();\n\nMeteor._DdpStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n self.server = sockjs.createServer({\n prefix: '/sockjs', log: function(){},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 25000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n jsessionid: false});\n self.server.installHandlers(__meteor_bootstrap__.app);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n\n // Send a welcome message with the serverId. Client uses this to\n // reload if needed.\n socket.send(JSON.stringify({server_id: __meteor_runtime_config__.serverId}));\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\n_.extend(Meteor._DdpStreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n _.each(['request', 'upgrade'], function(event) {\n var app = __meteor_bootstrap__.app;\n var oldAppListeners = app.listeners(event).slice(0);\n app.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n if (request.url === '/websocket' ||\n request.url === '/websocket/')\n request.url = '/sockjs/websocket';\n\n _.each(oldAppListeners, function(oldListener) {\n oldListener.apply(app, args);\n });\n };\n app.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/livedata/stream_server.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.9869536757469177, 0.0908748209476471, 0.00016630497702863067, 0.0005137032712809741, 0.2833701968193054]} {"hunk": {"id": 3, "code_window": ["Meteor._routePolicy.declare('/sockjs/', 'network');\n", "\n", "// unique id for this instantiation of the server. If this changes\n", "// between client reconnects, the client will reload. You can set the\n", "// environment variable \"SERVER_ID\" to control this. For example, if\n", "// you want to only force a reload on major changes, you can use a\n", "// custom serverId which you only change when something worth pushing\n"], "labels": ["replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 0}, "file": "\n Remote collection demo\n\n\n\n
\n \n\n {{> main}}\n \n
\n\n\n\n", "file_path": "examples/unfinished/leaderboard-remote/client/leaderboard-remote.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00019259992404840887, 0.0001760273880790919, 0.00016846453945618123, 0.00017152252257801592, 9.669402970757801e-06]} {"hunk": {"id": 3, "code_window": ["Meteor._routePolicy.declare('/sockjs/', 'network');\n", "\n", "// unique id for this instantiation of the server. If this changes\n", "// between client reconnects, the client will reload. You can set the\n", "// environment variable \"SERVER_ID\" to control this. For example, if\n", "// you want to only force a reload on major changes, you can use a\n", "// custom serverId which you only change when something worth pushing\n"], "labels": ["replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 0}, "file": "if (process.env.ROOT_URL &&\n typeof __meteor_runtime_config__ === \"object\")\n __meteor_runtime_config__.ROOT_URL = process.env.ROOT_URL;\n", "file_path": "packages/meteor/url_server.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0002463187847752124, 0.0002463187847752124, 0.0002463187847752124, 0.0002463187847752124, 0.0]} {"hunk": {"id": 3, "code_window": ["Meteor._routePolicy.declare('/sockjs/', 'network');\n", "\n", "// unique id for this instantiation of the server. If this changes\n", "// between client reconnects, the client will reload. You can set the\n", "// environment variable \"SERVER_ID\" to control this. For example, if\n", "// you want to only force a reload on major changes, you can use a\n", "// custom serverId which you only change when something worth pushing\n"], "labels": ["replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 0}, "file": "\n", "file_path": "docs/client/packages/spiderable.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0007415083819068968, 0.0003145727387163788, 0.00016459895414300263, 0.0001760917657520622, 0.00024656971800141037]} {"hunk": {"id": 4, "code_window": [" var self = this;\n", " self.registration_callbacks = [];\n", " self.open_sockets = [];\n", "\n", " // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" self.prefix = '/sockjs';\n", " // We don't depend directly on routepolicy because we don't want to pull in\n", " // webapp stuff if we're just doing server-to-server DDP as a client.\n", " if (Meteor._routePolicy)\n", " Meteor._routePolicy.declare(self.prefix + '/', 'network');\n", "\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 16}, "file": "Meteor._routePolicy.declare('/sockjs/', 'network');\n\n// unique id for this instantiation of the server. If this changes\n// between client reconnects, the client will reload. You can set the\n// environment variable \"SERVER_ID\" to control this. For example, if\n// you want to only force a reload on major changes, you can use a\n// custom serverId which you only change when something worth pushing\n// to clients immediately happens.\n__meteor_runtime_config__.serverId =\n process.env.SERVER_ID ? process.env.SERVER_ID : Random.id();\n\nMeteor._DdpStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n self.server = sockjs.createServer({\n prefix: '/sockjs', log: function(){},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 25000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n jsessionid: false});\n self.server.installHandlers(__meteor_bootstrap__.app);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n\n // Send a welcome message with the serverId. Client uses this to\n // reload if needed.\n socket.send(JSON.stringify({server_id: __meteor_runtime_config__.serverId}));\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\n_.extend(Meteor._DdpStreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n _.each(['request', 'upgrade'], function(event) {\n var app = __meteor_bootstrap__.app;\n var oldAppListeners = app.listeners(event).slice(0);\n app.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n if (request.url === '/websocket' ||\n request.url === '/websocket/')\n request.url = '/sockjs/websocket';\n\n _.each(oldAppListeners, function(oldListener) {\n oldListener.apply(app, args);\n });\n };\n app.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/livedata/stream_server.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.9983295798301697, 0.6250866651535034, 0.00017103039135690778, 0.9675814509391785, 0.47184449434280396]} {"hunk": {"id": 4, "code_window": [" var self = this;\n", " self.registration_callbacks = [];\n", " self.open_sockets = [];\n", "\n", " // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" self.prefix = '/sockjs';\n", " // We don't depend directly on routepolicy because we don't want to pull in\n", " // webapp stuff if we're just doing server-to-server DDP as a client.\n", " if (Meteor._routePolicy)\n", " Meteor._routePolicy.declare(self.prefix + '/', 'network');\n", "\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 16}, "file": "Package.describe({\n summary: \"Login service for Meetup accounts\"\n});\n\nPackage.on_use(function(api) {\n api.use('accounts-base', ['client', 'server']);\n api.use('accounts-oauth2-helper', ['client', 'server']);\n api.use('http', ['client', 'server']);\n api.use('templating', 'client');\n\n api.add_files(\n ['meetup_login_button.css', 'meetup_configure.html', 'meetup_configure.js'],\n 'client');\n\n api.add_files('meetup_common.js', ['client', 'server']);\n api.add_files('meetup_server.js', 'server');\n api.add_files('meetup_client.js', 'client');\n});\n", "file_path": "packages/accounts-meetup/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001694086386123672, 0.0001677583932178095, 0.00016610814782325178, 0.0001677583932178095, 1.6502453945577145e-06]} {"hunk": {"id": 4, "code_window": [" var self = this;\n", " self.registration_callbacks = [];\n", " self.open_sockets = [];\n", "\n", " // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" self.prefix = '/sockjs';\n", " // We don't depend directly on routepolicy because we don't want to pull in\n", " // webapp stuff if we're just doing server-to-server DDP as a client.\n", " if (Meteor._routePolicy)\n", " Meteor._routePolicy.declare(self.prefix + '/', 'network');\n", "\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 16}, "file": "\n", "file_path": "docs/client/packages/stylus.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001731604861561209, 0.0001699168496998027, 0.0001660797861404717, 0.00017051032045856118, 2.92098388854356e-06]} {"hunk": {"id": 4, "code_window": [" var self = this;\n", " self.registration_callbacks = [];\n", " self.open_sockets = [];\n", "\n", " // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" self.prefix = '/sockjs';\n", " // We don't depend directly on routepolicy because we don't want to pull in\n", " // webapp stuff if we're just doing server-to-server DDP as a client.\n", " if (Meteor._routePolicy)\n", " Meteor._routePolicy.declare(self.prefix + '/', 'network');\n", "\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 16}, "file": "### Filing Bug Reports\n\nIf you've found a bug in Meteor, file a bug report in [our issue\ntracker](https://github.com/meteor/meteor/issues). If the issue contains\nsensitive information or raises a security concern, email\nsecurity[]()@[]()meteor.com instead, which will page the\nsecurity team.\n\nA Meteor app has many moving parts, and it's often difficult to reproduce a bug\nbased on just a few lines of code. If you want somebody to be able to fix a bug\n(or verify a fix that you've contributed), the best way is:\n\n* Create a new Meteor app that displays the bug with as little code as possible. Try to delete any code that is unrelated to the precise bug you're reporting.\n* Create a new GitHub repository with a name like `meteor-reactivity-bug` (or if you're adding a new reproduction recipe to an existing issue, `meteor-issue-321`) and push your code to it. (Make sure to include the `.meteor/packages` file!)\n* Reproduce the bug from scratch, starting with a `git clone` command. Copy and paste the entire command-line input and output, starting with the `git clone` command, into the issue description of a new GitHub issue. Also describe any web browser interaction you need to do.\n* Specify what version of Meteor (`$ meteor --version`) and what web browser you used.\n\nBy making it as easy as possible for others to reproduce your bug, you make it easier for your bug to be fixed. **We're not always able to tackle issues opened without a reproduction recipe. In those cases we'll close them with a pointer to this wiki section and a request for more information.**\n\n\n### Contributing code to the Meteor project\n\nBefore submitting a pull request, make sure that it follows these guidelines:\n\n* Make sure that your branch is based off of the **devel** branch. The **devel** branch is where active development happens. **We can't merge non-trivial patches off master.**\n* Sign the [contributor's agreement](http://contribute.meteor.com/).\n* Follow the [Meteor style guide](https://github.com/meteor/meteor/wiki/Meteor-Style-Guide).\n* Limit yourself to one feature or bug fix per pull request.\n* Name your branch to match the feature/bug fix that you are submitting.\n* Write clear, descriptive commit messages.\n* Describe your pull request in as much detail as possible: why this pull request is important enough for us to consider, what changes it contains, what you had to do to get it to work, how you tested it, etc. Be detailed but be clear: use bullets, examples if needed, and simple, straightforward language.\n\nIf you're working on a big ticket item, please check in on [meteor-core](http://groups.google.com/group/meteor-core). We'd hate to have to steer you in a different direction after you've already put in a lot of hard work.\n\n### Package Submission Guidelines\n\nWe recommend submitting most new smart packages to [Atmosphere](https://atmosphere.meteor.com), rather than submitting a pull request.\n\nIf you submit a smart package pull request, we want to see strong community interest in the package before we include it in a Meteor release. Usage on atmosphere or comments on the pull request are great for this. This helps us keep Meteor core clean and streamlined.\n\n* Your package should have tests. See `packages/coffeescript` or `packages/less` for examples.\n* Your package should be documented. See `docs/client/packages`.\n* Because the package API is still in flux, and because you can include client-side JS/CSS files directly in your project's `client/lib` directory, the bar is higher for new packages that only include client-side JS/CSS files.\n* Similarly, the bar is higher for new packages that only include JS files with minimal integration. Generally, the test is whether a file can simply be put into your project's `lib` or `server/lib` directory, or if additional effort is needed to make it work.\n* Meteor minifies all JS/CSS. Packages should include only the original JS/CSS files, not the minified versions.\n", "file_path": "Contributing.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017214048421010375, 0.00016963554662652314, 0.00016611098544672132, 0.00017029617447406054, 2.2326369162328774e-06]} {"hunk": {"id": 5, "code_window": [" // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n", " prefix: '/sockjs', log: function(){},\n", " // this is the default, but we code it explicitly because we depend\n", " // on it in stream_client:HEARTBEAT_TIMEOUT\n", " heartbeat_delay: 25000,\n", " // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" prefix: self.prefix, log: function(){},\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 19}, "file": "var path = require('path');\nvar os = require('os');\nvar _ = require('underscore');\nvar files = require('./files.js');\nvar watch = require('./watch.js');\nvar bundler = require('./bundler.js');\nvar Builder = require('./builder.js');\nvar project = require('./project.js');\nvar buildmessage = require('./buildmessage.js');\nvar meteorNpm = require('./meteor_npm.js');\nvar archinfo = require(path.join(__dirname, 'archinfo.js'));\nvar linker = require(path.join(__dirname, 'linker.js'));\nvar fs = require('fs');\n\n// Find all files under `rootPath` that have an extension in\n// `extensions` (an array of extensions without leading dot), and\n// return them as a list of paths relative to sourceRoot. Ignore files\n// that match a regexp in the ignoreFiles array, if given. As a\n// special case (ugh), push all html files to the head of the list.\nvar scanForSources = function (rootPath, extensions, ignoreFiles) {\n var self = this;\n\n // find everything in tree, sorted depth-first alphabetically.\n var fileList = files.file_list_sync(rootPath, extensions);\n fileList = _.reject(fileList, function (file) {\n return _.any(ignoreFiles || [], function (pattern) {\n return file.match(pattern);\n });\n });\n fileList.sort(files.sort);\n\n // XXX HUGE HACK --\n // push html (template) files ahead of everything else. this is\n // important because the user wants to be able to say\n // Template.foo.events = { ... }\n //\n // maybe all of the templates should go in one file? packages\n // should probably have a way to request this treatment (load\n // order dependency tags?) .. who knows.\n var htmls = [];\n _.each(fileList, function (filename) {\n if (path.extname(filename) === '.html') {\n htmls.push(filename);\n fileList = _.reject(fileList, function (f) { return f === filename;});\n }\n });\n fileList = htmls.concat(fileList);\n\n // now make everything relative to rootPath\n var prefix = rootPath;\n if (prefix[prefix.length - 1] !== path.sep)\n prefix += path.sep;\n\n return fileList.map(function (abs) {\n if (path.relative(prefix, abs).match(/\\.\\./))\n // XXX audit to make sure it works in all possible symlink\n // scenarios\n throw new Error(\"internal error: source file outside of parent?\");\n return abs.substr(prefix.length);\n });\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Slice\n///////////////////////////////////////////////////////////////////////////////\n\n// Options:\n// - name [required]\n// - arch [required]\n// - uses\n// - getSourcesFunc\n// - forceExport\n// - dependencyInfo\n// - nodeModulesPath\n//\n// Do not include the source files in dependencyInfo. They will be\n// added at compile time when the sources are actually read.\nvar Slice = function (pkg, options) {\n var self = this;\n options = options || {};\n self.pkg = pkg;\n\n // Name for this slice. For example, the \"client\" in \"ddp.client\"\n // (which, NB, we might load on server arches.)\n self.sliceName = options.name;\n\n // The architecture (fully or partially qualified) that can use this\n // slice.\n self.arch = options.arch;\n\n // Unique ID for this slice. Unique across all slices of all\n // packages, but constant across reloads of this slice.\n self.id = pkg.id + \".\" + options.name + \"@\" + self.arch;\n\n // Packages used. The ordering is significant only for determining\n // import symbol priority (it doesn't affect load order), and a\n // given package could appear more than once in the list, so code\n // that consumes this value will need to guard appropriately. Each\n // element in the array has keys:\n // - spec: either 'packagename' or 'packagename.slicename'\n // - unordered: If true, we don't want the package's imports and we\n // don't want to force the package to load before us. We just want\n // to ensure that it loads if we load.\n self.uses = options.uses;\n\n // A function that returns the source files for this slice. Array of\n // paths. Null if loaded from unipackage.\n //\n // This is a function rather than a literal array because for an\n // app, we need to know the file extensions registered by the\n // plugins in order to compute the sources list, so we have to wait\n // until build time (after we have loaded any plugins, including\n // local plugins in this package) to compute this.\n self.getSourcesFunc = options.getSourcesFunc || null;\n\n // Symbols that this slice should export even if @export directives\n // don't appear in the source code. List of symbols (as strings.)\n // Empty if loaded from unipackage.\n self.forceExport = options.forceExport || [];\n\n // Files and directories that we want to monitor for changes in\n // development mode, such as source files and package.js, in the\n // format accepted by watch.Watcher.\n self.dependencyInfo = options.dependencyInfo ||\n { files: {}, directories: {} };\n\n // Has this slice been compiled?\n self.isBuilt = false;\n\n // All symbols exported from the JavaScript code in this\n // package. Array of string symbol (eg \"Foo\", \"Bar.baz\".) Set only\n // when isBuilt is true.\n self.exports = null;\n\n // Prelink output. 'boundary' is a magic cookie used for inserting\n // imports. 'prelinkFiles' is the partially linked JavaScript code\n // (an array of objects with keys 'source' and 'servePath', both\n // strings -- see prelink() in linker.js) Both of these are inputs\n // into the final link phase, which inserts the final JavaScript\n // resources into 'resources'. Set only when isBuilt is true.\n self.boundary = null;\n self.prelinkFiles = null;\n\n // All of the data provided for eventual inclusion in the bundle,\n // other than JavaScript that still needs to be fed through the\n // final link stage. A list of objects with these keys:\n //\n // type: \"js\", \"css\", \"head\", \"body\", \"static\"\n //\n // data: The contents of this resource, as a Buffer. For example,\n // for \"head\", the data to insert in ; for \"js\", the\n // JavaScript source code (which may be subject to further\n // processing such as minification); for \"static\", the contents of a\n // static resource such as an image.\n //\n // servePath: The (absolute) path at which the resource would prefer\n // to be served. Interpretation varies by type. For example, always\n // honored for \"static\", ignored for \"head\" and \"body\", sometimes\n // honored for CSS but ignored if we are concatenating.\n //\n // Set only when isBuilt is true.\n self.resources = null;\n\n // Absolute path to the node_modules directory to use at runtime to\n // resolve Npm.require() calls in this slice. null if this slice\n // does not have a node_modules.\n self.nodeModulesPath = options.nodeModulesPath;\n};\n\n_.extend(Slice.prototype, {\n // Move the slice to the 'built' state. Process all source files\n // through the appropriate handlers and run the prelink phase on any\n // resulting JavaScript. Also add all provided source files to the\n // package dependencies. Sets fields such as dependencies, exports,\n // boundary, prelinkFiles, and resources.\n build: function () {\n var self = this;\n var isApp = ! self.pkg.name;\n\n if (self.isBuilt)\n throw new Error(\"slice built twice?\");\n\n var resources = [];\n var js = [];\n\n // Preemptively check to make sure that each of the packages we\n // reference actually exist. If we find a package that doesn't\n // exist, emit an error and remove it from the package list. That\n // way we get one error about it instead of a new error at each\n // stage in the build process in which we try to retrieve the\n // package.\n var scrubbedUses = [];\n _.each(self.uses, function (u) {\n var parts = u.spec.split('.');\n var pkg = self.pkg.library.get(parts[0], /* throwOnError */ false);\n if (! pkg) {\n buildmessage.error(\"no such package: '\" + parts[0] + \"'\");\n // recover by omitting this package from 'uses'\n } else\n scrubbedUses.push(u);\n });\n self.uses = scrubbedUses;\n\n _.each(self.getSourcesFunc(), function (relPath) {\n var absPath = path.resolve(self.pkg.sourceRoot, relPath);\n var ext = path.extname(relPath).substr(1);\n var handler = self._getSourceHandler(ext);\n var contents = fs.readFileSync(absPath);\n self.dependencyInfo.files[absPath] = Builder.sha1(contents);\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n if (archinfo.matches(self.arch, \"browser\")) {\n resources.push({\n type: \"static\",\n data: contents,\n servePath: path.join(self.pkg.serveRoot, relPath)\n });\n }\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript.)\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - rootOutputPath: on browser targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-browser targets\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\" })\n // Browser targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // lineForLine: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. Set the misleadingly named lineForLine\n // option to true if line X, column Y in the input corresponds\n // to line X, column Y in the output. This will enable line\n // and column reporting in error messages. (XXX replace this\n // with source maps)\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Browser targets only. Add a file to serve as-is over HTTP.\n // This time `data` is a Buffer rather than a string. It will\n // be served at the exact path you request (concatenated with\n // rootOutputPath.)\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, columnEnd: 25, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces.) sourcePath,\n // line, column, columnEnd, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'browser'\n // vs 'native') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific slice will be emitted only if\n // there are native node modules.) Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force builds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n var compileStep = {\n inputSize: contents.length,\n inputPath: relPath,\n _fullInputPath: absPath, // avoid, see above..\n rootOutputPath: self.pkg.serveRoot,\n arch: self.arch,\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n appendDocument: function (options) {\n if (! archinfo.matches(self.arch, \"browser\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"browser targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(options.data, 'utf8')\n });\n },\n addStylesheet: function (options) {\n if (! archinfo.matches(self.arch, \"browser\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"browser targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n data: new Buffer(options.data, 'utf8'),\n servePath: path.join(self.pkg.serveRoot, options.path)\n });\n },\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n js.push({\n source: options.data,\n sourcePath: options.sourcePath,\n servePath: path.join(self.pkg.serveRoot, options.path),\n includePositionInErrors: options.lineForLine\n });\n },\n addAsset: function (options) {\n if (! archinfo.matches(self.arch, \"browser\"))\n throw new Error(\"Sorry, currently, static assets can only be \" +\n \"emitted to browser targets\");\n if (! (options.data instanceof Buffer))\n throw new Error(\"'data' option to addAsset must be a Buffer\");\n resources.push({\n type: \"static\",\n data: options.data,\n servePath: path.join(self.pkg.serveRoot, options.path)\n });\n },\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // Phase 1 link\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n combinedServePath: isApp ? null :\n \"/packages/\" + self.pkg.name +\n (self.sliceName === \"main\" ? \"\" : (\".\" + self.sliceName)) + \".js\",\n // XXX report an error if there is a package called global-imports\n importStubServePath: '/packages/global-imports.js',\n name: self.pkg.name || null,\n forceExport: self.forceExport\n });\n\n // Add dependencies on the source code to any plugins that we\n // could have used (we need to depend even on plugins that we\n // didn't use, because if they were changed they might become\n // relevant to us)\n //\n // XXX I guess they're probably properly disjoint since plugins\n // probably include only file dependencies? Anyway it would be a\n // strange situation if plugin source directories overlapped with\n // other parts of your app\n _.each(self._activePluginPackages(), function (otherPkg) {\n _.extend(self.dependencyInfo.files,\n otherPkg.pluginDependencyInfo.files);\n _.extend(self.dependencyInfo.directories,\n otherPkg.pluginDependencyInfo.directories);\n });\n\n self.prelinkFiles = results.files;\n self.boundary = results.boundary;\n self.exports = results.exports;\n self.resources = resources;\n self.isBuilt = true;\n },\n\n // Get the resources that this function contributes to a bundle, in\n // the same format as self.resources as documented above. This\n // includes static assets and fully linked JavaScript.\n //\n // @param bundleArch The architecture targeted by the bundle. Might\n // be more specific than self.arch.\n //\n // It is when you call this function that we read our dependent\n // packages and commit to whatever versions of them we currently\n // have in the library -- at least for the purpose of imports, which\n // is resolved at bundle time. (On the other hand, when it comes to\n // the extension handlers we'll use, we previously commited to those\n // versions at package build ('compile') time.)\n getResources: function (bundleArch) {\n var self = this;\n var library = self.pkg.library;\n\n if (! self.isBuilt)\n throw new Error(\"getting resources of unbuilt slice?\" + self.pkg.name + \" \" + self.sliceName + \" \" + self.arch);\n\n if (! archinfo.matches(bundleArch, self.arch))\n throw new Error(\"slice of arch '\" + self.arch + \"' does not support '\" +\n bundleArch + \"'?\");\n\n // Compute imports by merging the exports of all of the packages\n // we use. Note that in the case of conflicting symbols, later\n // packages get precedence.\n var imports = {}; // map from symbol to supplying package name\n _.each(_.values(self.uses), function (u) {\n if (! u.unordered) {\n _.each(library.getSlices(u.spec, bundleArch), function (otherSlice) {\n if (! otherSlice.isBuilt)\n throw new Error(\"dependency wasn't built?\");\n _.each(otherSlice.exports, function (symbol) {\n imports[symbol] = otherSlice.pkg.name;\n });\n });\n }\n });\n\n // Phase 2 link\n var isApp = ! self.pkg.name;\n var files = linker.link({\n imports: imports,\n useGlobalNamespace: isApp,\n prelinkFiles: self.prelinkFiles,\n boundary: self.boundary\n });\n\n // Add each output as a resource\n var jsResources = _.map(files, function (file) {\n return {\n type: \"js\",\n data: new Buffer(file.source, 'utf8'),\n servePath: file.servePath\n };\n });\n\n return _.union(self.resources, jsResources); // union preserves order\n },\n\n // Return an array of all plugins that are active in this slice, as\n // a list of Packages.\n _activePluginPackages: function () {\n var self = this;\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't\n // have a special \"use\" role anymore. it's not totally clear to me\n // what the correct behavior should be -- we need to resolve\n // whether we think about extensions as being global to a package\n // or particular to a slice.\n var ret = [self.pkg];\n\n _.each(self.uses, function (u) {\n ret.push(self.pkg.library.get(u.spec.split('.')[0]));\n });\n\n _.each(ret, function (pkg) {\n pkg._ensurePluginsInitialized();\n });\n\n return ret;\n },\n\n // Get all extensions handlers registered in this slice, as a map\n // from extension (no leading dot) to handler function. Throws an\n // exception if two packages are registered for the same extension.\n _allHandlers: function () {\n var self = this;\n var ret = {};\n\n // We provide a hardcoded handler for *.js files.. since plugins\n // are written in JavaScript we have to start somewhere.\n _.extend(ret, {\n js: function (compileStep) {\n compileStep.addJavaScript({\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n lineForLine: true\n });\n }\n });\n\n _.each(self._activePluginPackages(), function (otherPkg) {\n var all = _.extend({}, otherPkg.sourceHandlers);\n _.extend(all, otherPkg.legacyExtensionHandlers);\n\n _.each(all, function (handler, ext) {\n if (ext in ret && ret[ext] !== handler) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (self.pkg.name || \"the app\") + \", \" +\n (ret[ext].pkg.name || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n } else {\n ret[ext] = handler;\n }\n });\n });\n\n return ret;\n },\n\n // Return a list of all of the extension that indicate source files\n // for this slice, not including leading dots. Computed based on\n // this.uses, so should only be called once that has been set.\n registeredExtensions: function () {\n var self = this;\n return _.keys(self._allHandlers());\n },\n\n // Find the function that should be used to handle a source file for\n // this slice, or return null if there isn't one. We'll use handlers\n // that are defined in this package and in its immediate\n // dependencies. ('extension' should be the extension of the file\n // without a leading dot.)\n _getSourceHandler: function (extension) {\n var self = this;\n return (self._allHandlers())[extension] || null;\n }\n});\n\n///////////////////////////////////////////////////////////////////////////////\n// Packages\n///////////////////////////////////////////////////////////////////////////////\n\n// XXX This object conflates two things that now seem to be almost\n// totally separate: source code for a package, and an actual built\n// package that is ready to be used. In fact it contains a list of\n// Slice objects about which the same thing can be said. To see the\n// distinction, ask yourself, what fields are set when the package is\n// initialized via initFromUnipackage?\n//\n// Package and Slice should each be split into two objects, eg\n// PackageSource and SliceSource versus BuiltPackage and BuiltSlice\n// (find better names, though.)\n\nvar nextPackageId = 1;\nvar Package = function (library) {\n var self = this;\n\n // A unique ID (guaranteed to not be reused in this process -- if\n // the package is reloaded, it will get a different id the second\n // time)\n self.id = nextPackageId++;\n\n // The name of the package, or null for an app pseudo-package or\n // collection. The package's exports will reside in Package..\n // When it is null it is linked like an application instead of like\n // a package.\n self.name = null;\n\n // The path relative to which all source file paths are interpreted\n // in this package. Also used to compute the location of the\n // package's .npm directory (npm shrinkwrap state.) null if loaded\n // from unipackage.\n self.sourceRoot = null;\n\n // Path that will be prepended to the URLs of all resources emitted\n // by this package (assuming they don't end up getting\n // concatenated.) For non-browser targets, the only effect this will\n // have is to change the actual on-disk paths of the files in the\n // bundle, for those that care to open up the bundle and look (but\n // it's still nice to get it right.) null if loaded from unipackage.\n self.serveRoot = null;\n\n // Package library that should be used to resolve this package's\n // dependencies\n self.library = library;\n\n // Package metadata. Keys are 'summary' and 'internal'.\n self.metadata = {};\n\n // File handler extensions defined by this package. Map from file\n // extension to the handler function.\n self.legacyExtensionHandlers = {};\n\n // Available editions/subpackages (\"slices\") of this package. Array\n // of Slice.\n self.slices = [];\n\n // Map from an arch to the list of slice names that should be\n // included by default if this package is used without specifying a\n // slice (eg, as \"ddp\" rather than \"ddp.server\"). The most specific\n // arch will be used.\n self.defaultSlices = {};\n\n // Map from an arch to the list of slice names that should be\n // included when this package is tested. The most specific arch will\n // be used.\n self.testSlices = {};\n\n // The information necessary to build the plugins in this\n // package. Map from plugin name to object with keys 'name', 'us',\n // 'sources', and 'npmDependencies'.\n self.pluginInfo = {};\n\n // Plugins in this package. Map from plugin name to\n // bundler.Plugin. Present only when isBuilt is true.\n self.plugins = {};\n\n // Dependencies for any plugins in this package. Present only when\n // isBuilt is true.\n // XXX Refactor so that slice and plugin dependencies are handled by\n // the same mechanism.\n self.pluginDependencyInfo = { files: {}, directories: {} };\n\n // True if plugins have been initialized (if\n // _ensurePluginsInitialized has been called)\n self._pluginsInitialized = false;\n\n // Source file handlers registered by plugins. Map from extension\n // (without a dot) to a handler function that takes a\n // CompileStep. Valid only when _pluginsInitialized is true.\n self.sourceHandlers = null;\n\n // Is this package in a built state? If not (if you created it by\n // means that doesn't create it in a build state to start with) you\n // will need to call build() before you can use it. We break down\n // the two phases of the build process, plugin building and\n // building, into two flags.\n self.pluginsBuilt = false;\n self.slicesBuilt = false;\n};\n\n_.extend(Package.prototype, {\n // Make a dummy (empty) package that contains nothing of interest.\n initEmpty: function (name) {\n var self = this;\n self.name = name;\n self.defaultSlices = {'': []};\n self.testSlices = {'': []};\n },\n\n // Return the slice of the package to use for a given slice name\n // (eg, 'main' or 'test') and target architecture (eg,\n // 'native.linux.x86_64' or 'browser'), or throw an exception if\n // that packages can't be loaded under these circumstances.\n getSingleSlice: function (name, arch) {\n var self = this;\n\n var chosenArch = archinfo.mostSpecificMatch(\n arch, _.pluck(_.where(self.slices, { sliceName: name }), 'arch'));\n\n if (! chosenArch) {\n // XXX need improvement. The user should get a graceful error\n // message, not an exception, and all of this talk of slices an\n // architectures is likely to be confusing/overkill in many\n // contexts.\n throw new Error((self.name || \"this app\") +\n \" does not have a slice named '\" + name +\n \"' that runs on architecture '\" + arch + \"'\");\n }\n\n return _.where(self.slices, { sliceName: name, arch: chosenArch })[0];\n },\n\n // Return the slices that should be used on a given arch if the\n // package is named without any qualifiers (eg, 'ddp' rather than\n // 'ddp.client').\n //\n // On error, throw an exception, or if inside\n // buildmessage.capture(), log a build error and return [].\n getDefaultSlices: function (arch) {\n var self = this;\n\n var chosenArch = archinfo.mostSpecificMatch(arch,\n _.keys(self.defaultSlices));\n if (! chosenArch) {\n buildmessage.error(\n (self.name || \"this app\") +\n \" is not compatible with architecture '\" + arch + \"'\",\n { secondary: true });\n // recover by returning by no slices\n return [];\n }\n\n return _.map(self.defaultSlices[chosenArch], function (name) {\n return self.getSingleSlice(name, arch);\n });\n },\n\n // Return the slices that should be used to test the package on a\n // given arch.\n getTestSlices: function (arch) {\n var self = this;\n\n var chosenArch = archinfo.mostSpecificMatch(arch,\n _.keys(self.testSlices));\n if (! chosenArch) {\n buildmessage.error(\n (self.name || \"this app\") +\n \" does not have tests for architecture \" + arch + \"'\",\n { secondary: true });\n // recover by returning by no slices\n return [];\n }\n\n return _.map(self.testSlices[chosenArch], function (name) {\n return self.getSingleSlice(name, arch);\n });\n },\n\n // This is called on all packages at Meteor install time so they can\n // do any prep work necessary for the user's first Meteor run to be\n // fast, for example fetching npm dependencies. Currently thanks to\n // refactorings there's nothing to do here.\n // XXX remove?\n preheat: function () {\n },\n\n // If this package has plugins, initialize them (run the startup\n // code in them so that they register their extensions.) Idempotent.\n _ensurePluginsInitialized: function () {\n var self = this;\n\n if (! self.pluginsBuilt)\n throw new Error(\"running plugins of unbuilt package?\");\n\n if (self._pluginsInitialized)\n return;\n\n var Plugin = {\n // 'extension' is a file extension without a dot (eg 'js', 'coffee')\n //\n // 'handler' is a function that takes a single argument, a\n // CompileStep (#CompileStep)\n registerSourceHandler: function (extension, handler) {\n if (extension in self.sourceHandlers) {\n buildmessage.error(\"duplicate handler for '*.\" +\n extension + \"'; may only have one per Plugin\",\n { useMyCaller: true });\n // recover by ignoring all but the first\n return;\n }\n\n self.sourceHandlers[extension] = handler;\n }\n };\n\n self.sourceHandlers = [];\n _.each(self.plugins, function (plugin, name) {\n buildmessage.enterJob({\n title: \"loading plugin `\" + name +\n \"` from package `\" + self.name + \"`\"\n // don't necessarily have rootPath anymore\n // (XXX we do, if the unipackage was locally built, which is\n // the important case for debugging. it'd be nice to get this\n // case right.)\n }, function () {\n plugin.load({Plugin: Plugin});\n });\n });\n\n self._pluginsInitialized = true;\n },\n\n // Move a package to the built state (by running its source files\n // through the appropriate compiler plugins.) Once build has\n // completed, any errors detected in the package will have been\n // emitted to buildmessage.\n //\n // build() may retrieve the package's dependencies from the library,\n // so it is illegal to call build() from library.get() (until the\n // package has actually been put in the loaded package list.)\n build: function () {\n var self = this;\n\n if (self.pluginsBuilt || self.slicesBuilt)\n throw new Error(\"package already built?\");\n\n // Build plugins\n _.each(self.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + self.name + \"`\",\n rootPath: self.sourceRoot\n }, function () {\n var buildResult = bundler.buildJsImage({\n name: info.name,\n library: self.library,\n use: info.use,\n sourceRoot: self.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: path.resolve(path.join(self.sourceRoot, '.npm', 'plugin',\n info.name))\n });\n\n if (buildResult.dependencyInfo) {\n // Merge plugin dependencies\n // XXX is naive merge sufficient here? should be, because\n // plugins can't (for now) contain directory dependencies?\n _.extend(self.pluginDependencyInfo.files,\n buildResult.dependencyInfo.files);\n _.extend(self.pluginDependencyInfo.directories,\n buildResult.dependencyInfo.directories);\n }\n\n self.plugins[info.name] = buildResult.image;\n });\n });\n self.pluginsBuilt = true;\n\n // Build slices. Might use our plugins, so needs to happen\n // second.\n _.each(self.slices, function (slice) {\n slice.build();\n });\n self.slicesBuilt = true;\n },\n\n // Programmatically initialized a package from scratch. For now,\n // cannot create browser packages. This function does not retrieve\n // the package's dependencies from the library, and on return,\n // the package will be in an unbuilt state.\n //\n // Unlike user-facing methods of creating a package\n // (initFromPackageDir, initFromAppDir) this does not implicitly add\n // a dependency on the 'meteor' package. If you want such a\n // dependency then you must add it yourself.\n //\n // If called inside a buildmessage job, it will keep going if things\n // go wrong. Be sure to call jobHasMessages to see if it actually\n // succeeded.\n //\n // Options:\n // - sourceRoot (required if sources present)\n // - serveRoot (required if sources present)\n // - sliceName\n // - use\n // - sources\n // - npmDependencies\n // - npmDir\n initFromOptions: function (name, options) {\n var self = this;\n self.name = name;\n\n if (options.sources && options.sources.length > 1 &&\n (! options.sourceRoot || ! options.serveRoot))\n throw new Error(\"When source files are given, sourceRoot and \" +\n \"serveRoot must be specified\");\n self.sourceRoot = options.sourceRoot || path.sep;\n self.serveRoot = options.serveRoot || path.sep;\n\n var isPortable = true;\n var nodeModulesPath = null;\n if (options.npmDependencies) {\n meteorNpm.ensureOnlyExactVersions(options.npmDependencies);\n var npmOk =\n meteorNpm.updateDependencies(name, options.npmDir,\n options.npmDependencies);\n if (npmOk && ! meteorNpm.dependenciesArePortable(options.npmDir))\n isPortable = false;\n nodeModulesPath = path.join(options.npmDir, 'node_modules');\n }\n\n var arch = isPortable ? \"native\" : archinfo.host();\n var slice = new Slice(self, {\n name: options.sliceName,\n arch: arch,\n uses: _.map(options.use || [], function (spec) {\n return { spec: spec }\n }),\n getSourcesFunc: function () { return options.sources || []; },\n nodeModulesPath: nodeModulesPath\n });\n self.slices.push(slice);\n\n self.defaultSlices = {'native': [options.sliceName]};\n },\n\n // Initialize a package from a legacy-style (package.js) package\n // directory. This function does not retrieve the package's\n // dependencies from the library, and on return, the package will be\n // in an unbuilt state.\n //\n // options:\n // - skipNpmUpdate: if true, don't refresh .npm/node_modules (for\n // packages that use Npm.depend). Only use this when you are\n // certain that .npm/node_modules was previously created by some\n // other means, and you're certain that the package's Npm.depend\n // instructions haven't changed since then.\n initFromPackageDir: function (name, dir, options) {\n var self = this;\n var isPortable = true;\n options = options || {};\n self.name = name;\n self.sourceRoot = dir;\n self.serveRoot = path.join(path.sep, 'packages', name);\n\n if (! fs.existsSync(self.sourceRoot))\n throw new Error(\"putative package directory \" + dir + \" doesn't exist?\");\n\n var roleHandlers = {use: null, test: null};\n var npmDependencies = null;\n\n var packageJsPath = path.join(self.sourceRoot, 'package.js');\n var code = fs.readFileSync(packageJsPath);\n var packageJsHash = Builder.sha1(code);\n\n // == 'Package' object visible in package.js ==\n var Package = {\n // Set package metadata. Options:\n // - summary: for 'meteor list'\n // - internal: if true, hide in list\n // There used to be a third option documented here,\n // 'environments', but it was never implemented and no package\n // ever used it.\n describe: function (options) {\n _.extend(self.metadata, options);\n },\n\n on_use: function (f) {\n if (roleHandlers.use) {\n buildmessage.error(\"duplicate on_use handler; a package may have \" +\n \"only one\", { useMyCaller: true });\n // Recover by ignoring the duplicate\n return;\n }\n\n roleHandlers.use = f;\n },\n\n on_test: function (f) {\n if (roleHandlers.test) {\n buildmessage.error(\"duplicate on_test handler; a package may have \" +\n \"only one\", { useMyCaller: true });\n // Recover by ignoring the duplicate\n return;\n }\n\n roleHandlers.test = f;\n },\n\n // extension doesn't contain a dot\n register_extension: function (extension, callback) {\n if (_.has(self.legacyExtensionHandlers, extension)) {\n buildmessage.error(\"duplicate handler for '*.\" + extension +\n \"'; only one per package allowed\",\n { useMyCaller: true });\n // Recover by ignoring the duplicate\n return;\n }\n self.legacyExtensionHandlers[extension] = function (compileStep) {\n\n // In the old extension API, there is a 'where' parameter\n // that conflates architecture and slice name and can be\n // either \"client\" or \"server\".\n var clientOrServer = archinfo.matches(compileStep.arch, \"browser\") ?\n \"client\" : \"server\";\n\n var api = {\n /**\n * In the legacy extension API, this is the ultimate low-level\n * entry point to add data to the bundle.\n *\n * type: \"js\", \"css\", \"head\", \"body\", \"static\"\n *\n * path: the (absolute) path at which the file will be\n * served. ignored in the case of \"head\" and \"body\".\n *\n * source_file: the absolute path to read the data from. if\n * path is set, will default based on that. overridden by\n * data.\n *\n * data: the data to send. overrides source_file if\n * present. you must still set path (except for \"head\" and\n * \"body\".)\n */\n add_resource: function (options) {\n var sourceFile = options.source_file || options.path;\n\n var data;\n if (options.data) {\n data = options.data;\n if (!(data instanceof Buffer)) {\n if (!(typeof data === \"string\")) {\n buildmessage.error(\"bad type for 'data'\",\n { useMyCaller: true });\n // recover by ignoring resource\n return;\n }\n data = new Buffer(data, 'utf8');\n }\n } else {\n if (!sourceFile) {\n buildmessage.error(\"need either 'source_file' or 'data'\",\n { useMyCaller: true });\n // recover by ignoring resource\n return;\n }\n data = fs.readFileSync(sourceFile);\n }\n\n if (options.where && options.where !== clientOrServer) {\n buildmessage.error(\"'where' is deprecated here and if \" +\n \"provided must be '\" + clientOrServer + \"'\",\n { useMyCaller: true });\n // recover by ignoring resource\n return;\n }\n\n var relPath = path.relative(compileStep.rootOutputPath,\n options.path);\n if (options.type === \"js\")\n compileStep.addJavaScript({ path: relPath,\n data: data.toString('utf8') });\n else if (options.type === \"head\" || options.type === \"body\")\n compileStep.appendDocument({ section: options.type,\n data: data.toString('utf8') });\n else if (options.type === \"css\")\n compileStep.addStylesheet({ path: relPath,\n data: data.toString('utf8') });\n else if (options.type === \"static\")\n compileStep.addAsset({ path: relPath, data: data });\n },\n\n error: function (message) {\n buildmessage.error(message, { useMyCaller: true });\n // recover by just continuing\n }\n };\n\n // old-school extension can only take the input as a file on\n // disk, so write it out to a temporary file for them. take\n // care to preserve the original extension since some legacy\n // plugins depend on that (coffeescript.) Also (sigh) put it\n // in the same directory as the original file so that\n // relative paths work for include files, for plugins that\n // care about that.\n var tmpdir = path.resolve(path.dirname(compileStep._fullInputPath));\n do {\n var tempFilePath =\n path.join(tmpdir, \"build\" +\n Math.floor(Math.random() * 1000000) +\n \".\" + path.basename(compileStep.inputPath));\n } while (fs.existsSync(tempFilePath));\n var tempFile = fs.openSync(tempFilePath, \"wx\");\n var data = compileStep.read();\n fs.writeSync(tempFile, data, 0, data.length);\n fs.closeSync(tempFile);\n\n try {\n callback(api, tempFilePath,\n path.join(compileStep.rootOutputPath,\n compileStep.inputPath),\n clientOrServer);\n } finally {\n fs.unlinkSync(tempFilePath);\n }\n };\n },\n\n // Same as node's default `require` but is relative to the\n // package's directory. Regular `require` doesn't work well\n // because we read the package.js file and `runInThisContext` it\n // separately as a string. This means that paths are relative\n // to the top-level meteor.js script rather than the location of\n // package.js\n _require: function(filename) {\n return require(path.join(self.sourceRoot, filename));\n },\n\n // Define a plugin. A plugin extends the build process for\n // targets that use this package. For example, a Coffeescript\n // compiler would be a plugin. A plugin is its own little\n // program, with its own set of source files, used packages, and\n // npm dependencies.\n //\n // This is an experimental API and for now you should assume\n // that it will change frequently and radically (thus the\n // '_transitional_'.) For maximum R&D velocity and for the good\n // of the platform, we will push changes that break your\n // packages that use this API. You've been warned.\n //\n // Options:\n // - name: a name for this plugin. required (cosmetic -- string)\n // - use: package to use for the plugin (names, as strings)\n // - sources: sources for the plugin (array of string)\n // - npmDependencies: map from npm package name to required\n // version (string)\n _transitional_registerBuildPlugin: function (options) {\n if (! ('name' in options)) {\n buildmessage.error(\"build plugins require a name\",\n { useMyCaller: true });\n // recover by ignoring plugin\n return;\n }\n\n if (options.name in self.pluginInfo) {\n buildmessage.error(\"this package already has a plugin named '\" +\n options.name + \"'\",\n { useMyCaller: true });\n // recover by ignoring plugin\n return;\n }\n\n if (options.name.match(/\\.\\./) || options.name.match(/[\\\\\\/]/)) {\n buildmessage.error(\"bad plugin name\", { useMyCaller: true });\n // recover by ignoring plugin\n return;\n }\n\n // XXX probably want further type checking\n self.pluginInfo[options.name] = options;\n }\n };\n\n // == 'Npm' object visible in package.js ==\n var Npm = {\n depends: function (_npmDependencies) {\n // XXX make npmDependencies be per slice, so that production\n // doesn't have to ship all of the npm modules used by test\n // code\n if (npmDependencies) {\n buildmessage.error(\"Npm.depends may only be called once per package\",\n { useMyCaller: true });\n // recover by ignoring the Npm.depends line\n return;\n }\n if (typeof _npmDependencies !== 'object') {\n buildmessage.error(\"the argument to Npm.depends should be an \" +\n \"object, like this: {gcd: '0.0.0'}\",\n { useMyCaller: true });\n // recover by ignoring the Npm.depends line\n return;\n }\n\n // don't allow npm fuzzy versions so that there is complete\n // consistency when deploying a meteor app\n //\n // XXX use something like seal or lockdown to have *complete*\n // confidence we're running the same code?\n try {\n meteorNpm.ensureOnlyExactVersions(_npmDependencies);\n } catch (e) {\n buildmessage.error(e.message, { useMyCaller: true, downcase: true });\n // recover by ignoring the Npm.depends line\n return;\n }\n\n npmDependencies = _npmDependencies;\n },\n\n require: function (name) {\n var nodeModuleDir = path.join(self.sourceRoot,\n '.npm', 'node_modules', name);\n if (fs.existsSync(nodeModuleDir)) {\n return require(nodeModuleDir);\n } else {\n try {\n return require(name); // from the dev bundle\n } catch (e) {\n buildmessage.error(\"can't find npm module '\" + name +\n \"'. Did you forget to call 'Npm.depends'?\",\n { useMyCaller: true });\n // recover by, uh, returning undefined, which is likely to\n // have some knock-on effects\n return undefined;\n }\n }\n }\n };\n\n try {\n files.runJavaScript(code.toString('utf8'), 'package.js',\n { Package: Package, Npm: Npm });\n } catch (e) {\n buildmessage.exception(e);\n\n // Could be a syntax error or an exception. Recover by\n // continuing as if package.js is empty. (Pressing on with\n // whatever handlers were registered before the exception turns\n // out to feel pretty disconcerting -- definitely violates the\n // principle of least surprise.) Leave the metadata if we have\n // it, though.\n roleHandlers = {use: null, test: null};\n self.legacyExtensionHandlers = {};\n self.pluginInfo = {};\n npmDependencies = null;\n }\n\n // source files used\n var sources = {use: {client: [], server: []},\n test: {client: [], server: []}};\n\n // symbols force-exported\n var forceExport = {use: {client: [], server: []},\n test: {client: [], server: []}};\n\n // packages used (keys are 'name' and 'unordered')\n var uses = {use: {client: [], server: []},\n test: {client: [], server: []}};\n\n // For this old-style, on_use/on_test/where-based package, figure\n // out its dependencies by calling its on_xxx functions and seeing\n // what it does.\n //\n // We have a simple strategy. Call its on_xxx handler with no\n // 'where', which is what happens when the package is added\n // directly to an app, and see what files it adds to the client\n // and the server. Call the former the client version of the\n // package, and the latter the server version. Then, when a\n // package is used, include it in both the client and the server\n // by default. This simple strategy doesn't capture even 10% of\n // the complexity possible with on_use, on_test, and where, but\n // probably is sufficient for virtually all packages that actually\n // exist in the field, if not every single\n // one. #OldStylePackageSupport\n _.each([\"use\", \"test\"], function (role) {\n if (roleHandlers[role]) {\n var api = {\n // Called when this package wants to make another package be\n // used. Can also take literal package objects, if you have\n // anonymous packages you want to use (eg, app packages)\n //\n // options can include:\n //\n // - role: defaults to \"use\", but you could pass something\n // like \"test\" if for some reason you wanted to include a\n // package's tests\n //\n // - unordered: if true, don't require this package to load\n // before us -- just require it to be loaded anytime. Also\n // don't bring this package's imports into our\n // namespace. If false, override a true value specified in\n // a previous call to use for this package name. (A\n // limitation of the current implementation is that this\n // flag is not tracked per-environment or per-role.) This\n // option can be used to resolve circular dependencies in\n // exceptional circumstances, eg, the 'meteor' package\n // depends on 'handlebars', but all packages (including\n // 'handlebars') have an implicit dependency on\n // 'meteor'. Internal use only -- future support of this\n // is not guaranteed. #UnorderedPackageReferences\n use: function (names, where, options) {\n options = options || {};\n\n if (!(names instanceof Array))\n names = names ? [names] : [];\n\n if (!(where instanceof Array))\n where = where ? [where] : [\"client\", \"server\"];\n\n _.each(names, function (name) {\n _.each(where, function (w) {\n if (options.role && options.role !== \"use\")\n throw new Error(\"Role override is no longer supported\");\n uses[role][w].push({\n spec: name,\n unordered: options.unordered || false\n });\n });\n });\n },\n\n // Top-level call to add a source file to a package. It will\n // be processed according to its extension (eg, *.coffee\n // files will be compiled to JavaScript.)\n add_files: function (paths, where) {\n if (!(paths instanceof Array))\n paths = paths ? [paths] : [];\n\n if (!(where instanceof Array))\n where = where ? [where] : [];\n\n _.each(paths, function (path) {\n _.each(where, function (w) {\n sources[role][w].push(path);\n });\n });\n },\n\n // Force the export of a symbol from this package. An\n // alternative to using @export directives. Possibly helpful\n // when you don't want to modify the source code of a third\n // party library.\n //\n // @param symbols String (eg \"Foo\", \"Foo.bar\") or array of String\n // @param where 'client', 'server', or an array of those\n exportSymbol: function (symbols, where) {\n if (!(symbols instanceof Array))\n symbols = symbols ? [symbols] : [];\n\n if (!(where instanceof Array))\n where = where ? [where] : [];\n\n _.each(symbols, function (symbol) {\n _.each(where, function (w) {\n forceExport[role][w].push(symbol);\n });\n });\n },\n error: function () {\n // I would try to support this but I don't even know what\n // its signature was supposed to be anymore\n buildmessage.error(\n \"api.error(), ironically, is no longer supported\",\n { useMyCaller: true });\n // recover by ignoring\n },\n registered_extensions: function () {\n buildmessage.error(\n \"api.registered_extensions() is no longer supported\",\n { useMyCaller: true });\n // recover by returning dummy value\n return [];\n }\n };\n\n try {\n roleHandlers[role](api);\n } catch (e) {\n buildmessage.exception(e);\n // Recover by ignoring all of the source files in the\n // packages and any remaining role handlers. It violates the\n // principle of least surprise to half-run a role handler\n // and then continue.\n sources = {use: {client: [], server: []},\n test: {client: [], server: []}};\n roleHandlers = {use: null, test: null};\n self.legacyExtensionHandlers = {};\n self.pluginInfo = {};\n npmDependencies = null;\n }\n }\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n var nodeModulesPath = null;\n if (npmDependencies) {\n var packageNpmDir =\n path.resolve(path.join(self.sourceRoot, '.npm'));\n var npmOk = true;\n\n if (! options.skipNpmUpdate) {\n // go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any\n // (sub)dependencies. this process also runs mostly safely\n // multiple times in parallel (which could happen if you have\n // two apps running locally using the same package)\n npmOk = meteorNpm.updateDependencies(name, packageNpmDir,\n npmDependencies);\n }\n\n nodeModulesPath = path.join(packageNpmDir, 'node_modules');\n if (npmOk && ! meteorNpm.dependenciesArePortable(packageNpmDir))\n isPortable = false;\n }\n\n // Create slices\n var nativeArch = isPortable ? \"native\" : archinfo.host();\n _.each([\"use\", \"test\"], function (role) {\n _.each([\"browser\", nativeArch], function (arch) {\n var where = (arch === \"browser\") ? \"client\" : \"server\";\n\n // Everything depends on the package 'meteor', which sets up\n // the basic environment) (except 'meteor' itself).\n if (! (name === \"meteor\" && role === \"use\")) {\n // Don't add the dependency if one already exists. This\n // allows the package to create an unordered dependency and\n // override the one that we'd add here. This is necessary to\n // resolve the circular dependency between meteor and\n // underscore (underscore depends weakly on meteor; it just\n // needs the .js extension handler.)\n var alreadyDependsOnMeteor =\n !! _.find(uses[role][where], function (u) {\n return u.spec === \"meteor\";\n });\n if (! alreadyDependsOnMeteor)\n uses[role][where].unshift({ spec: \"meteor\" });\n }\n\n // We need to create a separate (non ===) copy of\n // dependencyInfo for each slice.\n var dependencyInfo = { files: {}, directories: {} };\n dependencyInfo.files[packageJsPath] = packageJsHash;\n\n self.slices.push(new Slice(self, {\n name: ({ use: \"main\", test: \"tests\" })[role],\n arch: arch,\n uses: uses[role][where],\n getSourcesFunc: function () { return sources[role][where]; },\n forceExport: forceExport[role][where],\n dependencyInfo: dependencyInfo,\n nodeModulesPath: arch === nativeArch && nodeModulesPath || undefined\n }));\n });\n });\n\n // Default slices\n self.defaultSlices = { browser: ['main'], 'native': ['main'] };\n self.testSlices = { browser: ['tests'], 'native': ['tests'] };\n },\n\n // Initialize a package from a legacy-style application directory\n // (has .meteor/packages.) This function does not retrieve the\n // package's dependencies from the library, and on return, the\n // package will be in an unbuilt state.\n initFromAppDir: function (appDir, ignoreFiles) {\n var self = this;\n appDir = path.resolve(appDir);\n self.name = null;\n self.sourceRoot = appDir;\n self.serveRoot = path.sep;\n\n _.each([\"client\", \"server\"], function (sliceName) {\n // Determine used packages\n var names = _.union(\n // standard client packages for the classic meteor stack.\n // XXX remove and make everyone explicitly declare all dependencies\n ['meteor', 'webapp', 'deps', 'session', 'livedata', 'mongo-livedata',\n 'spark', 'templating', 'startup', 'past', 'check'],\n project.get_packages(appDir));\n\n var arch = sliceName === \"server\" ? \"native\" : \"browser\";\n\n // Create slice\n var slice = new Slice(self, {\n name: sliceName,\n arch: arch,\n uses: _.map(names, function (name) {\n return { spec: name }\n })\n });\n self.slices.push(slice);\n\n // Watch control files for changes\n // XXX this read has a race with the actual read that is used\n _.each([path.join(appDir, '.meteor', 'packages'),\n path.join(appDir, '.meteor', 'releases')], function (p) {\n if (fs.existsSync(p)) {\n slice.dependencyInfo.files[p] =\n Builder.sha1(fs.readFileSync(p));\n }\n });\n\n // Determine source files\n slice.getSourcesFunc = function () {\n var allSources = scanForSources(\n self.sourceRoot, slice.registeredExtensions(),\n ignoreFiles || []);\n\n var withoutAppPackages = _.reject(allSources, function (sourcePath) {\n // Skip files that are in app packages. (Directories named \"packages\"\n // lower in the tree are OK.)\n return sourcePath.match(/^packages\\//);\n });\n\n var otherSliceName = (sliceName === \"server\") ? \"client\" : \"server\";\n var withoutOtherSlice =\n _.reject(withoutAppPackages, function (sourcePath) {\n return (path.sep + sourcePath + path.sep).indexOf(\n path.sep + otherSliceName + path.sep) !== -1;\n });\n\n var tests = false; /* for now */\n var withoutOtherRole =\n _.reject(withoutOtherSlice, function (sourcePath) {\n var isTest =\n ((path.sep + sourcePath + path.sep).indexOf(\n path.sep + 'tests' + path.sep) !== -1);\n return isTest !== (!!tests);\n });\n\n var withoutOtherPrograms =\n _.reject(withoutOtherRole, function (sourcePath) {\n return !! sourcePath.match(/^programs\\//);\n });\n\n // XXX Add directory dependencies to slice at the time that\n // getSourcesFunc is called. This is kind of a hack but it'll\n // do for the moment.\n\n // Directories to monitor for new files\n var appIgnores = _.clone(ignoreFiles);\n slice.dependencyInfo.directories[appDir] = {\n include: _.map(slice.registeredExtensions(), function (ext) {\n return new RegExp('\\\\.' + ext + \"$\");\n }),\n exclude: ignoreFiles.concat(['tests'])\n };\n\n // Inside the packages directory, only look for new packages\n // (which we can detect by the appearance of a package.js file.)\n // Other than that, packages explicitly call out the files they\n // use.\n slice.dependencyInfo.directories[path.resolve(appDir, 'packages')] = {\n include: [ /^package\\.js$/ ],\n exclude: ignoreFiles\n };\n\n // Ditto for the programs directory.\n slice.dependencyInfo.directories[path.resolve(appDir, 'programs')] = {\n include: [ /^package\\.js$/ ],\n exclude: ignoreFiles\n };\n\n // Exclude .meteor/local and everything under it.\n slice.dependencyInfo.directories[\n path.resolve(appDir, '.meteor', 'local')] = { exclude: [/.?/] };\n\n return withoutOtherPrograms;\n };\n });\n\n self.defaultSlices = { browser: ['client'], 'native': ['server'] };\n },\n\n // Initialize a package from a prebuilt Unipackage on disk. On\n // return, the package will be a built state. This function does not\n // retrieve the package's dependencies from the library (it is not\n // necessary.)\n //\n // options:\n // - onlyIfUpToDate: if true, then first check the unipackage's\n // dependencies (if present) to see if it's up to date. If not,\n // return false without loading the package. Otherwise return\n // true. (If onlyIfUpToDate is not passed, always return true.)\n // - buildOfPath: If present, the source directory (as an absolute\n // path on local disk) of which we think this unipackage is a\n // build. If it's not (it was copied from somewhere else), we\n // consider it not up to date (in the sense of onlyIfUpToDate) so\n // that we can rebuild it and correct the absolute paths in the\n // dependency information.\n initFromUnipackage: function (name, dir, options) {\n var self = this;\n options = options || {};\n\n var mainJson =\n JSON.parse(fs.readFileSync(path.join(dir, 'unipackage.json')));\n\n if (mainJson.format !== \"unipackage-pre1\")\n throw new Error(\"Unsupported unipackage format: \" +\n JSON.stringify(mainJson.format));\n\n var buildInfoPath = path.join(dir, 'buildinfo.json');\n var buildInfoJson = fs.existsSync(buildInfoPath) ?\n JSON.parse(fs.readFileSync(buildInfoPath)) : {};\n\n // XXX should comprehensively sanitize (eg, typecheck) everything\n // read from json files\n\n // Read the dependency info (if present), and make the strings\n // back into regexps\n var dependencies = buildInfoJson.dependencies ||\n { files: {}, directories: {} };\n _.each(dependencies.directories, function (d) {\n _.each([\"include\", \"exclude\"], function (k) {\n d[k] = _.map(d[k], function (s) {\n return new RegExp(s);\n });\n });\n });\n\n // If we're supposed to check the dependencies, go ahead and do so\n if (options.onlyIfUpToDate) {\n if (options.buildOfPath &&\n (buildInfoJson.source !== options.buildOfPath)) {\n // This catches the case where you copy a source tree that had\n // a .build directory and then modify a file. Without this\n // check you won't see a rebuild (even if you stop and restart\n // meteor), at least not until you modify the *original*\n // copies of the source files, because that is still where all\n // of the dependency info points.\n return false;\n }\n\n var isUpToDate = true;\n var watcher = new watch.Watcher({\n files: dependencies.files,\n directories: dependencies.directories,\n onChange: function () {\n isUpToDate = false;\n }\n });\n watcher.stop();\n\n if (! isUpToDate)\n return false;\n }\n\n self.name = name;\n self.metadata = {\n summary: mainJson.summary,\n internal: mainJson.internal\n };\n self.defaultSlices = mainJson.defaultSlices;\n self.testSlices = mainJson.testSlices;\n\n _.each(mainJson.plugins, function (pluginMeta) {\n if (pluginMeta.path.match(/\\.\\./))\n throw new Error(\"bad path in unipackage\");\n var plugin = bundler.readJsImage(path.join(dir, pluginMeta.path));\n\n if (! archinfo.matches(archinfo.host(), plugin.arch)) {\n buildmessage.error(\"package `\" + name + \"` is built for incompatible \" +\n \"architecture: \" + plugin.arch);\n // Recover by ignoring plugin\n return;\n }\n\n // XXX should refactor so that we can have plugins of multiple\n // different arches happily coexisting in memory, to match\n // slices. If this becomes a problem before we have a chance to\n // refactor, could just ignore plugins for arches that we don't\n // support, if we are careful to not then try to write out the\n // package and expect them to be intact..\n if (pluginMeta.name in self.plugins)\n throw new Error(\"Implementation limitation: this program \" +\n \"cannot yet handle fat plugins, sorry\");\n self.plugins[pluginMeta.name] = plugin;\n });\n self.pluginsBuilt = true;\n\n _.each(mainJson.slices, function (sliceMeta) {\n // aggressively sanitize path (don't let it escape to parent\n // directory)\n if (sliceMeta.path.match(/\\.\\./))\n throw new Error(\"bad path in unipackage\");\n var sliceJson = JSON.parse(\n fs.readFileSync(path.join(dir, sliceMeta.path)));\n var sliceBasePath = path.dirname(path.join(dir, sliceMeta.path));\n\n if (sliceJson.format!== \"unipackage-slice-pre1\")\n throw new Error(\"Unsupported unipackage slice format: \" +\n JSON.stringify(sliceJson.format));\n\n var nodeModulesPath = null;\n if (sliceJson.node_modules) {\n if (sliceJson.node_modules.match(/\\.\\./))\n throw new Error(\"bad node_modules path in unipackage\");\n nodeModulesPath = path.join(sliceBasePath, sliceJson.node_modules);\n }\n\n var slice = new Slice(self, {\n name: sliceMeta.name,\n arch: sliceMeta.arch,\n dependencyInfo: dependencies,\n nodeModulesPath: nodeModulesPath,\n uses: _.map(sliceJson.uses, function (u) {\n return {\n spec: u['package'] + (u.slice ? \".\" + u.slice : \"\"),\n unordered: u.unordered\n };\n })\n });\n\n slice.isBuilt = true;\n slice.exports = sliceJson.exports || [];\n slice.boundary = sliceJson.boundary;\n slice.prelinkFiles = [];\n slice.resources = [];\n\n _.each(sliceJson.resources, function (resource) {\n if (resource.file.match(/\\.\\./))\n throw new Error(\"bad resource file path in unipackage\");\n\n var fd = fs.openSync(path.join(sliceBasePath, resource.file), \"r\");\n var data = new Buffer(resource.length);\n var count = fs.readSync(fd, data, 0, resource.length, resource.offset);\n if (count !== resource.length)\n throw new Error(\"couldn't read entire resource\");\n\n if (resource.type === \"prelink\") {\n slice.prelinkFiles.push({\n source: data.toString('utf8'),\n servePath: resource.servePath\n });\n } else if (_.contains([\"head\", \"body\", \"css\", \"js\", \"static\"],\n resource.type)) {\n slice.resources.push({\n type: resource.type,\n data: data,\n servePath: resource.servePath || undefined\n });\n } else\n throw new Error(\"bad resource type in unipackage: \" +\n JSON.stringify(resource.type));\n });\n\n self.slices.push(slice);\n });\n self.slicesBuilt = true\n\n return true;\n },\n\n // True if this package can be saved as a unipackage\n canBeSavedAsUnipackage: function () {\n var self = this;\n return _.keys(self.legacyExtensionHandlers || []).length === 0;\n },\n\n // options:\n //\n // - buildOfPath: Optional. The absolute path on local disk of the\n // directory that was built to produce this package. Used as part\n // of the dependency info to detect builds that were moved and\n // then modified.\n saveAsUnipackage: function (outputPath, options) {\n var self = this;\n var builder = new Builder({ outputPath: outputPath });\n\n if (! self.canBeSavedAsUnipackage())\n throw new Error(\"This package can not yet be saved as a unipackage\");\n\n try {\n\n var mainJson = {\n format: \"unipackage-pre1\",\n summary: self.metadata.summary,\n internal: self.metadata.internal,\n slices: [],\n defaultSlices: self.defaultSlices,\n testSlices: self.testSlices,\n plugins: []\n };\n\n var buildInfoJson = {\n dependencies: { files: {}, directories: {} },\n source: options.buildOfPath || undefined,\n };\n\n builder.reserve(\"unipackage.json\");\n builder.reserve(\"buildinfo.json\");\n builder.reserve(\"node_modules\", { directory: true });\n builder.reserve(\"head\");\n builder.reserve(\"body\");\n\n // Slices\n _.each(self.slices, function (slice) {\n if (! slice.isBuilt)\n throw new Error(\"saving unbuilt slice?\");\n\n // Make up a filename for this slice\n var baseSliceName =\n (slice.sliceName === \"main\" ? \"\" : (slice.sliceName + \".\")) +\n slice.arch;\n var sliceDir =\n builder.generateFilename(baseSliceName, { directory: true });\n var sliceJsonFile =\n builder.generateFilename(baseSliceName + \".json\");\n\n mainJson.slices.push({\n name: slice.sliceName,\n arch: slice.arch,\n path: sliceJsonFile\n });\n\n // Merge slice dependencies\n // XXX is naive merge sufficient here?\n _.extend(buildInfoJson.dependencies.files,\n slice.dependencyInfo.files);\n _.extend(buildInfoJson.dependencies.directories,\n slice.dependencyInfo.directories);\n\n // Construct slice metadata\n var sliceJson = {\n format: \"unipackage-slice-pre1\",\n exports: slice.exports,\n uses: _.map(slice.uses, function (u) {\n var specParts = u.spec.split('.');\n if (specParts.length > 2)\n throw new Error(\"Bad package spec: \" + u.spec);\n return {\n 'package': specParts[0],\n slice: specParts[1] || undefined,\n unordered: u.unordered || undefined\n };\n }),\n node_modules: slice.nodeModulesPath ? 'node_modules' : undefined,\n resources: [],\n boundary: slice.boundary\n };\n\n // Output 'head', 'body' resources nicely\n var concat = {head: [], body: []};\n var offset = {head: 0, body: 0};\n _.each(slice.resources, function (resource) {\n if (_.contains([\"head\", \"body\"], resource.type)) {\n if (concat[resource.type].length) {\n concat[resource.type].push(new Buffer(\"\\n\", \"utf8\"));\n offset[resource.type]++;\n }\n if (! (resource.data instanceof Buffer))\n throw new Error(\"Resource data must be a Buffer\");\n sliceJson.resources.push({\n type: resource.type,\n file: path.join(sliceDir, resource.type),\n length: resource.data.length,\n offset: offset[resource.type]\n });\n concat[resource.type].push(resource.data);\n offset[resource.type] += resource.data.length;\n }\n });\n _.each(concat, function (parts, type) {\n if (parts.length) {\n builder.write(path.join(sliceDir, type), {\n data: Buffer.concat(concat[type], offset[type])\n });\n }\n });\n\n // Output other resources each to their own file\n _.each(slice.resources, function (resource) {\n if (_.contains([\"head\", \"body\"], resource.type))\n return; // already did this one\n\n var resourcePath = builder.generateFilename(\n path.join(sliceDir, resource.servePath));\n\n builder.write(resourcePath, { data: resource.data });\n sliceJson.resources.push({\n type: resource.type,\n file: resourcePath,\n length: resource.data.length,\n offset: 0,\n servePath: resource.servePath || undefined\n });\n });\n\n // Output prelink resources\n _.each(slice.prelinkFiles, function (file) {\n var resourcePath = builder.generateFilename(\n path.join(sliceDir, file.servePath));\n var data = new Buffer(file.source, 'utf8');\n\n builder.write(resourcePath, {\n data: data\n });\n\n sliceJson.resources.push({\n type: 'prelink',\n file: resourcePath,\n length: data.length,\n offset: 0,\n servePath: file.servePath || undefined\n });\n });\n\n // If slice has included node_modules, copy them in\n if (slice.nodeModulesPath) {\n builder.copyDirectory({\n from: slice.nodeModulesPath,\n to: 'node_modules',\n depend: false\n });\n }\n\n // Control file for slice\n builder.writeJson(sliceJsonFile, sliceJson);\n });\n\n // Plugins\n _.each(self.plugins, function (plugin, name) {\n var pluginDir =\n builder.generateFilename('plugin.' + name + '.' + plugin.arch,\n { directory: true });\n var relPath = plugin.write(builder.enter(pluginDir));\n mainJson.plugins.push({\n name: name,\n arch: plugin.arch,\n path: path.join(pluginDir, relPath)\n });\n });\n\n // Prep dependencies for serialization by turning regexps into\n // strings\n _.each(buildInfoJson.dependencies.directories, function (d) {\n _.each([\"include\", \"exclude\"], function (k) {\n d[k] = _.map(d[k], function (r) {\n return r.sources;\n });\n });\n });\n\n builder.writeJson(\"unipackage.json\", mainJson);\n builder.writeJson(\"buildinfo.json\", buildInfoJson);\n builder.complete();\n } catch (e) {\n builder.abort();\n throw e;\n }\n }\n});\n\nvar packages = exports;\n_.extend(exports, {\n Package: Package\n});\n", "file_path": "tools/packages.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0036192722618579865, 0.0003788636822719127, 0.00016111184959299862, 0.00016811199020594358, 0.0006098175654187799]} {"hunk": {"id": 5, "code_window": [" // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n", " prefix: '/sockjs', log: function(){},\n", " // this is the default, but we code it explicitly because we depend\n", " // on it in stream_client:HEARTBEAT_TIMEOUT\n", " heartbeat_delay: 25000,\n", " // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" prefix: self.prefix, log: function(){},\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 19}, "file": "# QA Notes\n\n## Viewing the app cache\n\nChrome: Navigate to chrome://appcache-internals/\n\nFirefox: Open Tools / Advanced / Network. The section reading \"The\nfollowing websites are allowed to store data for offline use\" will\nshow the amount of data in the app cache (\"1.2 MB\"). If this number\nis 0 the app is permitted to use the app cache but the app cache is\ncurrently turned off.\n\n\n## Setup\n\nCreate a simple static app and add the appcache package.\n\nstatic.html:\n\n````\n\n some static content\n\n````\n\nIf you're testing with Firefox, enable it:\n\nstatic.js:\n\n````\nif (Meteor.isServer) {\n Meteor.AppCache.config({\n firefox: true\n });\n}\n````\n\n\n## App is cached offline\n\nRun Meteor, load the app in the browser, stop Meteor. Reload the page\nin the browser and observe the content is still visible.\n\n\n## Hot code reload still works\n\nRun Meteor, open the app in the browser. Make a change to\nstatic.html. Observe the change appear in the web page.\n\nNote that it is normal when using the app cache for the page reload to\nbe delayed a bit while the browser fetches the changed code in the\nbackground.\n\nWithout app cache: (page goes blank) -> (browser fetches) -> (page renders)\n\nWith app cache: (browser fetches) -> (page goes blank) -> (page renders)\n\n\n## Enabling / disabling the appcache turns the app cache on / off\n\nRun Meteor, open the app in the browser.\n\nDisable your browser in the appcache config. For example, if you're\nusing Chrome:\n\n````\nif (Meteor.isServer) {\n Meteor.AppCache.config({\n chrome: false\n });\n}\n````\n\nObserve following the hot code reload the app is no longer cached.\n\nEnable your browser again:\n\n````\nif (Meteor.isServer) {\n Meteor.AppCache.config({\n chrome: true\n });\n}\n````\n\nObserve following the hot code reload the app is cached again.\n\n\n## Removing the appcache package turns off app caching\n\nStart Meteor, open the app in the browser.\n\nStop Meteor, remove the appcache package, remove or comment out the\ncall to Meteor.AppCache.config in static.js, start Meteor again.\n\nWait for the browser to reestablish its livedata connection. Observe\nfollowing the hot code reload that the app is no longer cached.\n", "file_path": "packages/appcache/QA.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00016873607819434255, 0.00016630561731290072, 0.00016388045332860202, 0.000166349156643264, 1.4673706800749642e-06]} {"hunk": {"id": 5, "code_window": [" // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n", " prefix: '/sockjs', log: function(){},\n", " // this is the default, but we code it explicitly because we depend\n", " // on it in stream_client:HEARTBEAT_TIMEOUT\n", " heartbeat_delay: 25000,\n", " // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" prefix: self.prefix, log: function(){},\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 19}, "file": "// This file is a partial analogue to fiber_helpers.js, which allows the client\n// to use a queue too, and also to call noYieldsAllowed.\n\n// The client has no ability to yield, so noYieldsAllowed is a noop.\nMeteor._noYieldsAllowed = function (f) {\n return f();\n};\n\n// An even simpler queue of tasks than the fiber-enabled one. This one just\n// runs all the tasks when you call runTask or flush, synchronously.\nMeteor._SynchronousQueue = function () {\n var self = this;\n self._tasks = [];\n self._running = false;\n};\n\n_.extend(Meteor._SynchronousQueue.prototype, {\n runTask: function (task) {\n var self = this;\n if (!self.safeToRunTask())\n throw new Error(\"Could not synchronously run a task from a running task\");\n self._tasks.push(task);\n var tasks = self._tasks;\n self._tasks = [];\n self._running = true;\n try {\n while (!_.isEmpty(tasks)) {\n var t = tasks.shift();\n try {\n t();\n } catch (e) {\n if (_.isEmpty(tasks)) {\n // this was the last task, that is, the one we're calling runTask\n // for.\n throw e;\n } else {\n Meteor._debug(\"Exception in queued task: \" + e.stack);\n }\n }\n }\n } finally {\n self._running = false;\n }\n },\n\n queueTask: function (task) {\n var self = this;\n var wasEmpty = _.isEmpty(self._tasks);\n self._tasks.push(task);\n // Intentionally not using Meteor.setTimeout, because it doesn't like runing\n // in stubs for now.\n if (wasEmpty)\n setTimeout(_.bind(self.flush, self), 0);\n },\n\n flush: function () {\n var self = this;\n self.runTask(function () {});\n },\n\n drain: function () {\n var self = this;\n if (!self.safeToRunTask())\n return;\n while (!_.isEmpty(self._tasks)) {\n self.flush();\n }\n },\n\n safeToRunTask: function () {\n var self = this;\n return !self._running;\n }\n});\n", "file_path": "packages/meteor/fiber_stubs_client.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.005192108452320099, 0.002112206071615219, 0.00016356509877368808, 0.002360901329666376, 0.0017237254651263356]} {"hunk": {"id": 5, "code_window": [" // set up sockjs\n", " var sockjs = Npm.require('sockjs');\n", " self.server = sockjs.createServer({\n", " prefix: '/sockjs', log: function(){},\n", " // this is the default, but we code it explicitly because we depend\n", " // on it in stream_client:HEARTBEAT_TIMEOUT\n", " heartbeat_delay: 25000,\n", " // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" prefix: self.prefix, log: function(){},\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 19}, "file": "Package.describe({\n summary: \"enable the application cache in the browser\"\n});\n\nPackage.on_use(function (api) {\n api.use('webapp', 'server');\n api.use('reload', 'client');\n api.use('routepolicy', 'server');\n api.use('startup', 'client');\n api.add_files('appcache-client.js', 'client');\n api.add_files('appcache-server.js', 'server');\n});\n", "file_path": "packages/appcache/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0002593621611595154, 0.00021432386711239815, 0.00016928558761719614, 0.00021432386711239815, 4.503828677115962e-05]} {"hunk": {"id": 6, "code_window": [" // Redirect /websocket to /sockjs/websocket in order to not expose\n", " // sockjs to clients that want to use raw websockets\n", " _redirectWebsocketEndpoint: function() {\n", " // Unfortunately we can't use a connect middleware here since\n", " // sockjs installs itself prior to all existing listeners\n", " // (meaning prior to any connect middlewares) so we need to take\n", " // an approach similar to overshadowListeners in\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" var self = this;\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 79}, "file": "Meteor._routePolicy.declare('/sockjs/', 'network');\n\n// unique id for this instantiation of the server. If this changes\n// between client reconnects, the client will reload. You can set the\n// environment variable \"SERVER_ID\" to control this. For example, if\n// you want to only force a reload on major changes, you can use a\n// custom serverId which you only change when something worth pushing\n// to clients immediately happens.\n__meteor_runtime_config__.serverId =\n process.env.SERVER_ID ? process.env.SERVER_ID : Random.id();\n\nMeteor._DdpStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n self.server = sockjs.createServer({\n prefix: '/sockjs', log: function(){},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 25000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n jsessionid: false});\n self.server.installHandlers(__meteor_bootstrap__.app);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n\n // Send a welcome message with the serverId. Client uses this to\n // reload if needed.\n socket.send(JSON.stringify({server_id: __meteor_runtime_config__.serverId}));\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\n_.extend(Meteor._DdpStreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n _.each(['request', 'upgrade'], function(event) {\n var app = __meteor_bootstrap__.app;\n var oldAppListeners = app.listeners(event).slice(0);\n app.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n if (request.url === '/websocket' ||\n request.url === '/websocket/')\n request.url = '/sockjs/websocket';\n\n _.each(oldAppListeners, function(oldListener) {\n oldListener.apply(app, args);\n });\n };\n app.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/livedata/stream_server.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.9831252694129944, 0.36197641491889954, 0.00021796712826471776, 0.026101944968104362, 0.4141949713230133]} {"hunk": {"id": 6, "code_window": [" // Redirect /websocket to /sockjs/websocket in order to not expose\n", " // sockjs to clients that want to use raw websockets\n", " _redirectWebsocketEndpoint: function() {\n", " // Unfortunately we can't use a connect middleware here since\n", " // sockjs installs itself prior to all existing listeners\n", " // (meaning prior to any connect middlewares) so we need to take\n", " // an approach similar to overshadowListeners in\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" var self = this;\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 79}, "file": "// if the database is empty on server start, create some sample data.\nMeteor.startup(function () {\n if (Lists.find().length === 0) {\n var list1 = Lists.insert({name: 'Things to do'});\n Todos.insert({list_id: list1._id,\n text: 'Write Meteor app', tags: ['fun']});\n Todos.insert({list_id: list1._id,\n text: 'Drink beer', tags: ['fun', 'yum']});\n\n var list2 = Lists.insert({name: 'Places to see'});\n Todos.insert({list_id: list2._id, text: 'San Francisco',\n tags: ['yum']});\n Todos.insert({list_id: list2._id, text: 'Paris',\n tags: ['fun']});\n Todos.insert({list_id: list2._id, text: 'Tokyo'});\n\n var list3 = Lists.insert({name: 'People to meet'});\n Todos.insert({list_id: list3._id,\n text: 'All the cool kids'});\n }\n});\n", "file_path": "examples/unfinished/todos-underscore/server/bootstrap.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0004254254454281181, 0.00026223852182738483, 0.00016888673417270184, 0.00019240334222558886, 0.00011578929115785286]} {"hunk": {"id": 6, "code_window": [" // Redirect /websocket to /sockjs/websocket in order to not expose\n", " // sockjs to clients that want to use raw websockets\n", " _redirectWebsocketEndpoint: function() {\n", " // Unfortunately we can't use a connect middleware here since\n", " // sockjs installs itself prior to all existing listeners\n", " // (meaning prior to any connect middlewares) so we need to take\n", " // an approach similar to overshadowListeners in\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" var self = this;\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 79}, "file": "local\n", "file_path": "tools/tests/empty-app/.meteor/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00018023737356998026, 0.00018023737356998026, 0.00018023737356998026, 0.00018023737356998026, 0.0]} {"hunk": {"id": 6, "code_window": [" // Redirect /websocket to /sockjs/websocket in order to not expose\n", " // sockjs to clients that want to use raw websockets\n", " _redirectWebsocketEndpoint: function() {\n", " // Unfortunately we can't use a connect middleware here since\n", " // sockjs installs itself prior to all existing listeners\n", " // (meaning prior to any connect middlewares) so we need to take\n", " // an approach similar to overshadowListeners in\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": [" var self = this;\n"], "file_path": "packages/livedata/stream_server.js", "type": "add", "edit_start_line_idx": 79}, "file": "_.extend(Meteor, {\n default_server: null,\n refresh: function (notification) {\n }\n});\n\nif (typeof __meteor_bootstrap__ == 'undefined' ||\n !__meteor_bootstrap__.app) {\n // We haven't been loaded in an environment with a HTTP server (for\n // example, we might be being loaded from a command-line tool.)\n // Don't create a server.. don't even map publish, methods, call,\n // etc onto Meteor.\n} else {\n if (process.env.DDP_DEFAULT_CONNECTION_URL) {\n __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL =\n process.env.DDP_DEFAULT_CONNECTION_URL;\n }\n\n Meteor.default_server = new Meteor._LivedataServer;\n\n Meteor.refresh = function (notification) {\n var fence = Meteor._CurrentWriteFence.get();\n if (fence) {\n // Block the write fence until all of the invalidations have\n // landed.\n var proxy_write = fence.beginWrite();\n }\n Meteor._InvalidationCrossbar.fire(notification, function () {\n if (proxy_write)\n proxy_write.committed();\n });\n };\n\n // Proxy the public methods of Meteor.default_server so they can\n // be called directly on Meteor.\n _.each(['publish', 'methods', 'call', 'apply'],\n function (name) {\n Meteor[name] = _.bind(Meteor.default_server[name],\n Meteor.default_server);\n });\n}\n", "file_path": "packages/livedata/server_convenience.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0013131139567121863, 0.0004659582918975502, 0.0001727559429127723, 0.00020894782210234553, 0.0004359740996733308]} {"hunk": {"id": 7, "code_window": [" // Store arguments for use within the closure below\n", " var args = arguments;\n", "\n", " if (request.url === '/websocket' ||\n", " request.url === '/websocket/')\n", " request.url = '/sockjs/websocket';\n", "\n", " _.each(oldAppListeners, function(oldListener) {\n", " oldListener.apply(app, args);\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" request.url = self.prefix + '/websocket';\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 97}, "file": "Package.describe({\n summary: \"Meteor's latency-compensated distributed data framework\",\n internal: true\n});\n\nNpm.depends({sockjs: \"0.3.7\",\n websocket: \"1.0.7\"});\n\nPackage.on_use(function (api) {\n api.use(['check', 'random', 'ejson', 'json', 'underscore', 'deps', 'logging'],\n ['client', 'server']);\n\n // XXX we do NOT require webapp here, because it's OK to use this package on a\n // server architecture without making a server (in order to do\n // server-to-server DDP as a client). So if you want to provide a DDP server,\n // you need to use webapp before you use livedata.\n\n // Transport\n api.use('reload', 'client');\n api.use('routepolicy', 'server');\n api.add_files(['sockjs-0.3.4.js',\n 'stream_client_sockjs.js'], 'client');\n api.add_files('stream_client_nodejs.js', 'server');\n api.add_files('stream_client_common.js', ['client', 'server']);\n api.add_files('stream_server.js', 'server');\n\n // livedata_connection.js uses a Minimongo collection internally to\n // manage the current set of subscriptions.\n api.use('minimongo', ['client', 'server']);\n\n api.add_files('writefence.js', 'server');\n api.add_files('crossbar.js', 'server');\n\n api.add_files('livedata_common.js', ['client', 'server']);\n\n api.add_files('livedata_connection.js', ['client', 'server']);\n\n api.add_files('livedata_server.js', 'server');\n\n\n api.add_files('client_convenience.js', 'client');\n api.add_files('server_convenience.js', 'server');\n});\n\nPackage.on_test(function (api) {\n api.use('livedata', ['client', 'server']);\n api.use('mongo-livedata', ['client', 'server']);\n api.use('test-helpers', ['client', 'server']);\n api.use(['underscore', 'tinytest', 'random', 'deps']);\n\n api.add_files('livedata_connection_tests.js', ['client', 'server']);\n api.add_files('livedata_tests.js', ['client', 'server']);\n api.add_files('livedata_test_service.js', ['client', 'server']);\n api.add_files('session_view_tests.js', ['server']);\n api.add_files('crossbar_tests.js', ['server']);\n\n api.use('http', 'client');\n api.add_files(['stream_tests.js'], 'client');\n api.use('check', ['client', 'server']);\n});\n", "file_path": "packages/livedata/package.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017501830006949604, 0.00017135324014816433, 0.0001674523955443874, 0.00017094511713366956, 2.3216937279357808e-06]} {"hunk": {"id": 7, "code_window": [" // Store arguments for use within the closure below\n", " var args = arguments;\n", "\n", " if (request.url === '/websocket' ||\n", " request.url === '/websocket/')\n", " request.url = '/sockjs/websocket';\n", "\n", " _.each(oldAppListeners, function(oldListener) {\n", " oldListener.apply(app, args);\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" request.url = self.prefix + '/websocket';\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 97}, "file": ".build*\n", "file_path": "packages/meteor/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017114117508754134, 0.00017114117508754134, 0.00017114117508754134, 0.00017114117508754134, 0.0]} {"hunk": {"id": 7, "code_window": [" // Store arguments for use within the closure below\n", " var args = arguments;\n", "\n", " if (request.url === '/websocket' ||\n", " request.url === '/websocket/')\n", " request.url = '/sockjs/websocket';\n", "\n", " _.each(oldAppListeners, function(oldListener) {\n", " oldListener.apply(app, args);\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" request.url = self.prefix + '/websocket';\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 97}, "file": ".build*\n", "file_path": "packages/handlebars/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017114117508754134, 0.00017114117508754134, 0.00017114117508754134, 0.00017114117508754134, 0.0]} {"hunk": {"id": 7, "code_window": [" // Store arguments for use within the closure below\n", " var args = arguments;\n", "\n", " if (request.url === '/websocket' ||\n", " request.url === '/websocket/')\n", " request.url = '/sockjs/websocket';\n", "\n", " _.each(oldAppListeners, function(oldListener) {\n", " oldListener.apply(app, args);\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" request.url = self.prefix + '/websocket';\n"], "file_path": "packages/livedata/stream_server.js", "type": "replace", "edit_start_line_idx": 97}, "file": "var makeCollection = function () {\n if (Meteor.isServer)\n return new Meteor.Collection(Random.id());\n else\n return new Meteor.Collection(null);\n};\n\n_.each ([{added:'added', forceOrdered: true},\n {added:'added', forceOrdered: false},\n {added: 'addedBefore', forceOrdered: false}], function (options) {\n var added = options.added;\n var forceOrdered = options.forceOrdered;\n Tinytest.addAsync(\"observeChanges - single id - basics \"\n + added\n + (forceOrdered ? \" force ordered\" : \"\"),\n function (test, onComplete) {\n var c = makeCollection();\n var counter = 0;\n var callbacks = [added, \"changed\", \"removed\"];\n if (forceOrdered)\n callbacks.push(\"movedBefore\");\n withCallbackLogger(test,\n [added, \"changed\", \"removed\"],\n Meteor.isServer,\n function (logger) {\n var barid = c.insert({thing: \"stuff\"});\n var fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n var handle = c.find(fooid).observeChanges(logger);\n if (added === 'added')\n logger.expectResult(added, [fooid, {noodles: \"good\", bacon: \"bad\",apples: \"ok\"}]);\n else\n logger.expectResult(added,\n [fooid, {noodles: \"good\", bacon: \"bad\", apples: \"ok\"}, null]);\n c.update(fooid, {noodles: \"alright\", potatoes: \"tasty\", apples: \"ok\"});\n logger.expectResult(\"changed\",\n [fooid, {noodles: \"alright\", potatoes: \"tasty\", bacon: undefined}]);\n\n c.remove(fooid);\n logger.expectResult(\"removed\", [fooid]);\n\n c.remove(barid);\n\n c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n logger.expectNoResult();\n handle.stop();\n onComplete();\n });\n });\n});\n\nTinytest.addAsync(\"observeChanges - callback isolation\", function (test, onComplete) {\n var c = makeCollection();\n withCallbackLogger(test, [\"added\", \"changed\", \"removed\"], Meteor.isServer, function (logger) {\n var handles = [];\n var cursor = c.find();\n handles.push(cursor.observeChanges(logger));\n // fields-tampering observer\n handles.push(cursor.observeChanges({\n added: function(id, fields) {\n fields.apples = 'green';\n },\n changed: function(id, fields) {\n fields.apples = 'green';\n },\n }));\n\n var fooid = c.insert({apples: \"ok\"});\n logger.expectResult(\"added\", [fooid, {apples: \"ok\"}]);\n\n c.update(fooid, {apples: \"not ok\"})\n logger.expectResult(\"changed\", [fooid, {apples: \"not ok\"}]);\n\n test.equal(c.findOne(fooid).apples, \"not ok\");\n\n _.each(handles, function(handle) { handle.stop(); });\n onComplete();\n });\n\n});\n\nTinytest.addAsync(\"observeChanges - single id - initial adds\", function (test, onComplete) {\n var c = makeCollection();\n withCallbackLogger(test, [\"added\", \"changed\", \"removed\"], Meteor.isServer, function (logger) {\n var fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n var handle = c.find(fooid).observeChanges(logger);\n logger.expectResult(\"added\", [fooid, {noodles: \"good\", bacon: \"bad\", apples: \"ok\"}]);\n logger.expectNoResult();\n handle.stop();\n onComplete();\n });\n});\n\n\n\nTinytest.addAsync(\"observeChanges - unordered - initial adds\", function (test, onComplete) {\n var c = makeCollection();\n withCallbackLogger(test, [\"added\", \"changed\", \"removed\"], Meteor.isServer, function (logger) {\n var fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n var barid = c.insert({noodles: \"good\", bacon: \"weird\", apples: \"ok\"});\n var handle = c.find().observeChanges(logger);\n logger.expectResultUnordered([\n {callback: \"added\",\n args: [fooid, {noodles: \"good\", bacon: \"bad\", apples: \"ok\"}]},\n {callback: \"added\",\n args: [barid, {noodles: \"good\", bacon: \"weird\", apples: \"ok\"}]}\n ]);\n logger.expectNoResult();\n handle.stop();\n onComplete();\n });\n});\n\nTinytest.addAsync(\"observeChanges - unordered - basics\", function (test, onComplete) {\n var c = makeCollection();\n withCallbackLogger(test, [\"added\", \"changed\", \"removed\"], Meteor.isServer, function (logger) {\n var handle = c.find().observeChanges(logger);\n var barid = c.insert({thing: \"stuff\"});\n logger.expectResultOnly(\"added\", [barid, {thing: \"stuff\"}]);\n\n var fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n\n logger.expectResultOnly(\"added\", [fooid, {noodles: \"good\", bacon: \"bad\", apples: \"ok\"}]);\n\n c.update(fooid, {noodles: \"alright\", potatoes: \"tasty\", apples: \"ok\"});\n c.update(fooid, {noodles: \"alright\", potatoes: \"tasty\", apples: \"ok\"});\n logger.expectResultOnly(\"changed\",\n [fooid, {noodles: \"alright\", potatoes: \"tasty\", bacon: undefined}]);\n c.remove(fooid);\n logger.expectResultOnly(\"removed\", [fooid]);\n c.remove(barid);\n logger.expectResultOnly(\"removed\", [barid]);\n\n fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n\n logger.expectResult(\"added\", [fooid, {noodles: \"good\", bacon: \"bad\", apples: \"ok\"}]);\n logger.expectNoResult();\n handle.stop();\n onComplete();\n });\n});\n\nif (Meteor.isServer) {\n Tinytest.addAsync(\"observeChanges - unordered - specific fields\", function (test, onComplete) {\n var c = makeCollection();\n withCallbackLogger(test, [\"added\", \"changed\", \"removed\"], Meteor.isServer, function (logger) {\n var handle = c.find({}, {fields:{noodles: 1, bacon: 1}}).observeChanges(logger);\n var barid = c.insert({thing: \"stuff\"});\n logger.expectResultOnly(\"added\", [barid, {}]);\n\n var fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n\n logger.expectResultOnly(\"added\", [fooid, {noodles: \"good\", bacon: \"bad\"}]);\n\n c.update(fooid, {noodles: \"alright\", potatoes: \"tasty\", apples: \"ok\"});\n logger.expectResultOnly(\"changed\",\n [fooid, {noodles: \"alright\", bacon: undefined}]);\n c.update(fooid, {noodles: \"alright\", potatoes: \"meh\", apples: \"ok\"});\n c.remove(fooid);\n logger.expectResultOnly(\"removed\", [fooid]);\n c.remove(barid);\n logger.expectResultOnly(\"removed\", [barid]);\n\n fooid = c.insert({noodles: \"good\", bacon: \"bad\"});\n\n logger.expectResult(\"added\", [fooid, {noodles: \"good\", bacon: \"bad\"}]);\n logger.expectNoResult();\n handle.stop();\n onComplete();\n });\n });\n}\n\n\nTinytest.addAsync(\"observeChanges - unordered - enters and exits result set through change\", function (test, onComplete) {\n var c = makeCollection();\n withCallbackLogger(test, [\"added\", \"changed\", \"removed\"], Meteor.isServer, function (logger) {\n var handle = c.find({noodles: \"good\"}).observeChanges(logger);\n var barid = c.insert({thing: \"stuff\"});\n\n var fooid = c.insert({noodles: \"good\", bacon: \"bad\", apples: \"ok\"});\n logger.expectResultOnly(\"added\", [fooid, {noodles: \"good\", bacon: \"bad\", apples: \"ok\"}]);\n\n c.update(fooid, {noodles: \"alright\", potatoes: \"tasty\", apples: \"ok\"});\n logger.expectResultOnly(\"removed\",\n [fooid]);\n c.remove(fooid);\n c.remove(barid);\n\n fooid = c.insert({noodles: \"ok\", bacon: \"bad\", apples: \"ok\"});\n c.update(fooid, {noodles: \"good\", potatoes: \"tasty\", apples: \"ok\"});\n logger.expectResult(\"added\", [fooid, {noodles: \"good\", potatoes: \"tasty\", apples: \"ok\"}]);\n logger.expectNoResult();\n handle.stop();\n onComplete();\n });\n});\n", "file_path": "packages/mongo-livedata/observe_changes_tests.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001778556761564687, 0.00017405449762009084, 0.00016882570344023407, 0.00017391348956152797, 2.639975036800024e-06]} {"hunk": {"id": 8, "code_window": [" _.each([\"client\", \"server\"], function (sliceName) {\n", " // Determine used packages\n", " var names = _.union(\n", " // standard client packages for the classic meteor stack.\n", " // XXX remove and make everyone explicitly declare all dependencies\n", " ['meteor', 'webapp', 'deps', 'session', 'livedata', 'mongo-livedata',\n", " 'spark', 'templating', 'startup', 'past', 'check'],\n", " project.get_packages(appDir));\n", "\n", " var arch = sliceName === \"server\" ? \"native\" : \"browser\";\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" ['meteor', 'webapp', 'routepolicy', 'deps', 'session', 'livedata',\n", " 'mongo-livedata', 'spark', 'templating', 'startup', 'past', 'check'],\n"], "file_path": "tools/packages.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "Meteor._routePolicy.declare('/sockjs/', 'network');\n\n// unique id for this instantiation of the server. If this changes\n// between client reconnects, the client will reload. You can set the\n// environment variable \"SERVER_ID\" to control this. For example, if\n// you want to only force a reload on major changes, you can use a\n// custom serverId which you only change when something worth pushing\n// to clients immediately happens.\n__meteor_runtime_config__.serverId =\n process.env.SERVER_ID ? process.env.SERVER_ID : Random.id();\n\nMeteor._DdpStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n self.server = sockjs.createServer({\n prefix: '/sockjs', log: function(){},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 25000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n jsessionid: false});\n self.server.installHandlers(__meteor_bootstrap__.app);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n\n // Send a welcome message with the serverId. Client uses this to\n // reload if needed.\n socket.send(JSON.stringify({server_id: __meteor_runtime_config__.serverId}));\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\n_.extend(Meteor._DdpStreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n _.each(['request', 'upgrade'], function(event) {\n var app = __meteor_bootstrap__.app;\n var oldAppListeners = app.listeners(event).slice(0);\n app.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n if (request.url === '/websocket' ||\n request.url === '/websocket/')\n request.url = '/sockjs/websocket';\n\n _.each(oldAppListeners, function(oldListener) {\n oldListener.apply(app, args);\n });\n };\n app.addListener(event, newListener);\n });\n }\n});\n", "file_path": "packages/livedata/stream_server.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0005683180061168969, 0.00026656349655240774, 0.0001650473423069343, 0.00017542162095196545, 0.00012896695989184082]} {"hunk": {"id": 8, "code_window": [" _.each([\"client\", \"server\"], function (sliceName) {\n", " // Determine used packages\n", " var names = _.union(\n", " // standard client packages for the classic meteor stack.\n", " // XXX remove and make everyone explicitly declare all dependencies\n", " ['meteor', 'webapp', 'deps', 'session', 'livedata', 'mongo-livedata',\n", " 'spark', 'templating', 'startup', 'past', 'check'],\n", " project.get_packages(appDir));\n", "\n", " var arch = sliceName === \"server\" ? \"native\" : \"browser\";\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" ['meteor', 'webapp', 'routepolicy', 'deps', 'session', 'livedata',\n", " 'mongo-livedata', 'spark', 'templating', 'startup', 'past', 'check'],\n"], "file_path": "tools/packages.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "Package.describe({\n summary: \"Toolkit for live-updating HTML interfaces\",\n internal: true\n});\n\nPackage.on_use(function (api) {\n api.use(['underscore', 'random', 'domutils', 'liverange', 'universal-events',\n 'ordered-dict', 'deps', 'ejson'],\n 'client');\n\n api.add_files(['spark.js', 'patch.js', 'convenience.js',\n 'utils.js'], 'client');\n});\n\nPackage.on_test(function (api) {\n api.use('webapp', 'server');\n api.use(['tinytest', 'underscore', 'liverange', 'deps', 'domutils',\n 'minimongo', 'random']);\n api.use(['spark', 'test-helpers'], 'client');\n\n api.add_files('test_form_responder.js', 'server');\n\n api.add_files([\n 'spark_tests.js',\n 'patch_tests.js'\n ], 'client');\n});\n", "file_path": "packages/spark/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00018053372332360595, 0.0001709749922156334, 0.00016453744319733232, 0.00016785379557404667, 6.893311820022063e-06]} {"hunk": {"id": 8, "code_window": [" _.each([\"client\", \"server\"], function (sliceName) {\n", " // Determine used packages\n", " var names = _.union(\n", " // standard client packages for the classic meteor stack.\n", " // XXX remove and make everyone explicitly declare all dependencies\n", " ['meteor', 'webapp', 'deps', 'session', 'livedata', 'mongo-livedata',\n", " 'spark', 'templating', 'startup', 'past', 'check'],\n", " project.get_packages(appDir));\n", "\n", " var arch = sliceName === \"server\" ? \"native\" : \"browser\";\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" ['meteor', 'webapp', 'routepolicy', 'deps', 'session', 'livedata',\n", " 'mongo-livedata', 'spark', 'templating', 'startup', 'past', 'check'],\n"], "file_path": "tools/packages.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "\n jsparse Docs\n\n\n\n
\n {{> page}}\n
\n\n\n\n", "file_path": "examples/unfinished/jsparse-docs/jsparse-docs.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.0001757283171173185, 0.00017226554336957633, 0.0001684666349319741, 0.00017252127872779965, 1.9561296085157664e-06]} {"hunk": {"id": 8, "code_window": [" _.each([\"client\", \"server\"], function (sliceName) {\n", " // Determine used packages\n", " var names = _.union(\n", " // standard client packages for the classic meteor stack.\n", " // XXX remove and make everyone explicitly declare all dependencies\n", " ['meteor', 'webapp', 'deps', 'session', 'livedata', 'mongo-livedata',\n", " 'spark', 'templating', 'startup', 'past', 'check'],\n", " project.get_packages(appDir));\n", "\n", " var arch = sliceName === \"server\" ? \"native\" : \"browser\";\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" ['meteor', 'webapp', 'routepolicy', 'deps', 'session', 'livedata',\n", " 'mongo-livedata', 'spark', 'templating', 'startup', 'past', 'check'],\n"], "file_path": "tools/packages.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "/**\n * History.js HTML4 Support\n * Depends on the HTML5 Support\n * @author Benjamin Arthur Lupton \n * @copyright 2010-2011 Benjamin Arthur Lupton \n * @license New BSD License \n */\n\n(function(window,undefined){\n\t\"use strict\";\n\n\t// ========================================================================\n\t// Initialise\n\n\t// Localise Globals\n\tvar\n\t\tdocument = window.document, // Make sure we are using the correct document\n\t\tsetTimeout = window.setTimeout||setTimeout,\n\t\tclearTimeout = window.clearTimeout||clearTimeout,\n\t\tsetInterval = window.setInterval||setInterval,\n\t\tHistory = window.History = window.History||{}; // Public History Object\n\n\t// Check Existence\n\tif ( typeof History.initHtml4 !== 'undefined' ) {\n\t\tthrow new Error('History.js HTML4 Support has already been loaded...');\n\t}\n\n\n\t// ========================================================================\n\t// Initialise HTML4 Support\n\n\t// Initialise HTML4 Support\n\tHistory.initHtml4 = function(){\n\t\t// Initialise\n\t\tif ( typeof History.initHtml4.initialized !== 'undefined' ) {\n\t\t\t// Already Loaded\n\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\tHistory.initHtml4.initialized = true;\n\t\t}\n\n\n\t\t// ====================================================================\n\t\t// Properties\n\n\t\t/**\n\t\t * History.enabled\n\t\t * Is History enabled?\n\t\t */\n\t\tHistory.enabled = true;\n\n\n\t\t// ====================================================================\n\t\t// Hash Storage\n\n\t\t/**\n\t\t * History.savedHashes\n\t\t * Store the hashes in an array\n\t\t */\n\t\tHistory.savedHashes = [];\n\n\t\t/**\n\t\t * History.isLastHash(newHash)\n\t\t * Checks if the hash is the last hash\n\t\t * @param {string} newHash\n\t\t * @return {boolean} true\n\t\t */\n\t\tHistory.isLastHash = function(newHash){\n\t\t\t// Prepare\n\t\t\tvar oldHash = History.getHashByIndex(),\n\t\t\t\tisLast;\n\n\t\t\t// Check\n\t\t\tisLast = newHash === oldHash;\n\n\t\t\t// Return isLast\n\t\t\treturn isLast;\n\t\t};\n\n\t\t/**\n\t\t * History.saveHash(newHash)\n\t\t * Push a Hash\n\t\t * @param {string} newHash\n\t\t * @return {boolean} true\n\t\t */\n\t\tHistory.saveHash = function(newHash){\n\t\t\t// Check Hash\n\t\t\tif ( History.isLastHash(newHash) ) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Push the Hash\n\t\t\tHistory.savedHashes.push(newHash);\n\n\t\t\t// Return true\n\t\t\treturn true;\n\t\t};\n\n\t\t/**\n\t\t * History.getHashByIndex()\n\t\t * Gets a hash by the index\n\t\t * @param {integer} index\n\t\t * @return {string}\n\t\t */\n\t\tHistory.getHashByIndex = function(index){\n\t\t\t// Prepare\n\t\t\tvar hash = null;\n\n\t\t\t// Handle\n\t\t\tif ( typeof index === 'undefined' ) {\n\t\t\t\t// Get the last inserted\n\t\t\t\thash = History.savedHashes[History.savedHashes.length-1];\n\t\t\t}\n\t\t\telse if ( index < 0 ) {\n\t\t\t\t// Get from the end\n\t\t\t\thash = History.savedHashes[History.savedHashes.length+index];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Get from the beginning\n\t\t\t\thash = History.savedHashes[index];\n\t\t\t}\n\n\t\t\t// Return hash\n\t\t\treturn hash;\n\t\t};\n\n\n\t\t// ====================================================================\n\t\t// Discarded States\n\n\t\t/**\n\t\t * History.discardedHashes\n\t\t * A hashed array of discarded hashes\n\t\t */\n\t\tHistory.discardedHashes = {};\n\n\t\t/**\n\t\t * History.discardedStates\n\t\t * A hashed array of discarded states\n\t\t */\n\t\tHistory.discardedStates = {};\n\n\t\t/**\n\t\t * History.discardState(State)\n\t\t * Discards the state by ignoring it through History\n\t\t * @param {object} State\n\t\t * @return {true}\n\t\t */\n\t\tHistory.discardState = function(discardedState,forwardState,backState){\n\t\t\t//History.debug('History.discardState', arguments);\n\t\t\t// Prepare\n\t\t\tvar discardedStateHash = History.getHashByState(discardedState),\n\t\t\t\tdiscardObject;\n\n\t\t\t// Create Discard Object\n\t\t\tdiscardObject = {\n\t\t\t\t'discardedState': discardedState,\n\t\t\t\t'backState': backState,\n\t\t\t\t'forwardState': forwardState\n\t\t\t};\n\n\t\t\t// Add to DiscardedStates\n\t\t\tHistory.discardedStates[discardedStateHash] = discardObject;\n\n\t\t\t// Return true\n\t\t\treturn true;\n\t\t};\n\n\t\t/**\n\t\t * History.discardHash(hash)\n\t\t * Discards the hash by ignoring it through History\n\t\t * @param {string} hash\n\t\t * @return {true}\n\t\t */\n\t\tHistory.discardHash = function(discardedHash,forwardState,backState){\n\t\t\t//History.debug('History.discardState', arguments);\n\t\t\t// Create Discard Object\n\t\t\tvar discardObject = {\n\t\t\t\t'discardedHash': discardedHash,\n\t\t\t\t'backState': backState,\n\t\t\t\t'forwardState': forwardState\n\t\t\t};\n\n\t\t\t// Add to discardedHash\n\t\t\tHistory.discardedHashes[discardedHash] = discardObject;\n\n\t\t\t// Return true\n\t\t\treturn true;\n\t\t};\n\n\t\t/**\n\t\t * History.discardState(State)\n\t\t * Checks to see if the state is discarded\n\t\t * @param {object} State\n\t\t * @return {bool}\n\t\t */\n\t\tHistory.discardedState = function(State){\n\t\t\t// Prepare\n\t\t\tvar StateHash = History.getHashByState(State),\n\t\t\t\tdiscarded;\n\n\t\t\t// Check\n\t\t\tdiscarded = History.discardedStates[StateHash]||false;\n\n\t\t\t// Return true\n\t\t\treturn discarded;\n\t\t};\n\n\t\t/**\n\t\t * History.discardedHash(hash)\n\t\t * Checks to see if the state is discarded\n\t\t * @param {string} State\n\t\t * @return {bool}\n\t\t */\n\t\tHistory.discardedHash = function(hash){\n\t\t\t// Check\n\t\t\tvar discarded = History.discardedHashes[hash]||false;\n\n\t\t\t// Return true\n\t\t\treturn discarded;\n\t\t};\n\n\t\t/**\n\t\t * History.recycleState(State)\n\t\t * Allows a discarded state to be used again\n\t\t * @param {object} data\n\t\t * @param {string} title\n\t\t * @param {string} url\n\t\t * @return {true}\n\t\t */\n\t\tHistory.recycleState = function(State){\n\t\t\t//History.debug('History.recycleState', arguments);\n\t\t\t// Prepare\n\t\t\tvar StateHash = History.getHashByState(State);\n\n\t\t\t// Remove from DiscardedStates\n\t\t\tif ( History.discardedState(State) ) {\n\t\t\t\tdelete History.discardedStates[StateHash];\n\t\t\t}\n\n\t\t\t// Return true\n\t\t\treturn true;\n\t\t};\n\n\n\t\t// ====================================================================\n\t\t// HTML4 HashChange Support\n\n\t\tif ( History.emulated.hashChange ) {\n\t\t\t/*\n\t\t\t * We must emulate the HTML4 HashChange Support by manually checking for hash changes\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * History.hashChangeInit()\n\t\t\t * Init the HashChange Emulation\n\t\t\t */\n\t\t\tHistory.hashChangeInit = function(){\n\t\t\t\t// Define our Checker Function\n\t\t\t\tHistory.checkerFunction = null;\n\n\t\t\t\t// Define some variables that will help in our checker function\n\t\t\t\tvar lastDocumentHash = '',\n\t\t\t\t\tiframeId, iframe,\n\t\t\t\t\tlastIframeHash, checkerRunning;\n\n\t\t\t\t// Handle depending on the browser\n\t\t\t\tif ( History.isInternetExplorer() ) {\n\t\t\t\t\t// IE6 and IE7\n\t\t\t\t\t// We need to use an iframe to emulate the back and forward buttons\n\n\t\t\t\t\t// Create iFrame\n\t\t\t\t\tiframeId = 'historyjs-iframe';\n\t\t\t\t\tiframe = document.createElement('iframe');\n\n\t\t\t\t\t// Adjust iFarme\n\t\t\t\t\tiframe.setAttribute('id', iframeId);\n\t\t\t\t\tiframe.style.display = 'none';\n\n\t\t\t\t\t// Append iFrame\n\t\t\t\t\tdocument.body.appendChild(iframe);\n\n\t\t\t\t\t// Create initial history entry\n\t\t\t\t\tiframe.contentWindow.document.open();\n\t\t\t\t\tiframe.contentWindow.document.close();\n\n\t\t\t\t\t// Define some variables that will help in our checker function\n\t\t\t\t\tlastIframeHash = '';\n\t\t\t\t\tcheckerRunning = false;\n\n\t\t\t\t\t// Define the checker function\n\t\t\t\t\tHistory.checkerFunction = function(){\n\t\t\t\t\t\t// Check Running\n\t\t\t\t\t\tif ( checkerRunning ) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update Running\n\t\t\t\t\t\tcheckerRunning = true;\n\n\t\t\t\t\t\t// Fetch\n\t\t\t\t\t\tvar documentHash = History.getHash()||'',\n\t\t\t\t\t\t\tiframeHash = History.unescapeHash(iframe.contentWindow.document.location.hash)||'';\n\n\t\t\t\t\t\t// The Document Hash has changed (application caused)\n\t\t\t\t\t\tif ( documentHash !== lastDocumentHash ) {\n\t\t\t\t\t\t\t// Equalise\n\t\t\t\t\t\t\tlastDocumentHash = documentHash;\n\n\t\t\t\t\t\t\t// Create a history entry in the iframe\n\t\t\t\t\t\t\tif ( iframeHash !== documentHash ) {\n\t\t\t\t\t\t\t\t//History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);\n\n\t\t\t\t\t\t\t\t// Equalise\n\t\t\t\t\t\t\t\tlastIframeHash = iframeHash = documentHash;\n\n\t\t\t\t\t\t\t\t// Create History Entry\n\t\t\t\t\t\t\t\tiframe.contentWindow.document.open();\n\t\t\t\t\t\t\t\tiframe.contentWindow.document.close();\n\n\t\t\t\t\t\t\t\t// Update the iframe's hash\n\t\t\t\t\t\t\t\tiframe.contentWindow.document.location.hash = History.escapeHash(documentHash);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Trigger Hashchange Event\n\t\t\t\t\t\t\tHistory.Adapter.trigger(window,'hashchange');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// The iFrame Hash has changed (back button caused)\n\t\t\t\t\t\telse if ( iframeHash !== lastIframeHash ) {\n\t\t\t\t\t\t\t//History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);\n\n\t\t\t\t\t\t\t// Equalise\n\t\t\t\t\t\t\tlastIframeHash = iframeHash;\n\n\t\t\t\t\t\t\t// Update the Hash\n\t\t\t\t\t\t\tHistory.setHash(iframeHash,false);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Reset Running\n\t\t\t\t\t\tcheckerRunning = false;\n\n\t\t\t\t\t\t// Return true\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// We are not IE\n\t\t\t\t\t// Firefox 1 or 2, Opera\n\n\t\t\t\t\t// Define the checker function\n\t\t\t\t\tHistory.checkerFunction = function(){\n\t\t\t\t\t\t// Prepare\n\t\t\t\t\t\tvar documentHash = History.getHash();\n\n\t\t\t\t\t\t// The Document Hash has changed (application caused)\n\t\t\t\t\t\tif ( documentHash !== lastDocumentHash ) {\n\t\t\t\t\t\t\t// Equalise\n\t\t\t\t\t\t\tlastDocumentHash = documentHash;\n\n\t\t\t\t\t\t\t// Trigger Hashchange Event\n\t\t\t\t\t\t\tHistory.Adapter.trigger(window,'hashchange');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Return true\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Apply the checker function\n\t\t\t\tHistory.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));\n\n\t\t\t\t// Done\n\t\t\t\treturn true;\n\t\t\t}; // History.hashChangeInit\n\n\t\t\t// Bind hashChangeInit\n\t\t\tHistory.Adapter.onDomLoad(History.hashChangeInit);\n\n\t\t} // History.emulated.hashChange\n\n\n\t\t// ====================================================================\n\t\t// HTML5 State Support\n\n\t\t// Non-Native pushState Implementation\n\t\tif ( History.emulated.pushState ) {\n\t\t\t/*\n\t\t\t * We must emulate the HTML5 State Management by using HTML4 HashChange\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * History.onHashChange(event)\n\t\t\t * Trigger HTML5's window.onpopstate via HTML4 HashChange Support\n\t\t\t */\n\t\t\tHistory.onHashChange = function(event){\n\t\t\t\t//History.debug('History.onHashChange', arguments);\n\n\t\t\t\t// Prepare\n\t\t\t\tvar currentUrl = ((event && event.newURL) || document.location.href),\n\t\t\t\t\tcurrentHash = History.getHashByUrl(currentUrl),\n\t\t\t\t\tcurrentState = null,\n\t\t\t\t\tcurrentStateHash = null,\n\t\t\t\t\tcurrentStateHashExits = null,\n\t\t\t\t\tdiscardObject;\n\n\t\t\t\t// Check if we are the same state\n\t\t\t\tif ( History.isLastHash(currentHash) ) {\n\t\t\t\t\t// There has been no change (just the page's hash has finally propagated)\n\t\t\t\t\t//History.debug('History.onHashChange: no change');\n\t\t\t\t\tHistory.busy(false);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Reset the double check\n\t\t\t\tHistory.doubleCheckComplete();\n\n\t\t\t\t// Store our location for use in detecting back/forward direction\n\t\t\t\tHistory.saveHash(currentHash);\n\n\t\t\t\t// Expand Hash\n\t\t\t\tif ( currentHash && History.isTraditionalAnchor(currentHash) ) {\n\t\t\t\t\t//History.debug('History.onHashChange: traditional anchor', currentHash);\n\t\t\t\t\t// Traditional Anchor Hash\n\t\t\t\t\tHistory.Adapter.trigger(window,'anchorchange');\n\t\t\t\t\tHistory.busy(false);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Create State\n\t\t\t\tcurrentState = History.extractState(History.getFullUrl(currentHash||document.location.href,false),true);\n\n\t\t\t\t// Check if we are the same state\n\t\t\t\tif ( History.isLastSavedState(currentState) ) {\n\t\t\t\t\t//History.debug('History.onHashChange: no change');\n\t\t\t\t\t// There has been no change (just the page's hash has finally propagated)\n\t\t\t\t\tHistory.busy(false);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Create the state Hash\n\t\t\t\tcurrentStateHash = History.getHashByState(currentState);\n\n\t\t\t\t// Check if we are DiscardedState\n\t\t\t\tdiscardObject = History.discardedState(currentState);\n\t\t\t\tif ( discardObject ) {\n\t\t\t\t\t// Ignore this state as it has been discarded and go back to the state before it\n\t\t\t\t\tif ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {\n\t\t\t\t\t\t// We are going backwards\n\t\t\t\t\t\t//History.debug('History.onHashChange: go backwards');\n\t\t\t\t\t\tHistory.back(false);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We are going forwards\n\t\t\t\t\t\t//History.debug('History.onHashChange: go forwards');\n\t\t\t\t\t\tHistory.forward(false);\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Push the new HTML5 State\n\t\t\t\t//History.debug('History.onHashChange: success hashchange');\n\t\t\t\tHistory.pushState(currentState.data,currentState.title,currentState.url,false);\n\n\t\t\t\t// End onHashChange closure\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tHistory.Adapter.bind(window,'hashchange',History.onHashChange);\n\n\t\t\t/**\n\t\t\t * History.pushState(data,title,url)\n\t\t\t * Add a new State to the history object, become it, and trigger onpopstate\n\t\t\t * We have to trigger for HTML4 compatibility\n\t\t\t * @param {object} data\n\t\t\t * @param {string} title\n\t\t\t * @param {string} url\n\t\t\t * @return {true}\n\t\t\t */\n\t\t\tHistory.pushState = function(data,title,url,queue){\n\t\t\t\t//History.debug('History.pushState: called', arguments);\n\n\t\t\t\t// Check the State\n\t\t\t\tif ( History.getHashByUrl(url) ) {\n\t\t\t\t\tthrow new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');\n\t\t\t\t}\n\n\t\t\t\t// Handle Queueing\n\t\t\t\tif ( queue !== false && History.busy() ) {\n\t\t\t\t\t// Wait + Push to Queue\n\t\t\t\t\t//History.debug('History.pushState: we must wait', arguments);\n\t\t\t\t\tHistory.pushQueue({\n\t\t\t\t\t\tscope: History,\n\t\t\t\t\t\tcallback: History.pushState,\n\t\t\t\t\t\targs: arguments,\n\t\t\t\t\t\tqueue: queue\n\t\t\t\t\t});\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Make Busy\n\t\t\t\tHistory.busy(true);\n\n\t\t\t\t// Fetch the State Object\n\t\t\t\tvar newState = History.createStateObject(data,title,url),\n\t\t\t\t\tnewStateHash = History.getHashByState(newState),\n\t\t\t\t\toldState = History.getState(false),\n\t\t\t\t\toldStateHash = History.getHashByState(oldState),\n\t\t\t\t\thtml4Hash = History.getHash();\n\n\t\t\t\t// Store the newState\n\t\t\t\tHistory.storeState(newState);\n\t\t\t\tHistory.expectedStateId = newState.id;\n\n\t\t\t\t// Recycle the State\n\t\t\t\tHistory.recycleState(newState);\n\n\t\t\t\t// Force update of the title\n\t\t\t\tHistory.setTitle(newState);\n\n\t\t\t\t// Check if we are the same State\n\t\t\t\tif ( newStateHash === oldStateHash ) {\n\t\t\t\t\t//History.debug('History.pushState: no change', newStateHash);\n\t\t\t\t\tHistory.busy(false);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Update HTML4 Hash\n\t\t\t\tif ( newStateHash !== html4Hash && newStateHash !== History.getShortUrl(document.location.href) ) {\n\t\t\t\t\t//History.debug('History.pushState: update hash', newStateHash, html4Hash);\n\t\t\t\t\tHistory.setHash(newStateHash,false);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Update HTML5 State\n\t\t\t\tHistory.saveState(newState);\n\n\t\t\t\t// Fire HTML5 Event\n\t\t\t\t//History.debug('History.pushState: trigger popstate');\n\t\t\t\tHistory.Adapter.trigger(window,'statechange');\n\t\t\t\tHistory.busy(false);\n\n\t\t\t\t// End pushState closure\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\t/**\n\t\t\t * History.replaceState(data,title,url)\n\t\t\t * Replace the State and trigger onpopstate\n\t\t\t * We have to trigger for HTML4 compatibility\n\t\t\t * @param {object} data\n\t\t\t * @param {string} title\n\t\t\t * @param {string} url\n\t\t\t * @return {true}\n\t\t\t */\n\t\t\tHistory.replaceState = function(data,title,url,queue){\n\t\t\t\t//History.debug('History.replaceState: called', arguments);\n\n\t\t\t\t// Check the State\n\t\t\t\tif ( History.getHashByUrl(url) ) {\n\t\t\t\t\tthrow new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');\n\t\t\t\t}\n\n\t\t\t\t// Handle Queueing\n\t\t\t\tif ( queue !== false && History.busy() ) {\n\t\t\t\t\t// Wait + Push to Queue\n\t\t\t\t\t//History.debug('History.replaceState: we must wait', arguments);\n\t\t\t\t\tHistory.pushQueue({\n\t\t\t\t\t\tscope: History,\n\t\t\t\t\t\tcallback: History.replaceState,\n\t\t\t\t\t\targs: arguments,\n\t\t\t\t\t\tqueue: queue\n\t\t\t\t\t});\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// Make Busy\n\t\t\t\tHistory.busy(true);\n\n\t\t\t\t// Fetch the State Objects\n\t\t\t\tvar newState = History.createStateObject(data,title,url),\n\t\t\t\t\toldState = History.getState(false),\n\t\t\t\t\tpreviousState = History.getStateByIndex(-2);\n\n\t\t\t\t// Discard Old State\n\t\t\t\tHistory.discardState(oldState,newState,previousState);\n\n\t\t\t\t// Alias to PushState\n\t\t\t\tHistory.pushState(newState.data,newState.title,newState.url,false);\n\n\t\t\t\t// End replaceState closure\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t} // History.emulated.pushState\n\n\n\n\t\t// ====================================================================\n\t\t// Initialise\n\n\t\t// Non-Native pushState Implementation\n\t\tif ( History.emulated.pushState ) {\n\t\t\t/**\n\t\t\t * Ensure initial state is handled correctly\n\t\t\t */\n\t\t\tif ( History.getHash() && !History.emulated.hashChange ) {\n\t\t\t\tHistory.Adapter.onDomLoad(function(){\n\t\t\t\t\tHistory.Adapter.trigger(window,'hashchange');\n\t\t\t\t});\n\t\t\t}\n\n\t\t} // History.emulated.pushState\n\n\t}; // History.initHtml4\n\n\t// Try and Initialise History\n\tif ( typeof History.init !== 'undefined' ) {\n\t\tHistory.init();\n\t}\n\n})(window);\n", "file_path": "packages/jquery-history/history.html4.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/d156f080af9fefce82252c0920f7acab15aa4315", "dependency_score": [0.00017563770234119147, 0.00017088564345613122, 0.0001637583045521751, 0.0001713338278932497, 2.6925106340058846e-06]} {"hunk": {"id": 0, "code_window": [" [nodoc] boolean? transparent;\n", " [nodoc] boolean? kiosk;\n", " [nodoc] boolean? focus;\n", " [nodoc] boolean? new_instance;\n", " [nodoc] boolean? show_in_taskbar;\n", " [nodoc] DOMString? title;\n", " [nodoc] DOMString? position;\n", " [nodoc] DOMString? icon;\n", " [nodoc] DOMString? inject_js_start;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" [nodoc] boolean? mixed_context;\n"], "file_path": "src/api/nw_window.idl", "type": "add", "edit_start_line_idx": 37}, "file": "#include \"nw_content_browser_hooks.h\"\n\n// base\n#include \"base/command_line.h\"\n#include \"base/files/file_util.h\"\n#include \"base/logging.h\"\n#include \"base/threading/thread_restrictions.h\"\n#include \"base/strings/string_number_conversions.h\"\n#include \"base/strings/utf_string_conversions.h\"\n\n\n// content\n#include \"content/public/browser/child_process_security_policy.h\"\n#include \"content/public/browser/notification_service.h\"\n#include \"content/public/browser/notification_types.h\"\n// #include \"content/public/browser/plugin_service.h\"\n#include \"content/public/browser/render_process_host.h\"\n#include \"content/public/browser/render_view_host.h\"\n#include \"content/public/renderer/v8_value_converter.h\"\n#include \"content/public/common/web_preferences.h\"\n#include \"content/public/browser/child_process_termination_info.h\"\n\n// content/nw\n#include \"content/nw/src/nw_base.h\"\n#include \"content/nw/src/common/shell_switches.h\"\n\n#include \"net/cert/x509_certificate.h\"\n\n// ui\n#include \"ui/base/resource/resource_bundle.h\"\n#include \"ui/base/ui_base_types.h\"\n#include \"ui/gfx/image/image.h\"\n#include \"ui/gfx/image/image_skia_rep.h\"\n#include \"ui/gfx/codec/png_codec.h\"\n\n// gen\n#include \"nw/id/commit.h\"\n\n#include \"third_party/node-nw/src/node_webkit.h\"\n\n#if defined(OS_WIN)\n#define _USE_MATH_DEFINES\n#include \n#endif\n\nusing content::RenderProcessHost;\n\nnamespace content {\n class WebContents;\n}\n\nnamespace nw {\n\nnamespace {\n\nbool g_pinning_renderer = true;\nbool g_in_webview_apply_attr = false;\nbool g_in_webview_apply_attr_allow_nw = false;\n} //namespace\n\n#if defined(OS_MAC)\ntypedef void (*SendEventToAppFn)(const std::string& event_name, std::unique_ptr event_args);\nCONTENT_EXPORT SendEventToAppFn gSendEventToApp = nullptr;\n\nbool GetDirUserData(base::FilePath*);\n\nvoid SetTrustAnchors(net::CertificateList&);\n#endif\n// browser\n\nbool GetPackageImage(nw::Package* package,\n const FilePath& icon_path,\n gfx::Image* image) {\n FilePath path = package->ConvertToAbsoutePath(icon_path);\n\n // Read the file from disk.\n std::string file_contents;\n if (path.empty() || !base::ReadFileToString(path, &file_contents))\n return false;\n\n // Decode the bitmap using WebKit's image decoder.\n const unsigned char* data =\n reinterpret_cast(file_contents.data());\n std::unique_ptr decoded(new SkBitmap());\n // Note: This class only decodes bitmaps from extension resources. Chrome\n // doesn't (for security reasons) directly load extension resources provided\n // by the extension author, but instead decodes them in a separate\n // locked-down utility process. Only if the decoding succeeds is the image\n // saved from memory to disk and subsequently used in the Chrome UI.\n // Chrome is therefore decoding bitmaps here that were generated by Chrome.\n gfx::PNGCodec::Decode(data, file_contents.length(), decoded.get());\n if (decoded->empty())\n return false; // Unable to decode.\n\n *image = gfx::Image::CreateFrom1xBitmap(*decoded);\n return true;\n}\n\nvoid MainPartsPostDestroyThreadsHook() {\n ReleaseNWPackage();\n}\n\nvoid RendererProcessTerminatedHook(content::RenderProcessHost* process,\n const content::NotificationDetails& details) {\n content::ChildProcessTerminationInfo* process_info =\n content::Details(details).ptr();\n int exit_code = process_info->exit_code;\n#if defined(OS_POSIX)\n if (WIFEXITED(exit_code))\n exit_code = WEXITSTATUS(exit_code);\n#endif\n SetExitCode(exit_code);\n}\n\nbool GetImage(Package* package, const FilePath& icon_path, gfx::Image* image) {\n FilePath path = package->ConvertToAbsoutePath(icon_path);\n\n // Read the file from disk.\n std::string file_contents;\n if (path.empty() || !base::ReadFileToString(path, &file_contents))\n return false;\n\n // Decode the bitmap using WebKit's image decoder.\n const unsigned char* data =\n reinterpret_cast(file_contents.data());\n std::unique_ptr decoded(new SkBitmap());\n // Note: This class only decodes bitmaps from extension resources. Chrome\n // doesn't (for security reasons) directly load extension resources provided\n // by the extension author, but instead decodes them in a separate\n // locked-down utility process. Only if the decoding succeeds is the image\n // saved from memory to disk and subsequently used in the Chrome UI.\n // Chrome is therefore decoding bitmaps here that were generated by Chrome.\n gfx::PNGCodec::Decode(data, file_contents.length(), decoded.get());\n if (decoded->empty())\n return false; // Unable to decode.\n\n *image = gfx::Image::CreateFrom1xBitmap(*decoded);\n return true;\n}\n\n#if defined(OS_MAC)\nCONTENT_EXPORT bool ApplicationShouldHandleReopenHook(bool hasVisibleWindows) {\n std::unique_ptr arguments(new base::ListValue());\n if (gSendEventToApp)\n gSendEventToApp(\"nw.App.onReopen\",std::move(arguments));\n return true;\n}\n\nCONTENT_EXPORT void OSXOpenURLsHook(const std::vector& startup_urls) {\n std::unique_ptr arguments(new base::ListValue());\n for (size_t i = 0; i < startup_urls.size(); i++)\n arguments->AppendString(startup_urls[i].spec());\n if (gSendEventToApp)\n gSendEventToApp(\"nw.App.onOpen\", std::move(arguments));\n}\n#endif\n\nvoid OverrideWebkitPrefsHook(content::RenderViewHost* rvh, content::WebPreferences* web_prefs) {\n nw::Package* package = nw::package();\n if (!package)\n return;\n base::DictionaryValue* webkit;\n web_prefs->plugins_enabled = true;\n if (package->root()->GetDictionary(switches::kmWebkit, &webkit)) {\n webkit->GetBoolean(\"double_tap_to_zoom_enabled\", &web_prefs->double_tap_to_zoom_enabled);\n webkit->GetBoolean(\"plugin\", &web_prefs->plugins_enabled);\n }\n#if 0\n FilePath plugins_dir = package->path();\n\n plugins_dir = plugins_dir.AppendASCII(\"plugins\");\n\n content::PluginService* plugin_service = content::PluginService::GetInstance();\n plugin_service->AddExtraPluginDir(plugins_dir);\n#endif\n}\n\n#if 0\nbool ShouldServiceRequestHook(int child_id, const GURL& url) {\n RenderProcessHost* rph = RenderProcessHost::FromID(child_id);\n if (!rph)\n return false;\n return RphGuestFilterURLHook(rph, &url);\n}\n#endif\n\nbool PinningRenderer() {\n return g_pinning_renderer;\n}\n\nvoid SetPinningRenderer(bool pin) {\n g_pinning_renderer = pin;\n}\n\nvoid SetInWebViewApplyAttr(bool flag, bool allow_nw) {\n g_in_webview_apply_attr = flag;\n g_in_webview_apply_attr_allow_nw = allow_nw;\n}\n\nbool GetInWebViewApplyAttr(bool* allow_nw) {\n if (allow_nw)\n *allow_nw = g_in_webview_apply_attr_allow_nw;\n return g_in_webview_apply_attr;\n}\n\n} //namespace nw\n", "file_path": "src/browser/nw_content_browser_hooks.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00020805739040952176, 0.00017258661682717502, 0.00016790887457318604, 0.00017125315207522362, 8.078341124928556e-06]} {"hunk": {"id": 0, "code_window": [" [nodoc] boolean? transparent;\n", " [nodoc] boolean? kiosk;\n", " [nodoc] boolean? focus;\n", " [nodoc] boolean? new_instance;\n", " [nodoc] boolean? show_in_taskbar;\n", " [nodoc] DOMString? title;\n", " [nodoc] DOMString? position;\n", " [nodoc] DOMString? icon;\n", " [nodoc] DOMString? inject_js_start;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" [nodoc] boolean? mixed_context;\n"], "file_path": "src/api/nw_window.idl", "type": "add", "edit_start_line_idx": 37}, "file": "var mkdirp = require('../').mkdirp;\nvar path = require('path');\nvar fs = require('fs');\nvar test = require('tap').test;\nvar _0755 = parseInt('0755', 8);\n\nvar ps = [ '', 'tmp' ];\n\nfor (var i = 0; i < 25; i++) {\n var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);\n ps.push(dir);\n}\n\nvar file = ps.join('/');\n\n// a file in the way\nvar itw = ps.slice(0, 3).join('/');\n\n\ntest('clobber-pre', function (t) {\n console.error(\"about to write to \"+itw)\n fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.');\n\n fs.stat(itw, function (er, stat) {\n t.ifError(er)\n t.ok(stat && stat.isFile(), 'should be file')\n t.end()\n })\n})\n\ntest('clobber', function (t) {\n t.plan(2);\n mkdirp(file, _0755, function (err) {\n t.ok(err);\n t.equal(err.code, 'ENOTDIR');\n t.end();\n });\n});\n", "file_path": "test/node_modules/mkdirp/test/clobber.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017427692364435643, 0.0001725418696878478, 0.0001706118055153638, 0.00017263938207179308, 1.4454413985731662e-06]} {"hunk": {"id": 0, "code_window": [" [nodoc] boolean? transparent;\n", " [nodoc] boolean? kiosk;\n", " [nodoc] boolean? focus;\n", " [nodoc] boolean? new_instance;\n", " [nodoc] boolean? show_in_taskbar;\n", " [nodoc] DOMString? title;\n", " [nodoc] DOMString? position;\n", " [nodoc] DOMString? icon;\n", " [nodoc] DOMString? inject_js_start;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" [nodoc] boolean? mixed_context;\n"], "file_path": "src/api/nw_window.idl", "type": "add", "edit_start_line_idx": 37}, "file": "function output(id, msg) {\n var h1 = document.createElement('h1');\n h1.innerHTML = msg;\n h1.setAttribute('id', id);\n document.body.appendChild(h1);\n}\n\nfunction success(id, msg) {\n output(id, 'success' + (msg ? ': ' + msg: ''));\n}\n\nfunction fail(id, msg) {\n output(id, 'fail' + (msg ? ': ' + msg: ''));\n}", "file_path": "test/sanity/require-path/common.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017379086057189852, 0.00017368950648233294, 0.0001735881669446826, 0.00017368950648233294, 1.0134681360796094e-07]} {"hunk": {"id": 0, "code_window": [" [nodoc] boolean? transparent;\n", " [nodoc] boolean? kiosk;\n", " [nodoc] boolean? focus;\n", " [nodoc] boolean? new_instance;\n", " [nodoc] boolean? show_in_taskbar;\n", " [nodoc] DOMString? title;\n", " [nodoc] DOMString? position;\n", " [nodoc] DOMString? icon;\n", " [nodoc] DOMString? inject_js_start;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" [nodoc] boolean? mixed_context;\n"], "file_path": "src/api/nw_window.idl", "type": "add", "edit_start_line_idx": 37}, "file": "# MenuItem {: .doctitle}\n---\n\n[TOC]\n\n`MenuItem` represents an item in a menu. A `MenuItem` can be a separator or a normal item which has label and icon or a checkbox. It can response to mouse click or keyboard shortcut.\n\n## Synopsis\n\n```javascript\nvar item;\n\n// Create a separator\nitem = new nw.MenuItem({ type: 'separator' });\n\n// Create a normal item with label and icon\nitem = new nw.MenuItem({\n type: \"normal\", \n label: \"I'm a menu item\",\n icon: \"img/icon.png\"\n});\n\n// Or you can omit the 'type' field for normal items\nitem = new nw.MenuItem({ label: 'Simple item' });\n\n// Bind a callback to item\nitem = new nw.MenuItem({\n label: \"Click me\",\n click: function() {\n console.log(\"I'm clicked\");\n },\n key: \"s\",\n modifiers: \"ctrl+alt\",\n});\n\n// You can have submenu!\nvar submenu = new nw.Menu();\nsubmenu.append(new nw.MenuItem({ label: 'Item 1' }));\nsubmenu.append(new nw.MenuItem({ label: 'Item 2' }));\nsubmenu.append(new nw.MenuItem({ label: 'Item 3' }));\nitem.submenu = submenu;\n\n// And everything can be changed at runtime\nitem.label = 'New label';\nitem.click = function() { console.log('New click callback'); };\n```\n\n## new MenuItem(option)\n\n* `option` `{Object}` an object contains initial settings for the `MenuItem`\n - `label` `{String}` _Optional_ label for normal item or checkbox\n - `icon` `{String}` _Optional_ icon for normal item or checkbox\n - `tooltip` `{String}` _Optional_ tooltip for normal item or checkbox\n - `type` `{String}` _Optional_ the type of the item. Three types are accepted: `normal`, `checkbox`, `separator`\n - `click` `{Function}` _Optional_ the callback function when item is triggered by mouse click or keyboard shortcut\n - `enabled` `{Boolean}` _Optional_ whether the item is enabled or disabled. It's set to `true` by default.\n - `checked` `{Boolean}` _Optional_ whether the checkbox is checked or not. It's set to `false` by default.\n - `submenu` `{Menu}` _Optional_ a submenu\n - `key` `{String}` _Optional_ the key of the shortcut\n - `modifiers` `{String}` _Optional_ the modifiers of the shortcut\n\nEvery field has its own property in the `MenuItem`, see documentation of each property for details.\n\n`MenuItem` is inherited from `EventEmitter`. You can use `on` to listen to the events.\n\n## item.type\n\nGet the `type` of a `MenuItem`, it can be `separator`, `checkbox` and `normal`.\n\n!!! note\n The type can be set only when you create it. It cannot be changed at runtime.\n\n## item.label\n\nGet or set the `label` of a `MenuItem`, it can only be plain text for now.\n\n## item.icon\n\nGet or set the `icon` of a `MenuItem`, it must a path to your icon file. It can be a relative path which points to an icon in your app, or an absolute path pointing to a file in user's system.\n\nIt has no effect on setting `icon` of a `separator` item.\n\n## item.iconIsTemplate (Mac)\n\nGet or set whether `icon` image is treated as \"template\" (`true` by default). When the property is set to `true` the image is treated as \"template\" and the system automatically ensures proper styling according to the various states of the status item (e.g. dark menu, light menu, etc.). Template images should consist only of black and clear colours and can use the alpha channel in the image to adjust the opacity of black content. It has no effects on Linux and Windows.\n\n## item.tooltip (Mac)\n\nGet or set the `tooltip` of a `MenuItem`, it can only be plain text. A `tooltip` is short string that describes the menu item, it will show when you hover your mouse on the item.\n\n## item.checked\n\nGet or set whether the `MenuItem` is `checked`. Usually if a `MenuItem` is checked. There will be a mark on the left side of it. It's used mostly to indicate whether an option is on.\n\n## item.enabled\n\nGet or set whether the `MenuItem` is `enabled`. An disabled `MenuItem` will be greyed out and you will not be able to click on it.\n\n## item.submenu\n\nGet or set the `submenu` of a `MenuItem`, the `submenu` must be a `Menu` object. You should set `submenu` in the `option` when creating the `MenuItem`. Changing it at runtime is slow on some platforms.\n\n## item.click\n\nGet or set the `click` callback of a `MenuItem`, the `click` must be a valid function. It will be called when users activate the item.\n\n## item.key\n\nA single character string to specify the shortcut key for the menu item.\n\n### Valid Keys for All Platforms\n\n* Alphabet: `a`-`z`\n* Digits: `0`-`9`\n* Other keys on main area: `[` , `]` , `'` , `,` , `.` , `/` , `` ` `` , `-` , `=` , `\\` , `'` , `;` , `Tab`\n* `Esc`\n* `Down` , `Up` , `Left` , `Right`\n* [W3C DOM Level 3 KeyboardEvent Key Values](http://www.w3.org/TR/DOM-Level-3-Events-key/): `KeyA` (same as `A`), `Escape` (same as `Esc`), `F1`, `ArrowDown` (same as `Down`) etc.\n\n### Special Keys for Mac Only\nOn Mac, you can also use special keys as shortcut key with `String.fromCharCode(specialKey)`. Here are some useful keys:\n\n* **28**: Left ()\n* **29**: Right ()\n* **30**: Up ()\n* **31**: Down ()\n* **27**: Escape ()\n* **11**: PageUp ()\n* **12**: PageDown ()\n\nFor full list of special keys supported on Mac, see [NSMenuItem.keyEquivalent](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMenuItem_Class/#//apple_ref/occ/instp/NSMenuItem/keyEquivalent) and [NSEvent: Function-Key Unicodes](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/index.html#//apple_ref/doc/constant_group/Function_Key_Unicodes).\n\n## item.modifiers\n\nA string to specify the modifier keys for the shortcut of the menu item. It should be the concatenation of the following strings: `cmd` / `command` / `super`, `shift`, `ctrl`, `alt`. e.g. `\"cmd+shift+alt\"`.\n\n`cmd` represents different keys on all platforms: Windows key (Windows) on Windows and Linux, Apple key () on Mac. `super` and `command` are aliases of `cmd`.\n\n## Event: click\n\nEmitted when user activates the menu item.\n", "file_path": "docs/References/MenuItem.md", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0003109918616246432, 0.00017761188792064786, 0.00016087328549474478, 0.00016831779794301838, 3.5948909498983994e-05]} {"hunk": {"id": 1, "code_window": ["namespace nw {\n", "\n", "namespace {\n", "\n", "bool g_pinning_renderer = true;\n", "bool g_in_webview_apply_attr = false;\n", "bool g_in_webview_apply_attr_allow_nw = false;\n", "} //namespace\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["bool g_mixed_context = false;\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 56}, "file": "// Copyright 2015 The NW.js Authors. All rights reserved.\n// Use of this source code is governed by a MIT-style license that can be\n// found in the LICENSE file.\n\n// nw Window API\nnamespace nw.Window {\n callback CreateWindowCallback =\n void ([instanceOf=NWWindow] object createdWindow);\n callback EventCallback = void();\n callback GetAllWinCallback = void (object[] windows);\n\n callback CapturePageCallback = void (DOMString dataUrl);\n [noinline_doc] dictionary CapturePageOptions {\n [nodoc] DOMString? format;\n [nodoc] DOMString? datatype;\n [nodoc] long? quality;\n };\n [noinline_doc] dictionary CreateWindowOptions {\n [nodoc] DOMString? id;\n [nodoc] long? x;\n [nodoc] long? y;\n [nodoc] long? width;\n [nodoc] long? height;\n [nodoc] long? min_width;\n [nodoc] long? min_height;\n [nodoc] long? max_width;\n [nodoc] long? max_height;\n [nodoc] boolean? frame;\n [nodoc] boolean? resizable;\n [nodoc] boolean? fullscreen;\n [nodoc] boolean? show;\n [nodoc] boolean? always_on_top;\n [nodoc] boolean? visible_on_all_workspaces;\n [nodoc] boolean? transparent;\n [nodoc] boolean? kiosk;\n [nodoc] boolean? focus;\n [nodoc] boolean? new_instance;\n [nodoc] boolean? show_in_taskbar;\n [nodoc] DOMString? title;\n [nodoc] DOMString? position;\n [nodoc] DOMString? icon;\n [nodoc] DOMString? inject_js_start;\n [nodoc] DOMString? inject_js_end;\n };\n\n [noinline_doc] dictionary NWWindow {\n // show devtools for the current window\n static void showDevTools(optional any frm, optional EventCallback callback);\n static void capturePage(optional CapturePageCallback callback, optional CapturePageOptions options);\n static void show();\n static void hide();\n static void focus();\n static void blur();\n static void close(optional boolean force);\n static void minimize();\n static void maximize();\n static void unmaximize();\n static void restore();\n static void setPosition(DOMString pos);\n static void setMaximumSize(long width, long height);\n static void setMinimumSize(long width, long height);\n static void setResizable(boolean resizable);\n static void enterFullscreen();\n static void leaveFullscreen();\n static void toggleFullscreen();\n static void setVisibleOnAllWorkspaces(boolean all_visible);\n static bool canSetVisibleOnAllWorkspaces();\n static void on(DOMString event,\n EventCallback callback);\n static void once(DOMString event,\n EventCallback callback);\n static void removeListener(DOMString event,\n EventCallback callback);\n static void removeAllListeners(DOMString event);\n static void reload();\n static void reloadIgnoringCache();\n\n static void eval(object frame, DOMString script);\n static void evalNWBin(object frame, DOMString path);\n static void evalNWBinModule(object frame, DOMString path, DOMString module_path);\n static void print(optional object options);\n\n object appWindow;\n object cWindow;\n object window;\n object menu;\n long x;\n long y;\n long width;\n long height;\n double zoomLevel;\n DOMString title;\n long frameId;\n };\n interface Functions {\n // get the current window\n [nocompile] static NWWindow get(optional object domWindow);\n [nocompile] static void getAll(GetAllWinCallback callback);\n [nocompile] static void open(DOMString url,\n optional CreateWindowOptions options,\n optional CreateWindowCallback callback);\n\n };\n interface Events {\n [nocompile] static void onNewWinPolicy();\n [nocompile] static void onNavigation();\n [nocompile] static void LoadingStateChanged();\n [nocompile] static void onDocumentStart();\n [nocompile] static void onDocumentEnd();\n [nocompile] static void onZoom();\n [supportsFilters=true] static void onClose();\n };\n};\n", "file_path": "src/api/nw_window.idl", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0013827676884829998, 0.00027564054471440613, 0.00016919475456234068, 0.00017106749874074012, 0.00033404488931410015]} {"hunk": {"id": 1, "code_window": ["namespace nw {\n", "\n", "namespace {\n", "\n", "bool g_pinning_renderer = true;\n", "bool g_in_webview_apply_attr = false;\n", "bool g_in_webview_apply_attr_allow_nw = false;\n", "} //namespace\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["bool g_mixed_context = false;\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 56}, "file": "// Copyright (c) 2012 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"content/nw/src/media/media_stream_devices_controller.h\"\n\n#include \"base/command_line.h\"\n#include \"base/values.h\"\n#include \"chrome/common/chrome_switches.h\"\n#include \"content/nw/src/media/media_capture_devices_dispatcher.h\"\n#include \"content/nw/src/media/media_internals.h\"\n#include \"content/public/browser/browser_thread.h\"\n#include \"content/public/browser/desktop_media_id.h\"\n#include \"content/public/common/media_stream_request.h\"\n\n#include \"third_party/webrtc/modules/desktop_capture/desktop_capture_types.h\"\n\nusing content::BrowserThread;\n\nnamespace {\n\nbool HasAnyAvailableDevice() {\n MediaCaptureDevicesDispatcher* dispatcher =\n MediaInternals::GetInstance()->GetMediaCaptureDevicesDispatcher();\n const content::MediaStreamDevices& audio_devices =\n dispatcher->GetAudioCaptureDevices();\n const content::MediaStreamDevices& video_devices =\n dispatcher->GetVideoCaptureDevices();\n\n return !audio_devices.empty() || !video_devices.empty();\n};\n\n//const char kAudioKey[] = \"audio\";\n//const char kVideoKey[] = \"video\";\n\n} // namespace\n\nMediaStreamDevicesController::MediaStreamDevicesController(\n const content::MediaStreamRequest& request,\n const content::MediaResponseCallback& callback)\n :\n request_(request),\n callback_(callback),\n has_audio_(content::IsAudioInputMediaType(request.audio_type) &&\n !IsAudioDeviceBlockedByPolicy()),\n has_video_(content::IsVideoMediaType(request.video_type) &&\n !IsVideoDeviceBlockedByPolicy()) {\n}\n\nMediaStreamDevicesController::~MediaStreamDevicesController() {}\n\n#if 0\n// static\nvoid MediaStreamDevicesController::RegisterUserPrefs(\n PrefServiceSyncable* prefs) {\n prefs->RegisterBooleanPref(prefs::kVideoCaptureAllowed,\n true,\n PrefServiceSyncable::UNSYNCABLE_PREF);\n prefs->RegisterBooleanPref(prefs::kAudioCaptureAllowed,\n true,\n PrefServiceSyncable::UNSYNCABLE_PREF);\n}\n#endif\n\nbool MediaStreamDevicesController::DismissInfoBarAndTakeActionOnSettings() {\n // If this is a no UI check for policies only go straight to accept - policy\n // check will be done automatically on the way.\n if (request_.request_type == content::MEDIA_OPEN_DEVICE) {\n Accept(false);\n return true;\n }\n\n if (request_.audio_type == content::MEDIA_TAB_AUDIO_CAPTURE ||\n request_.video_type == content::MEDIA_TAB_VIDEO_CAPTURE ||\n request_.video_type == content::MEDIA_DESKTOP_VIDEO_CAPTURE) {\n HandleTapMediaRequest();\n return true;\n }\n\n#if 0\n // Deny the request if the security origin is empty, this happens with\n // file access without |--allow-file-access-from-files| flag.\n if (request_.security_origin.is_empty()) {\n Deny(false);\n return true;\n }\n#endif\n // Deny the request if there is no device attached to the OS.\n if (!HasAnyAvailableDevice()) {\n Deny(false);\n return true;\n }\n\n // Check if any allow exception has been made for this request.\n if (IsRequestAllowedByDefault()) {\n Accept(false);\n return true;\n }\n#if 0\n // Check if any block exception has been made for this request.\n if (IsRequestBlockedByDefault()) {\n Deny(false);\n return true;\n }\n\n // Check if the media default setting is set to block.\n if (IsDefaultMediaAccessBlocked()) {\n Deny(false);\n return true;\n }\n#endif\n // Don't show the infobar.\n return true;\n}\n\nconst std::string& MediaStreamDevicesController::GetSecurityOriginSpec() const {\n return request_.security_origin.spec();\n}\n\nvoid MediaStreamDevicesController::Accept(bool update_content_setting) {\n // Get the default devices for the request.\n content::MediaStreamDevices devices;\n MediaCaptureDevicesDispatcher* dispatcher =\n MediaInternals::GetInstance()->GetMediaCaptureDevicesDispatcher();\n switch (request_.request_type) {\n case content::MEDIA_OPEN_DEVICE: {\n const content::MediaStreamDevice* device = NULL;\n // For open device request pick the desired device or fall back to the\n // first available of the given type.\n if (request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE) {\n device = dispatcher->\n GetRequestedAudioDevice(request_.requested_audio_device_id);\n // TODO(wjia): Confirm this is the intended behavior.\n if (!device) {\n device = dispatcher->GetFirstAvailableAudioDevice();\n }\n } else if (request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE) {\n // Pepper API opens only one device at a time.\n device = dispatcher->GetRequestedVideoDevice(request_.requested_video_device_id);\n // TODO(wjia): Confirm this is the intended behavior.\n if (!device) {\n device = dispatcher->GetFirstAvailableVideoDevice();\n }\n }\n if (device)\n devices.push_back(*device);\n break;\n } case content::MEDIA_GENERATE_STREAM: {\n bool needs_audio_device = has_audio_;\n bool needs_video_device = has_video_;\n\n // Get the exact audio or video device if an id is specified.\n if (!request_.requested_audio_device_id.empty()) {\n const content::MediaStreamDevice* audio_device =\n dispatcher->GetRequestedAudioDevice(request_.requested_audio_device_id);\n if (audio_device) {\n devices.push_back(*audio_device);\n needs_audio_device = false;\n }\n }\n if (!request_.requested_video_device_id.empty()) {\n const content::MediaStreamDevice* video_device =\n dispatcher->GetRequestedVideoDevice(request_.requested_video_device_id);\n if (video_device) {\n devices.push_back(*video_device);\n needs_video_device = false;\n }\n }\n\n // If either or both audio and video devices were requested but not\n // specified by id, get the default devices.\n if (needs_audio_device || needs_video_device) {\n media::GetDefaultDevicesForProfile(\n needs_audio_device,\n needs_video_device,\n &devices);\n }\n break;\n } case content::MEDIA_DEVICE_ACCESS:\n // Get the default devices for the request.\n media::GetDefaultDevicesForProfile(\n has_audio_,\n has_video_,\n &devices);\n break;\n case content::MEDIA_ENUMERATE_DEVICES:\n // Do nothing.\n NOTREACHED();\n break;\n }\n\n callback_.Run(devices,\n devices.empty() ?\n content::MEDIA_DEVICE_NO_HARDWARE : content::MEDIA_DEVICE_OK,\n scoped_ptr());\n}\n\nvoid MediaStreamDevicesController::Deny(bool update_content_setting) {\n callback_.Run(content::MediaStreamDevices(), content::MEDIA_DEVICE_NO_HARDWARE, scoped_ptr());\n}\n\nbool MediaStreamDevicesController::IsAudioDeviceBlockedByPolicy() const {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n return false;\n}\n\nbool MediaStreamDevicesController::IsVideoDeviceBlockedByPolicy() const {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n return false;\n}\n\nbool MediaStreamDevicesController::IsRequestAllowedByDefault() const {\n return true;\n}\n\nbool MediaStreamDevicesController::IsRequestBlockedByDefault() const {\n return false;\n}\n\nbool MediaStreamDevicesController::IsDefaultMediaAccessBlocked() const {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n return false;\n}\n\nvoid MediaStreamDevicesController::HandleTapMediaRequest() {\n content::MediaStreamDevices devices;\n\n if (request_.audio_type == content::MEDIA_TAB_AUDIO_CAPTURE) {\n devices.push_back(content::MediaStreamDevice(\n content::MEDIA_TAB_VIDEO_CAPTURE, \"\", \"\"));\n }\n if (request_.video_type == content::MEDIA_TAB_VIDEO_CAPTURE) {\n devices.push_back(content::MediaStreamDevice(\n content::MEDIA_TAB_AUDIO_CAPTURE, \"\", \"\"));\n }\n if (request_.video_type == content::MEDIA_DESKTOP_VIDEO_CAPTURE) {\n const bool screen_capture_enabled =\n CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableUserMediaScreenCapturing);\n\n if (screen_capture_enabled) {\n content::DesktopMediaID media_id;\n // If the device id wasn't specified then this is a screen capture request\n // (i.e. chooseDesktopMedia() API wasn't used to generate device id).\n if (request_.requested_video_device_id.empty()) {\n media_id =\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN,\n webrtc::kFullDesktopScreenId);\n } else {\n media_id =\n content::DesktopMediaID::Parse(request_.requested_video_device_id);\n }\n\n devices.push_back(content::MediaStreamDevice(\n content::MEDIA_DESKTOP_VIDEO_CAPTURE, media_id.ToString(), \"Screen\"));\n }\n }\n\n callback_.Run(devices,\n devices.empty() ?\n content::MEDIA_DEVICE_NO_HARDWARE : content::MEDIA_DEVICE_OK,\n scoped_ptr());\n}\n\nbool MediaStreamDevicesController::IsSchemeSecure() const {\n return (request_.security_origin.SchemeIsSecure());\n}\n\nbool MediaStreamDevicesController::ShouldAlwaysAllowOrigin() const {\n return true;\n}\n\n", "file_path": "src/media/media_stream_devices_controller.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.07499975711107254, 0.002841878216713667, 0.00016524545208085328, 0.00016909025725908577, 0.013886791653931141]} {"hunk": {"id": 1, "code_window": ["namespace nw {\n", "\n", "namespace {\n", "\n", "bool g_pinning_renderer = true;\n", "bool g_in_webview_apply_attr = false;\n", "bool g_in_webview_apply_attr_allow_nw = false;\n", "} //namespace\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["bool g_mixed_context = false;\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 56}, "file": "// Copyright 2014 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef EXTENSIONS_SHELL_BROWSER_MEDIA_CAPTURE_UTIL_H_\n#define EXTENSIONS_SHELL_BROWSER_MEDIA_CAPTURE_UTIL_H_\n\n#include \"base/macros.h\"\n#include \"content/public/common/media_stream_request.h\"\n\nnamespace content {\nclass WebContents;\n}\n\nnamespace extensions {\n\nclass Extension;\n\nnamespace media_capture_util {\n\n// Grants access to audio and video capture devices.\n// * If the caller requests specific device ids, grants access to those.\n// * If the caller does not request specific ids, grants access to the first\n// available device.\n// Usually used as a helper for media capture ProcessMediaAccessRequest().\nvoid GrantMediaStreamRequest(content::WebContents* web_contents,\n const content::MediaStreamRequest& request,\n const content::MediaResponseCallback& callback,\n const Extension* extension);\n\n// Verifies that the extension has permission for |type|. If not, crash.\nvoid VerifyMediaAccessPermission(content::MediaStreamType type,\n const Extension* extension);\n\n} // namespace media_capture_util\n} // namespace extensions\n\n#endif // EXTENSIONS_SHELL_BROWSER_MEDIA_CAPTURE_UTIL_H_\n", "file_path": "src/browser/media_capture_util.h", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.033572111278772354, 0.008549200370907784, 0.00016959465574473143, 0.0002275483711855486, 0.014447052963078022]} {"hunk": {"id": 1, "code_window": ["namespace nw {\n", "\n", "namespace {\n", "\n", "bool g_pinning_renderer = true;\n", "bool g_in_webview_apply_attr = false;\n", "bool g_in_webview_apply_attr_allow_nw = false;\n", "} //namespace\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": ["bool g_mixed_context = false;\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 56}, "file": "var tap = require(\"tap\")\n , tar = require(\"../tar.js\")\n , fs = require(\"fs\")\n , path = require(\"path\")\n , file = path.resolve(__dirname, \"fixtures/c.tar\")\n , index = 0\n\n , expect =\n[ [ 'entry',\n { path: 'c.txt',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 513,\n mtime: new Date('Wed, 26 Oct 2011 01:10:58 GMT'),\n cksum: 5422,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n undefined ],\n [ 'entry',\n { path: 'cc.txt',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 513,\n mtime: new Date('Wed, 26 Oct 2011 01:11:02 GMT'),\n cksum: 5525,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n undefined ],\n [ 'entry',\n { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 100,\n mtime: new Date('Thu, 27 Oct 2011 03:43:23 GMT'),\n cksum: 18124,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n undefined ],\n [ 'entry',\n { path: 'Ω.txt',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 2,\n mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'),\n cksum: 5695,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n undefined ],\n [ 'extendedHeader',\n { path: 'PaxHeader/Ω.txt',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 120,\n mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'),\n cksum: 6702,\n type: 'x',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n { path: 'Ω.txt',\n ctime: 1319737909,\n atime: 1319739061,\n dev: 234881026,\n ino: 51693379,\n nlink: 1 } ],\n [ 'entry',\n { path: 'Ω.txt',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 2,\n mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'),\n cksum: 5695,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '',\n ctime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'),\n atime: new Date('Thu, 27 Oct 2011 18:11:01 GMT'),\n dev: 234881026,\n ino: 51693379,\n nlink: 1 },\n undefined ],\n [ 'extendedHeader',\n { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 353,\n mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n cksum: 14488,\n type: 'x',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n ctime: 1319686868,\n atime: 1319741254,\n 'LIBARCHIVE.creationtime': '1319686852',\n dev: 234881026,\n ino: 51681874,\n nlink: 1 } ],\n [ 'entry',\n { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 200,\n mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n cksum: 14570,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '',\n ctime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n atime: new Date('Thu, 27 Oct 2011 18:47:34 GMT'),\n 'LIBARCHIVE.creationtime': '1319686852',\n dev: 234881026,\n ino: 51681874,\n nlink: 1 },\n undefined ],\n [ 'longPath',\n { path: '././@LongLink',\n mode: 0,\n uid: 0,\n gid: 0,\n size: 201,\n mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'),\n cksum: 4976,\n type: 'L',\n linkpath: '',\n ustar: false },\n '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ],\n [ 'entry',\n { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n mode: 420,\n uid: 1000,\n gid: 1000,\n size: 201,\n mtime: new Date('Thu, 27 Oct 2011 22:21:50 GMT'),\n cksum: 14086,\n type: '0',\n linkpath: '',\n ustar: false },\n undefined ],\n [ 'longLinkpath',\n { path: '././@LongLink',\n mode: 0,\n uid: 0,\n gid: 0,\n size: 201,\n mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'),\n cksum: 4975,\n type: 'K',\n linkpath: '',\n ustar: false },\n '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ],\n [ 'longPath',\n { path: '././@LongLink',\n mode: 0,\n uid: 0,\n gid: 0,\n size: 201,\n mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'),\n cksum: 4976,\n type: 'L',\n linkpath: '',\n ustar: false },\n '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL' ],\n [ 'entry',\n { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL',\n mode: 511,\n uid: 1000,\n gid: 1000,\n size: 0,\n mtime: new Date('Fri, 28 Oct 2011 23:05:17 GMT'),\n cksum: 21603,\n type: '2',\n linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n ustar: false },\n undefined ],\n [ 'extendedHeader',\n { path: 'PaxHeader/200-hard',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 143,\n mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n cksum: 6533,\n type: 'x',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n { ctime: 1320617144,\n atime: 1320617232,\n 'LIBARCHIVE.creationtime': '1319686852',\n dev: 234881026,\n ino: 51681874,\n nlink: 2 } ],\n [ 'entry',\n { path: '200-hard',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 200,\n mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n cksum: 5526,\n type: '0',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '',\n ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'),\n atime: new Date('Sun, 06 Nov 2011 22:07:12 GMT'),\n 'LIBARCHIVE.creationtime': '1319686852',\n dev: 234881026,\n ino: 51681874,\n nlink: 2 },\n undefined ],\n [ 'extendedHeader',\n { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 353,\n mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n cksum: 14488,\n type: 'x',\n linkpath: '',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '' },\n { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n ctime: 1320617144,\n atime: 1320617406,\n 'LIBARCHIVE.creationtime': '1319686852',\n dev: 234881026,\n ino: 51681874,\n nlink: 2 } ],\n [ 'entry',\n { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',\n mode: 420,\n uid: 24561,\n gid: 20,\n size: 0,\n mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'),\n cksum: 15173,\n type: '1',\n linkpath: '200-hard',\n ustar: 'ustar\\0',\n ustarver: '00',\n uname: 'isaacs',\n gname: 'staff',\n devmaj: 0,\n devmin: 0,\n fill: '',\n ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'),\n atime: new Date('Sun, 06 Nov 2011 22:10:06 GMT'),\n 'LIBARCHIVE.creationtime': '1319686852',\n dev: 234881026,\n ino: 51681874,\n nlink: 2 },\n undefined ] ]\n\n\ntap.test(\"parser test\", function (t) {\n var parser = tar.Parse()\n\n parser.on(\"end\", function () {\n t.equal(index, expect.length, \"saw all expected events\")\n t.end()\n })\n\n fs.createReadStream(file)\n .pipe(parser)\n .on(\"*\", function (ev, entry) {\n var wanted = expect[index]\n if (!wanted) {\n return t.fail(\"Unexpected event: \" + ev)\n }\n var result = [ev, entry.props]\n entry.on(\"end\", function () {\n result.push(entry.fields || entry.body)\n\n t.equal(ev, wanted[0], index + \" event type\")\n t.equivalent(entry.props, wanted[1], wanted[1].path + \" entry properties\")\n if (wanted[2]) {\n t.equivalent(result[2], wanted[2], \"metadata values\")\n }\n index ++\n })\n })\n})\n", "file_path": "test/sanity/tar/node_modules/tar/test/parse.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00020215471158735454, 0.0001723964960547164, 0.00016740322462283075, 0.00017188121273647994, 5.461861292133108e-06]} {"hunk": {"id": 2, "code_window": ["\n", "void SetPinningRenderer(bool pin) {\n", " g_pinning_renderer = pin;\n", "}\n", "\n", "void SetInWebViewApplyAttr(bool flag, bool allow_nw) {\n", " g_in_webview_apply_attr = flag;\n", " g_in_webview_apply_attr_allow_nw = allow_nw;\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["bool MixedContext() {\n", " return g_mixed_context;\n", "}\n", "\n", "void SetMixedContext(bool mixed) {\n", " g_mixed_context = mixed;\n", "}\n", "\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 194}, "file": "#define INSIDE_BLINK 1\n#include \"third_party/blink/public/platform/web_rect.h\"\n#undef INSIDE_BLINK\n\n#include \"nw_extensions_renderer_hooks.h\"\n#include \"content/public/common/content_features.h\"\n// nw\n#include \"content/nw/src/nw_version.h\"\n\n// base\n#include \"base/command_line.h\"\n#include \"base/files/file_util.h\"\n#include \"base/json/json_writer.h\"\n#include \"base/logging.h\"\n#include \"base/i18n/icu_util.h\"\n#include \"base/strings/utf_string_conversions.h\"\n#include \"base/threading/thread.h\"\n#include \"base/values.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n\n// content\n#include \"content/public/renderer/v8_value_converter.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/renderer/render_view.h\"\n#include \"content/renderer/render_view_impl.h\"\n\n#include \"content/common/frame.mojom.h\"\n\n// extensions\n#include \"extensions/renderer/dispatcher.h\"\n#include \"extensions/renderer/renderer_extension_registry.h\"\n#include \"extensions/renderer/script_context.h\"\n#include \"extensions/common/extension.h\"\n#include \"extensions/common/manifest.h\"\n#include \"extensions/common/manifest_constants.h\"\n#include \"extensions/renderer/native_extension_bindings_system.h\"\n#include \"extensions/common/extension_features.h\"\n\n#include \"extensions/grit/extensions_renderer_resources.h\"\n\n// third_party/blink/\n#include \"third_party/blink/public/web/web_document.h\"\n#include \"third_party/blink/public/web/web_local_frame.h\"\n#include \"third_party/blink/public/web/web_script_source.h\"\n#include \"third_party/blink/public/web/web_view.h\"\n#include \"third_party/blink/renderer/platform/bindings/script_forbidden_scope.h\"\n#include \"third_party/blink/public/web/blink.h\"\n#include \"third_party/blink/renderer/platform/bindings/dom_wrapper_world.h\"\n#include \"third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h\"\n#include \"third_party/blink/renderer/platform/wtf/casting.h\"\n#include \"third_party/blink/renderer/core/frame/web_local_frame_impl.h\"\n\n#include \"third_party/node-nw/src/node_webkit.h\"\n\n// gen\n#include \"nw/id/commit.h\"\n\n// NEED TO STAY SYNC WITH NODE\n#ifndef NODE_CONTEXT_EMBEDDER_DATA_INDEX\n#define NODE_CONTEXT_EMBEDDER_DATA_INDEX 32\n#endif\n\n#if defined(OS_WIN)\n#define _USE_MATH_DEFINES\n#include \n#endif\n\nusing content::RenderViewImpl;\n\nusing extensions::ScriptContext;\nusing extensions::Extension;\nusing extensions::RendererExtensionRegistry;\nusing extensions::Dispatcher;\n\nusing blink::WebScriptSource;\n\nnamespace manifest_keys = extensions::manifest_keys;\n\n#if defined(COMPONENT_BUILD) && defined(WIN32)\n#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn;\n#define BLINK_HOOK_MAP(type, sym, fn) BLINK_EXPORT type fn;\n#define PLATFORM_HOOK_MAP(type, sym, fn) PLATFORM_EXPORT type fn;\n#else\n#define NW_HOOK_MAP(type, sym, fn) extern type fn;\n#define BLINK_HOOK_MAP(type, sym, fn) extern type fn;\n#define PLATFORM_HOOK_MAP(type, sym, fn) extern type fn;\n#endif\n#include \"content/nw/src/common/node_hooks.h\"\n#undef NW_HOOK_MAP\n\nnamespace nw {\n\nnamespace {\nstd::string g_extension_id, g_extension_root;\nextensions::Dispatcher* g_dispatcher = NULL;\nbool g_skip_render_widget_hidden = false;\n\nstatic inline v8::Local v8_str(const char* x) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n return v8::String::NewFromUtf8(isolate, x, v8::NewStringType::kNormal).ToLocalChecked();\n}\n\nv8::Handle CallNWTickCallback(void* env, const v8::Handle ret) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n g_call_tick_callback_fn(env);\n return Undefined(v8::Isolate::GetCurrent());\n}\n\nv8::Handle CreateNW(ScriptContext* context,\n v8::Handle node_global,\n v8::Handle node_context) {\n v8::Handle nw_string(\n v8::String::NewFromUtf8(context->isolate(), \"nw\", v8::NewStringType::kNormal).ToLocalChecked());\n v8::Handle global(context->v8_context()->Global());\n v8::Handle nw(global->Get(context->v8_context(), nw_string).ToLocalChecked());\n if (nw->IsUndefined()) {\n nw = v8::Object::New(context->isolate());;\n //node_context->Enter();\n ignore_result(global->Set(context->v8_context(), nw_string, nw));\n //node_context->Exit();\n }\n return nw;\n}\n\n// Returns |value| cast to an object if possible, else an empty handle.\nv8::Handle AsObjectOrEmpty(v8::Handle value) {\n return value->IsObject() ? value.As() : v8::Handle();\n}\n\n}\n\nconst std::string& get_main_extension_id() {\n return g_extension_id;\n}\n\nconst char* GetChromiumVersion();\n\n// renderer\n\nvoid WebWorkerNewThreadHook(const char* name, bool* is_node) {\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n if (!command_line.HasSwitch(switches::kEnableNodeWorker))\n return;\n if (!strcmp(name, \"DedicatedWorker thread\") || !strcmp(name, \"SharedWorker thread\"))\n *is_node = true;\n}\n\nvoid WebWorkerStartThreadHook(blink::Frame* frame, const char* path, std::string* script, bool* isNodeJS) {\n std::string root_path;\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n if (!command_line.HasSwitch(switches::kEnableNodeWorker)) {\n *isNodeJS = false;\n return;\n }\n if (frame) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n blink::WebFrame* web_frame = blink::WebFrame::FromFrame(frame);\n blink::WebLocalFrame* local_frame = web_frame->ToWebLocalFrame();\n v8::Local v8_context = local_frame->MainWorldScriptContext();\n ScriptContext* script_context =\n g_dispatcher->script_context_set().GetByV8Context(v8_context);\n if (!script_context || !script_context->extension())\n return;\n root_path = g_extension_root;\n } else {\n root_path = *script;\n }\n std::string url_path(path);\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n *script = \"global.__filename = '\" + url_path + \"';\";\n *script += \"global.__dirname = '\" + root_path + \"';\";\n *script += \"{ let root = '\" + root_path + \"';\"\n \" let p = '\" + url_path + \"';\"\n \"process.mainModule.filename = root + p;\"\n \"process.mainModule.paths = global.require('module')._nodeModulePaths(process.cwd());\"\n \"process.mainModule.loaded = true;\"\n \"}\";\n}\n\nvoid ContextCreationHook(blink::WebLocalFrame* frame, ScriptContext* context) {\n v8::Isolate* isolate = context->isolate();\n\n const Extension* extension = context->extension();\n std::string extension_root;\n\n if (g_extension_id.empty() && extension)\n g_extension_id = extension->id();\n\n bool nodejs_enabled = true;\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n bool worker_support = command_line.HasSwitch(switches::kEnableNodeWorker);\n\n if (extension) {\n extension->manifest()->GetBoolean(manifest_keys::kNWJSEnableNode, &nodejs_enabled);\n extension_root = extension->path().AsUTF8Unsafe();\n } else {\n extension_root = command_line.GetSwitchValuePath(switches::kNWAppPath).AsUTF8Unsafe();\n }\n g_extension_root = extension_root;\n\n if (!nodejs_enabled)\n return;\n\n blink::set_web_worker_hooks((void*)WebWorkerStartThreadHook);\n g_web_worker_thread_new_fn = (VoidPtr2Fn)WebWorkerNewThreadHook;\n if (!g_is_node_initialized_fn())\n g_setup_nwnode_fn(0, nullptr, worker_support);\n\n bool mixed_context = false;\n bool node_init_run = false;\n bool nwjs_guest_nw = command_line.HasSwitch(\"nwjs-guest-nw\");\n\n if (extension)\n extension->manifest()->GetBoolean(manifest_keys::kNWJSMixedContext, &mixed_context);\n // handle navigation in webview #5622\n if (nwjs_guest_nw)\n mixed_context = true;\n v8::Local node_context;\n g_get_node_context_fn(&node_context);\n if (node_context.IsEmpty() || mixed_context) {\n node_init_run = true;\n {\n int argc = 1;\n char argv0[] = \"node\";\n char* argv[3];\n argv[0] = argv0;\n argv[1] = argv[2] = nullptr;\n std::string main_fn;\n\n if (extension && extension->manifest()->GetString(\"node-main\", &main_fn)) {\n argc = 2;\n argv[1] = strdup(main_fn.c_str());\n }\n\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n v8::MicrotasksScope microtasks(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);\n\n g_set_nw_tick_callback_fn(&CallNWTickCallback);\n v8::Local dom_context;\n bool is_background_page = extension &&\n (context->url().host() == extension->id()) &&\n (context->url().path() == \"/_generated_background_page.html\");\n if (node_context.IsEmpty() && !mixed_context && !is_background_page) {\n dom_context = v8::Context::New(isolate);\n void* data = context->v8_context()->GetAlignedPointerFromEmbedderData(2); //v8ContextPerContextDataIndex\n dom_context->SetAlignedPointerInEmbedderData(2, data);\n dom_context->SetAlignedPointerInEmbedderData(50, (void*)0x08110800);\n } else\n dom_context = context->v8_context();\n if (!mixed_context)\n g_set_node_context_fn(isolate, &dom_context);\n dom_context->SetSecurityToken(v8::String::NewFromUtf8(isolate, \"nw-token\", v8::NewStringType::kNormal).ToLocalChecked());\n dom_context->Enter();\n\n g_start_nw_instance_fn(argc, argv, dom_context, (void*)base::i18n::GetRawIcuMemory());\n {\n#if defined(NWJS_SDK)\n std::string flavor = \"sdk\";\n#else\n std::string flavor = \"normal\";\n#endif\n v8::Local script =\n v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (std::string(\"process.versions['nw'] = '\" NW_VERSION_STRING \"';\") +\n \"process.versions['node-webkit'] = '\" NW_VERSION_STRING \"';\"\n \"process.versions['nw-commit-id'] = '\" NW_COMMIT_HASH \"';\"\n \"process.versions['nw-flavor'] = '\" + flavor + \"';\"\n \"process.versions['chromium'] = '\" + GetChromiumVersion() + \"';\").c_str(), v8::NewStringType::kNormal\n ).ToLocalChecked()).ToLocalChecked();\n ignore_result(script->Run(dom_context));\n }\n\n if (extension && extension->manifest()->GetString(manifest_keys::kNWJSInternalMainFilename, &main_fn)) {\n v8::Local script = v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (\"global.__filename = '\" + main_fn + \"';\").c_str(), v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();\n ignore_result(script->Run(dom_context));\n }\n {\n std::string root_path = extension_root;\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n v8::Local script = v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (\"global.__dirname = '\" + root_path + \"';\").c_str(), v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();\n ignore_result(script->Run(dom_context));\n }\n bool content_verification = false;\n if (extension && extension->manifest()->GetBoolean(manifest_keys::kNWJSContentVerifyFlag,\n &content_verification) && content_verification) {\n v8::Local script =\n v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (std::string(\"global.__nwjs_cv = true;\") +\n \"global.__nwjs_ext_id = '\" + extension->id() + \"';\").c_str(), v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();\n\n ignore_result(script->Run(dom_context));\n }\n\n dom_context->Exit();\n }\n }\n\n v8::Local node_context2;\n if (mixed_context)\n node_context2 = context->v8_context();\n else\n g_get_node_context_fn(&node_context2);\n v8::Local g_context =\n v8::Local::New(isolate, node_context2);\n v8::Local node_global = g_context->Global();\n\n if (!mixed_context) {\n context->v8_context()->SetAlignedPointerInEmbedderData(NODE_CONTEXT_EMBEDDER_DATA_INDEX, g_get_node_env_fn());\n context->v8_context()->SetSecurityToken(g_context->GetSecurityToken());\n }\n v8::Handle nw = AsObjectOrEmpty(CreateNW(context, node_global, g_context));\n\n v8::Local symbols = v8::Array::New(isolate, 4);\n ignore_result(symbols->Set(context->v8_context(), 0, v8::String::NewFromUtf8(isolate, \"global\", v8::NewStringType::kNormal).ToLocalChecked()));\n ignore_result(symbols->Set(context->v8_context(), 1, v8::String::NewFromUtf8(isolate, \"process\", v8::NewStringType::kNormal).ToLocalChecked()));\n ignore_result(symbols->Set(context->v8_context(), 2, v8::String::NewFromUtf8(isolate, \"Buffer\", v8::NewStringType::kNormal).ToLocalChecked()));\n ignore_result(symbols->Set(context->v8_context(), 3, v8::String::NewFromUtf8(isolate, \"require\", v8::NewStringType::kNormal).ToLocalChecked()));\n\n g_context->Enter();\n for (unsigned i = 0; i < symbols->Length(); ++i) {\n v8::Local key = symbols->Get(context->v8_context(), i).ToLocalChecked();\n v8::Local val = node_global->Get(context->v8_context(), key).ToLocalChecked();\n ignore_result(nw->Set(context->v8_context(), key, val));\n if (nwjs_guest_nw && !node_init_run) {\n //running in nwjs webview and node was initialized in\n //chromedriver automation extension\n ignore_result(context->v8_context()->Global()->Set(context->v8_context(), key, val));\n }\n }\n g_context->Exit();\n\n std::string set_nw_script = \"'use strict';\";\n {\n v8::MicrotasksScope microtasks(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);\n v8::Context::Scope cscope(context->v8_context());\n // Make node's relative modules work\n std::string root_path = extension_root;\n GURL frame_url = ScriptContext::GetDocumentLoaderURLForFrame(frame);\n std::string url_path = frame_url.path();\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n v8::ScriptOrigin origin(v8::String::NewFromUtf8(isolate, \"process_main\", v8::NewStringType::kNormal).ToLocalChecked());\n v8::Local script = v8::Script::Compile(context->v8_context(), v8::String::NewFromUtf8(isolate, (\n set_nw_script +\n // Make node's relative modules work\n \"if (typeof nw.process != 'undefined' && \"\n \"(!nw.process.mainModule.filename || nw.process.mainModule.filename === 'blank' ||\"\n \"nw.process.mainModule.filename.indexOf('_generated_background_page.html') >= 0)) {\"\n \" let root = '\" + root_path + \"';\"\n \" let p = '\" + url_path + \"';\"\n \"nw.process.mainModule.filename = root + p;\"\n \"nw.process.mainModule.paths = nw.global.require('module')._nodeModulePaths(nw.process.cwd());\"\n \"nw.process.mainModule.loaded = true;\"\n \"}\").c_str(), v8::NewStringType::kNormal).ToLocalChecked(), &origin).ToLocalChecked();\n CHECK(*script);\n ignore_result(script->Run(context->v8_context()));\n }\n}\n\nbase::FilePath GetRootPathRenderer() {\n base::FilePath ret;\n const Extension* extension = RendererExtensionRegistry::Get()->GetByID(g_extension_id);\n if (!extension)\n return ret;\n if (!(extension->is_extension() || extension->is_platform_app()))\n return ret;\n return extension->path();\n}\n\nvoid TryInjectStartScript(blink::WebLocalFrame* frame, const Extension* extension, bool start) {\n RenderViewImpl* rv = content::RenderFrameImpl::FromWebFrame(frame)->render_view();\n if (!rv)\n return;\n\n std::string js_fn = start ? rv->renderer_preferences().nw_inject_js_doc_start :\n rv->renderer_preferences().nw_inject_js_doc_end;\n if (js_fn.empty())\n return;\n base::FilePath fpath = base::FilePath::FromUTF8Unsafe(js_fn);\n if (!fpath.IsAbsolute()) {\n const Extension* extension = nullptr;\n if (!extension) {\n extension = RendererExtensionRegistry::Get()->GetByID(g_extension_id);\n if (!extension)\n return;\n }\n if (!(extension->is_extension() || extension->is_platform_app()))\n return;\n base::FilePath root(extension->path());\n fpath = root.AppendASCII(js_fn);\n }\n v8::Local v8_context = frame->MainWorldScriptContext();\n std::string content;\n if (!base::ReadFileToString(fpath, &content)) {\n //LOG(WARNING) << \"Failed to load js script file: \" << js_file.value();\n return;\n }\n if (!v8_context.IsEmpty()) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n v8::Context::Scope cscope(v8_context);\n // v8::Handle result;\n frame->ExecuteScriptAndReturnValue(WebScriptSource(blink::WebString::FromUTF8(content)));\n }\n}\n\nvoid DocumentFinishHook(blink::WebLocalFrame* frame,\n const extensions::Extension* extension,\n const GURL& effective_document_url) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope hscope(isolate);\n\n TryInjectStartScript(frame, extension, false);\n}\n\nvoid DocumentHook2(bool start, content::RenderFrame* frame, Dispatcher* dispatcher) {\n // ignore the first invocation of this hook for iframe\n // or we'll trigger creating a context with invalid type\n // there will follow another one with valid url\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n blink::WebLocalFrame* web_frame = frame->GetWebFrame();\n GURL frame_url = ScriptContext::GetDocumentLoaderURLForFrame(web_frame);\n if (web_frame->Parent() && (!frame_url.is_valid() || frame_url.is_empty()))\n return;\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n blink::WebFrame* f = frame->GetRenderView()->GetWebView()->MainFrame();\n if (!f->IsWebLocalFrame())\n return;\n blink::WebLocalFrame* local_frame = f->ToWebLocalFrame();\n v8::Local v8_context = local_frame->MainWorldScriptContext();\n ScriptContext* script_context =\n dispatcher->script_context_set().GetByV8Context(v8_context);\n if (start)\n TryInjectStartScript(web_frame, script_context ? script_context->extension() : nullptr, true);\n if (!script_context)\n return;\n std::vector > arguments;\n v8::Local window =\n web_frame->MainWorldScriptContext()->Global();\n arguments.push_back(v8::Boolean::New(isolate, start));\n arguments.push_back(window);\n if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {\n content::RenderFrame* main_frame = frame->GetRenderView()->GetMainRenderFrame();\n arguments.push_back(v8::Integer::New(isolate, main_frame->GetRoutingID()));\n\n std::set contexts(dispatcher->script_context_set().contexts());\n std::set::iterator it = contexts.begin();\n while (it != contexts.end()) {\n ScriptContext* c = *it;\n if (extensions::binding::IsContextValid(c->v8_context())) {\n extensions::ModuleSystem::NativesEnabledScope natives_enabled(c->module_system());\n c->module_system()->CallModuleMethodSafe(\"nw.Window\", \"onDocumentStartEnd\", &arguments);\n it++;\n }\n }\n } else {\n // need require in m61 since the following CallModuleMethodSafe\n // won't load it anymore: fedbe848f3024dd690f93545a337a2a6fb2aa81f\n extensions::ModuleSystem::NativesEnabledScope natives_enabled(script_context->module_system());\n extensions::NativeExtensionBindingsSystem* binding_sys = (extensions::NativeExtensionBindingsSystem*)dispatcher->bindings_system();\n v8_context->Enter();\n v8::Local nw_win = binding_sys->GetAPIObjectForTesting(script_context, \"nw.Window\");\n if (nw_win.IsEmpty())\n binding_sys->GetAPIObjectForTesting(script_context, \"nw.Window\", true);\n v8_context->Exit();\n script_context->module_system()->CallModuleMethodSafe(\"nw.Window\", \"onDocumentStartEnd\", &arguments);\n }\n}\n\nvoid DocumentElementHook(blink::WebLocalFrame* frame,\n const extensions::Extension* extension,\n const GURL& effective_document_url) {\n // ignore the first invocation of this hook for iframe\n // or we'll trigger creating a context with invalid type\n // there will follow another one with valid url\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n GURL frame_url = ScriptContext::GetDocumentLoaderURLForFrame(frame);\n if (frame->Parent() && (!frame_url.is_valid() || frame_url.is_empty()))\n return;\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope hscope(isolate);\n frame->GetDocument().GetSecurityOrigin().grantUniversalAccess();\n frame->setNodeJS(true);\n content::RenderFrameImpl* render_frame = content::RenderFrameImpl::FromWebFrame(frame);\n auto* frame_host = render_frame->GetFrameHost();\n frame_host->SetNodeJS(true);\n std::string path = effective_document_url.path();\n v8::Local v8_context = frame->MainWorldScriptContext();\n std::string root_path = g_extension_root;\n if (!v8_context.IsEmpty()) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n v8::Context::Scope cscope(v8_context);\n // Make node's relative modules work\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n\n v8::ScriptOrigin origin(v8::String::NewFromUtf8(isolate, \"process_main2\", v8::NewStringType::kNormal).ToLocalChecked());\n v8::Local script2 = v8::Script::Compile(v8_context, v8::String::NewFromUtf8(isolate, (\n \"'use strict';\"\n \"if (typeof nw != 'undefined' && typeof __filename == 'undefined') {\"\n \" let root = '\" + root_path + \"';\"\n \" let path = '\" + path + \"';\"\n \"nw.__filename = root + path;\"\n \"nw.__dirname = root;\"\n \"}\").c_str(), v8::NewStringType::kNormal).ToLocalChecked(), &origin).ToLocalChecked();\n CHECK(*script2);\n ignore_result(script2->Run(v8_context));\n }\n RenderViewImpl* rv = content::RenderFrameImpl::FromWebFrame(frame)->render_view();\n if (!rv)\n return;\n\n ui::ResourceBundle* resource_bundle = &ui::ResourceBundle::GetSharedInstance();\n base::StringPiece resource =\n resource_bundle->GetRawDataResource(IDR_NW_PRE13_SHIM_JS);\n if (resource.empty())\n return;\n if (!v8_context.IsEmpty()) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n v8::Context::Scope cscope(v8_context);\n frame->ExecuteScriptAndReturnValue(WebScriptSource(blink::WebString::FromUTF8(resource.as_string())));\n }\n}\n\nvoid willHandleNavigationPolicy(content::RenderView* rv,\n blink::WebFrame* frame,\n const blink::WebURLRequest& request,\n blink::WebNavigationPolicy* policy,\n blink::WebString* manifest,\n bool new_win) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n blink::WebFrame* f = rv->GetWebView()->MainFrame();\n if (!f->IsWebLocalFrame())\n return;\n blink::WebLocalFrame* local_frame = f->ToWebLocalFrame();\n blink::LocalFrame* core_frame = blink::To(local_frame)->GetFrame();\n\n if (core_frame->ContextNotReady(blink::DOMWrapperWorld::MainWorld()))\n return;\n v8::Handle v8_context = local_frame->MainWorldScriptContext();\n ScriptContext* script_context =\n g_dispatcher->script_context_set().GetByV8Context(v8_context);\n v8::Context::Scope cscope (v8_context);\n v8::Handle element = v8::Null(isolate);\n v8::Handle policy_obj = v8::Object::New(isolate);\n\n#if 0\n blink::LocalFrame* core_frame = blink::toWebLocalFrameImpl(frame)->frame();\n if (core_frame->deprecatedLocalOwner()) {\n element = blink::toV8((blink::HTMLElement*)core_frame->deprecatedLocalOwner(),\n frame->mainWorldScriptContext()->Global(),\n frame->mainWorldScriptContext()->GetIsolate());\n }\n#endif\n std::vector > arguments;\n arguments.push_back(element);\n arguments.push_back(v8_str(request.Url().GetString().Utf8().c_str()));\n arguments.push_back(policy_obj);\n if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {\n content::RenderFrame* main_frame = rv->GetMainRenderFrame();\n arguments.push_back(v8::Integer::New(isolate, main_frame->GetRoutingID()));\n\n std::set contexts(g_dispatcher->script_context_set().contexts());\n std::set::iterator it = contexts.begin();\n while (it != contexts.end()) {\n ScriptContext* c = *it;\n extensions::ModuleSystem::NativesEnabledScope natives_enabled(c->module_system());\n if (new_win) {\n c->module_system()->CallModuleMethodSafe(\"nw.Window\", \"onNewWinPolicy\", &arguments);\n } else {\n const char* req_context = nullptr;\n switch (request.GetRequestContext()) {\n case blink::mojom::RequestContextType::HYPERLINK:\n req_context = \"hyperlink\";\n break;\n case blink::mojom::RequestContextType::FRAME:\n req_context = \"form\";\n break;\n case blink::mojom::RequestContextType::LOCATION:\n req_context = \"location\";\n break;\n default:\n break;\n }\n if (req_context) {\n arguments.push_back(v8_str(req_context));\n c->module_system()->CallModuleMethodSafe(\"nw.Window\",\n \"onNavigation\", &arguments);\n }\n }\n it++;\n }\n } else {\n if (new_win) {\n script_context->module_system()->CallModuleMethodSafe(\"nw.Window\",\n \"onNewWinPolicy\", &arguments);\n } else {\n const char* req_context = nullptr;\n switch (request.GetRequestContext()) {\n case blink::mojom::RequestContextType::HYPERLINK:\n req_context = \"hyperlink\";\n break;\n case blink::mojom::RequestContextType::FRAME:\n req_context = \"form\";\n break;\n case blink::mojom::RequestContextType::LOCATION:\n req_context = \"location\";\n break;\n default:\n break;\n }\n if (req_context) {\n arguments.push_back(v8_str(req_context));\n script_context->module_system()->CallModuleMethodSafe(\"nw.Window\",\n \"onNavigation\", &arguments);\n }\n }\n }\n\n std::unique_ptr converter(content::V8ValueConverter::Create());\n v8::Local manifest_v8 = policy_obj->Get(v8_context, v8_str(\"manifest\")).ToLocalChecked();\n std::unique_ptr manifest_val(converter->FromV8Value(manifest_v8, v8_context));\n std::string manifest_str;\n if (manifest_val.get() && base::JSONWriter::Write(*manifest_val, &manifest_str)) {\n *manifest = blink::WebString::FromUTF8(manifest_str.c_str());\n }\n\n v8::Local val = policy_obj->Get(v8_context, v8_str(\"val\")).ToLocalChecked();\n if (!val->IsString())\n return;\n v8::String::Utf8Value policy_str(isolate, val);\n if (!strcmp(*policy_str, \"ignore\"))\n *policy = blink::kWebNavigationPolicyIgnore;\n else if (!strcmp(*policy_str, \"download\"))\n *policy = blink::kWebNavigationPolicyDownload;\n else if (!strcmp(*policy_str, \"current\"))\n *policy = blink::kWebNavigationPolicyCurrentTab;\n else if (!strcmp(*policy_str, \"new-window\"))\n *policy = blink::kWebNavigationPolicyNewWindow;\n else if (!strcmp(*policy_str, \"new-popup\"))\n *policy = blink::kWebNavigationPolicyNewPopup;\n}\n\ntypedef bool (*RenderWidgetWasHiddenHookFn)(content::RenderWidget*);\n#if defined(COMPONENT_BUILD)\nCONTENT_EXPORT RenderWidgetWasHiddenHookFn gRenderWidgetWasHiddenHook;\n#else\nextern RenderWidgetWasHiddenHookFn gRenderWidgetWasHiddenHook;\n#endif\n\nbool RenderWidgetWasHiddenHook(content::RenderWidget* rw) {\n return g_skip_render_widget_hidden;\n}\n\nvoid ExtensionDispatcherCreated(extensions::Dispatcher* dispatcher) {\n g_dispatcher = dispatcher;\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n if (command_line.HasSwitch(switches::kDisableRAFThrottling))\n g_skip_render_widget_hidden = true;\n nw::gRenderWidgetWasHiddenHook = RenderWidgetWasHiddenHook;\n}\n\nvoid OnRenderProcessShutdownHook(extensions::ScriptContext* context) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n void* env = g_get_current_env_fn(context->v8_context());\n if (g_is_node_initialized_fn()) {\n g_emit_exit_fn(env);\n g_run_at_exit_fn(env);\n }\n}\n\n} // namespace nw\n", "file_path": "src/renderer/nw_extensions_renderer_hooks.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.07011283189058304, 0.0019438572926446795, 0.00016710357158444822, 0.0001743860193528235, 0.008878820575773716]} {"hunk": {"id": 2, "code_window": ["\n", "void SetPinningRenderer(bool pin) {\n", " g_pinning_renderer = pin;\n", "}\n", "\n", "void SetInWebViewApplyAttr(bool flag, bool allow_nw) {\n", " g_in_webview_apply_attr = flag;\n", " g_in_webview_apply_attr_allow_nw = allow_nw;\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["bool MixedContext() {\n", " return g_mixed_context;\n", "}\n", "\n", "void SetMixedContext(bool mixed) {\n", " g_mixed_context = mixed;\n", "}\n", "\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 194}, "file": "var colors = require('../colors');\n\nmodule['exports'] = (function () {\n var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];\n return function(letter, i, exploded) {\n return letter === \" \" ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter);\n };\n})();", "file_path": "test/node_modules/colors/lib/maps/random.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017529221076983958, 0.00017529221076983958, 0.00017529221076983958, 0.00017529221076983958, 0.0]} {"hunk": {"id": 2, "code_window": ["\n", "void SetPinningRenderer(bool pin) {\n", " g_pinning_renderer = pin;\n", "}\n", "\n", "void SetInWebViewApplyAttr(bool flag, bool allow_nw) {\n", " g_in_webview_apply_attr = flag;\n", " g_in_webview_apply_attr_allow_nw = allow_nw;\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["bool MixedContext() {\n", " return g_mixed_context;\n", "}\n", "\n", "void SetMixedContext(bool mixed) {\n", " g_mixed_context = mixed;\n", "}\n", "\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 194}, "file": "#!/usr/bin/env python\n\nimport SimpleHTTPServer\nimport SocketServer\nimport sys\n\nPORT = int(sys.argv[1])\n\nHandler = SimpleHTTPServer.SimpleHTTPRequestHandler\n\nhttpd = SocketServer.TCPServer((\"\", PORT), Handler)\n\nprint \"serving at port\", PORT\nhttpd.serve_forever()\n\n", "file_path": "test/sanity/http-server.py", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00016994464385788888, 0.00016706378664821386, 0.00016418294399045408, 0.00016706378664821386, 2.8808501610910753e-06]} {"hunk": {"id": 2, "code_window": ["\n", "void SetPinningRenderer(bool pin) {\n", " g_pinning_renderer = pin;\n", "}\n", "\n", "void SetInWebViewApplyAttr(bool flag, bool allow_nw) {\n", " g_in_webview_apply_attr = flag;\n", " g_in_webview_apply_attr_allow_nw = allow_nw;\n", "}\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["bool MixedContext() {\n", " return g_mixed_context;\n", "}\n", "\n", "void SetMixedContext(bool mixed) {\n", " g_mixed_context = mixed;\n", "}\n", "\n"], "file_path": "src/browser/nw_content_browser_hooks.cc", "type": "add", "edit_start_line_idx": 194}, "file": "import time\nimport os\nimport platform\nimport sys\n\nif platform.system() == 'Linux':\n print 'Skiping win-move because of upstream issue. See nwjs/nw.js#4217.'\n sys.exit(0)\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nchrome_options = Options()\nchrome_options.add_argument(\"nwapp=\" + os.path.dirname(os.path.abspath(__file__)))\n\ndriver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options)\ndriver.implicitly_wait(10)\ntry:\n print driver.current_url\n driver.find_element_by_id('moveto').click()\n result = driver.find_element_by_id('moveto-result').get_attribute('innerHTML')\n print result\n assert('success' in result)\n\n driver.find_element_by_id('moveby').click()\n result = driver.find_element_by_id('moveby-result').get_attribute('innerHTML')\n print result\n assert('success' in result)\nfinally:\n driver.quit()\n", "file_path": "test/sanity/win-move/test.py", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017469219164922833, 0.00017208620556630194, 0.00016922250506468117, 0.00017221507732756436, 2.250812030979432e-06]} {"hunk": {"id": 3, "code_window": ["// content/browser/renderer_host/render_process_host_impl.cc\n", "// content/browser/site_instance_impl.cc\n", "CONTENT_EXPORT bool PinningRenderer();\n", "\n", "#if defined(OS_MAC)\n", "// ref in chrome/browser/app_controller_mac.mm\n", "CONTENT_EXPORT bool ApplicationShouldHandleReopenHook(bool hasVisibleWindows);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT bool MixedContext();\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 50}, "file": "// Copyright 2015 The NW.js Authors. All rights reserved.\n// Use of this source code is governed by a MIT-style license that can be\n// found in the LICENSE file.\n\n// nw Window API\nnamespace nw.Window {\n callback CreateWindowCallback =\n void ([instanceOf=NWWindow] object createdWindow);\n callback EventCallback = void();\n callback GetAllWinCallback = void (object[] windows);\n\n callback CapturePageCallback = void (DOMString dataUrl);\n [noinline_doc] dictionary CapturePageOptions {\n [nodoc] DOMString? format;\n [nodoc] DOMString? datatype;\n [nodoc] long? quality;\n };\n [noinline_doc] dictionary CreateWindowOptions {\n [nodoc] DOMString? id;\n [nodoc] long? x;\n [nodoc] long? y;\n [nodoc] long? width;\n [nodoc] long? height;\n [nodoc] long? min_width;\n [nodoc] long? min_height;\n [nodoc] long? max_width;\n [nodoc] long? max_height;\n [nodoc] boolean? frame;\n [nodoc] boolean? resizable;\n [nodoc] boolean? fullscreen;\n [nodoc] boolean? show;\n [nodoc] boolean? always_on_top;\n [nodoc] boolean? visible_on_all_workspaces;\n [nodoc] boolean? transparent;\n [nodoc] boolean? kiosk;\n [nodoc] boolean? focus;\n [nodoc] boolean? new_instance;\n [nodoc] boolean? show_in_taskbar;\n [nodoc] DOMString? title;\n [nodoc] DOMString? position;\n [nodoc] DOMString? icon;\n [nodoc] DOMString? inject_js_start;\n [nodoc] DOMString? inject_js_end;\n };\n\n [noinline_doc] dictionary NWWindow {\n // show devtools for the current window\n static void showDevTools(optional any frm, optional EventCallback callback);\n static void capturePage(optional CapturePageCallback callback, optional CapturePageOptions options);\n static void show();\n static void hide();\n static void focus();\n static void blur();\n static void close(optional boolean force);\n static void minimize();\n static void maximize();\n static void unmaximize();\n static void restore();\n static void setPosition(DOMString pos);\n static void setMaximumSize(long width, long height);\n static void setMinimumSize(long width, long height);\n static void setResizable(boolean resizable);\n static void enterFullscreen();\n static void leaveFullscreen();\n static void toggleFullscreen();\n static void setVisibleOnAllWorkspaces(boolean all_visible);\n static bool canSetVisibleOnAllWorkspaces();\n static void on(DOMString event,\n EventCallback callback);\n static void once(DOMString event,\n EventCallback callback);\n static void removeListener(DOMString event,\n EventCallback callback);\n static void removeAllListeners(DOMString event);\n static void reload();\n static void reloadIgnoringCache();\n\n static void eval(object frame, DOMString script);\n static void evalNWBin(object frame, DOMString path);\n static void evalNWBinModule(object frame, DOMString path, DOMString module_path);\n static void print(optional object options);\n\n object appWindow;\n object cWindow;\n object window;\n object menu;\n long x;\n long y;\n long width;\n long height;\n double zoomLevel;\n DOMString title;\n long frameId;\n };\n interface Functions {\n // get the current window\n [nocompile] static NWWindow get(optional object domWindow);\n [nocompile] static void getAll(GetAllWinCallback callback);\n [nocompile] static void open(DOMString url,\n optional CreateWindowOptions options,\n optional CreateWindowCallback callback);\n\n };\n interface Events {\n [nocompile] static void onNewWinPolicy();\n [nocompile] static void onNavigation();\n [nocompile] static void LoadingStateChanged();\n [nocompile] static void onDocumentStart();\n [nocompile] static void onDocumentEnd();\n [nocompile] static void onZoom();\n [supportsFilters=true] static void onClose();\n };\n};\n", "file_path": "src/api/nw_window.idl", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00034238610533066094, 0.0001871545537142083, 0.00016796716954559088, 0.000170179147971794, 4.764956247527152e-05]} {"hunk": {"id": 3, "code_window": ["// content/browser/renderer_host/render_process_host_impl.cc\n", "// content/browser/site_instance_impl.cc\n", "CONTENT_EXPORT bool PinningRenderer();\n", "\n", "#if defined(OS_MAC)\n", "// ref in chrome/browser/app_controller_mac.mm\n", "CONTENT_EXPORT bool ApplicationShouldHandleReopenHook(bool hasVisibleWindows);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT bool MixedContext();\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 50}, "file": "{\n \"name\": \"issue5980-aws-sdk-embedded-youtobe-video-crash\",\n \"main\": \"index.js\",\n \"window\": {\n \"frame\": true,\n \"toolbar\": true,\n \"width\": 1600,\n \"height\": 900,\n \"position\": \"center\",\n \"show\": true\n },\n \"chromium-args\": \"--mixed-context --enable-webgl --ignore-certificate-errors\",\n \"dependencies\": {\n \"aws-sdk\": \"*\"\n }\n}\n", "file_path": "test/sanity/issue5980-aws-sdk-embedded-youtobe-video-crash/package.json", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0001852024142863229, 0.00017726272926665843, 0.0001693230587989092, 0.00017726272926665843, 7.939677743706852e-06]} {"hunk": {"id": 3, "code_window": ["// content/browser/renderer_host/render_process_host_impl.cc\n", "// content/browser/site_instance_impl.cc\n", "CONTENT_EXPORT bool PinningRenderer();\n", "\n", "#if defined(OS_MAC)\n", "// ref in chrome/browser/app_controller_mac.mm\n", "CONTENT_EXPORT bool ApplicationShouldHandleReopenHook(bool hasVisibleWindows);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT bool MixedContext();\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 50}, "file": "# App {: .doctitle}\n\n---\n\n[TOC]\n\n## App.argv\n\nGet the filtered command line arguments when starting the app. In NW.js, some command line arguments are used by NW.js, which should not be interested of your app. `App.argv` will filter out those arguments and return the ones left. You can get filtered patterns from `App.filteredArgv` and the full arguments from `App.fullArgv`.\n\n## App.fullArgv\n\nGet all the command line arguments when starting the app. The return values contains the arguments used by NW.js, such as `--nwapp`, `--remote-debugging-port` etc.\n\n## App.filteredArgv\n\nGet a list of patterns of filtered command line arguments used by `App.argv`. By default, following patterns are used to filter the arguments:\n\n```javascript\n[\n /^--url=/,\n /^--remote-debugging-port=/,\n /^--renderer-cmd-prefix=/,\n /^--nwapp=/\n]\n```\n\n## App.startPath\n\nGet the directory where the application starts. The application will change the current directory to where the package files reside after start.\n\n## App.dataPath\n\nGet the application's data path in user's directory.\n\n* Windows: `%LOCALAPPDATA%/`\n* Linux: `~/.config/`\n* OS X: `~/Library/Application Support//Default` (was `~/Library/Application Support/` in v0.12.3 and below)\n\n`` is the **name** field in the `package.json` manifest.\n\n## App.manifest\n\nGet the JSON object of the manifest file.\n\n## App.clearCache()\n\nClear the HTTP cache in memory and the one on disk. This method call is synchronized.\n\n## App.clearAppCache(manifest_url)\n\nMark the Application cache group specified by manifest_url obsolete. This method call is synchronized.\n\n## App.closeAllWindows()\n\nSend the `close` event to all windows of current app, if no window is blocking the `close` event, then the app will quit after all windows have done shutdown. Use this method to quit an app will give windows a chance to save data.\n\n## App.crashBrowser()\n## App.crashRenderer()\n\nThese 2 functions crashes the browser process and the renderer process respectively, to test the [Crash dump](../For Developers/Understanding Crash Dump.md) feature.\n\n## App.getProxyForURL(url)\n\n* `url` `{String}` the URL to query for proxy\n\nQuery the proxy to be used for loading `url` in DOM. The return value is in the same format used in [PAC](http://en.wikipedia.org/wiki/Proxy_auto-config) (e.g. \"DIRECT\", \"PROXY localhost:8080\").\n\n## App.setProxyConfig(config, pac_url)\n\n* `config` `{String}` Proxy rules\n* `pac_url` `{String}` PAC url\n\nSet the proxy config which the web engine will be used to request network resources or PAC url to detect proxy automatically.\n\nRule (copied from [`net/proxy/proxy_config.h`](https://github.com/nwjs/chromium.src/blob/nw13/net/proxy/proxy_config.h))\n\n```\n // Parses the rules from a string, indicating which proxies to use.\n //\n // proxy-uri = [\"://\"][\":\"]\n //\n // proxy-uri-list = [\",\"]\n //\n // url-scheme = \"http\" | \"https\" | \"ftp\" | \"socks\"\n //\n // scheme-proxies = [\"=\"]\n //\n // proxy-rules = scheme-proxies[\";\"]\n //\n // Thus, the proxy-rules string should be a semicolon-separated list of\n // ordered proxies that apply to a particular URL scheme. Unless specified,\n // the proxy scheme for proxy-uris is assumed to be http.\n //\n // Some special cases:\n // * If the scheme is omitted from the first proxy list, that list applies\n // to all URL schemes and subsequent lists are ignored.\n // * If a scheme is omitted from any proxy list after a list where a scheme\n // has been provided, the list without a scheme is ignored.\n // * If the url-scheme is set to 'socks', that sets a fallback list that\n // to all otherwise unspecified url-schemes, however the default proxy-\n // scheme for proxy urls in the 'socks' list is understood to be\n // socks4:// if unspecified.\n //\n // For example:\n // \"http=foopy:80;ftp=foopy2\" -- use HTTP proxy \"foopy:80\" for http://\n // URLs, and HTTP proxy \"foopy2:80\" for\n // ftp:// URLs.\n // \"foopy:80\" -- use HTTP proxy \"foopy:80\" for all URLs.\n // \"foopy:80,bar,direct://\" -- use HTTP proxy \"foopy:80\" for all URLs,\n // failing over to \"bar\" if \"foopy:80\" is\n // unavailable, and after that using no\n // proxy.\n // \"socks4://foopy\" -- use SOCKS v4 proxy \"foopy:1080\" for all\n // URLs.\n // \"http=foop,socks5://bar.com -- use HTTP proxy \"foopy\" for http URLs,\n // and fail over to the SOCKS5 proxy\n // \"bar.com\" if \"foop\" is unavailable.\n // \"http=foopy,direct:// -- use HTTP proxy \"foopy\" for http URLs,\n // and use no proxy if \"foopy\" is\n // unavailable.\n // \"http=foopy;socks=foopy2 -- use HTTP proxy \"foopy\" for http URLs,\n // and use socks4://foopy2 for all other\n // URLs.\n```\n\n## App.quit()\n\nQuit current app. This method will **not** send `close` event to windows and app will just quit quietly.\n\n## App.setCrashDumpDir(dir)\n\n!!! warning \"Deprecated\"\n This API was deprecated since 0.11.0.\n\n* `dir` `{String}` path to generate the crash dump\n\nSet the directory where the minidump file will be saved on crash. For more information, see [Crash dump](../For Developers/Understanding Crash Dump.md).\n\n## App.addOriginAccessWhitelistEntry(sourceOrigin, destinationProtocol, destinationHost, allowDestinationSubdomains)\n\n* `sourceOrigin` `{String}` The source origin. e.g. `http://github.com/`\n* `destinationProtocol` `{String}` The destination protocol where the `sourceOrigin` can access to. e.g. `app`\n* `destinationHost` `{String}` The destination host where the `sourceOrigin` can access to. e.g. `myapp`\n* `allowDestinationSubdomains` `{Boolean}` If set to true, the `sourceOrigin` is allowed to access subdomains of destinations.\n\nAdd an entry to the whitelist used for controlling cross-origin access. Suppose you want to allow HTTP redirecting from `github.com` to the page of your app, use something like this:\n\n```javascript\nApp.addOriginAccessWhitelistEntry('http://github.com/', 'chrome-extension', location.host, true);\n```\n\nUse `App.removeOriginAccessWhitelistEntry` with exactly the same arguments to do the contrary.\n\n## App.removeOriginAccessWhitelistEntry(sourceOrigin, destinationProtocol, destinationHost, allowDestinationSubdomains)\n\n* `sourceOrigin` `{String}` The source origin. e.g. `http://github.com/`\n* `destinationProtocol` `{String}` The destination protocol where the `sourceOrigin` can access to. e.g. `app`\n* `destinationHost` `{String}` The destination host where the `sourceOrigin` can access to. e.g. `myapp`\n* `allowDestinationSubdomains` `{Boolean}` If set to true, the `sourceOrigin` is allowed to access subdomains of destinations.\n\nRemove an entry from the whitelist used for controlling cross-origin access. See `addOriginAccessWhitelistEntry` above.\n\n## App.registerGlobalHotKey(shortcut)\n\n* `shortcut` `{Shortcut}` the `Shortcut` object to register.\n\nRegister a global keyboard shortcut (also known as system-wide hot key) to the system.\n\nSee [Shortcut](Shortcut.md) for more information.\n\n## App.unregisterGlobalHotKey(shortcut)\n\n* `shortcut` `{Shortcut}` the `Shortcut` object to unregister.\n\nUnregisters a global keyboard shortcut.\n\nSee [Shortcut](Shortcut.md) for more information.\n\n## Event: open(args)\n\n* `args` `{String}` the full command line of the program.\n\nEmitted when users opened a file with your app.\n\n## Event: reopen\n\nThis is a Mac specific feature. This event is sent when the user clicks the dock icon for an already running application.\n", "file_path": "docs/References/App.md", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0003669637080747634, 0.0002051391202257946, 0.00016203468840103596, 0.00018067474593408406, 6.105515785748139e-05]} {"hunk": {"id": 3, "code_window": ["// content/browser/renderer_host/render_process_host_impl.cc\n", "// content/browser/site_instance_impl.cc\n", "CONTENT_EXPORT bool PinningRenderer();\n", "\n", "#if defined(OS_MAC)\n", "// ref in chrome/browser/app_controller_mac.mm\n", "CONTENT_EXPORT bool ApplicationShouldHandleReopenHook(bool hasVisibleWindows);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT bool MixedContext();\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 50}, "file": "{\n \"main\": \"index.html\",\n \"name\": \"canhuang\",\n \"appname\": \"canhuang\",\n \"version\": \"1.0.0\",\n \"window\": {\n \"title\": \"v1.0.0\",\n \"toolbar\": true,\n \"width\": 800,\n \"height\": 800,\n \"frame\": true\n },\n \"chromium-args\": \"-load-extension=./extensions/ -ignore-certificate-errors\",\n \"webview\": {\n \"partitions\": [\n {\n \"name\": \"trusted\",\n \"accessible_resources\": [\n \"\"\n ]\n }\n ]\n }\n}\n", "file_path": "test/sanity/webview-cdt-ext/package.json", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017820383072830737, 0.00017244757327716798, 0.00016907943063415587, 0.00017005942936521024, 4.089910817128839e-06]} {"hunk": {"id": 4, "code_window": [" gfx::Image* image);\n", "// ref in extensions/browser/api/app_window/app_window_api.cc\n", "CONTENT_EXPORT void SetPinningRenderer(bool pin);\n", "\n", "// browser\n", "// ref in content/nw/src/api/tray/tray_aura.cc\n", "// content/nw/src/api/menuitem/menuitem_views.cc\n", "CONTENT_EXPORT bool GetImage(Package* package, const base::FilePath& icon_path, gfx::Image* image);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT void SetMixedContext(bool);\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 64}, "file": "#define INSIDE_BLINK 1\n#include \"third_party/blink/public/platform/web_rect.h\"\n#undef INSIDE_BLINK\n\n#include \"nw_extensions_renderer_hooks.h\"\n#include \"content/public/common/content_features.h\"\n// nw\n#include \"content/nw/src/nw_version.h\"\n\n// base\n#include \"base/command_line.h\"\n#include \"base/files/file_util.h\"\n#include \"base/json/json_writer.h\"\n#include \"base/logging.h\"\n#include \"base/i18n/icu_util.h\"\n#include \"base/strings/utf_string_conversions.h\"\n#include \"base/threading/thread.h\"\n#include \"base/values.h\"\n#include \"ui/base/resource/resource_bundle.h\"\n\n// content\n#include \"content/public/renderer/v8_value_converter.h\"\n#include \"content/public/common/content_switches.h\"\n#include \"content/public/renderer/render_view.h\"\n#include \"content/renderer/render_view_impl.h\"\n\n#include \"content/common/frame.mojom.h\"\n\n// extensions\n#include \"extensions/renderer/dispatcher.h\"\n#include \"extensions/renderer/renderer_extension_registry.h\"\n#include \"extensions/renderer/script_context.h\"\n#include \"extensions/common/extension.h\"\n#include \"extensions/common/manifest.h\"\n#include \"extensions/common/manifest_constants.h\"\n#include \"extensions/renderer/native_extension_bindings_system.h\"\n#include \"extensions/common/extension_features.h\"\n\n#include \"extensions/grit/extensions_renderer_resources.h\"\n\n// third_party/blink/\n#include \"third_party/blink/public/web/web_document.h\"\n#include \"third_party/blink/public/web/web_local_frame.h\"\n#include \"third_party/blink/public/web/web_script_source.h\"\n#include \"third_party/blink/public/web/web_view.h\"\n#include \"third_party/blink/renderer/platform/bindings/script_forbidden_scope.h\"\n#include \"third_party/blink/public/web/blink.h\"\n#include \"third_party/blink/renderer/platform/bindings/dom_wrapper_world.h\"\n#include \"third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h\"\n#include \"third_party/blink/renderer/platform/wtf/casting.h\"\n#include \"third_party/blink/renderer/core/frame/web_local_frame_impl.h\"\n\n#include \"third_party/node-nw/src/node_webkit.h\"\n\n// gen\n#include \"nw/id/commit.h\"\n\n// NEED TO STAY SYNC WITH NODE\n#ifndef NODE_CONTEXT_EMBEDDER_DATA_INDEX\n#define NODE_CONTEXT_EMBEDDER_DATA_INDEX 32\n#endif\n\n#if defined(OS_WIN)\n#define _USE_MATH_DEFINES\n#include \n#endif\n\nusing content::RenderViewImpl;\n\nusing extensions::ScriptContext;\nusing extensions::Extension;\nusing extensions::RendererExtensionRegistry;\nusing extensions::Dispatcher;\n\nusing blink::WebScriptSource;\n\nnamespace manifest_keys = extensions::manifest_keys;\n\n#if defined(COMPONENT_BUILD) && defined(WIN32)\n#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn;\n#define BLINK_HOOK_MAP(type, sym, fn) BLINK_EXPORT type fn;\n#define PLATFORM_HOOK_MAP(type, sym, fn) PLATFORM_EXPORT type fn;\n#else\n#define NW_HOOK_MAP(type, sym, fn) extern type fn;\n#define BLINK_HOOK_MAP(type, sym, fn) extern type fn;\n#define PLATFORM_HOOK_MAP(type, sym, fn) extern type fn;\n#endif\n#include \"content/nw/src/common/node_hooks.h\"\n#undef NW_HOOK_MAP\n\nnamespace nw {\n\nnamespace {\nstd::string g_extension_id, g_extension_root;\nextensions::Dispatcher* g_dispatcher = NULL;\nbool g_skip_render_widget_hidden = false;\n\nstatic inline v8::Local v8_str(const char* x) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n return v8::String::NewFromUtf8(isolate, x, v8::NewStringType::kNormal).ToLocalChecked();\n}\n\nv8::Handle CallNWTickCallback(void* env, const v8::Handle ret) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n g_call_tick_callback_fn(env);\n return Undefined(v8::Isolate::GetCurrent());\n}\n\nv8::Handle CreateNW(ScriptContext* context,\n v8::Handle node_global,\n v8::Handle node_context) {\n v8::Handle nw_string(\n v8::String::NewFromUtf8(context->isolate(), \"nw\", v8::NewStringType::kNormal).ToLocalChecked());\n v8::Handle global(context->v8_context()->Global());\n v8::Handle nw(global->Get(context->v8_context(), nw_string).ToLocalChecked());\n if (nw->IsUndefined()) {\n nw = v8::Object::New(context->isolate());;\n //node_context->Enter();\n ignore_result(global->Set(context->v8_context(), nw_string, nw));\n //node_context->Exit();\n }\n return nw;\n}\n\n// Returns |value| cast to an object if possible, else an empty handle.\nv8::Handle AsObjectOrEmpty(v8::Handle value) {\n return value->IsObject() ? value.As() : v8::Handle();\n}\n\n}\n\nconst std::string& get_main_extension_id() {\n return g_extension_id;\n}\n\nconst char* GetChromiumVersion();\n\n// renderer\n\nvoid WebWorkerNewThreadHook(const char* name, bool* is_node) {\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n if (!command_line.HasSwitch(switches::kEnableNodeWorker))\n return;\n if (!strcmp(name, \"DedicatedWorker thread\") || !strcmp(name, \"SharedWorker thread\"))\n *is_node = true;\n}\n\nvoid WebWorkerStartThreadHook(blink::Frame* frame, const char* path, std::string* script, bool* isNodeJS) {\n std::string root_path;\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n if (!command_line.HasSwitch(switches::kEnableNodeWorker)) {\n *isNodeJS = false;\n return;\n }\n if (frame) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n blink::WebFrame* web_frame = blink::WebFrame::FromFrame(frame);\n blink::WebLocalFrame* local_frame = web_frame->ToWebLocalFrame();\n v8::Local v8_context = local_frame->MainWorldScriptContext();\n ScriptContext* script_context =\n g_dispatcher->script_context_set().GetByV8Context(v8_context);\n if (!script_context || !script_context->extension())\n return;\n root_path = g_extension_root;\n } else {\n root_path = *script;\n }\n std::string url_path(path);\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n *script = \"global.__filename = '\" + url_path + \"';\";\n *script += \"global.__dirname = '\" + root_path + \"';\";\n *script += \"{ let root = '\" + root_path + \"';\"\n \" let p = '\" + url_path + \"';\"\n \"process.mainModule.filename = root + p;\"\n \"process.mainModule.paths = global.require('module')._nodeModulePaths(process.cwd());\"\n \"process.mainModule.loaded = true;\"\n \"}\";\n}\n\nvoid ContextCreationHook(blink::WebLocalFrame* frame, ScriptContext* context) {\n v8::Isolate* isolate = context->isolate();\n\n const Extension* extension = context->extension();\n std::string extension_root;\n\n if (g_extension_id.empty() && extension)\n g_extension_id = extension->id();\n\n bool nodejs_enabled = true;\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n bool worker_support = command_line.HasSwitch(switches::kEnableNodeWorker);\n\n if (extension) {\n extension->manifest()->GetBoolean(manifest_keys::kNWJSEnableNode, &nodejs_enabled);\n extension_root = extension->path().AsUTF8Unsafe();\n } else {\n extension_root = command_line.GetSwitchValuePath(switches::kNWAppPath).AsUTF8Unsafe();\n }\n g_extension_root = extension_root;\n\n if (!nodejs_enabled)\n return;\n\n blink::set_web_worker_hooks((void*)WebWorkerStartThreadHook);\n g_web_worker_thread_new_fn = (VoidPtr2Fn)WebWorkerNewThreadHook;\n if (!g_is_node_initialized_fn())\n g_setup_nwnode_fn(0, nullptr, worker_support);\n\n bool mixed_context = false;\n bool node_init_run = false;\n bool nwjs_guest_nw = command_line.HasSwitch(\"nwjs-guest-nw\");\n\n if (extension)\n extension->manifest()->GetBoolean(manifest_keys::kNWJSMixedContext, &mixed_context);\n // handle navigation in webview #5622\n if (nwjs_guest_nw)\n mixed_context = true;\n v8::Local node_context;\n g_get_node_context_fn(&node_context);\n if (node_context.IsEmpty() || mixed_context) {\n node_init_run = true;\n {\n int argc = 1;\n char argv0[] = \"node\";\n char* argv[3];\n argv[0] = argv0;\n argv[1] = argv[2] = nullptr;\n std::string main_fn;\n\n if (extension && extension->manifest()->GetString(\"node-main\", &main_fn)) {\n argc = 2;\n argv[1] = strdup(main_fn.c_str());\n }\n\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n v8::MicrotasksScope microtasks(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);\n\n g_set_nw_tick_callback_fn(&CallNWTickCallback);\n v8::Local dom_context;\n bool is_background_page = extension &&\n (context->url().host() == extension->id()) &&\n (context->url().path() == \"/_generated_background_page.html\");\n if (node_context.IsEmpty() && !mixed_context && !is_background_page) {\n dom_context = v8::Context::New(isolate);\n void* data = context->v8_context()->GetAlignedPointerFromEmbedderData(2); //v8ContextPerContextDataIndex\n dom_context->SetAlignedPointerInEmbedderData(2, data);\n dom_context->SetAlignedPointerInEmbedderData(50, (void*)0x08110800);\n } else\n dom_context = context->v8_context();\n if (!mixed_context)\n g_set_node_context_fn(isolate, &dom_context);\n dom_context->SetSecurityToken(v8::String::NewFromUtf8(isolate, \"nw-token\", v8::NewStringType::kNormal).ToLocalChecked());\n dom_context->Enter();\n\n g_start_nw_instance_fn(argc, argv, dom_context, (void*)base::i18n::GetRawIcuMemory());\n {\n#if defined(NWJS_SDK)\n std::string flavor = \"sdk\";\n#else\n std::string flavor = \"normal\";\n#endif\n v8::Local script =\n v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (std::string(\"process.versions['nw'] = '\" NW_VERSION_STRING \"';\") +\n \"process.versions['node-webkit'] = '\" NW_VERSION_STRING \"';\"\n \"process.versions['nw-commit-id'] = '\" NW_COMMIT_HASH \"';\"\n \"process.versions['nw-flavor'] = '\" + flavor + \"';\"\n \"process.versions['chromium'] = '\" + GetChromiumVersion() + \"';\").c_str(), v8::NewStringType::kNormal\n ).ToLocalChecked()).ToLocalChecked();\n ignore_result(script->Run(dom_context));\n }\n\n if (extension && extension->manifest()->GetString(manifest_keys::kNWJSInternalMainFilename, &main_fn)) {\n v8::Local script = v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (\"global.__filename = '\" + main_fn + \"';\").c_str(), v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();\n ignore_result(script->Run(dom_context));\n }\n {\n std::string root_path = extension_root;\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n v8::Local script = v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (\"global.__dirname = '\" + root_path + \"';\").c_str(), v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();\n ignore_result(script->Run(dom_context));\n }\n bool content_verification = false;\n if (extension && extension->manifest()->GetBoolean(manifest_keys::kNWJSContentVerifyFlag,\n &content_verification) && content_verification) {\n v8::Local script =\n v8::Script::Compile(dom_context, v8::String::NewFromUtf8(isolate,\n (std::string(\"global.__nwjs_cv = true;\") +\n \"global.__nwjs_ext_id = '\" + extension->id() + \"';\").c_str(), v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();\n\n ignore_result(script->Run(dom_context));\n }\n\n dom_context->Exit();\n }\n }\n\n v8::Local node_context2;\n if (mixed_context)\n node_context2 = context->v8_context();\n else\n g_get_node_context_fn(&node_context2);\n v8::Local g_context =\n v8::Local::New(isolate, node_context2);\n v8::Local node_global = g_context->Global();\n\n if (!mixed_context) {\n context->v8_context()->SetAlignedPointerInEmbedderData(NODE_CONTEXT_EMBEDDER_DATA_INDEX, g_get_node_env_fn());\n context->v8_context()->SetSecurityToken(g_context->GetSecurityToken());\n }\n v8::Handle nw = AsObjectOrEmpty(CreateNW(context, node_global, g_context));\n\n v8::Local symbols = v8::Array::New(isolate, 4);\n ignore_result(symbols->Set(context->v8_context(), 0, v8::String::NewFromUtf8(isolate, \"global\", v8::NewStringType::kNormal).ToLocalChecked()));\n ignore_result(symbols->Set(context->v8_context(), 1, v8::String::NewFromUtf8(isolate, \"process\", v8::NewStringType::kNormal).ToLocalChecked()));\n ignore_result(symbols->Set(context->v8_context(), 2, v8::String::NewFromUtf8(isolate, \"Buffer\", v8::NewStringType::kNormal).ToLocalChecked()));\n ignore_result(symbols->Set(context->v8_context(), 3, v8::String::NewFromUtf8(isolate, \"require\", v8::NewStringType::kNormal).ToLocalChecked()));\n\n g_context->Enter();\n for (unsigned i = 0; i < symbols->Length(); ++i) {\n v8::Local key = symbols->Get(context->v8_context(), i).ToLocalChecked();\n v8::Local val = node_global->Get(context->v8_context(), key).ToLocalChecked();\n ignore_result(nw->Set(context->v8_context(), key, val));\n if (nwjs_guest_nw && !node_init_run) {\n //running in nwjs webview and node was initialized in\n //chromedriver automation extension\n ignore_result(context->v8_context()->Global()->Set(context->v8_context(), key, val));\n }\n }\n g_context->Exit();\n\n std::string set_nw_script = \"'use strict';\";\n {\n v8::MicrotasksScope microtasks(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);\n v8::Context::Scope cscope(context->v8_context());\n // Make node's relative modules work\n std::string root_path = extension_root;\n GURL frame_url = ScriptContext::GetDocumentLoaderURLForFrame(frame);\n std::string url_path = frame_url.path();\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n v8::ScriptOrigin origin(v8::String::NewFromUtf8(isolate, \"process_main\", v8::NewStringType::kNormal).ToLocalChecked());\n v8::Local script = v8::Script::Compile(context->v8_context(), v8::String::NewFromUtf8(isolate, (\n set_nw_script +\n // Make node's relative modules work\n \"if (typeof nw.process != 'undefined' && \"\n \"(!nw.process.mainModule.filename || nw.process.mainModule.filename === 'blank' ||\"\n \"nw.process.mainModule.filename.indexOf('_generated_background_page.html') >= 0)) {\"\n \" let root = '\" + root_path + \"';\"\n \" let p = '\" + url_path + \"';\"\n \"nw.process.mainModule.filename = root + p;\"\n \"nw.process.mainModule.paths = nw.global.require('module')._nodeModulePaths(nw.process.cwd());\"\n \"nw.process.mainModule.loaded = true;\"\n \"}\").c_str(), v8::NewStringType::kNormal).ToLocalChecked(), &origin).ToLocalChecked();\n CHECK(*script);\n ignore_result(script->Run(context->v8_context()));\n }\n}\n\nbase::FilePath GetRootPathRenderer() {\n base::FilePath ret;\n const Extension* extension = RendererExtensionRegistry::Get()->GetByID(g_extension_id);\n if (!extension)\n return ret;\n if (!(extension->is_extension() || extension->is_platform_app()))\n return ret;\n return extension->path();\n}\n\nvoid TryInjectStartScript(blink::WebLocalFrame* frame, const Extension* extension, bool start) {\n RenderViewImpl* rv = content::RenderFrameImpl::FromWebFrame(frame)->render_view();\n if (!rv)\n return;\n\n std::string js_fn = start ? rv->renderer_preferences().nw_inject_js_doc_start :\n rv->renderer_preferences().nw_inject_js_doc_end;\n if (js_fn.empty())\n return;\n base::FilePath fpath = base::FilePath::FromUTF8Unsafe(js_fn);\n if (!fpath.IsAbsolute()) {\n const Extension* extension = nullptr;\n if (!extension) {\n extension = RendererExtensionRegistry::Get()->GetByID(g_extension_id);\n if (!extension)\n return;\n }\n if (!(extension->is_extension() || extension->is_platform_app()))\n return;\n base::FilePath root(extension->path());\n fpath = root.AppendASCII(js_fn);\n }\n v8::Local v8_context = frame->MainWorldScriptContext();\n std::string content;\n if (!base::ReadFileToString(fpath, &content)) {\n //LOG(WARNING) << \"Failed to load js script file: \" << js_file.value();\n return;\n }\n if (!v8_context.IsEmpty()) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n v8::Context::Scope cscope(v8_context);\n // v8::Handle result;\n frame->ExecuteScriptAndReturnValue(WebScriptSource(blink::WebString::FromUTF8(content)));\n }\n}\n\nvoid DocumentFinishHook(blink::WebLocalFrame* frame,\n const extensions::Extension* extension,\n const GURL& effective_document_url) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope hscope(isolate);\n\n TryInjectStartScript(frame, extension, false);\n}\n\nvoid DocumentHook2(bool start, content::RenderFrame* frame, Dispatcher* dispatcher) {\n // ignore the first invocation of this hook for iframe\n // or we'll trigger creating a context with invalid type\n // there will follow another one with valid url\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n blink::WebLocalFrame* web_frame = frame->GetWebFrame();\n GURL frame_url = ScriptContext::GetDocumentLoaderURLForFrame(web_frame);\n if (web_frame->Parent() && (!frame_url.is_valid() || frame_url.is_empty()))\n return;\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n blink::WebFrame* f = frame->GetRenderView()->GetWebView()->MainFrame();\n if (!f->IsWebLocalFrame())\n return;\n blink::WebLocalFrame* local_frame = f->ToWebLocalFrame();\n v8::Local v8_context = local_frame->MainWorldScriptContext();\n ScriptContext* script_context =\n dispatcher->script_context_set().GetByV8Context(v8_context);\n if (start)\n TryInjectStartScript(web_frame, script_context ? script_context->extension() : nullptr, true);\n if (!script_context)\n return;\n std::vector > arguments;\n v8::Local window =\n web_frame->MainWorldScriptContext()->Global();\n arguments.push_back(v8::Boolean::New(isolate, start));\n arguments.push_back(window);\n if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {\n content::RenderFrame* main_frame = frame->GetRenderView()->GetMainRenderFrame();\n arguments.push_back(v8::Integer::New(isolate, main_frame->GetRoutingID()));\n\n std::set contexts(dispatcher->script_context_set().contexts());\n std::set::iterator it = contexts.begin();\n while (it != contexts.end()) {\n ScriptContext* c = *it;\n if (extensions::binding::IsContextValid(c->v8_context())) {\n extensions::ModuleSystem::NativesEnabledScope natives_enabled(c->module_system());\n c->module_system()->CallModuleMethodSafe(\"nw.Window\", \"onDocumentStartEnd\", &arguments);\n it++;\n }\n }\n } else {\n // need require in m61 since the following CallModuleMethodSafe\n // won't load it anymore: fedbe848f3024dd690f93545a337a2a6fb2aa81f\n extensions::ModuleSystem::NativesEnabledScope natives_enabled(script_context->module_system());\n extensions::NativeExtensionBindingsSystem* binding_sys = (extensions::NativeExtensionBindingsSystem*)dispatcher->bindings_system();\n v8_context->Enter();\n v8::Local nw_win = binding_sys->GetAPIObjectForTesting(script_context, \"nw.Window\");\n if (nw_win.IsEmpty())\n binding_sys->GetAPIObjectForTesting(script_context, \"nw.Window\", true);\n v8_context->Exit();\n script_context->module_system()->CallModuleMethodSafe(\"nw.Window\", \"onDocumentStartEnd\", &arguments);\n }\n}\n\nvoid DocumentElementHook(blink::WebLocalFrame* frame,\n const extensions::Extension* extension,\n const GURL& effective_document_url) {\n // ignore the first invocation of this hook for iframe\n // or we'll trigger creating a context with invalid type\n // there will follow another one with valid url\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n GURL frame_url = ScriptContext::GetDocumentLoaderURLForFrame(frame);\n if (frame->Parent() && (!frame_url.is_valid() || frame_url.is_empty()))\n return;\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope hscope(isolate);\n frame->GetDocument().GetSecurityOrigin().grantUniversalAccess();\n frame->setNodeJS(true);\n content::RenderFrameImpl* render_frame = content::RenderFrameImpl::FromWebFrame(frame);\n auto* frame_host = render_frame->GetFrameHost();\n frame_host->SetNodeJS(true);\n std::string path = effective_document_url.path();\n v8::Local v8_context = frame->MainWorldScriptContext();\n std::string root_path = g_extension_root;\n if (!v8_context.IsEmpty()) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n v8::Context::Scope cscope(v8_context);\n // Make node's relative modules work\n#if defined(OS_WIN)\n base::ReplaceChars(root_path, \"\\\\\", \"\\\\\\\\\", &root_path);\n#endif\n base::ReplaceChars(root_path, \"'\", \"\\\\'\", &root_path);\n\n v8::ScriptOrigin origin(v8::String::NewFromUtf8(isolate, \"process_main2\", v8::NewStringType::kNormal).ToLocalChecked());\n v8::Local script2 = v8::Script::Compile(v8_context, v8::String::NewFromUtf8(isolate, (\n \"'use strict';\"\n \"if (typeof nw != 'undefined' && typeof __filename == 'undefined') {\"\n \" let root = '\" + root_path + \"';\"\n \" let path = '\" + path + \"';\"\n \"nw.__filename = root + path;\"\n \"nw.__dirname = root;\"\n \"}\").c_str(), v8::NewStringType::kNormal).ToLocalChecked(), &origin).ToLocalChecked();\n CHECK(*script2);\n ignore_result(script2->Run(v8_context));\n }\n RenderViewImpl* rv = content::RenderFrameImpl::FromWebFrame(frame)->render_view();\n if (!rv)\n return;\n\n ui::ResourceBundle* resource_bundle = &ui::ResourceBundle::GetSharedInstance();\n base::StringPiece resource =\n resource_bundle->GetRawDataResource(IDR_NW_PRE13_SHIM_JS);\n if (resource.empty())\n return;\n if (!v8_context.IsEmpty()) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n v8::Context::Scope cscope(v8_context);\n frame->ExecuteScriptAndReturnValue(WebScriptSource(blink::WebString::FromUTF8(resource.as_string())));\n }\n}\n\nvoid willHandleNavigationPolicy(content::RenderView* rv,\n blink::WebFrame* frame,\n const blink::WebURLRequest& request,\n blink::WebNavigationPolicy* policy,\n blink::WebString* manifest,\n bool new_win) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::HandleScope scope(isolate);\n blink::WebFrame* f = rv->GetWebView()->MainFrame();\n if (!f->IsWebLocalFrame())\n return;\n blink::WebLocalFrame* local_frame = f->ToWebLocalFrame();\n blink::LocalFrame* core_frame = blink::To(local_frame)->GetFrame();\n\n if (core_frame->ContextNotReady(blink::DOMWrapperWorld::MainWorld()))\n return;\n v8::Handle v8_context = local_frame->MainWorldScriptContext();\n ScriptContext* script_context =\n g_dispatcher->script_context_set().GetByV8Context(v8_context);\n v8::Context::Scope cscope (v8_context);\n v8::Handle element = v8::Null(isolate);\n v8::Handle policy_obj = v8::Object::New(isolate);\n\n#if 0\n blink::LocalFrame* core_frame = blink::toWebLocalFrameImpl(frame)->frame();\n if (core_frame->deprecatedLocalOwner()) {\n element = blink::toV8((blink::HTMLElement*)core_frame->deprecatedLocalOwner(),\n frame->mainWorldScriptContext()->Global(),\n frame->mainWorldScriptContext()->GetIsolate());\n }\n#endif\n std::vector > arguments;\n arguments.push_back(element);\n arguments.push_back(v8_str(request.Url().GetString().Utf8().c_str()));\n arguments.push_back(policy_obj);\n if (base::FeatureList::IsEnabled(::features::kNWNewWin)) {\n content::RenderFrame* main_frame = rv->GetMainRenderFrame();\n arguments.push_back(v8::Integer::New(isolate, main_frame->GetRoutingID()));\n\n std::set contexts(g_dispatcher->script_context_set().contexts());\n std::set::iterator it = contexts.begin();\n while (it != contexts.end()) {\n ScriptContext* c = *it;\n extensions::ModuleSystem::NativesEnabledScope natives_enabled(c->module_system());\n if (new_win) {\n c->module_system()->CallModuleMethodSafe(\"nw.Window\", \"onNewWinPolicy\", &arguments);\n } else {\n const char* req_context = nullptr;\n switch (request.GetRequestContext()) {\n case blink::mojom::RequestContextType::HYPERLINK:\n req_context = \"hyperlink\";\n break;\n case blink::mojom::RequestContextType::FRAME:\n req_context = \"form\";\n break;\n case blink::mojom::RequestContextType::LOCATION:\n req_context = \"location\";\n break;\n default:\n break;\n }\n if (req_context) {\n arguments.push_back(v8_str(req_context));\n c->module_system()->CallModuleMethodSafe(\"nw.Window\",\n \"onNavigation\", &arguments);\n }\n }\n it++;\n }\n } else {\n if (new_win) {\n script_context->module_system()->CallModuleMethodSafe(\"nw.Window\",\n \"onNewWinPolicy\", &arguments);\n } else {\n const char* req_context = nullptr;\n switch (request.GetRequestContext()) {\n case blink::mojom::RequestContextType::HYPERLINK:\n req_context = \"hyperlink\";\n break;\n case blink::mojom::RequestContextType::FRAME:\n req_context = \"form\";\n break;\n case blink::mojom::RequestContextType::LOCATION:\n req_context = \"location\";\n break;\n default:\n break;\n }\n if (req_context) {\n arguments.push_back(v8_str(req_context));\n script_context->module_system()->CallModuleMethodSafe(\"nw.Window\",\n \"onNavigation\", &arguments);\n }\n }\n }\n\n std::unique_ptr converter(content::V8ValueConverter::Create());\n v8::Local manifest_v8 = policy_obj->Get(v8_context, v8_str(\"manifest\")).ToLocalChecked();\n std::unique_ptr manifest_val(converter->FromV8Value(manifest_v8, v8_context));\n std::string manifest_str;\n if (manifest_val.get() && base::JSONWriter::Write(*manifest_val, &manifest_str)) {\n *manifest = blink::WebString::FromUTF8(manifest_str.c_str());\n }\n\n v8::Local val = policy_obj->Get(v8_context, v8_str(\"val\")).ToLocalChecked();\n if (!val->IsString())\n return;\n v8::String::Utf8Value policy_str(isolate, val);\n if (!strcmp(*policy_str, \"ignore\"))\n *policy = blink::kWebNavigationPolicyIgnore;\n else if (!strcmp(*policy_str, \"download\"))\n *policy = blink::kWebNavigationPolicyDownload;\n else if (!strcmp(*policy_str, \"current\"))\n *policy = blink::kWebNavigationPolicyCurrentTab;\n else if (!strcmp(*policy_str, \"new-window\"))\n *policy = blink::kWebNavigationPolicyNewWindow;\n else if (!strcmp(*policy_str, \"new-popup\"))\n *policy = blink::kWebNavigationPolicyNewPopup;\n}\n\ntypedef bool (*RenderWidgetWasHiddenHookFn)(content::RenderWidget*);\n#if defined(COMPONENT_BUILD)\nCONTENT_EXPORT RenderWidgetWasHiddenHookFn gRenderWidgetWasHiddenHook;\n#else\nextern RenderWidgetWasHiddenHookFn gRenderWidgetWasHiddenHook;\n#endif\n\nbool RenderWidgetWasHiddenHook(content::RenderWidget* rw) {\n return g_skip_render_widget_hidden;\n}\n\nvoid ExtensionDispatcherCreated(extensions::Dispatcher* dispatcher) {\n g_dispatcher = dispatcher;\n const base::CommandLine& command_line =\n *base::CommandLine::ForCurrentProcess();\n if (command_line.HasSwitch(switches::kDisableRAFThrottling))\n g_skip_render_widget_hidden = true;\n nw::gRenderWidgetWasHiddenHook = RenderWidgetWasHiddenHook;\n}\n\nvoid OnRenderProcessShutdownHook(extensions::ScriptContext* context) {\n v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks);\n blink::ScriptForbiddenScope::AllowUserAgentScript script;\n void* env = g_get_current_env_fn(context->v8_context());\n if (g_is_node_initialized_fn()) {\n g_emit_exit_fn(env);\n g_run_at_exit_fn(env);\n }\n}\n\n} // namespace nw\n", "file_path": "src/renderer/nw_extensions_renderer_hooks.cc", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.01002771407365799, 0.0004033797304145992, 0.00016086469986476004, 0.00016798294382169843, 0.001254051341675222]} {"hunk": {"id": 4, "code_window": [" gfx::Image* image);\n", "// ref in extensions/browser/api/app_window/app_window_api.cc\n", "CONTENT_EXPORT void SetPinningRenderer(bool pin);\n", "\n", "// browser\n", "// ref in content/nw/src/api/tray/tray_aura.cc\n", "// content/nw/src/api/menuitem/menuitem_views.cc\n", "CONTENT_EXPORT bool GetImage(Package* package, const base::FilePath& icon_path, gfx::Image* image);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT void SetMixedContext(bool);\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 64}, "file": "\n\n \n \n\t\n \n \n

this is webview

\n \n \n\n", "file_path": "test/sanity/webview-node/webview.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00016963786038104445, 0.0001692705845925957, 0.00016890330880414695, 0.0001692705845925957, 3.6727578844875097e-07]} {"hunk": {"id": 4, "code_window": [" gfx::Image* image);\n", "// ref in extensions/browser/api/app_window/app_window_api.cc\n", "CONTENT_EXPORT void SetPinningRenderer(bool pin);\n", "\n", "// browser\n", "// ref in content/nw/src/api/tray/tray_aura.cc\n", "// content/nw/src/api/menuitem/menuitem_views.cc\n", "CONTENT_EXPORT bool GetImage(Package* package, const base::FilePath& icon_path, gfx::Image* image);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT void SetMixedContext(bool);\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 64}, "file": "// It is expected that, when .add() returns false, the consumer\n// of the DirWriter will pause until a \"drain\" event occurs. Note\n// that this is *almost always going to be the case*, unless the\n// thing being written is some sort of unsupported type, and thus\n// skipped over.\n\nmodule.exports = DirWriter\n\nvar Writer = require('./writer.js')\nvar inherits = require('inherits')\nvar mkdir = require('mkdirp')\nvar path = require('path')\nvar collect = require('./collect.js')\n\ninherits(DirWriter, Writer)\n\nfunction DirWriter (props) {\n var self = this\n if (!(self instanceof DirWriter)) {\n self.error('DirWriter must be called as constructor.', null, true)\n }\n\n // should already be established as a Directory type\n if (props.type !== 'Directory' || !props.Directory) {\n self.error('Non-directory type ' + props.type + ' ' +\n JSON.stringify(props), null, true)\n }\n\n Writer.call(this, props)\n}\n\nDirWriter.prototype._create = function () {\n var self = this\n mkdir(self._path, Writer.dirmode, function (er) {\n if (er) return self.error(er)\n // ready to start getting entries!\n self.ready = true\n self.emit('ready')\n self._process()\n })\n}\n\n// a DirWriter has an add(entry) method, but its .write() doesn't\n// do anything. Why a no-op rather than a throw? Because this\n// leaves open the door for writing directory metadata for\n// gnu/solaris style dumpdirs.\nDirWriter.prototype.write = function () {\n return true\n}\n\nDirWriter.prototype.end = function () {\n this._ended = true\n this._process()\n}\n\nDirWriter.prototype.add = function (entry) {\n var self = this\n\n // console.error('\\tadd', entry._path, '->', self._path)\n collect(entry)\n if (!self.ready || self._currentEntry) {\n self._buffer.push(entry)\n return false\n }\n\n // create a new writer, and pipe the incoming entry into it.\n if (self._ended) {\n return self.error('add after end')\n }\n\n self._buffer.push(entry)\n self._process()\n\n return this._buffer.length === 0\n}\n\nDirWriter.prototype._process = function () {\n var self = this\n\n // console.error('DW Process p=%j', self._processing, self.basename)\n\n if (self._processing) return\n\n var entry = self._buffer.shift()\n if (!entry) {\n // console.error(\"DW Drain\")\n self.emit('drain')\n if (self._ended) self._finish()\n return\n }\n\n self._processing = true\n // console.error(\"DW Entry\", entry._path)\n\n self.emit('entry', entry)\n\n // ok, add this entry\n //\n // don't allow recursive copying\n var p = entry\n var pp\n do {\n pp = p._path || p.path\n if (pp === self.root._path || pp === self._path ||\n (pp && pp.indexOf(self._path) === 0)) {\n // console.error('DW Exit (recursive)', entry.basename, self._path)\n self._processing = false\n if (entry._collected) entry.pipe()\n return self._process()\n }\n p = p.parent\n } while (p)\n\n // console.error(\"DW not recursive\")\n\n // chop off the entry's root dir, replace with ours\n var props = {\n parent: self,\n root: self.root || self,\n type: entry.type,\n depth: self.depth + 1\n }\n\n pp = entry._path || entry.path || entry.props.path\n if (entry.parent) {\n pp = pp.substr(entry.parent._path.length + 1)\n }\n // get rid of any ../../ shenanigans\n props.path = path.join(self.path, path.join('/', pp))\n\n // if i have a filter, the child should inherit it.\n props.filter = self.filter\n\n // all the rest of the stuff, copy over from the source.\n Object.keys(entry.props).forEach(function (k) {\n if (!props.hasOwnProperty(k)) {\n props[k] = entry.props[k]\n }\n })\n\n // not sure at this point what kind of writer this is.\n var child = self._currentChild = new Writer(props)\n child.on('ready', function () {\n // console.error(\"DW Child Ready\", child.type, child._path)\n // console.error(\" resuming\", entry._path)\n entry.pipe(child)\n entry.resume()\n })\n\n // XXX Make this work in node.\n // Long filenames should not break stuff.\n child.on('error', function (er) {\n if (child._swallowErrors) {\n self.warn(er)\n child.emit('end')\n child.emit('close')\n } else {\n self.emit('error', er)\n }\n })\n\n // we fire _end internally *after* end, so that we don't move on\n // until any \"end\" listeners have had their chance to do stuff.\n child.on('close', onend)\n var ended = false\n function onend () {\n if (ended) return\n ended = true\n // console.error(\"* DW Child end\", child.basename)\n self._currentChild = null\n self._processing = false\n self._process()\n }\n}\n", "file_path": "test/sanity/tar/node_modules/tar/node_modules/fstream/lib/dir-writer.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0001755923149175942, 0.00017138448311015964, 0.00016626248543616384, 0.00017179913993459195, 2.5916065169440117e-06]} {"hunk": {"id": 4, "code_window": [" gfx::Image* image);\n", "// ref in extensions/browser/api/app_window/app_window_api.cc\n", "CONTENT_EXPORT void SetPinningRenderer(bool pin);\n", "\n", "// browser\n", "// ref in content/nw/src/api/tray/tray_aura.cc\n", "// content/nw/src/api/menuitem/menuitem_views.cc\n", "CONTENT_EXPORT bool GetImage(Package* package, const base::FilePath& icon_path, gfx::Image* image);\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["CONTENT_EXPORT void SetMixedContext(bool);\n"], "file_path": "src/browser/nw_content_browser_hooks.h", "type": "add", "edit_start_line_idx": 64}, "file": "\n0.3.4 / 2012-07-24\n==================\n\n * Added SPDY support\n * Added http redirect utility function\n\n", "file_path": "test/node_modules/union/CHANGELOG.md", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00016379189037252218, 0.00016379189037252218, 0.00016379189037252218, 0.00016379189037252218, 0.0]} {"hunk": {"id": 5, "code_window": [" bool nwjs_guest_nw = command_line.HasSwitch(\"nwjs-guest-nw\");\n", "\n", " if (extension)\n", " extension->manifest()->GetBoolean(manifest_keys::kNWJSMixedContext, &mixed_context);\n", " // handle navigation in webview #5622\n", " if (nwjs_guest_nw)\n", " mixed_context = true;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" if (!mixed_context) {\n", " mixed_context = command_line.HasSwitch(\"mixed-context\");\n", " }\n"], "file_path": "src/renderer/nw_extensions_renderer_hooks.cc", "type": "add", "edit_start_line_idx": 221}, "file": "var nwNatives = requireNative('nw_natives');\nvar forEach = require('utils').forEach;\nvar runtimeNatives = requireNative('runtime');\nvar renderFrameObserverNatives = requireNative('renderFrameObserverNatives');\nvar appWindowNatives = requireNative('app_window_natives');\n\nvar GetExtensionViews = runtimeNatives.GetExtensionViews;\n\nvar currentNWWindow = null;\nvar currentNWWindowInternal = null;\nvar currentRoutingID = nwNatives.getRoutingID();\nvar currentWidgetRoutingID = nwNatives.getWidgetRoutingID();\n\nvar bgPage = GetExtensionViews(-1, -1, 'BACKGROUND')[0];\n\nvar try_hidden = function (view) {\n if (view.chrome.windows)\n return view;\n return privates(view);\n};\n\nvar try_nw = function (view) {\n if (view.nw)\n return view;\n return privates(view);\n};\n\nfunction getPlatform() {\n var platforms = [\n [/CrOS Touch/, \"chromeos touch\"],\n [/CrOS/, \"chromeos\"],\n [/Linux/, \"linux\"],\n [/Mac/, \"mac\"],\n [/Win/, \"win\"],\n ];\n\n for (var i = 0; i < platforms.length; i++) {\n if ($RegExp.exec(platforms[i][0], navigator.appVersion)) {\n return platforms[i][1];\n }\n }\n return \"unknown\";\n}\n\nvar canSetVisibleOnAllWorkspaces = /(mac|linux)/.exec(getPlatform());\n\nvar nwWinEventsMap = {\n 'minimize': 'onMinimized',\n 'maximize': 'onMaximized',\n 'restore': 'onRestore',\n 'enter-fullscreen': 'onFullscreen',\n 'zoom': 'onZoom',\n 'resize': 'onResized'\n};\n\nvar nwWrapEventsMap = {\n 'new-win-policy': 'onNewWinPolicy',\n 'navigation': 'onNavigation'\n};\n\nvar wrapEventsMapNewWin = {\n 'move': 'onMove',\n 'focus': 'onFocusChanged',\n 'blur': 'onFocusChanged',\n 'closed': 'onRemoved',\n 'close': 'onRemoving'\n};\n\nfunction NWWindow(cWindow) {\n var self = this;\n if (cWindow) {\n this.cWindow = cWindow;\n //console.log(`---> NWWindow: ${this.cWindow.id}`);\n } else {\n this.cWindow = currentNWWindowInternal.getCurrent(-2, {'populate': true});\n //console.log(`---> NWWindow: ${this.cWindow.id}`);\n if (!this.cWindow)\n console.error('The JavaScript context calling ' +\n 'nw.Window.get() has no associated Browser window.');\n }\n\n function updateWindowAttributes(w) {\n if (w.id !== self.cWindow.id)\n return;\n var oldState = self.cWindow.state;\n var oldWidth = self.cWindow.width;\n var oldHeight = self.cWindow.height;\n\n self.cWindow.state = w.state;\n self.cWindow.width = w.width;\n self.cWindow.height = w.height;\n\n if (oldState != 'minimized' && w.state == 'minimized') {\n dispatchEventIfExists(self, 'onMinimized', [w.id]);\n } else if (oldState != 'maximized' && w.state == 'maximized') {\n dispatchEventIfExists(self, 'onMaximized', [w.id]);\n } else if (oldState != 'fullscreen' && w.state == 'fullscreen') {\n dispatchEventIfExists(self, 'onFullscreen', [w.id]);\n } else if (oldState != 'normal' && w.state == 'normal') {\n dispatchEventIfExists(self, 'onRestore', [w.id]);\n } else if (oldWidth != w.width || oldHeight != w.height) {\n dispatchEventIfExists(self, 'onResized', [w.id, w.width, w.height]);\n }\n }\n privates(this).menu = null;\n chrome.windows.onWindowChanged.addListener(updateWindowAttributes);\n}\n\nNWWindow.prototype.onNewWinPolicy = bindingUtil.createCustomEvent(\"nw.Window.onNewWinPolicy\", false, false);\nNWWindow.prototype.onNavigation = bindingUtil.createCustomEvent(\"nw.Window.onNavigation\", false, false);\nNWWindow.prototype.LoadingStateChanged = bindingUtil.createCustomEvent(\"nw.Window.LoadingStateChanged\", false, false);\nNWWindow.prototype.onDocumentStart = bindingUtil.createCustomEvent(\"nw.Window.onDocumentStart\", false, false);\nNWWindow.prototype.onDocumentEnd = bindingUtil.createCustomEvent(\"nw.Window.onDocumentEnd\", false, false);\nNWWindow.prototype.onZoom = bindingUtil.createCustomEvent(\"nw.Window.onZoom\", false, false);\nNWWindow.prototype.onClose = bindingUtil.createCustomEvent(\"nw.Window.onClose\", true, false);\nNWWindow.prototype.onMinimized = bindingUtil.createCustomEvent(\"nw.Window.onMinimized\", false, false);\nNWWindow.prototype.onMaximized = bindingUtil.createCustomEvent(\"nw.Window.onMaximized\", false, false);\nNWWindow.prototype.onFullscreen = bindingUtil.createCustomEvent(\"nw.Window.onFullscreen\", false, false);\nNWWindow.prototype.onResized = bindingUtil.createCustomEvent(\"nw.Window.onResized\", false, false);\nNWWindow.prototype.onRestore = bindingUtil.createCustomEvent(\"nw.Window.onRestore\", false, false);\n\nNWWindow.prototype.close = function (force) {\n //console.log(`---> NWWindow.close: ${force} ${this.cWindow.id}`);\n currentNWWindowInternal.close(force, this.cWindow.id);\n}\n\nNWWindow.prototype.once = function (event, listener, record) {\n if (typeof listener !== 'function')\n throw new TypeError('listener must be a function');\n var fired = false;\n var self = this;\n\n function g() {\n self.removeListener(event, g);\n if (!fired) {\n fired = true;\n listener.apply(self, arguments);\n }\n }\n this.on(event, g, false);\n return this;\n};\n\nNWWindow.prototype.on = function (event, callback, record) {\n var self = this;\n\n // Wrap callback to bind to `self`.\n // If `cb` is given, use `cb` instead of original `callback`.\n function wrap(cb) {\n var fn = (cb || callback).bind(self);\n fn.listener = callback;\n fn.c_win_id = self.cWindow.id;\n callback.__nw_cb = fn;\n return fn;\n }\n\n if (event === 'close') {\n var cbc = wrap(function(windowId, flag) {\n if (self.cWindow.id !== windowId)\n return;\n callback.call(self, flag);\n });\n chrome.windows.onRemoving.addListener(cbc, {instanceId: self.cWindow.id});\n return this;\n }\n switch (event) {\n case 'focus':\n var cbf = wrap(function(windowId) {\n if (self.cWindow.id !== windowId)\n return;\n callback.call(self);\n });\n chrome.windows.onFocusChanged.addListener(cbf);\n break;\n case 'blur':\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n var cbf = wrap(function(windowId) {\n if (self.cWindow.id === windowId) {\n callback.__nw_cb.focused = true;\n return;\n }\n if (!callback.__nw_cb.focused)\n return;\n callback.__nw_cb.focused = false;\n callback.call(self);\n });\n chrome.windows.onFocusChanged.addListener(cbf);\n break;\n case 'closed':\n var cbr = wrap(function(windowId) {\n if (self.cWindow.id !== windowId)\n return;\n callback.call(self);\n });\n chrome.windows.onRemoved.addListener(cbr);\n break;\n case 'loaded':\n var g = wrap(function(tabId, changeInfo, tab) {\n if (tab.windowId !== self.cWindow.id)\n return;\n if ('nwstatus' in changeInfo && changeInfo.nwstatus == 'complete')\n callback.call(self);\n });\n chrome.tabs.onUpdated.addListener(g);\n break;\n case 'document-start':\n var cb1 = wrap(function(frame, top_routing_id) {\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n callback.call(self, frame);\n });\n this.onDocumentStart.addListener(cb1);\n break;\n case 'document-end':\n var cb0 = wrap(function(frame, top_routing_id) {\n //console.log(\"document-end: cWindow: \" + self.cWindow.id + \"; top routing id: \" + top_routing_id + \"; main frame id: \" + self.cWindow.tabs[0].mainFrameId);\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n callback.call(self, frame);\n });\n this.onDocumentEnd.addListener(cb0);\n break;\n case 'new-win-policy':\n var h = wrap(function(frame, url, policy, top_routing_id) {\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n policy.ignore = function () { this.val = 'ignore'; };\n policy.forceCurrent = function () { this.val = 'current'; };\n policy.forceDownload = function () { this.val = 'download'; };\n policy.forceNewWindow = function () { this.val = 'new-window'; };\n policy.forceNewPopup = function () { this.val = 'new-popup'; };\n policy.setNewWindowManifest = function (m) { this.manifest = m; };\n callback.call(self, frame, url, policy);\n });\n this.onNewWinPolicy.addListener(h);\n break;\n case 'navigation':\n var j = wrap(function(frame, url, policy, context, top_routing_id) {\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n policy.ignore = function () { this.val = 'ignore'; };\n callback.call(self, frame, url, policy, context);\n });\n this.onNavigation.addListener(j);\n break;\n case 'move':\n var k = wrap(function(w) {\n if (w.id != self.cWindow.id)\n return;\n callback.call(self, w.left, w.top);\n });\n chrome.windows.onMove.addListener(k);\n return this; //return early\n break;\n }\n if (nwWinEventsMap.hasOwnProperty(event)) {\n let cb = wrap(function(id, ...args) {\n if (id != self.cWindow.id)\n return;\n callback.call(self, ...args);\n });\n this[nwWinEventsMap[event]].addListener(cb);\n return this;\n }\n return this;\n};\nNWWindow.prototype.removeListener = function (event, callback) {\n if (event === 'loaded') {\n for (let l of chrome.tabs.onUpdated.getListeners()) {\n if (l.listener && l.listener === callback) {\n chrome.tabs.onUpdated.removeListener(l);\n return this;\n }\n }\n }\n if (nwWinEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWinEventsMap[event]].getListeners()) {\n if (l.listener && l.listener === callback) {\n this[nwWinEventsMap[event]].removeListener(l);\n return this;\n }\n }\n }\n if (nwWrapEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWrapEventsMap[event]].getListeners()) {\n if (l.listener && l.listener === callback) {\n this[nwWrapEventsMap[event]].removeListener(l);\n return this;\n }\n }\n }\n if (wrapEventsMapNewWin.hasOwnProperty(event)) {\n for (let l of chrome.windows[wrapEventsMapNewWin[event]].getListeners()) {\n if (l.listener && l.listener === callback) {\n chrome.windows[wrapEventsMapNewWin[event]].removeListener(l);\n return this;\n }\n }\n }\n return this;\n};\n\nNWWindow.prototype.removeAllListeners = function (event) {\n if (arguments.length === 0) {\n var obj = Object.assign({}, nwWinEventsMap, nwWrapEventsMap);\n var keys = Object.keys(obj);\n for (var i = 0, key; i < keys.length; ++i) {\n key = keys[i];\n this.removeAllListeners(key);\n }\n return this;\n }\n if (nwWinEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWinEventsMap[event]].getListeners()) {\n this[nwWinEventsMap[event]].removeListener(l);\n }\n return this;\n }\n if (nwWrapEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWrapEventsMap[event]].getListeners()) {\n this[nwWrapEventsMap[event]].removeListener(l);\n }\n return this;\n }\n if (wrapEventsMapNewWin.hasOwnProperty(event)) {\n for (let l of chrome.windows[wrapEventsMapNewWin[event]].getListeners()) {\n if (l.c_win_id === this.cWindow.id) {\n chrome.windows[wrapEventsMapNewWin[event]].removeListener(l);\n }\n }\n return this;\n }\n if (event === 'loaded') {\n for (let l of chrome.tabs.onUpdated.getListeners()) {\n if (l.c_win_id === this.cWindow.id) {\n chrome.tabs.onUpdated.removeListener(l);\n }\n }\n return this;\n }\n return this;\n};\n\nNWWindow.prototype.setShadow = function(shadow) {\n currentNWWindowInternal.setShadowInternal(shadow, this.cWindow.id);\n};\n\nNWWindow.prototype.setBadgeLabel = function(label) {\n currentNWWindowInternal.setBadgeLabelInternal(label, this.cWindow.id);\n};\n\nNWWindow.prototype.setProgressBar = function(progress) {\n currentNWWindowInternal.setProgressBarInternal(progress, this.cWindow.id);\n};\n\nNWWindow.prototype.setShowInTaskbar = function(show) {\n currentNWWindowInternal.setShowInTaskbarInternal(show, this.cWindow.id);\n};\n\nNWWindow.prototype.enterKioskMode = function() {\n currentNWWindowInternal.enterKioskModeInternal(this.cWindow.id);\n};\n\nNWWindow.prototype.leaveKioskMode = function() {\n currentNWWindowInternal.leaveKioskModeInternal(this.cWindow.id);\n};\n\nNWWindow.prototype.toggleKioskMode = function() {\n currentNWWindowInternal.toggleKioskModeInternal(this.cWindow.id);\n};\n\nNWWindow.prototype.showDevTools = function(frm, callback) {\n var id = '';\n if (typeof frm === 'string')\n id = frm;\n var f = null;\n if (id)\n f = this.window.getElementById(id);\n else\n f = frm || null;\n nwNatives.setDevToolsJail(f);\n currentNWWindowInternal.showDevTools2Internal(this.cWindow.id, callback);\n};\n\nNWWindow.prototype.capturePage = function (callback, options) {\n var cb = callback;\n if (!options)\n options = {'format':'jpeg', 'datatype':'datauri'};\n if (typeof options == 'string')\n options = {'format':options, 'datatype':'datauri'};\n if (options.datatype != 'datauri') {\n cb = function (format, datauri) {\n var raw = datauri.replace(/^data:[^;]*;base64,/, '');\n switch(format){\n case 'buffer' :\n callback(new nw.Buffer(raw, \"base64\"));\n break;\n case 'raw' :\n callback(raw);\n break;\n }\n };\n cb = cb.bind(undefined, options.datatype);\n }\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n currentNWWindowInternal.capturePageInternal(this.cWindow.id, options, cb);\n};\n\nfunction sendCommand(tabId, name, options) {\n return new Promise((resolve, reject) => {\n chrome.debugger.sendCommand({tabId: tabId}, name, options, (result) => {\n if (!result) {\n reject(chrome.runtime.lastError);\n return;\n }\n resolve(result);\n });\n });\n}\n\nfunction attach(tabId) {\n return new Promise((resolve, reject) => {\n chrome.debugger.attach({tabId: tabId}, \"1.0\", () => {\n if (chrome.runtime.lastError) {\n reject(chrome.runtime.lastError);\n return;\n }\n resolve();\n });\n });\n}\n\nfunction detach(tabId) {\n return new Promise((resolve, reject) => {\n chrome.debugger.detach({tabId: tabId}, () => {\n if (chrome.runtime.lastError) {\n reject(chrome.runtime.lastError);\n return;\n }\n resolve();\n });\n });\n}\n\nasync function captureScreenshotHelper(tabId, options) {\n await attach(tabId);\n let layoutMetrics = await sendCommand(tabId, \"Page.getLayoutMetrics\");\n if (options.fullSize) {\n const contentHeight = Math.min((1 << 14) / window.devicePixelRatio, layoutMetrics.contentSize.height);\n await sendCommand(tabId, \"Emulation.setDeviceMetricsOverride\",\n {deviceScaleFactor: 0, mobile: false,\n width: layoutMetrics.contentSize.width,\n height: Math.floor(contentHeight)});\n }\n let result = await sendCommand(tabId, \"Page.captureScreenshot\", options);\n if (options.fullSize)\n await sendCommand(tabId, \"Emulation.clearDeviceMetricsOverride\");\n await detach(tabId);\n return result.data;\n}\n\nNWWindow.prototype.captureScreenshot = function(options, cb) {\n let tab = this.cWindow.tabs[0].id;\n if (!cb)\n return captureScreenshotHelper(tab, options);\n captureScreenshotHelper(tab, options).then((data) => { cb(null, data); }).catch(cb);\n};\n\nNWWindow.prototype.reload = function () {\n chrome.tabs.reload(this.cWindow.tabs[0].id);\n};\nNWWindow.prototype.reloadIgnoringCache = function () {\n chrome.tabs.reload(this.cWindow.tabs[0].id, {'bypassCache': true});\n};\nNWWindow.prototype.eval = function (frame, script) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return nwNatives.evalScript(frame, script, this.cWindow.tabs[0].mainFrameId);\n};\nNWWindow.prototype.evalNWBin = function (frame, path) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n this.evalNWBinInternal(frame, path, null, this.cWindow.tabs[0].mainFrameId);\n};\nNWWindow.prototype.evalNWBinModule = function (frame, path, module_path) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n this.evalNWBinInternal(frame, path, module_path, this.cWindow.tabs[0].mainFrameId);\n};\nNWWindow.prototype.evalNWBinInternal = function (frame, path, module_path, main_frame_id) {\n var ab;\n if (Buffer.isBuffer(path)) {\n let buf = path;\n ab = new global.ArrayBuffer(path.length);\n path.copy(Buffer.from(ab));\n } else if ($Object.prototype.toString.apply(path) === '[object ArrayBuffer]') {\n ab = path;\n } else {\n let buf = global.require('fs').readFileSync(path);\n ab = new global.ArrayBuffer(buf.length);\n buf.copy(Buffer.from(ab));\n }\n return nwNatives.evalNWBin(frame, ab, module_path, main_frame_id);\n};\nNWWindow.prototype.show = function () {\n chrome.windows.update(this.cWindow.id, {'show': true});\n};\nNWWindow.prototype.hide = function () {\n chrome.windows.update(this.cWindow.id, {'state':'hidden'});\n};\nNWWindow.prototype.focus = function () {\n chrome.windows.update(this.cWindow.id, {'focused':true});\n};\nNWWindow.prototype.blur = function () {\n chrome.windows.update(this.cWindow.id, {'focused':false});\n};\nNWWindow.prototype.minimize = function () {\n chrome.windows.update(this.cWindow.id, {'state':'minimized'});\n};\nNWWindow.prototype.maximize = function () {\n chrome.windows.update(this.cWindow.id, {'state':\"maximized\"});\n};\nNWWindow.prototype.unmaximize = NWWindow.prototype.restore = function () {\n chrome.windows.update(this.cWindow.id, {'state':\"normal\"});\n};\nNWWindow.prototype.enterFullscreen = function () {\n chrome.windows.update(this.cWindow.id, {'state':\"fullscreen\"});\n};\nNWWindow.prototype.leaveFullscreen = function () {\n var self = this;\n chrome.windows.get(this.cWindow.id, {}, function(w) {\n self.cWindow = w;\n if (w.state === 'fullscreen')\n chrome.windows.update(w.id, {'state':\"normal\"});\n });\n};\n\nNWWindow.prototype.toggleFullscreen = function () {\n var self = this;\n chrome.windows.get(this.cWindow.id, {}, function(w) {\n self.cWindow = w;\n if (w.state === 'fullscreen')\n chrome.windows.update(w.id, {'state':\"normal\"});\n else\n self.enterFullscreen();\n });\n};\n\nNWWindow.prototype.setAlwaysOnTop = function (top) {\n chrome.windows.update(this.cWindow.id, {'alwaysOnTop': top});\n};\nNWWindow.prototype.setPosition = function (pos) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n if (pos == \"center\") {\n var screenWidth = screen.availWidth;\n var screenHeight = screen.availHeight;\n var width = this.cWindow.width;\n var height = this.cWindow.height;\n chrome.windows.update(this.cWindow.id, {'left': Math.round((screenWidth-width)/2),\n 'top': Math.round((screenHeight-height)/2)});\n } else if (pos == \"mouse\") {\n chrome.windows.update(this.cWindow.id, {'position': \"mouse\" });\n }\n};\nNWWindow.prototype.setVisibleOnAllWorkspaces = function(all_visible) {\n chrome.windows.update(this.cWindow.id, {'allVisible': all_visible});\n};\nNWWindow.prototype.canSetVisibleOnAllWorkspaces = function() {\n return canSetVisibleOnAllWorkspaces;\n};\nNWWindow.prototype.setMaximumSize = function (width, height) {\n chrome.windows.update(this.cWindow.id, {'maxWidth': width, 'maxHeight': height});\n};\nNWWindow.prototype.setMinimumSize = function (width, height) {\n //TODO: cover glass frame case in windows\n chrome.windows.update(this.cWindow.id, {'minWidth': width, 'minHeight': height});\n};\nNWWindow.prototype.resizeTo = function (width, height) {\n chrome.windows.update(this.cWindow.id, {'innerWidth': width, 'innerHeight': height});\n};\nNWWindow.prototype.setInnerWidth = function (width) {\n chrome.windows.update(this.cWindow.id, {'innerWidth': width});\n};\nNWWindow.prototype.setInnerHeight = function (height) {\n chrome.windows.update(this.cWindow.id, {'innerHeight': height});\n};\nNWWindow.prototype.resizeBy = function (width, height) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n chrome.windows.update(this.cWindow.id,\n {'width': this.cWindow.width + width,\n 'height': this.cWindow.height + height});\n};\nNWWindow.prototype.moveTo = function (x, y) {\n chrome.windows.update(this.cWindow.id, {'left': x, 'top': y});\n};\nNWWindow.prototype.moveBy = function (x, y) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n chrome.windows.update(this.cWindow.id,\n {'left': this.cWindow.left + x,\n 'top': this.cWindow.top + y});\n};\nNWWindow.prototype.setResizable = function (resizable) {\n chrome.windows.update(this.cWindow.id, {'resizable': resizable});\n};\nNWWindow.prototype.requestAttention = function (flash) {\n if (typeof flash == 'boolean')\n flash = flash ? -1 : 0;\n currentNWWindowInternal.requestAttentionInternal(flash);\n};\nNWWindow.prototype.cookies = chrome.cookies;\n\nNWWindow.prototype.print = function(option) {\n var _option = JSON.parse(JSON.stringify(option));\n if (!(\"autoprint\" in _option))\n _option[\"autoprint\"] = true;\n if (option.pdf_path)\n _option[\"printer\"] = \"Save as PDF\";\n currentNWWindowInternal.setPrintSettingsInternal(_option, this.cWindow.id);\n this.window.print();\n // autoprint will be set to false in print_preview_handler.cc after printing is done\n // window.print will return immediately for PDF window #5002\n};\nObject.defineProperty(NWWindow.prototype, 'x', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.left;\n },\n set: function(x) {\n chrome.windows.update(this.cWindow.id, {'left': x});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'y', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.top;\n },\n set: function(y) {\n chrome.windows.update(this.cWindow.id, {'top': y});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'width', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.width;\n },\n set: function(val) {\n chrome.windows.update(this.cWindow.id, {'width': val});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'height', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.height;\n },\n set: function(val) {\n chrome.windows.update(this.cWindow.id, {'height': val});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'title', {\n get: function() {\n return currentNWWindowInternal.getTitleInternal(this.cWindow.id);\n },\n set: function(val) {\n currentNWWindowInternal.setTitleInternal(val, this.cWindow.id);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'zoomLevel', {\n get: function() {\n return currentNWWindowInternal.getZoom(this.cWindow.id);\n },\n set: function(val) {\n currentNWWindowInternal.setZoom(val, this.cWindow.id);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isTransparent', {\n get: function() {\n return this.appWindow.alphaEnabled();\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isKioskMode', {\n get: function() {\n return currentNWWindowInternal.isKioskInternal(this.cWindow.id);\n },\n set: function(val) {\n if (val)\n currentNWWindowInternal.enterKioskModeInternal(this.cWindow.id);\n else\n currentNWWindowInternal.leaveKioskModeInternal(this.cWindow.id);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isFullscreen', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.state === 'fullscreen';\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isAlwaysOnTop', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.alwaysOnTop;\n }\n});\nObject.defineProperty(NWWindow.prototype, 'menu', {\n get: function() {\n var ret = privates(this).menu || {};\n return ret;\n },\n set: function(menu) {\n if(!menu) {\n privates(this).menu = null;\n currentNWWindowInternal.clearMenu(this.cWindow.id);\n return;\n }\n if (menu.type != 'menubar')\n throw new TypeError('Only menu of type \"menubar\" can be used as this.window menu');\n\n privates(this).menu = menu;\n var menuPatch = currentNWWindowInternal.setMenu(menu.id, this.cWindow.id);\n if (menuPatch.length) {\n menuPatch.forEach((patch)=>{\n let menuIndex = patch.menu;\n let itemIndex = patch.index;\n let menuToPatch = menu.items[menuIndex];\n if (menuToPatch && menuToPatch.submenu) {\n menuToPatch.submenu.insert(new nw.MenuItem(patch.option), itemIndex);\n }\n });\n }\n }\n});\nObject.defineProperty(NWWindow.prototype, 'window', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return appWindowNatives.GetFrame(this.cWindow.tabs[0].mainFrameId, false);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'frameId', {\n get: function() {\n return currentRoutingID;\n }\n});\n\napiBridge.registerCustomHook(function(bindingsAPI) {\n var apiFunctions = bindingsAPI.apiFunctions;\n currentNWWindowInternal = getInternalApi('nw.currentWindowInternal');\n forEach(currentNWWindowInternal, function(key, value) {\n if (!key.endsWith('Internal') && key !== 'close')\n NWWindow.prototype[key] = value;\n });\n apiFunctions.setHandleRequest('get', function(domWindow) {\n if (domWindow)\n return try_nw(domWindow.top).nw.Window.get();\n if (currentNWWindow)\n return currentNWWindow;\n\n currentNWWindow = new NWWindow;\n return currentNWWindow;\n });\n\n apiFunctions.setHandleRequest('getAll', function(callback) {\n chrome.windows.getAll({populate: true}, function (cwindows) {\n let create_nw_win = cwin => new NWWindow(cwin);\n callback(cwindows.map(create_nw_win));\n });\n });\n\n apiFunctions.setHandleRequest('open', function(url, params, callback) {\n var options = {'url': url, 'setSelfAsOpener': true, 'type': 'popup'};\n //FIXME: unify this conversion code with nwjs/default.js\n if (params) {\n if (params.frame === false)\n options.frameless = true;\n if (params.resizable === false)\n options.resizable = false;\n if (params.focus === false)\n options.focused = false;\n if (params.x)\n options.left = params.x;\n if (params.y)\n options.top = params.y;\n if (params.height)\n options.height = params.height;\n if (params.width)\n options.width = params.width;\n if (params.min_width)\n options.minWidth = params.min_width;\n if (params.max_width)\n options.maxWidth = params.max_width;\n if (params.min_height)\n options.minHeight = params.min_height;\n if (params.max_height)\n options.maxHeight = params.max_height;\n if (params.fullscreen === true)\n options.state = 'fullscreen';\n if (params.show === false)\n options.hidden = true;\n if (params.show_in_taskbar === false)\n options.showInTaskbar = false;\n if (params['always_on_top'] === true)\n options.alwaysOnTop = true;\n if (params['visible_on_all_workspaces'] === true)\n options.allVisible = true;\n if (typeof params['inject_js_start'] == 'string')\n options.inject_js_start = params['inject_js_start'];\n if (typeof params['inject_js_end'] == 'string')\n options.inject_js_end = params['inject_js_end'];\n if (params.transparent)\n options.alphaEnabled = true;\n // if (params.kiosk === true)\n // options.kiosk = true;\n if (params.new_instance === true) {\n options.new_instance = true;\n options.setSelfAsOpener = false;\n }\n if (params.position)\n options.position = params.position;\n if (params.title)\n options.title = params.title;\n if (params.icon)\n options.icon = params.icon;\n if (params.id)\n options.id = params.id;\n }\n if (callback && !(options.new_instance === true))\n options.block_parser = true;\n try_hidden(window).chrome.windows.create(options, function(cWin) {\n try {\n if (callback) {\n if (cWin)\n callback(new NWWindow(cWin));\n else\n callback();\n }\n } finally {\n if (options.block_parser)\n appWindowNatives.ResumeParser(cWin.tabs[0].mainFrameId);\n }\n });\n });\n\n});\n\nfunction dispatchEventIfExists(target, name, varargs) {\n // Sometimes apps like to put their own properties on the window which\n // break our assumptions.\n var event = target[name];\n if (event && (typeof event.dispatch == 'function'))\n $Function.apply(event.dispatch, event, varargs);\n else\n console.warn('Could not dispatch ' + name + ', event has been clobbered');\n}\n\nfunction onNewWinPolicy(frame, url, policy, top_routing_id) {\n //console.log(\"onNewWinPolicy called: \" + url + \", \" + policy);\n dispatchEventIfExists(NWWindow.prototype, \"onNewWinPolicy\", [frame, url, policy, top_routing_id]);\n}\n\nfunction onNavigation(frame, url, policy, top_routing_id, context) {\n //console.log(\"onNavigation called: \" + url + \", \" + context);\n dispatchEventIfExists(NWWindow.prototype, \"onNavigation\", [frame, url, policy, context, top_routing_id]);\n}\n\nfunction onLoadingStateChanged(status) {\n //console.log(\"onLoadingStateChanged: \" + status);\n if (!currentNWWindow)\n return;\n dispatchEventIfExists(currentNWWindow, \"LoadingStateChanged\", [status]);\n}\n\nfunction onDocumentStartEnd(start, frame, top_routing_id) {\n //console.log(`---> onDocumentStartEnd ${start} ${top_routing_id}`);\n if (start) {\n dispatchEventIfExists(NWWindow.prototype, \"onDocumentStart\", [frame, top_routing_id]);\n }\n else\n dispatchEventIfExists(NWWindow.prototype, \"onDocumentEnd\", [frame, top_routing_id]);\n}\n\nfunction updateAppWindowZoom(old_level, new_level) {\n if (!currentNWWindow)\n return;\n dispatchEventIfExists(currentNWWindow, \"onZoom\", [new_level]);\n}\n\nfunction onClose(user_force) {\n if (!currentNWWindow)\n return;\n currentNWWindow.onClose.dispatchNW({instanceId: currentWidgetRoutingID}, user_force);\n}\n\nfunction get_nw() {\n appWindowNatives.FixGamePadAPI();\n var nw0 = try_nw(window).nw;\n if (nw0)\n nw0.Window.get();\n}\n\n//if (bgPage !== window) {\n// renderFrameObserverNatives.OnDocumentElementCreated(currentRoutingID, get_nw);\n//}\n\nexports.onNewWinPolicy = onNewWinPolicy;\nexports.onNavigation = onNavigation;\nexports.LoadingStateChanged = onLoadingStateChanged;\nexports.onDocumentStartEnd = onDocumentStartEnd;\nexports.onClose = onClose;\nexports.updateAppWindowZoom = updateAppWindowZoom;\n", "file_path": "src/resources/api_nw_newwin.js", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0008019846864044666, 0.00019176906789653003, 0.00016287628386635333, 0.0001707840128801763, 8.861416426952928e-05]} {"hunk": {"id": 5, "code_window": [" bool nwjs_guest_nw = command_line.HasSwitch(\"nwjs-guest-nw\");\n", "\n", " if (extension)\n", " extension->manifest()->GetBoolean(manifest_keys::kNWJSMixedContext, &mixed_context);\n", " // handle navigation in webview #5622\n", " if (nwjs_guest_nw)\n", " mixed_context = true;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" if (!mixed_context) {\n", " mixed_context = command_line.HasSwitch(\"mixed-context\");\n", " }\n"], "file_path": "src/renderer/nw_extensions_renderer_hooks.cc", "type": "add", "edit_start_line_idx": 221}, "file": "// Copyright (c) 2012 Intel Corp\n// Copyright (c) 2012 The Chromium Authors\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy \n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co\n// pies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in al\n// l copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM\n// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES\n// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH\n// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n#include \"content/nw/src/renderer/autofill_agent.h\"\n\n#include \"base/bind.h\"\n#include \"base/message_loop/message_loop.h\"\n#include \"base/strings/string_util.h\"\n#include \"base/strings/string_split.h\"\n#include \"content/public/renderer/render_view.h\"\n#include \"third_party/WebKit/public/web/WebInputEvent.h\"\n#include \"third_party/WebKit/public/web/WebNode.h\"\n#include \"third_party/WebKit/public/web/WebNodeCollection.h\"\n#include \"third_party/WebKit/public/web/WebOptionElement.h\"\n#include \"third_party/WebKit/public/web/WebView.h\"\n#include \"ui/events/keycodes/keyboard_codes.h\"\n\nusing WebKit::WebAutofillClient;\nusing WebKit::WebFormElement;\nusing WebKit::WebFrame;\nusing WebKit::WebInputElement;\nusing WebKit::WebKeyboardEvent;\nusing WebKit::WebNode;\nusing WebKit::WebNodeCollection;\nusing WebKit::WebOptionElement;\nusing WebKit::WebString;\n\nnamespace nw {\n\nnamespace {\n\n// The size above which we stop triggering autofill for an input text field\n// (so to avoid sending long strings through IPC).\nconst size_t kMaximumTextSizeForAutofill = 1000;\n\nvoid AppendDataListSuggestions(const WebKit::WebInputElement& element,\n std::vector* values,\n std::vector* labels,\n std::vector* icons,\n std::vector* item_ids) {\n WebNodeCollection options = element.dataListOptions();\n if (options.isNull())\n return;\n\n string16 prefix = element.editingValue();\n if (element.isMultiple() &&\n element.formControlType() == WebString::fromUTF8(\"email\")) {\n std::vector parts;\n base::SplitStringDontTrim(prefix, ',', &parts);\n if (parts.size() > 0)\n TrimWhitespace(parts[parts.size() - 1], TRIM_LEADING, &prefix);\n }\n for (WebOptionElement option = options.firstItem().to();\n !option.isNull(); option = options.nextItem().to()) {\n if (!StartsWith(option.value(), prefix, false) ||\n option.value() == prefix ||\n !element.isValidValue(option.value()))\n continue;\n\n values->push_back(option.value());\n if (option.value() != option.label())\n labels->push_back(option.label());\n else\n labels->push_back(string16());\n icons->push_back(string16());\n item_ids->push_back(WebAutofillClient::MenuItemIDDataListEntry);\n }\n}\n\n} // namespace\n\nAutofillAgent::AutofillAgent(content::RenderView* render_view)\n : content::RenderViewObserver(render_view),\n weak_ptr_factory_(this) {\n render_view->GetWebView()->setAutofillClient(this);\n}\n\nAutofillAgent::~AutofillAgent() {\n}\n\nvoid AutofillAgent::InputElementClicked(const WebInputElement& element,\n bool was_focused,\n bool is_focused) {\n if (was_focused)\n ShowSuggestions(element, true, false, true);\n\n}\n\nvoid AutofillAgent::InputElementLostFocus() {\n}\n\nvoid AutofillAgent::didAcceptAutofillSuggestion(const WebNode& node,\n const WebString& value,\n const WebString& label,\n int item_id,\n unsigned index) {\n DCHECK(node == element_);\n\n switch (item_id) {\n case WebAutofillClient::MenuItemIDAutocompleteEntry:\n case WebAutofillClient::MenuItemIDPasswordEntry:\n // User selected an Autocomplete or password entry, so we fill directly.\n SetNodeText(value, &element_);\n break;\n case WebAutofillClient::MenuItemIDDataListEntry:\n AcceptDataListSuggestion(value);\n break;\n }\n}\n\nvoid AutofillAgent::didSelectAutofillSuggestion(const WebNode& node,\n const WebString& value,\n const WebString& label,\n int item_id) {\n didClearAutofillSelection(node);\n}\n\nvoid AutofillAgent::didClearAutofillSelection(const WebNode& node) {\n}\n\nvoid AutofillAgent::removeAutocompleteSuggestion(const WebString& name,\n const WebString& value) {\n}\n\nvoid AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {\n}\n\nvoid AutofillAgent::textFieldDidChange(const WebInputElement& element) {\n if (did_set_node_text_) {\n did_set_node_text_ = false;\n return;\n }\n\n // We post a task for doing the Autofill as the caret position is not set\n // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and\n // it is needed to trigger autofill.\n weak_ptr_factory_.InvalidateWeakPtrs();\n base::MessageLoop::current()->PostTask(\n FROM_HERE,\n base::Bind(&AutofillAgent::TextFieldDidChangeImpl,\n weak_ptr_factory_.GetWeakPtr(), element));\n}\n\nvoid AutofillAgent::TextFieldDidChangeImpl(const WebInputElement& element) {\n ShowSuggestions(element, false, true, false);\n}\n\nvoid AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,\n const WebKeyboardEvent& event) {\n if (event.windowsKeyCode == ui::VKEY_DOWN ||\n event.windowsKeyCode == ui::VKEY_UP)\n ShowSuggestions(element, true, true, true);\n}\n\nvoid AutofillAgent::ShowSuggestions(const WebInputElement& element,\n bool autofill_on_empty_values,\n bool requires_caret_at_end,\n bool display_warning_if_disabled) {\n if (!element.isEnabled() || element.isReadOnly() || !element.isTextField() ||\n element.isPasswordField() || !element.suggestedValue().isEmpty())\n return;\n\n // Don't attempt to autofill with values that are too large or if filling\n // criteria are not met.\n WebString value = element.editingValue();\n if (value.length() > kMaximumTextSizeForAutofill ||\n (!autofill_on_empty_values && value.isEmpty()) ||\n (requires_caret_at_end &&\n (element.selectionStart() != element.selectionEnd() ||\n element.selectionEnd() != static_cast(value.length())))) {\n // Any popup currently showing is obsolete.\n WebKit::WebView* web_view = render_view()->GetWebView();\n if (web_view)\n web_view->hidePopups();\n\n return;\n }\n\n element_ = element;\n\n // TODO: Currently node-webkit didn't support HTML5 attribute |autocomplete|\n // of the |input|.\n std::vector v;\n std::vector l;\n std::vector i;\n std::vector ids;\n AppendDataListSuggestions(element, &v, &l, &i, &ids);\n\n WebKit::WebView* web_view = render_view()->GetWebView();\n if (!web_view)\n return;\n\n if (v.empty()) {\n // No suggestions, any popup currently showing is obsolete.\n web_view->hidePopups();\n return;\n }\n\n // Send to WebKit for display.\n web_view->applyAutofillSuggestions(element, v, l, i, ids);\n}\n\nvoid AutofillAgent::AcceptDataListSuggestion(const string16& suggested_value) {\n string16 new_value = suggested_value;\n // If this element takes multiple values then replace the last part with\n // the suggestion.\n if (element_.isMultiple() &&\n element_.formControlType() == WebString::fromUTF8(\"email\")) {\n std::vector parts;\n\n base::SplitStringDontTrim(element_.editingValue(), ',', &parts);\n if (parts.size() == 0)\n parts.push_back(string16());\n\n string16 last_part = parts.back();\n // We want to keep just the leading whitespace.\n for (size_t i = 0; i < last_part.size(); ++i) {\n if (!IsWhitespace(last_part[i])) {\n last_part = last_part.substr(0, i);\n break;\n }\n }\n last_part.append(suggested_value);\n parts[parts.size() - 1] = last_part;\n\n new_value = JoinString(parts, ',');\n }\n SetNodeText(new_value, &element_);\n}\n\nvoid AutofillAgent::SetNodeText(const string16& value,\n WebKit::WebInputElement* node) {\n did_set_node_text_ = true;\n string16 substring = value;\n substring = substring.substr(0, node->maxLength());\n\n node->setEditingValue(substring);\n}\n \n} // namespace nw\n", "file_path": "src/renderer/autofill_agent.cc", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.0005176534759812057, 0.00018614629516378045, 0.00016589304141234607, 0.00017343307263217866, 6.648863200098276e-05]} {"hunk": {"id": 5, "code_window": [" bool nwjs_guest_nw = command_line.HasSwitch(\"nwjs-guest-nw\");\n", "\n", " if (extension)\n", " extension->manifest()->GetBoolean(manifest_keys::kNWJSMixedContext, &mixed_context);\n", " // handle navigation in webview #5622\n", " if (nwjs_guest_nw)\n", " mixed_context = true;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" if (!mixed_context) {\n", " mixed_context = command_line.HasSwitch(\"mixed-context\");\n", " }\n"], "file_path": "src/renderer/nw_extensions_renderer_hooks.cc", "type": "add", "edit_start_line_idx": 221}, "file": "\n\n\nModifica\nFinestra\nInformazioni su \nNascondi \nNascondi altre\nMostra tutte\nEsci da \nAnnulla\nRipeti\nTaglia\nCopia\nIncolla\nElimina\nSeleziona tutto\nRiduci a icona\nRiduci a icona\nChiudi finestra\nPorta tutto in primo piano\n\n", "file_path": "src/resources/locale/nw_strings_it.xtb", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017214525723829865, 0.00017065128486137837, 0.0001694441889412701, 0.00017036436474882066, 1.1212132449145429e-06]} {"hunk": {"id": 5, "code_window": [" bool nwjs_guest_nw = command_line.HasSwitch(\"nwjs-guest-nw\");\n", "\n", " if (extension)\n", " extension->manifest()->GetBoolean(manifest_keys::kNWJSMixedContext, &mixed_context);\n", " // handle navigation in webview #5622\n", " if (nwjs_guest_nw)\n", " mixed_context = true;\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" if (!mixed_context) {\n", " mixed_context = command_line.HasSwitch(\"mixed-context\");\n", " }\n"], "file_path": "src/renderer/nw_extensions_renderer_hooks.cc", "type": "add", "edit_start_line_idx": 221}, "file": "/******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n\n\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ function(module, exports) {\n\n\t/**\n\t * Copyright (c) 2015-present, Facebook, Inc.\n\t * All rights reserved.\n\t *\n\t * This source code is licensed under the BSD-style license found in the\n\t * LICENSE file in the root directory of this source tree. An additional grant\n\t * of patent rights can be found in the PATENTS file in the same directory.\n\t *\n\t * \n\t */\n\t'use strict';\n\n\t/* global chrome */\n\n\t// proxy from main page to devtools (via the background page)\n\n\tvar port = chrome.runtime.connect({\n\t name: 'content-script'\n\t});\n\n\tport.onMessage.addListener(handleMessageFromDevtools);\n\tport.onDisconnect.addListener(handleDisconnect);\n\twindow.addEventListener('message', handleMessageFromPage);\n\n\twindow.postMessage({\n\t source: 'react-devtools-content-script',\n\t hello: true\n\t}, '*');\n\n\tfunction handleMessageFromDevtools(message) {\n\t window.postMessage({\n\t source: 'react-devtools-content-script',\n\t payload: message\n\t }, '*');\n\t}\n\n\tfunction handleMessageFromPage(evt) {\n\t if (evt.data && evt.data.source === 'react-devtools-bridge') {\n\t // console.log('page -> rep -> dev', evt.data);\n\t port.postMessage(evt.data.payload);\n\t }\n\t}\n\n\tfunction handleDisconnect() {\n\t window.removeEventListener('message', handleMessageFromPage);\n\t window.postMessage({\n\t source: 'react-devtools-content-script',\n\t payload: {\n\t type: 'event',\n\t evt: 'shutdown'\n\t }\n\t }, '*');\n\t}\n\n/***/ }\n/******/ ]);", "file_path": "test/sanity/react-devtools-extension/react-devtools/build/contentScript.js", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017738145834300667, 0.0001740520674502477, 0.00017127829778473824, 0.00017417242634110153, 1.5540806543867802e-06]} {"hunk": {"id": 6, "code_window": [" if (params.new_instance === true) {\n", " options.new_instance = true;\n", " options.setSelfAsOpener = false;\n", " }\n", " if (params.position)\n", " options.position = params.position;\n", " if (params.title)\n", " options.title = params.title;\n", " if (params.icon)\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" if (params.mixed_context === true) {\n", " if (params.new_instance !== true) {\n", " throw new Error('mixed_context should be set with new_instance in nw.Window.open');\n", " }\n", " options.mixed_context = true;\n", " }\n"], "file_path": "src/resources/api_nw_newwin.js", "type": "add", "edit_start_line_idx": 811}, "file": "var nwNatives = requireNative('nw_natives');\nvar forEach = require('utils').forEach;\nvar runtimeNatives = requireNative('runtime');\nvar renderFrameObserverNatives = requireNative('renderFrameObserverNatives');\nvar appWindowNatives = requireNative('app_window_natives');\n\nvar GetExtensionViews = runtimeNatives.GetExtensionViews;\n\nvar currentNWWindow = null;\nvar currentNWWindowInternal = null;\nvar currentRoutingID = nwNatives.getRoutingID();\nvar currentWidgetRoutingID = nwNatives.getWidgetRoutingID();\n\nvar bgPage = GetExtensionViews(-1, -1, 'BACKGROUND')[0];\n\nvar try_hidden = function (view) {\n if (view.chrome.windows)\n return view;\n return privates(view);\n};\n\nvar try_nw = function (view) {\n if (view.nw)\n return view;\n return privates(view);\n};\n\nfunction getPlatform() {\n var platforms = [\n [/CrOS Touch/, \"chromeos touch\"],\n [/CrOS/, \"chromeos\"],\n [/Linux/, \"linux\"],\n [/Mac/, \"mac\"],\n [/Win/, \"win\"],\n ];\n\n for (var i = 0; i < platforms.length; i++) {\n if ($RegExp.exec(platforms[i][0], navigator.appVersion)) {\n return platforms[i][1];\n }\n }\n return \"unknown\";\n}\n\nvar canSetVisibleOnAllWorkspaces = /(mac|linux)/.exec(getPlatform());\n\nvar nwWinEventsMap = {\n 'minimize': 'onMinimized',\n 'maximize': 'onMaximized',\n 'restore': 'onRestore',\n 'enter-fullscreen': 'onFullscreen',\n 'zoom': 'onZoom',\n 'resize': 'onResized'\n};\n\nvar nwWrapEventsMap = {\n 'new-win-policy': 'onNewWinPolicy',\n 'navigation': 'onNavigation'\n};\n\nvar wrapEventsMapNewWin = {\n 'move': 'onMove',\n 'focus': 'onFocusChanged',\n 'blur': 'onFocusChanged',\n 'closed': 'onRemoved',\n 'close': 'onRemoving'\n};\n\nfunction NWWindow(cWindow) {\n var self = this;\n if (cWindow) {\n this.cWindow = cWindow;\n //console.log(`---> NWWindow: ${this.cWindow.id}`);\n } else {\n this.cWindow = currentNWWindowInternal.getCurrent(-2, {'populate': true});\n //console.log(`---> NWWindow: ${this.cWindow.id}`);\n if (!this.cWindow)\n console.error('The JavaScript context calling ' +\n 'nw.Window.get() has no associated Browser window.');\n }\n\n function updateWindowAttributes(w) {\n if (w.id !== self.cWindow.id)\n return;\n var oldState = self.cWindow.state;\n var oldWidth = self.cWindow.width;\n var oldHeight = self.cWindow.height;\n\n self.cWindow.state = w.state;\n self.cWindow.width = w.width;\n self.cWindow.height = w.height;\n\n if (oldState != 'minimized' && w.state == 'minimized') {\n dispatchEventIfExists(self, 'onMinimized', [w.id]);\n } else if (oldState != 'maximized' && w.state == 'maximized') {\n dispatchEventIfExists(self, 'onMaximized', [w.id]);\n } else if (oldState != 'fullscreen' && w.state == 'fullscreen') {\n dispatchEventIfExists(self, 'onFullscreen', [w.id]);\n } else if (oldState != 'normal' && w.state == 'normal') {\n dispatchEventIfExists(self, 'onRestore', [w.id]);\n } else if (oldWidth != w.width || oldHeight != w.height) {\n dispatchEventIfExists(self, 'onResized', [w.id, w.width, w.height]);\n }\n }\n privates(this).menu = null;\n chrome.windows.onWindowChanged.addListener(updateWindowAttributes);\n}\n\nNWWindow.prototype.onNewWinPolicy = bindingUtil.createCustomEvent(\"nw.Window.onNewWinPolicy\", false, false);\nNWWindow.prototype.onNavigation = bindingUtil.createCustomEvent(\"nw.Window.onNavigation\", false, false);\nNWWindow.prototype.LoadingStateChanged = bindingUtil.createCustomEvent(\"nw.Window.LoadingStateChanged\", false, false);\nNWWindow.prototype.onDocumentStart = bindingUtil.createCustomEvent(\"nw.Window.onDocumentStart\", false, false);\nNWWindow.prototype.onDocumentEnd = bindingUtil.createCustomEvent(\"nw.Window.onDocumentEnd\", false, false);\nNWWindow.prototype.onZoom = bindingUtil.createCustomEvent(\"nw.Window.onZoom\", false, false);\nNWWindow.prototype.onClose = bindingUtil.createCustomEvent(\"nw.Window.onClose\", true, false);\nNWWindow.prototype.onMinimized = bindingUtil.createCustomEvent(\"nw.Window.onMinimized\", false, false);\nNWWindow.prototype.onMaximized = bindingUtil.createCustomEvent(\"nw.Window.onMaximized\", false, false);\nNWWindow.prototype.onFullscreen = bindingUtil.createCustomEvent(\"nw.Window.onFullscreen\", false, false);\nNWWindow.prototype.onResized = bindingUtil.createCustomEvent(\"nw.Window.onResized\", false, false);\nNWWindow.prototype.onRestore = bindingUtil.createCustomEvent(\"nw.Window.onRestore\", false, false);\n\nNWWindow.prototype.close = function (force) {\n //console.log(`---> NWWindow.close: ${force} ${this.cWindow.id}`);\n currentNWWindowInternal.close(force, this.cWindow.id);\n}\n\nNWWindow.prototype.once = function (event, listener, record) {\n if (typeof listener !== 'function')\n throw new TypeError('listener must be a function');\n var fired = false;\n var self = this;\n\n function g() {\n self.removeListener(event, g);\n if (!fired) {\n fired = true;\n listener.apply(self, arguments);\n }\n }\n this.on(event, g, false);\n return this;\n};\n\nNWWindow.prototype.on = function (event, callback, record) {\n var self = this;\n\n // Wrap callback to bind to `self`.\n // If `cb` is given, use `cb` instead of original `callback`.\n function wrap(cb) {\n var fn = (cb || callback).bind(self);\n fn.listener = callback;\n fn.c_win_id = self.cWindow.id;\n callback.__nw_cb = fn;\n return fn;\n }\n\n if (event === 'close') {\n var cbc = wrap(function(windowId, flag) {\n if (self.cWindow.id !== windowId)\n return;\n callback.call(self, flag);\n });\n chrome.windows.onRemoving.addListener(cbc, {instanceId: self.cWindow.id});\n return this;\n }\n switch (event) {\n case 'focus':\n var cbf = wrap(function(windowId) {\n if (self.cWindow.id !== windowId)\n return;\n callback.call(self);\n });\n chrome.windows.onFocusChanged.addListener(cbf);\n break;\n case 'blur':\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n var cbf = wrap(function(windowId) {\n if (self.cWindow.id === windowId) {\n callback.__nw_cb.focused = true;\n return;\n }\n if (!callback.__nw_cb.focused)\n return;\n callback.__nw_cb.focused = false;\n callback.call(self);\n });\n chrome.windows.onFocusChanged.addListener(cbf);\n break;\n case 'closed':\n var cbr = wrap(function(windowId) {\n if (self.cWindow.id !== windowId)\n return;\n callback.call(self);\n });\n chrome.windows.onRemoved.addListener(cbr);\n break;\n case 'loaded':\n var g = wrap(function(tabId, changeInfo, tab) {\n if (tab.windowId !== self.cWindow.id)\n return;\n if ('nwstatus' in changeInfo && changeInfo.nwstatus == 'complete')\n callback.call(self);\n });\n chrome.tabs.onUpdated.addListener(g);\n break;\n case 'document-start':\n var cb1 = wrap(function(frame, top_routing_id) {\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n callback.call(self, frame);\n });\n this.onDocumentStart.addListener(cb1);\n break;\n case 'document-end':\n var cb0 = wrap(function(frame, top_routing_id) {\n //console.log(\"document-end: cWindow: \" + self.cWindow.id + \"; top routing id: \" + top_routing_id + \"; main frame id: \" + self.cWindow.tabs[0].mainFrameId);\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n callback.call(self, frame);\n });\n this.onDocumentEnd.addListener(cb0);\n break;\n case 'new-win-policy':\n var h = wrap(function(frame, url, policy, top_routing_id) {\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n policy.ignore = function () { this.val = 'ignore'; };\n policy.forceCurrent = function () { this.val = 'current'; };\n policy.forceDownload = function () { this.val = 'download'; };\n policy.forceNewWindow = function () { this.val = 'new-window'; };\n policy.forceNewPopup = function () { this.val = 'new-popup'; };\n policy.setNewWindowManifest = function (m) { this.manifest = m; };\n callback.call(self, frame, url, policy);\n });\n this.onNewWinPolicy.addListener(h);\n break;\n case 'navigation':\n var j = wrap(function(frame, url, policy, context, top_routing_id) {\n if (top_routing_id !== self.cWindow.tabs[0].mainFrameId)\n return;\n policy.ignore = function () { this.val = 'ignore'; };\n callback.call(self, frame, url, policy, context);\n });\n this.onNavigation.addListener(j);\n break;\n case 'move':\n var k = wrap(function(w) {\n if (w.id != self.cWindow.id)\n return;\n callback.call(self, w.left, w.top);\n });\n chrome.windows.onMove.addListener(k);\n return this; //return early\n break;\n }\n if (nwWinEventsMap.hasOwnProperty(event)) {\n let cb = wrap(function(id, ...args) {\n if (id != self.cWindow.id)\n return;\n callback.call(self, ...args);\n });\n this[nwWinEventsMap[event]].addListener(cb);\n return this;\n }\n return this;\n};\nNWWindow.prototype.removeListener = function (event, callback) {\n if (event === 'loaded') {\n for (let l of chrome.tabs.onUpdated.getListeners()) {\n if (l.listener && l.listener === callback) {\n chrome.tabs.onUpdated.removeListener(l);\n return this;\n }\n }\n }\n if (nwWinEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWinEventsMap[event]].getListeners()) {\n if (l.listener && l.listener === callback) {\n this[nwWinEventsMap[event]].removeListener(l);\n return this;\n }\n }\n }\n if (nwWrapEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWrapEventsMap[event]].getListeners()) {\n if (l.listener && l.listener === callback) {\n this[nwWrapEventsMap[event]].removeListener(l);\n return this;\n }\n }\n }\n if (wrapEventsMapNewWin.hasOwnProperty(event)) {\n for (let l of chrome.windows[wrapEventsMapNewWin[event]].getListeners()) {\n if (l.listener && l.listener === callback) {\n chrome.windows[wrapEventsMapNewWin[event]].removeListener(l);\n return this;\n }\n }\n }\n return this;\n};\n\nNWWindow.prototype.removeAllListeners = function (event) {\n if (arguments.length === 0) {\n var obj = Object.assign({}, nwWinEventsMap, nwWrapEventsMap);\n var keys = Object.keys(obj);\n for (var i = 0, key; i < keys.length; ++i) {\n key = keys[i];\n this.removeAllListeners(key);\n }\n return this;\n }\n if (nwWinEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWinEventsMap[event]].getListeners()) {\n this[nwWinEventsMap[event]].removeListener(l);\n }\n return this;\n }\n if (nwWrapEventsMap.hasOwnProperty(event)) {\n for (let l of this[nwWrapEventsMap[event]].getListeners()) {\n this[nwWrapEventsMap[event]].removeListener(l);\n }\n return this;\n }\n if (wrapEventsMapNewWin.hasOwnProperty(event)) {\n for (let l of chrome.windows[wrapEventsMapNewWin[event]].getListeners()) {\n if (l.c_win_id === this.cWindow.id) {\n chrome.windows[wrapEventsMapNewWin[event]].removeListener(l);\n }\n }\n return this;\n }\n if (event === 'loaded') {\n for (let l of chrome.tabs.onUpdated.getListeners()) {\n if (l.c_win_id === this.cWindow.id) {\n chrome.tabs.onUpdated.removeListener(l);\n }\n }\n return this;\n }\n return this;\n};\n\nNWWindow.prototype.setShadow = function(shadow) {\n currentNWWindowInternal.setShadowInternal(shadow, this.cWindow.id);\n};\n\nNWWindow.prototype.setBadgeLabel = function(label) {\n currentNWWindowInternal.setBadgeLabelInternal(label, this.cWindow.id);\n};\n\nNWWindow.prototype.setProgressBar = function(progress) {\n currentNWWindowInternal.setProgressBarInternal(progress, this.cWindow.id);\n};\n\nNWWindow.prototype.setShowInTaskbar = function(show) {\n currentNWWindowInternal.setShowInTaskbarInternal(show, this.cWindow.id);\n};\n\nNWWindow.prototype.enterKioskMode = function() {\n currentNWWindowInternal.enterKioskModeInternal(this.cWindow.id);\n};\n\nNWWindow.prototype.leaveKioskMode = function() {\n currentNWWindowInternal.leaveKioskModeInternal(this.cWindow.id);\n};\n\nNWWindow.prototype.toggleKioskMode = function() {\n currentNWWindowInternal.toggleKioskModeInternal(this.cWindow.id);\n};\n\nNWWindow.prototype.showDevTools = function(frm, callback) {\n var id = '';\n if (typeof frm === 'string')\n id = frm;\n var f = null;\n if (id)\n f = this.window.getElementById(id);\n else\n f = frm || null;\n nwNatives.setDevToolsJail(f);\n currentNWWindowInternal.showDevTools2Internal(this.cWindow.id, callback);\n};\n\nNWWindow.prototype.capturePage = function (callback, options) {\n var cb = callback;\n if (!options)\n options = {'format':'jpeg', 'datatype':'datauri'};\n if (typeof options == 'string')\n options = {'format':options, 'datatype':'datauri'};\n if (options.datatype != 'datauri') {\n cb = function (format, datauri) {\n var raw = datauri.replace(/^data:[^;]*;base64,/, '');\n switch(format){\n case 'buffer' :\n callback(new nw.Buffer(raw, \"base64\"));\n break;\n case 'raw' :\n callback(raw);\n break;\n }\n };\n cb = cb.bind(undefined, options.datatype);\n }\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n currentNWWindowInternal.capturePageInternal(this.cWindow.id, options, cb);\n};\n\nfunction sendCommand(tabId, name, options) {\n return new Promise((resolve, reject) => {\n chrome.debugger.sendCommand({tabId: tabId}, name, options, (result) => {\n if (!result) {\n reject(chrome.runtime.lastError);\n return;\n }\n resolve(result);\n });\n });\n}\n\nfunction attach(tabId) {\n return new Promise((resolve, reject) => {\n chrome.debugger.attach({tabId: tabId}, \"1.0\", () => {\n if (chrome.runtime.lastError) {\n reject(chrome.runtime.lastError);\n return;\n }\n resolve();\n });\n });\n}\n\nfunction detach(tabId) {\n return new Promise((resolve, reject) => {\n chrome.debugger.detach({tabId: tabId}, () => {\n if (chrome.runtime.lastError) {\n reject(chrome.runtime.lastError);\n return;\n }\n resolve();\n });\n });\n}\n\nasync function captureScreenshotHelper(tabId, options) {\n await attach(tabId);\n let layoutMetrics = await sendCommand(tabId, \"Page.getLayoutMetrics\");\n if (options.fullSize) {\n const contentHeight = Math.min((1 << 14) / window.devicePixelRatio, layoutMetrics.contentSize.height);\n await sendCommand(tabId, \"Emulation.setDeviceMetricsOverride\",\n {deviceScaleFactor: 0, mobile: false,\n width: layoutMetrics.contentSize.width,\n height: Math.floor(contentHeight)});\n }\n let result = await sendCommand(tabId, \"Page.captureScreenshot\", options);\n if (options.fullSize)\n await sendCommand(tabId, \"Emulation.clearDeviceMetricsOverride\");\n await detach(tabId);\n return result.data;\n}\n\nNWWindow.prototype.captureScreenshot = function(options, cb) {\n let tab = this.cWindow.tabs[0].id;\n if (!cb)\n return captureScreenshotHelper(tab, options);\n captureScreenshotHelper(tab, options).then((data) => { cb(null, data); }).catch(cb);\n};\n\nNWWindow.prototype.reload = function () {\n chrome.tabs.reload(this.cWindow.tabs[0].id);\n};\nNWWindow.prototype.reloadIgnoringCache = function () {\n chrome.tabs.reload(this.cWindow.tabs[0].id, {'bypassCache': true});\n};\nNWWindow.prototype.eval = function (frame, script) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return nwNatives.evalScript(frame, script, this.cWindow.tabs[0].mainFrameId);\n};\nNWWindow.prototype.evalNWBin = function (frame, path) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n this.evalNWBinInternal(frame, path, null, this.cWindow.tabs[0].mainFrameId);\n};\nNWWindow.prototype.evalNWBinModule = function (frame, path, module_path) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n this.evalNWBinInternal(frame, path, module_path, this.cWindow.tabs[0].mainFrameId);\n};\nNWWindow.prototype.evalNWBinInternal = function (frame, path, module_path, main_frame_id) {\n var ab;\n if (Buffer.isBuffer(path)) {\n let buf = path;\n ab = new global.ArrayBuffer(path.length);\n path.copy(Buffer.from(ab));\n } else if ($Object.prototype.toString.apply(path) === '[object ArrayBuffer]') {\n ab = path;\n } else {\n let buf = global.require('fs').readFileSync(path);\n ab = new global.ArrayBuffer(buf.length);\n buf.copy(Buffer.from(ab));\n }\n return nwNatives.evalNWBin(frame, ab, module_path, main_frame_id);\n};\nNWWindow.prototype.show = function () {\n chrome.windows.update(this.cWindow.id, {'show': true});\n};\nNWWindow.prototype.hide = function () {\n chrome.windows.update(this.cWindow.id, {'state':'hidden'});\n};\nNWWindow.prototype.focus = function () {\n chrome.windows.update(this.cWindow.id, {'focused':true});\n};\nNWWindow.prototype.blur = function () {\n chrome.windows.update(this.cWindow.id, {'focused':false});\n};\nNWWindow.prototype.minimize = function () {\n chrome.windows.update(this.cWindow.id, {'state':'minimized'});\n};\nNWWindow.prototype.maximize = function () {\n chrome.windows.update(this.cWindow.id, {'state':\"maximized\"});\n};\nNWWindow.prototype.unmaximize = NWWindow.prototype.restore = function () {\n chrome.windows.update(this.cWindow.id, {'state':\"normal\"});\n};\nNWWindow.prototype.enterFullscreen = function () {\n chrome.windows.update(this.cWindow.id, {'state':\"fullscreen\"});\n};\nNWWindow.prototype.leaveFullscreen = function () {\n var self = this;\n chrome.windows.get(this.cWindow.id, {}, function(w) {\n self.cWindow = w;\n if (w.state === 'fullscreen')\n chrome.windows.update(w.id, {'state':\"normal\"});\n });\n};\n\nNWWindow.prototype.toggleFullscreen = function () {\n var self = this;\n chrome.windows.get(this.cWindow.id, {}, function(w) {\n self.cWindow = w;\n if (w.state === 'fullscreen')\n chrome.windows.update(w.id, {'state':\"normal\"});\n else\n self.enterFullscreen();\n });\n};\n\nNWWindow.prototype.setAlwaysOnTop = function (top) {\n chrome.windows.update(this.cWindow.id, {'alwaysOnTop': top});\n};\nNWWindow.prototype.setPosition = function (pos) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n if (pos == \"center\") {\n var screenWidth = screen.availWidth;\n var screenHeight = screen.availHeight;\n var width = this.cWindow.width;\n var height = this.cWindow.height;\n chrome.windows.update(this.cWindow.id, {'left': Math.round((screenWidth-width)/2),\n 'top': Math.round((screenHeight-height)/2)});\n } else if (pos == \"mouse\") {\n chrome.windows.update(this.cWindow.id, {'position': \"mouse\" });\n }\n};\nNWWindow.prototype.setVisibleOnAllWorkspaces = function(all_visible) {\n chrome.windows.update(this.cWindow.id, {'allVisible': all_visible});\n};\nNWWindow.prototype.canSetVisibleOnAllWorkspaces = function() {\n return canSetVisibleOnAllWorkspaces;\n};\nNWWindow.prototype.setMaximumSize = function (width, height) {\n chrome.windows.update(this.cWindow.id, {'maxWidth': width, 'maxHeight': height});\n};\nNWWindow.prototype.setMinimumSize = function (width, height) {\n //TODO: cover glass frame case in windows\n chrome.windows.update(this.cWindow.id, {'minWidth': width, 'minHeight': height});\n};\nNWWindow.prototype.resizeTo = function (width, height) {\n chrome.windows.update(this.cWindow.id, {'innerWidth': width, 'innerHeight': height});\n};\nNWWindow.prototype.setInnerWidth = function (width) {\n chrome.windows.update(this.cWindow.id, {'innerWidth': width});\n};\nNWWindow.prototype.setInnerHeight = function (height) {\n chrome.windows.update(this.cWindow.id, {'innerHeight': height});\n};\nNWWindow.prototype.resizeBy = function (width, height) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n chrome.windows.update(this.cWindow.id,\n {'width': this.cWindow.width + width,\n 'height': this.cWindow.height + height});\n};\nNWWindow.prototype.moveTo = function (x, y) {\n chrome.windows.update(this.cWindow.id, {'left': x, 'top': y});\n};\nNWWindow.prototype.moveBy = function (x, y) {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n chrome.windows.update(this.cWindow.id,\n {'left': this.cWindow.left + x,\n 'top': this.cWindow.top + y});\n};\nNWWindow.prototype.setResizable = function (resizable) {\n chrome.windows.update(this.cWindow.id, {'resizable': resizable});\n};\nNWWindow.prototype.requestAttention = function (flash) {\n if (typeof flash == 'boolean')\n flash = flash ? -1 : 0;\n currentNWWindowInternal.requestAttentionInternal(flash);\n};\nNWWindow.prototype.cookies = chrome.cookies;\n\nNWWindow.prototype.print = function(option) {\n var _option = JSON.parse(JSON.stringify(option));\n if (!(\"autoprint\" in _option))\n _option[\"autoprint\"] = true;\n if (option.pdf_path)\n _option[\"printer\"] = \"Save as PDF\";\n currentNWWindowInternal.setPrintSettingsInternal(_option, this.cWindow.id);\n this.window.print();\n // autoprint will be set to false in print_preview_handler.cc after printing is done\n // window.print will return immediately for PDF window #5002\n};\nObject.defineProperty(NWWindow.prototype, 'x', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.left;\n },\n set: function(x) {\n chrome.windows.update(this.cWindow.id, {'left': x});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'y', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.top;\n },\n set: function(y) {\n chrome.windows.update(this.cWindow.id, {'top': y});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'width', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.width;\n },\n set: function(val) {\n chrome.windows.update(this.cWindow.id, {'width': val});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'height', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.height;\n },\n set: function(val) {\n chrome.windows.update(this.cWindow.id, {'height': val});\n }\n});\nObject.defineProperty(NWWindow.prototype, 'title', {\n get: function() {\n return currentNWWindowInternal.getTitleInternal(this.cWindow.id);\n },\n set: function(val) {\n currentNWWindowInternal.setTitleInternal(val, this.cWindow.id);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'zoomLevel', {\n get: function() {\n return currentNWWindowInternal.getZoom(this.cWindow.id);\n },\n set: function(val) {\n currentNWWindowInternal.setZoom(val, this.cWindow.id);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isTransparent', {\n get: function() {\n return this.appWindow.alphaEnabled();\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isKioskMode', {\n get: function() {\n return currentNWWindowInternal.isKioskInternal(this.cWindow.id);\n },\n set: function(val) {\n if (val)\n currentNWWindowInternal.enterKioskModeInternal(this.cWindow.id);\n else\n currentNWWindowInternal.leaveKioskModeInternal(this.cWindow.id);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isFullscreen', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.state === 'fullscreen';\n }\n});\nObject.defineProperty(NWWindow.prototype, 'isAlwaysOnTop', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return this.cWindow.alwaysOnTop;\n }\n});\nObject.defineProperty(NWWindow.prototype, 'menu', {\n get: function() {\n var ret = privates(this).menu || {};\n return ret;\n },\n set: function(menu) {\n if(!menu) {\n privates(this).menu = null;\n currentNWWindowInternal.clearMenu(this.cWindow.id);\n return;\n }\n if (menu.type != 'menubar')\n throw new TypeError('Only menu of type \"menubar\" can be used as this.window menu');\n\n privates(this).menu = menu;\n var menuPatch = currentNWWindowInternal.setMenu(menu.id, this.cWindow.id);\n if (menuPatch.length) {\n menuPatch.forEach((patch)=>{\n let menuIndex = patch.menu;\n let itemIndex = patch.index;\n let menuToPatch = menu.items[menuIndex];\n if (menuToPatch && menuToPatch.submenu) {\n menuToPatch.submenu.insert(new nw.MenuItem(patch.option), itemIndex);\n }\n });\n }\n }\n});\nObject.defineProperty(NWWindow.prototype, 'window', {\n get: function() {\n this.cWindow = currentNWWindowInternal.getCurrent(this.cWindow.id, {'populate': true});\n return appWindowNatives.GetFrame(this.cWindow.tabs[0].mainFrameId, false);\n }\n});\nObject.defineProperty(NWWindow.prototype, 'frameId', {\n get: function() {\n return currentRoutingID;\n }\n});\n\napiBridge.registerCustomHook(function(bindingsAPI) {\n var apiFunctions = bindingsAPI.apiFunctions;\n currentNWWindowInternal = getInternalApi('nw.currentWindowInternal');\n forEach(currentNWWindowInternal, function(key, value) {\n if (!key.endsWith('Internal') && key !== 'close')\n NWWindow.prototype[key] = value;\n });\n apiFunctions.setHandleRequest('get', function(domWindow) {\n if (domWindow)\n return try_nw(domWindow.top).nw.Window.get();\n if (currentNWWindow)\n return currentNWWindow;\n\n currentNWWindow = new NWWindow;\n return currentNWWindow;\n });\n\n apiFunctions.setHandleRequest('getAll', function(callback) {\n chrome.windows.getAll({populate: true}, function (cwindows) {\n let create_nw_win = cwin => new NWWindow(cwin);\n callback(cwindows.map(create_nw_win));\n });\n });\n\n apiFunctions.setHandleRequest('open', function(url, params, callback) {\n var options = {'url': url, 'setSelfAsOpener': true, 'type': 'popup'};\n //FIXME: unify this conversion code with nwjs/default.js\n if (params) {\n if (params.frame === false)\n options.frameless = true;\n if (params.resizable === false)\n options.resizable = false;\n if (params.focus === false)\n options.focused = false;\n if (params.x)\n options.left = params.x;\n if (params.y)\n options.top = params.y;\n if (params.height)\n options.height = params.height;\n if (params.width)\n options.width = params.width;\n if (params.min_width)\n options.minWidth = params.min_width;\n if (params.max_width)\n options.maxWidth = params.max_width;\n if (params.min_height)\n options.minHeight = params.min_height;\n if (params.max_height)\n options.maxHeight = params.max_height;\n if (params.fullscreen === true)\n options.state = 'fullscreen';\n if (params.show === false)\n options.hidden = true;\n if (params.show_in_taskbar === false)\n options.showInTaskbar = false;\n if (params['always_on_top'] === true)\n options.alwaysOnTop = true;\n if (params['visible_on_all_workspaces'] === true)\n options.allVisible = true;\n if (typeof params['inject_js_start'] == 'string')\n options.inject_js_start = params['inject_js_start'];\n if (typeof params['inject_js_end'] == 'string')\n options.inject_js_end = params['inject_js_end'];\n if (params.transparent)\n options.alphaEnabled = true;\n // if (params.kiosk === true)\n // options.kiosk = true;\n if (params.new_instance === true) {\n options.new_instance = true;\n options.setSelfAsOpener = false;\n }\n if (params.position)\n options.position = params.position;\n if (params.title)\n options.title = params.title;\n if (params.icon)\n options.icon = params.icon;\n if (params.id)\n options.id = params.id;\n }\n if (callback && !(options.new_instance === true))\n options.block_parser = true;\n try_hidden(window).chrome.windows.create(options, function(cWin) {\n try {\n if (callback) {\n if (cWin)\n callback(new NWWindow(cWin));\n else\n callback();\n }\n } finally {\n if (options.block_parser)\n appWindowNatives.ResumeParser(cWin.tabs[0].mainFrameId);\n }\n });\n });\n\n});\n\nfunction dispatchEventIfExists(target, name, varargs) {\n // Sometimes apps like to put their own properties on the window which\n // break our assumptions.\n var event = target[name];\n if (event && (typeof event.dispatch == 'function'))\n $Function.apply(event.dispatch, event, varargs);\n else\n console.warn('Could not dispatch ' + name + ', event has been clobbered');\n}\n\nfunction onNewWinPolicy(frame, url, policy, top_routing_id) {\n //console.log(\"onNewWinPolicy called: \" + url + \", \" + policy);\n dispatchEventIfExists(NWWindow.prototype, \"onNewWinPolicy\", [frame, url, policy, top_routing_id]);\n}\n\nfunction onNavigation(frame, url, policy, top_routing_id, context) {\n //console.log(\"onNavigation called: \" + url + \", \" + context);\n dispatchEventIfExists(NWWindow.prototype, \"onNavigation\", [frame, url, policy, context, top_routing_id]);\n}\n\nfunction onLoadingStateChanged(status) {\n //console.log(\"onLoadingStateChanged: \" + status);\n if (!currentNWWindow)\n return;\n dispatchEventIfExists(currentNWWindow, \"LoadingStateChanged\", [status]);\n}\n\nfunction onDocumentStartEnd(start, frame, top_routing_id) {\n //console.log(`---> onDocumentStartEnd ${start} ${top_routing_id}`);\n if (start) {\n dispatchEventIfExists(NWWindow.prototype, \"onDocumentStart\", [frame, top_routing_id]);\n }\n else\n dispatchEventIfExists(NWWindow.prototype, \"onDocumentEnd\", [frame, top_routing_id]);\n}\n\nfunction updateAppWindowZoom(old_level, new_level) {\n if (!currentNWWindow)\n return;\n dispatchEventIfExists(currentNWWindow, \"onZoom\", [new_level]);\n}\n\nfunction onClose(user_force) {\n if (!currentNWWindow)\n return;\n currentNWWindow.onClose.dispatchNW({instanceId: currentWidgetRoutingID}, user_force);\n}\n\nfunction get_nw() {\n appWindowNatives.FixGamePadAPI();\n var nw0 = try_nw(window).nw;\n if (nw0)\n nw0.Window.get();\n}\n\n//if (bgPage !== window) {\n// renderFrameObserverNatives.OnDocumentElementCreated(currentRoutingID, get_nw);\n//}\n\nexports.onNewWinPolicy = onNewWinPolicy;\nexports.onNavigation = onNavigation;\nexports.LoadingStateChanged = onLoadingStateChanged;\nexports.onDocumentStartEnd = onDocumentStartEnd;\nexports.onClose = onClose;\nexports.updateAppWindowZoom = updateAppWindowZoom;\n", "file_path": "src/resources/api_nw_newwin.js", "label": 1, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.9979881048202515, 0.02177123725414276, 0.000162489726790227, 0.00017204579489771277, 0.13875621557235718]} {"hunk": {"id": 6, "code_window": [" if (params.new_instance === true) {\n", " options.new_instance = true;\n", " options.setSelfAsOpener = false;\n", " }\n", " if (params.position)\n", " options.position = params.position;\n", " if (params.title)\n", " options.title = params.title;\n", " if (params.icon)\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" if (params.mixed_context === true) {\n", " if (params.new_instance !== true) {\n", " throw new Error('mixed_context should be set with new_instance in nw.Window.open');\n", " }\n", " options.mixed_context = true;\n", " }\n"], "file_path": "src/resources/api_nw_newwin.js", "type": "add", "edit_start_line_idx": 811}, "file": "language: node_js\nnode_js:\n - 0.10\n - 0.11\n", "file_path": "test/sanity/tar/node_modules/tar/.travis.yml", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00016976066399365664, 0.00016976066399365664, 0.00016976066399365664, 0.00016976066399365664, 0.0]} {"hunk": {"id": 6, "code_window": [" if (params.new_instance === true) {\n", " options.new_instance = true;\n", " options.setSelfAsOpener = false;\n", " }\n", " if (params.position)\n", " options.position = params.position;\n", " if (params.title)\n", " options.title = params.title;\n", " if (params.icon)\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" if (params.mixed_context === true) {\n", " if (params.new_instance !== true) {\n", " throw new Error('mixed_context should be set with new_instance in nw.Window.open');\n", " }\n", " options.mixed_context = true;\n", " }\n"], "file_path": "src/resources/api_nw_newwin.js", "type": "add", "edit_start_line_idx": 811}, "file": "Copyright (c) 2010-2014 Caolan McMahon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", "file_path": "test/node_modules/async/LICENSE", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017326751549262553, 0.00017261778702959418, 0.00017196805856656283, 0.00017261778702959418, 6.497284630313516e-07]} {"hunk": {"id": 6, "code_window": [" if (params.new_instance === true) {\n", " options.new_instance = true;\n", " options.setSelfAsOpener = false;\n", " }\n", " if (params.position)\n", " options.position = params.position;\n", " if (params.title)\n", " options.title = params.title;\n", " if (params.icon)\n"], "labels": ["keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" if (params.mixed_context === true) {\n", " if (params.new_instance !== true) {\n", " throw new Error('mixed_context should be set with new_instance in nw.Window.open');\n", " }\n", " options.mixed_context = true;\n", " }\n"], "file_path": "src/resources/api_nw_newwin.js", "type": "add", "edit_start_line_idx": 811}, "file": "", "file_path": "test/sanity/issue6663-window-getPrinters-return-array/index.html", "label": 0, "commit_url": "https://github.com/nwjs/nw.js/commit/9f2c53113920cda4fee9359ab182a19c4d9ef052", "dependency_score": [0.00017408143321517855, 0.00017408143321517855, 0.00017408143321517855, 0.00017408143321517855, 0.0]} {"hunk": {"id": 0, "code_window": [" first running `meteor add user:package`.\n", "\n", "* iOS icons and launch screens have been updated to support iOS 11\n", " [Issue #9196](https://github.com/meteor/meteor/issues/9196)\n", " [PR #9198](https://github.com/meteor/meteor/pull/9198)\n", "\n", "## v1.5.4, 2017-11-08\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" [Issue #9236] Allow Npm.depends to specify any http or https URL [#9236](https://github.com/meteor/meteor/issues/9236)\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 234}, "file": "var selftest = require('../tool-testing/selftest.js');\nvar utils = require('../utils/utils.js');\n\nimport { sha1 } from '../fs/watch.js';\nimport httpHelpers from '../utils/http-helpers';\n\nselftest.define('subset generator', function () {\n var out = [];\n utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {\n out.push(x);\n });\n selftest.expectEqual(out, [\n [],\n [ 'a' ],\n [ 'b' ],\n [ 'c' ],\n [ 'a', 'b' ],\n [ 'a', 'c' ],\n [ 'b', 'c' ],\n [ 'a', 'b', 'c' ]\n ]);\n out = [];\n utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {\n out.push(x);\n if (x[1] === 'c') {\n // stop iterating\n return true;\n }\n });\n selftest.expectEqual(out, [\n [],\n [ 'a' ],\n [ 'b' ],\n [ 'c' ],\n [ 'a', 'b' ],\n [ 'a', 'c' ]\n ]);\n});\n\nselftest.define(\"url has scheme\", function () {\n // URL scheme must start with a letter, and then can be followed by\n // any number of alphanumerics, +, -, . RFC 2396 Appendix A.\n selftest.expectEqual(utils.hasScheme(\"http://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"https://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"http://example.com:80\"), true);\n selftest.expectEqual(utils.hasScheme(\"https://example.com:443\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example.com:443\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example.comhttp://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example+com+http://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example-com+http://\"), true);\n\n selftest.expectEqual(utils.hasScheme(\"example\"), false);\n selftest.expectEqual(utils.hasScheme(\"example.com\"), false);\n selftest.expectEqual(utils.hasScheme(\"example.com:443\"), false);\n selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n});\n\nselftest.define(\"parse url\", function () {\n selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"3000\"), {\n hostname: undefined,\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"3000example.com:3000\"), {\n hostname: \"3000example.com\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"http://example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"127.0.0.1:3000\"), {\n hostname: \"127.0.0.1\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"http://[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"[0000:0000:0000:0000:0000:0000:0000:0001]:3000\"), {\n hostname: \"0000:0000:0000:0000:0000:0000:0000:0001\",\n port: \"3000\",\n protocol: undefined\n });\n\n // tests for defaults\n selftest.expectEqual(utils.parseUrl(\"http://example.com:3000\", {\n hostname: \"foo.com\",\n port: \"4000\",\n protocol: \"https\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"example.com:3000\", {\n port: \"4000\",\n protocol: \"https\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"3000\", {\n port: \"4000\",\n protocol: \"https\",\n hostname: \"example.com\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n});\n\nselftest.define(\"resume downloads\", ['net'], function () {\n // A reasonably big file that (I think) should take more than 1s to download\n // and that we know the size of\n const url = 'https://warehouse.meteor.com/builds/EXSxwGqYjjJKh3WMJ/1467929945102/DRyKg3bYHL/babel-compiler-6.8.4-os+web.browser+web.cordova.tgz';\n\n let interruptCount = 0;\n let bytesSinceLastInterrupt = 0;\n\n const resumedPromise = Promise.resolve().then(\n () => httpHelpers.getUrlWithResuming({\n url: url,\n encoding: null,\n retryDelaySecs: 1,\n onRequest(request) {\n request.on(\"data\", chunk => {\n bytesSinceLastInterrupt += chunk.length\n if (bytesSinceLastInterrupt > 500000) {\n bytesSinceLastInterrupt = 0;\n ++interruptCount;\n request.emit('error', 'pretend-http-error');\n request.emit('end');\n request.abort();\n }\n });\n }\n })\n );\n\n const normalPromise = Promise.resolve().then(\n () => httpHelpers.getUrl({\n url,\n encoding: null,\n })\n );\n\n Promise.all([\n resumedPromise,\n normalPromise,\n ]).then(bodies => {\n selftest.expectTrue(interruptCount > 1);\n\n selftest.expectEqual(\n bodies[0].length,\n bodies[1].length\n );\n\n selftest.expectEqual(\n sha1(bodies[0]),\n sha1(bodies[1])\n );\n }).await();\n});\n", "file_path": "tools/tests/utils-tests.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.0002880050160456449, 0.0001770055532688275, 0.0001671944191912189, 0.00017204572213813663, 2.4326975108124316e-05]} {"hunk": {"id": 0, "code_window": [" first running `meteor add user:package`.\n", "\n", "* iOS icons and launch screens have been updated to support iOS 11\n", " [Issue #9196](https://github.com/meteor/meteor/issues/9196)\n", " [PR #9198](https://github.com/meteor/meteor/pull/9198)\n", "\n", "## v1.5.4, 2017-11-08\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" [Issue #9236] Allow Npm.depends to specify any http or https URL [#9236](https://github.com/meteor/meteor/issues/9236)\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 234}, "file": "import {basename} from \"path\"\nimport {readFileSync as readFile} from \"fs\"\nimport * as acorn from \"acorn\"\n\nlet infile, forceFile, silent = false, compact = false, tokenize = false\nconst options = {}\n\nfunction help(status) {\n const print = (status == 0) ? console.log : console.error\n print(\"usage: \" + basename(process.argv[1]) + \" [--ecma3|--ecma5|--ecma6|--ecma7|...|--ecma2015|--ecma2016|...]\")\n print(\" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]\")\n process.exit(status)\n}\n\nfor (let i = 2; i < process.argv.length; ++i) {\n const arg = process.argv[i]\n if ((arg == \"-\" || arg[0] != \"-\") && !infile) infile = arg\n else if (arg == \"--\" && !infile && i + 2 == process.argv.length) forceFile = infile = process.argv[++i]\n else if (arg == \"--locations\") options.locations = true\n else if (arg == \"--allow-hash-bang\") options.allowHashBang = true\n else if (arg == \"--silent\") silent = true\n else if (arg == \"--compact\") compact = true\n else if (arg == \"--help\") help(0)\n else if (arg == \"--tokenize\") tokenize = true\n else if (arg == \"--module\") options.sourceType = 'module'\n else {\n let match = arg.match(/^--ecma(\\d+)$/)\n if (match)\n options.ecmaVersion = +match[1]\n else\n help(1)\n }\n}\n\nfunction run(code) {\n let result\n if (!tokenize) {\n try { result = acorn.parse(code, options) }\n catch(e) { console.error(e.message); process.exit(1) }\n } else {\n result = []\n let tokenizer = acorn.tokenizer(code, options), token\n while (true) {\n try { token = tokenizer.getToken() }\n catch(e) { console.error(e.message); process.exit(1) }\n result.push(token)\n if (token.type == acorn.tokTypes.eof) break\n }\n }\n if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2))\n}\n\nif (forceFile || infile && infile != \"-\") {\n run(readFile(infile, \"utf8\"))\n} else {\n let code = \"\"\n process.stdin.resume()\n process.stdin.on(\"data\", chunk => code += chunk)\n process.stdin.on(\"end\", () => run(code))\n}\n", "file_path": "tools/tests/apps/modules/packages/modules-test-package/node_modules/acorn/src/bin/acorn.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00017430334992241114, 0.00016940210480242968, 0.00016221075202338398, 0.00016986882837954909, 3.3949468161154073e-06]} {"hunk": {"id": 0, "code_window": [" first running `meteor add user:package`.\n", "\n", "* iOS icons and launch screens have been updated to support iOS 11\n", " [Issue #9196](https://github.com/meteor/meteor/issues/9196)\n", " [PR #9198](https://github.com/meteor/meteor/pull/9198)\n", "\n", "## v1.5.4, 2017-11-08\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" [Issue #9236] Allow Npm.depends to specify any http or https URL [#9236](https://github.com/meteor/meteor/issues/9236)\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 234}, "file": "local\n", "file_path": "examples/unfinished/chat-benchmark/.meteor/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00016791735833976418, 0.00016791735833976418, 0.00016791735833976418, 0.00016791735833976418, 0.0]} {"hunk": {"id": 0, "code_window": [" first running `meteor add user:package`.\n", "\n", "* iOS icons and launch screens have been updated to support iOS 11\n", " [Issue #9196](https://github.com/meteor/meteor/issues/9196)\n", " [PR #9198](https://github.com/meteor/meteor/pull/9198)\n", "\n", "## v1.5.4, 2017-11-08\n", "\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" [Issue #9236] Allow Npm.depends to specify any http or https URL [#9236](https://github.com/meteor/meteor/issues/9236)\n"], "file_path": "History.md", "type": "add", "edit_start_line_idx": 234}, "file": "const path = Plugin.path;\nconst Future = Npm.require('fibers/future');\nconst LRU = Npm.require('lru-cache');\nconst async = Npm.require('async');\n\n// MultiFileCachingCompiler is like CachingCompiler, but for implementing\n// languages which allow files to reference each other, such as CSS\n// preprocessors with `@import` directives.\n//\n// Like CachingCompiler, you should subclass MultiFileCachingCompiler and define\n// the following methods: getCacheKey, compileOneFile, addCompileResult, and\n// compileResultSize. compileOneFile gets an additional allFiles argument and\n// returns an array of referenced import paths in addition to the CompileResult.\n// You may also override isRoot and getAbsoluteImportPath to customize\n// MultiFileCachingCompiler further.\nMultiFileCachingCompiler = class MultiFileCachingCompiler\nextends CachingCompilerBase {\n constructor({\n compilerName,\n defaultCacheSize,\n maxParallelism\n }) {\n super({compilerName, defaultCacheSize, maxParallelism});\n\n // Maps from absolute import path to { compileResult, cacheKeys }, where\n // cacheKeys is an object mapping from absolute import path to hashed\n // cacheKey for each file referenced by this file (including itself).\n this._cache = new LRU({\n max: this._cacheSize,\n // We ignore the size of cacheKeys here.\n length: (value) => this.compileResultSize(value.compileResult),\n });\n }\n\n // Your subclass must override this method to define the transformation from\n // InputFile to its cacheable CompileResult).\n //\n // Arguments:\n // - inputFile is the InputFile to process\n // - allFiles is a a Map mapping from absolute import path to InputFile of\n // all files being processed in the target\n // Returns an object with keys:\n // - compileResult: the CompileResult (the cacheable data type specific to\n // your subclass).\n // - referencedImportPaths: an array of absolute import paths of files\n // which were refererenced by the current file. The current file\n // is included implicitly.\n //\n // This method is not called on files when a valid cache entry exists in\n // memory or on disk.\n //\n // On a compile error, you should call `inputFile.error` appropriately and\n // return null; this will not be cached.\n //\n // This method should not call `inputFile.addJavaScript` and similar files!\n // That's what addCompileResult is for.\n compileOneFile(inputFile, allFiles) {\n throw Error(\n 'MultiFileCachingCompiler subclass should implement compileOneFile!');\n }\n\n // Your subclass may override this to declare that a file is not a \"root\" ---\n // ie, it can be included from other files but is not processed on its own. In\n // this case, MultiFileCachingCompiler won't waste time trying to look for a\n // cache for its compilation on disk.\n isRoot(inputFile) {\n return true;\n }\n\n // Returns the absolute import path for an InputFile. By default, this is a\n // path is a path of the form \"{package}/path/to/file\" for files in packages\n // and \"{}/path/to/file\" for files in apps. Your subclass may override and/or\n // call this method.\n getAbsoluteImportPath(inputFile) {\n if (inputFile.getPackageName() === null) {\n return '{}/' + inputFile.getPathInPackage();\n }\n return '{' + inputFile.getPackageName() + '}/'\n + inputFile.getPathInPackage();\n }\n\n // The processFilesForTarget method from the Plugin.registerCompiler API.\n processFilesForTarget(inputFiles) {\n const allFiles = new Map;\n const cacheKeyMap = new Map;\n const cacheMisses = [];\n\n inputFiles.forEach((inputFile) => {\n const importPath = this.getAbsoluteImportPath(inputFile);\n allFiles.set(importPath, inputFile);\n cacheKeyMap.set(importPath, this._deepHash(this.getCacheKey(inputFile)));\n });\n\n const allProcessedFuture = new Future;\n async.eachLimit(inputFiles, this._maxParallelism, (inputFile, cb) => {\n let error = null;\n try {\n // If this isn't a root, skip it (and definitely don't waste time\n // looking for a cache file that won't be there).\n if (!this.isRoot(inputFile)) {\n return;\n }\n\n const absoluteImportPath = this.getAbsoluteImportPath(inputFile);\n let cacheEntry = this._cache.get(absoluteImportPath);\n if (! cacheEntry) {\n cacheEntry = this._readCache(absoluteImportPath);\n if (cacheEntry) {\n this._cacheDebug(`Loaded ${ absoluteImportPath }`);\n }\n }\n if (! (cacheEntry && this._cacheEntryValid(cacheEntry, cacheKeyMap))) {\n cacheMisses.push(inputFile.getDisplayPath());\n\n const compileOneFileReturn = this.compileOneFile(inputFile, allFiles);\n if (! compileOneFileReturn) {\n // compileOneFile should have called inputFile.error.\n // We don't cache failures for now.\n return;\n }\n const {compileResult, referencedImportPaths} = compileOneFileReturn;\n\n cacheEntry = {\n compileResult,\n cacheKeys: {\n // Include the hashed cache key of the file itself...\n [absoluteImportPath]: cacheKeyMap.get(absoluteImportPath)\n }\n };\n\n // ... and of the other referenced files.\n referencedImportPaths.forEach((path) => {\n if (!cacheKeyMap.has(path)) {\n throw Error(`Unknown absolute import path ${ path }`);\n }\n cacheEntry.cacheKeys[path] = cacheKeyMap.get(path);\n });\n\n // Save the cache entry.\n this._cache.set(absoluteImportPath, cacheEntry);\n this._writeCacheAsync(absoluteImportPath, cacheEntry);\n }\n\n this.addCompileResult(inputFile, cacheEntry.compileResult);\n } catch (e) {\n error = e;\n } finally {\n cb(error);\n }\n }, allProcessedFuture.resolver());\n allProcessedFuture.wait();\n\n if (this._cacheDebugEnabled) {\n cacheMisses.sort();\n this._cacheDebug(\n `Ran (#${ ++this._callCount }) on: ${ JSON.stringify(cacheMisses) }`);\n }\n }\n\n _cacheEntryValid(cacheEntry, cacheKeyMap) {\n return Object.keys(cacheEntry.cacheKeys).every(\n (path) => cacheEntry.cacheKeys[path] === cacheKeyMap.get(path)\n );\n }\n\n // The format of a cache file on disk is the JSON-stringified cacheKeys\n // object, a newline, followed by the CompileResult as returned from\n // this.stringifyCompileResult.\n _cacheFilename(absoluteImportPath) {\n return path.join(this._diskCache,\n this._deepHash(absoluteImportPath) + '.cache');\n }\n // Loads a {compileResult, cacheKeys} cache entry from disk. Returns the whole\n // cache entry and loads it into the in-memory cache too.\n _readCache(absoluteImportPath) {\n if (! this._diskCache) {\n return null;\n }\n const cacheFilename = this._cacheFilename(absoluteImportPath);\n const raw = this._readFileOrNull(cacheFilename);\n if (!raw) {\n return null;\n }\n\n // Split on newline.\n const newlineIndex = raw.indexOf('\\n');\n if (newlineIndex === -1) {\n return null;\n }\n const cacheKeysString = raw.substring(0, newlineIndex);\n const compileResultString = raw.substring(newlineIndex + 1);\n\n const cacheKeys = this._parseJSONOrNull(cacheKeysString);\n if (!cacheKeys) {\n return null;\n }\n const compileResult = this.parseCompileResult(compileResultString);\n if (! compileResult) {\n return null;\n }\n\n const cacheEntry = {compileResult, cacheKeys};\n this._cache.set(absoluteImportPath, cacheEntry);\n return cacheEntry;\n }\n _writeCacheAsync(absoluteImportPath, cacheEntry) {\n if (! this._diskCache) {\n return null;\n }\n const cacheFilename = this._cacheFilename(absoluteImportPath);\n const cacheContents =\n JSON.stringify(cacheEntry.cacheKeys) + '\\n'\n + this.stringifyCompileResult(cacheEntry.compileResult);\n this._writeFileAsync(cacheFilename, cacheContents);\n }\n}\n", "file_path": "packages/caching-compiler/multi-file-caching-compiler.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00029833425651304424, 0.0001766448694979772, 0.0001654675870668143, 0.0001694020174909383, 2.7012782084057108e-05]} {"hunk": {"id": 1, "code_window": [" * your Meteor package depends on.\n", " * @param {Object} dependencies An object where the keys are package\n", " * names and the values are one of:\n", " * 1. Version numbers in string form\n", " * 2. Http(s) URLs to a git commit by SHA.\n", " * 3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)\n", " *\n", " * Https URL example:\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" * 2. Http(s) URLs to a npm package\n"], "file_path": "tools/isobuild/package-npm.js", "type": "replace", "edit_start_line_idx": 26}, "file": "var selftest = require('../tool-testing/selftest.js');\nvar utils = require('../utils/utils.js');\n\nimport { sha1 } from '../fs/watch.js';\nimport httpHelpers from '../utils/http-helpers';\n\nselftest.define('subset generator', function () {\n var out = [];\n utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {\n out.push(x);\n });\n selftest.expectEqual(out, [\n [],\n [ 'a' ],\n [ 'b' ],\n [ 'c' ],\n [ 'a', 'b' ],\n [ 'a', 'c' ],\n [ 'b', 'c' ],\n [ 'a', 'b', 'c' ]\n ]);\n out = [];\n utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {\n out.push(x);\n if (x[1] === 'c') {\n // stop iterating\n return true;\n }\n });\n selftest.expectEqual(out, [\n [],\n [ 'a' ],\n [ 'b' ],\n [ 'c' ],\n [ 'a', 'b' ],\n [ 'a', 'c' ]\n ]);\n});\n\nselftest.define(\"url has scheme\", function () {\n // URL scheme must start with a letter, and then can be followed by\n // any number of alphanumerics, +, -, . RFC 2396 Appendix A.\n selftest.expectEqual(utils.hasScheme(\"http://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"https://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"http://example.com:80\"), true);\n selftest.expectEqual(utils.hasScheme(\"https://example.com:443\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example.com:443\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example.comhttp://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example+com+http://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example-com+http://\"), true);\n\n selftest.expectEqual(utils.hasScheme(\"example\"), false);\n selftest.expectEqual(utils.hasScheme(\"example.com\"), false);\n selftest.expectEqual(utils.hasScheme(\"example.com:443\"), false);\n selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n});\n\nselftest.define(\"parse url\", function () {\n selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"3000\"), {\n hostname: undefined,\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"3000example.com:3000\"), {\n hostname: \"3000example.com\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"http://example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"127.0.0.1:3000\"), {\n hostname: \"127.0.0.1\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"http://[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"[0000:0000:0000:0000:0000:0000:0000:0001]:3000\"), {\n hostname: \"0000:0000:0000:0000:0000:0000:0000:0001\",\n port: \"3000\",\n protocol: undefined\n });\n\n // tests for defaults\n selftest.expectEqual(utils.parseUrl(\"http://example.com:3000\", {\n hostname: \"foo.com\",\n port: \"4000\",\n protocol: \"https\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"example.com:3000\", {\n port: \"4000\",\n protocol: \"https\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"3000\", {\n port: \"4000\",\n protocol: \"https\",\n hostname: \"example.com\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n});\n\nselftest.define(\"resume downloads\", ['net'], function () {\n // A reasonably big file that (I think) should take more than 1s to download\n // and that we know the size of\n const url = 'https://warehouse.meteor.com/builds/EXSxwGqYjjJKh3WMJ/1467929945102/DRyKg3bYHL/babel-compiler-6.8.4-os+web.browser+web.cordova.tgz';\n\n let interruptCount = 0;\n let bytesSinceLastInterrupt = 0;\n\n const resumedPromise = Promise.resolve().then(\n () => httpHelpers.getUrlWithResuming({\n url: url,\n encoding: null,\n retryDelaySecs: 1,\n onRequest(request) {\n request.on(\"data\", chunk => {\n bytesSinceLastInterrupt += chunk.length\n if (bytesSinceLastInterrupt > 500000) {\n bytesSinceLastInterrupt = 0;\n ++interruptCount;\n request.emit('error', 'pretend-http-error');\n request.emit('end');\n request.abort();\n }\n });\n }\n })\n );\n\n const normalPromise = Promise.resolve().then(\n () => httpHelpers.getUrl({\n url,\n encoding: null,\n })\n );\n\n Promise.all([\n resumedPromise,\n normalPromise,\n ]).then(bodies => {\n selftest.expectTrue(interruptCount > 1);\n\n selftest.expectEqual(\n bodies[0].length,\n bodies[1].length\n );\n\n selftest.expectEqual(\n sha1(bodies[0]),\n sha1(bodies[1])\n );\n }).await();\n});\n", "file_path": "tools/tests/utils-tests.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00022096378961578012, 0.00017282605404034257, 0.0001655783853493631, 0.00017001866945065558, 1.1117781468783505e-05]} {"hunk": {"id": 1, "code_window": [" * your Meteor package depends on.\n", " * @param {Object} dependencies An object where the keys are package\n", " * names and the values are one of:\n", " * 1. Version numbers in string form\n", " * 2. Http(s) URLs to a git commit by SHA.\n", " * 3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)\n", " *\n", " * Https URL example:\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" * 2. Http(s) URLs to a npm package\n"], "file_path": "tools/isobuild/package-npm.js", "type": "replace", "edit_start_line_idx": 26}, "file": ".build*\n", "file_path": "packages/accounts-google/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00016420330211985856, 0.00016420330211985856, 0.00016420330211985856, 0.00016420330211985856, 0.0]} {"hunk": {"id": 1, "code_window": [" * your Meteor package depends on.\n", " * @param {Object} dependencies An object where the keys are package\n", " * names and the values are one of:\n", " * 1. Version numbers in string form\n", " * 2. Http(s) URLs to a git commit by SHA.\n", " * 3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)\n", " *\n", " * Https URL example:\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" * 2. Http(s) URLs to a npm package\n"], "file_path": "tools/isobuild/package-npm.js", "type": "replace", "edit_start_line_idx": 26}, "file": "none\n", "file_path": "tools/tests/apps/package-stats-tests/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00016613442858215421, 0.00016613442858215421, 0.00016613442858215421, 0.00016613442858215421, 0.0]} {"hunk": {"id": 1, "code_window": [" * your Meteor package depends on.\n", " * @param {Object} dependencies An object where the keys are package\n", " * names and the values are one of:\n", " * 1. Version numbers in string form\n", " * 2. Http(s) URLs to a git commit by SHA.\n", " * 3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)\n", " *\n", " * Https URL example:\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" * 2. Http(s) URLs to a npm package\n"], "file_path": "tools/isobuild/package-npm.js", "type": "replace", "edit_start_line_idx": 26}, "file": "{\n \"lockfileVersion\": 1,\n \"dependencies\": {\n \"babel-plugin-syntax-class-properties\": {\n \"version\": \"6.13.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-syntax-class-properties/-/babel-plugin-syntax-class-properties-6.13.0.tgz\",\n \"integrity\": \"sha1-1+sjt5oxf4VDlixQW4J8fWysJ94=\"\n },\n \"babel-plugin-transform-class-properties\": {\n \"version\": \"6.9.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-class-properties/-/babel-plugin-transform-class-properties-6.9.0.tgz\",\n \"integrity\": \"sha1-DxgxuPeNcuT4FqC4vVk0Yj5RJms=\"\n },\n \"babel-plugin-transform-strict-mode\": {\n \"version\": \"6.8.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.8.0.tgz\",\n \"integrity\": \"sha1-wM5mIMtfLB+xArIPZXQRVcq8REo=\"\n },\n \"babel-runtime\": {\n \"version\": \"6.23.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.23.0.tgz\",\n \"integrity\": \"sha1-CpSJ8UTecO+zzkMArM2zKeL8VDs=\"\n },\n \"babel-types\": {\n \"version\": \"6.25.0\",\n \"resolved\": \"https://registry.npmjs.org/babel-types/-/babel-types-6.25.0.tgz\",\n \"integrity\": \"sha1-cK+ySNVmDl0Y+BHZHIMDtUE0oY4=\"\n },\n \"core-js\": {\n \"version\": \"2.4.1\",\n \"resolved\": \"https://registry.npmjs.org/core-js/-/core-js-2.4.1.tgz\",\n \"integrity\": \"sha1-TekR5mew6ukSTjQlS1OupvxhjT4=\"\n },\n \"esutils\": {\n \"version\": \"2.0.2\",\n \"resolved\": \"https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz\",\n \"integrity\": \"sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=\"\n },\n \"lodash\": {\n \"version\": \"4.17.4\",\n \"resolved\": \"https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz\",\n \"integrity\": \"sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=\"\n },\n \"regenerator-runtime\": {\n \"version\": \"0.10.5\",\n \"resolved\": \"https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz\",\n \"integrity\": \"sha1-M2w+/BIgrc7dosn6tntaeVWjNlg=\"\n },\n \"to-fast-properties\": {\n \"version\": \"1.0.3\",\n \"resolved\": \"https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz\",\n \"integrity\": \"sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=\"\n }\n }\n}\n", "file_path": "tools/tests/apps/modules/packages/modules-test-plugin/.npm/plugin/compile-arson/npm-shrinkwrap.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.0001822624763008207, 0.00016891815175767988, 0.00016578976646997035, 0.00016627056174911559, 5.974355644866591e-06]} {"hunk": {"id": 2, "code_window": [" selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n", "});\n", "\n", "selftest.define(\"parse url\", function () {\n", " selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n", " hostname: \"localhost\",\n", " port: \"3000\",\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", "selftest.define(\"isNpmUrl\", function () {\n", " selftest.expectTrue(utils.isNpmUrl(\"https://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"http://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+ssh://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+http://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+https://github.com/foo/bar\"));\n", "});\n", "\n"], "file_path": "tools/tests/utils-tests.js", "type": "add", "edit_start_line_idx": 62}, "file": "var selftest = require('../tool-testing/selftest.js');\nvar utils = require('../utils/utils.js');\n\nimport { sha1 } from '../fs/watch.js';\nimport httpHelpers from '../utils/http-helpers';\n\nselftest.define('subset generator', function () {\n var out = [];\n utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {\n out.push(x);\n });\n selftest.expectEqual(out, [\n [],\n [ 'a' ],\n [ 'b' ],\n [ 'c' ],\n [ 'a', 'b' ],\n [ 'a', 'c' ],\n [ 'b', 'c' ],\n [ 'a', 'b', 'c' ]\n ]);\n out = [];\n utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {\n out.push(x);\n if (x[1] === 'c') {\n // stop iterating\n return true;\n }\n });\n selftest.expectEqual(out, [\n [],\n [ 'a' ],\n [ 'b' ],\n [ 'c' ],\n [ 'a', 'b' ],\n [ 'a', 'c' ]\n ]);\n});\n\nselftest.define(\"url has scheme\", function () {\n // URL scheme must start with a letter, and then can be followed by\n // any number of alphanumerics, +, -, . RFC 2396 Appendix A.\n selftest.expectEqual(utils.hasScheme(\"http://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"https://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example.com\"), true);\n selftest.expectEqual(utils.hasScheme(\"http://example.com:80\"), true);\n selftest.expectEqual(utils.hasScheme(\"https://example.com:443\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example.com:443\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://example\"), true);\n selftest.expectEqual(utils.hasScheme(\"ddp://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example.comhttp://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example+com+http://\"), true);\n selftest.expectEqual(utils.hasScheme(\"example-com+http://\"), true);\n\n selftest.expectEqual(utils.hasScheme(\"example\"), false);\n selftest.expectEqual(utils.hasScheme(\"example.com\"), false);\n selftest.expectEqual(utils.hasScheme(\"example.com:443\"), false);\n selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n});\n\nselftest.define(\"parse url\", function () {\n selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"localhost:3000\"), {\n hostname: \"localhost\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"3000\"), {\n hostname: undefined,\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"3000example.com:3000\"), {\n hostname: \"3000example.com\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"http://example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"example.com:3000\"), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"127.0.0.1:3000\"), {\n hostname: \"127.0.0.1\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: undefined\n });\n selftest.expectEqual(utils.parseUrl(\"http://[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"https://[::]:3000\"), {\n hostname: \"::\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"[0000:0000:0000:0000:0000:0000:0000:0001]:3000\"), {\n hostname: \"0000:0000:0000:0000:0000:0000:0000:0001\",\n port: \"3000\",\n protocol: undefined\n });\n\n // tests for defaults\n selftest.expectEqual(utils.parseUrl(\"http://example.com:3000\", {\n hostname: \"foo.com\",\n port: \"4000\",\n protocol: \"https\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"http\"\n });\n selftest.expectEqual(utils.parseUrl(\"example.com:3000\", {\n port: \"4000\",\n protocol: \"https\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n selftest.expectEqual(utils.parseUrl(\"3000\", {\n port: \"4000\",\n protocol: \"https\",\n hostname: \"example.com\"\n }), {\n hostname: \"example.com\",\n port: \"3000\",\n protocol: \"https\"\n });\n});\n\nselftest.define(\"resume downloads\", ['net'], function () {\n // A reasonably big file that (I think) should take more than 1s to download\n // and that we know the size of\n const url = 'https://warehouse.meteor.com/builds/EXSxwGqYjjJKh3WMJ/1467929945102/DRyKg3bYHL/babel-compiler-6.8.4-os+web.browser+web.cordova.tgz';\n\n let interruptCount = 0;\n let bytesSinceLastInterrupt = 0;\n\n const resumedPromise = Promise.resolve().then(\n () => httpHelpers.getUrlWithResuming({\n url: url,\n encoding: null,\n retryDelaySecs: 1,\n onRequest(request) {\n request.on(\"data\", chunk => {\n bytesSinceLastInterrupt += chunk.length\n if (bytesSinceLastInterrupt > 500000) {\n bytesSinceLastInterrupt = 0;\n ++interruptCount;\n request.emit('error', 'pretend-http-error');\n request.emit('end');\n request.abort();\n }\n });\n }\n })\n );\n\n const normalPromise = Promise.resolve().then(\n () => httpHelpers.getUrl({\n url,\n encoding: null,\n })\n );\n\n Promise.all([\n resumedPromise,\n normalPromise,\n ]).then(bodies => {\n selftest.expectTrue(interruptCount > 1);\n\n selftest.expectEqual(\n bodies[0].length,\n bodies[1].length\n );\n\n selftest.expectEqual(\n sha1(bodies[0]),\n sha1(bodies[1])\n );\n }).await();\n});\n", "file_path": "tools/tests/utils-tests.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.5414947271347046, 0.06082042679190636, 0.00017152722284663469, 0.014375685714185238, 0.14749789237976074]} {"hunk": {"id": 2, "code_window": [" selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n", "});\n", "\n", "selftest.define(\"parse url\", function () {\n", " selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n", " hostname: \"localhost\",\n", " port: \"3000\",\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", "selftest.define(\"isNpmUrl\", function () {\n", " selftest.expectTrue(utils.isNpmUrl(\"https://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"http://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+ssh://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+http://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+https://github.com/foo/bar\"));\n", "});\n", "\n"], "file_path": "tools/tests/utils-tests.js", "type": "add", "edit_start_line_idx": 62}, "file": "# browser-policy-content\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/browser-policy-content) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/browser-policy-content)\n***\n\nThis is one of a family of packages that can be used to easily\nconfigure an app's browser-side security policies. The documentation\nis in the\n[browser-policy](https://atmospherejs.com/meteor/browser-policy)\npackage.\n", "file_path": "packages/browser-policy-content/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00016570537991356105, 0.00016570537991356105, 0.00016570537991356105, 0.00016570537991356105, 0.0]} {"hunk": {"id": 2, "code_window": [" selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n", "});\n", "\n", "selftest.define(\"parse url\", function () {\n", " selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n", " hostname: \"localhost\",\n", " port: \"3000\",\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", "selftest.define(\"isNpmUrl\", function () {\n", " selftest.expectTrue(utils.isNpmUrl(\"https://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"http://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+ssh://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+http://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+https://github.com/foo/bar\"));\n", "});\n", "\n"], "file_path": "tools/tests/utils-tests.js", "type": "add", "edit_start_line_idx": 62}, "file": "# accounts-ui-unstyled\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/accounts-ui-unstyled) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/accounts-ui-unstyled)\n***\n\nA version of `accounts-ui` without the CSS, so that you can add your\nown styling. See the [`accounts-ui`\nREADME](https://atmospherejs.com/meteor/accounts-ui) and the\nMeteor Accounts [project page](https://www.meteor.com/accounts) for\ndetails.", "file_path": "packages/accounts-ui-unstyled/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00016987936396617442, 0.00016987936396617442, 0.00016987936396617442, 0.00016987936396617442, 0.0]} {"hunk": {"id": 2, "code_window": [" selftest.expectEqual(utils.hasScheme(\"http:/example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"http:example\"), false);\n", " selftest.expectEqual(utils.hasScheme(\"example_com+http://\"), false);\n", "});\n", "\n", "selftest.define(\"parse url\", function () {\n", " selftest.expectEqual(utils.parseUrl(\"http://localhost:3000\"), {\n", " hostname: \"localhost\",\n", " port: \"3000\",\n"], "labels": ["keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep"], "after_edit": ["\n", "selftest.define(\"isNpmUrl\", function () {\n", " selftest.expectTrue(utils.isNpmUrl(\"https://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"http://github.com/caolan/async/archive/v2.3.0.tar.gz\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+ssh://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+http://github.com/foo/bar\"));\n", " selftest.expectTrue(utils.isNpmUrl(\"git+https://github.com/foo/bar\"));\n", "});\n", "\n"], "file_path": "tools/tests/utils-tests.js", "type": "add", "edit_start_line_idx": 62}, "file": "var Fiber = require(\"fibers\");\nvar _ = require(\"underscore\");\n\nvar config = require('./config.js');\nvar files = require('../fs/files.js');\nvar auth = require('./auth.js');\nvar ServiceConnection = require('./service-connection.js');\nvar httpHelpers = require('../utils/http-helpers.js');\nvar Console = require('../console/console.js').Console;\n\n// The name of the package that you add to your app to opt out of\n// sending stats.\nvar OPT_OUT_PACKAGE_NAME = \"package-stats-opt-out\";\n\n// Return a list of packages used by this app, both directly and\n// indirectly. Formatted as a list of objects with 'name', 'version'\n// and 'direct', which is how the `recordAppPackages` method on the\n// stats server expects to get this list.\nvar packageList = function (projectContext) {\n var versions = [];\n projectContext.packageMap.eachPackage(function (name, info) {\n versions.push({\n name: name,\n version: info.version,\n local: info.kind === 'local',\n direct: !! projectContext.projectConstraintsFile.getConstraint(name)\n });\n });\n return versions;\n};\n\n// Options:\n// - what: one of \"sdk.bundle\", \"sdk.deploy\", \"sdk.run\".\n// - projectContext: the ProjectContext. prepareProjectForBuild\n// must have run successfully. We must extract all necessary data\n// from this before yielding.\n// - site: If it's a deploy, the name of the site (\"foo.meteor.com\") that we're\n// deploying to.\nvar recordPackages = function (options) {\n // Before doing anything, look at the app's dependencies to see if the\n // opt-out package is there; if present, we don't record any stats.\n var packages = packageList(options.projectContext);\n if (_.findWhere(packages, { name: OPT_OUT_PACKAGE_NAME })) {\n // Print some output for the 'report-stats' self-test.\n if (process.env.METEOR_PACKAGE_STATS_TEST_OUTPUT) {\n process.stdout.write(\"PACKAGE STATS NOT SENT\\n\");\n }\n return;\n }\n\n var appIdentifier = options.projectContext.appIdentifier;\n\n // We do this inside a new fiber to avoid blocking anything on talking\n // to the package stats server. If we can't connect, for example, we\n // don't care; we'll just miss out on recording these packages.\n // This also gives it its own buildmessage state.\n // However, we do make sure to have already extracted the package list from\n // projectContext, since it might mutate out from under us otherwise.\n Fiber(function () {\n\n var details = {\n what: options.what,\n userAgent: httpHelpers.getUserAgent(),\n sessionId: auth.getSessionId(config.getAccountsDomain()),\n site: options.site\n };\n\n try {\n var conn = connectToPackagesStatsServer();\n var accountsConfiguration = auth.getAccountsConfiguration(conn);\n\n if (auth.isLoggedIn()) {\n try {\n auth.loginWithTokenOrOAuth(\n conn,\n accountsConfiguration,\n config.getPackageStatsServerUrl(),\n config.getPackageStatsServerDomain(),\n \"package-stats-server\"\n );\n } catch (err) {\n // Do nothing. If we can't log in, we should continue and report\n // stats anonymously.\n //\n // We log other errors with `logErrorIfInCheckout`, but login\n // errors can happen in normal operation when nothing is wrong\n // (e.g. login token expired or revoked) so we don't log them.\n }\n }\n\n var result = conn.call(\"recordAppPackages\",\n appIdentifier,\n packages,\n details);\n\n // If the stats server sent us a new session, save it for use on\n // subsequent requests.\n if (result && result.newSessionId) {\n auth.setSessionId(config.getAccountsDomain(), result.newSessionId);\n }\n\n if (process.env.METEOR_PACKAGE_STATS_TEST_OUTPUT) {\n // Print some output for the 'report-stats' self-test.\n process.stdout.write(\"PACKAGE STATS SENT\\n\");\n }\n } catch (err) {\n logErrorIfInCheckout(err);\n // Do nothing. A failure to record package stats shouldn't be\n // visible to the end user and shouldn't affect whatever command\n // they are running.\n } finally {\n conn && conn.close();\n }\n }).run();\n};\n\nvar logErrorIfInCheckout = function (err) {\n if (files.inCheckout() || process.env.METEOR_PACKAGE_STATS_TEST_OUTPUT) {\n Console.warn(\"Failed to record package usage.\");\n Console.warn(\n \"(This error is hidden when you are not running Meteor from a\",\n \"checkout.)\");\n var printErr = err.stack || err;\n Console.rawWarn(printErr + \"\\n\");\n Console.warn();\n Console.warn();\n }\n};\n\n// Used in a test (and can only be used against the testing packages\n// server) to fetch one package stats entry for a given application.\nvar getPackagesForAppIdInTest = function (projectContext) {\n var conn = connectToPackagesStatsServer();\n var result;\n try {\n result = conn.call(\n \"getPackagesForAppId\",\n projectContext.appIdentifier);\n if (result && result.details) {\n result.details.packages = _.sortBy(result.details.packages, \"name\");\n }\n } finally {\n conn.close();\n }\n\n return result;\n};\n\nvar connectToPackagesStatsServer = function () {\n return new ServiceConnection(\n config.getPackageStatsServerUrl(),\n {_dontPrintErrors: true}\n );\n};\n\nexports.recordPackages = recordPackages;\nexports.packageList = packageList; // for use in the \"stats\" self-test.\nexports.getPackagesForAppIdInTest = getPackagesForAppIdInTest;\n", "file_path": "tools/meteor-services/stats.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00017767041572369635, 0.00017325332737527788, 0.00016794232942629606, 0.00017351467977277935, 2.5757590265129693e-06]} {"hunk": {"id": 3, "code_window": ["\n", "exports.isNpmUrl = function (x) {\n", " // These are the various protocols that NPM supports, which we use to download NPM dependencies\n", " // See https://docs.npmjs.com/files/package.json#git-urls-as-dependencies\n", " return exports.isUrlWithSha(x) || /^(git|git\\+ssh|git\\+http|git\\+https)?:\\/\\//.test(x);\n", "};\n", "\n", "exports.isPathRelative = function (x) {\n", " return x.charAt(0) !== '/';\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" return /^(git|git\\+ssh|git\\+http|git\\+https|https|http)?:\\/\\//.test(x);\n"], "file_path": "tools/utils/utils.js", "type": "replace", "edit_start_line_idx": 500}, "file": "import { ensureOnlyValidVersions } from \"../utils/utils.js\";\nimport buildmessage from \"../utils/buildmessage.js\";\nimport NpmDiscards from \"./npm-discards.js\";\n\nconst nodeRequire = require;\n\nexport class PackageNpm {\n /**\n * @summary Class of the 'Npm' object visible in package.js\n * @locus package.js\n * @instanceName Npm\n * @showInstanceName true\n */\n constructor() {\n // Files to be stripped from the installed NPM dependency tree. See\n // the Npm.strip comment below for further usage information.\n this._discards = new NpmDiscards;\n this._dependencies = null;\n }\n\n /**\n * @summary Specify which [NPM](https://www.npmjs.org/) packages\n * your Meteor package depends on.\n * @param {Object} dependencies An object where the keys are package\n * names and the values are one of:\n * 1. Version numbers in string form\n * 2. Http(s) URLs to a git commit by SHA.\n * 3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)\n *\n * Https URL example:\n *\n * ```js\n * Npm.depends({\n * moment: \"2.8.3\",\n * async: \"https://github.com/caolan/async/archive/71fa2638973dafd8761fa5457c472a312cc820fe.tar.gz\"\n * });\n * ```\n *\n * Git URL example:\n *\n * ```js\n * Npm.depends({\n * moment: \"2.8.3\",\n * async: \"git+https://github.com/caolan/async#master\"\n * });\n * ```\n * @locus package.js\n */\n depends(dependencies) {\n // XXX make dependencies be separate between use and test, so that\n // production doesn't have to ship all of the npm modules used by test\n // code\n if (this._dependencies) {\n buildmessage.error(\"Npm.depends may only be called once per package\",\n { useMyCaller: true });\n // recover by ignoring the Npm.depends line\n return;\n }\n\n if (typeof dependencies !== 'object') {\n buildmessage.error(\"the argument to Npm.depends should be an \" +\n \"object, like this: {gcd: '0.0.0'}\",\n { useMyCaller: true });\n // recover by ignoring the Npm.depends line\n return;\n }\n\n // don't allow npm fuzzy versions so that there is complete\n // consistency when deploying a meteor app\n //\n // XXX use something like seal or lockdown to have *complete*\n // confidence we're running the same code?\n try {\n ensureOnlyValidVersions(dependencies, {\n forCordova: false\n });\n\n } catch (e) {\n buildmessage.error(e.message, {\n useMyCaller: true,\n downcase: true\n });\n\n // recover by ignoring the Npm.depends line\n return;\n }\n\n this._dependencies = dependencies;\n }\n\n // The `Npm.strip` method makes up for packages that have missing\n // or incomplete .npmignore files by telling the bundler to strip out\n // certain unnecessary files and/or directories during `meteor build`.\n //\n // The `discards` parameter should be an object whose keys are\n // top-level package names and whose values are arrays of strings\n // (or regular expressions) that match paths in that package's\n // directory that should be stripped before installation. For\n // example:\n //\n // Npm.strip({\n // connect: [/*\\.wmv$/],\n // useragent: [\"tests/\"]\n // });\n //\n // This means (1) \"remove any files with the `.wmv` extension from\n // the 'connect' package directory\" and (2) \"remove the 'tests'\n // directory from the 'useragent' package directory.\"\n strip(discards) {\n this._discards.merge(discards);\n }\n\n require(name) {\n try {\n return nodeRequire(name); // from the dev bundle\n } catch (e) {\n buildmessage.error(\n \"can't find npm module '\" + name +\n \"'. In package.js, Npm.require can only find built-in modules.\",\n { useMyCaller: true });\n // recover by, uh, returning undefined, which is likely to\n // have some knock-on effects\n }\n }\n}\n", "file_path": "tools/isobuild/package-npm.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.005665197502821684, 0.0010410093236714602, 0.00016641618276480585, 0.0004949423600919545, 0.0015148100210353732]} {"hunk": {"id": 3, "code_window": ["\n", "exports.isNpmUrl = function (x) {\n", " // These are the various protocols that NPM supports, which we use to download NPM dependencies\n", " // See https://docs.npmjs.com/files/package.json#git-urls-as-dependencies\n", " return exports.isUrlWithSha(x) || /^(git|git\\+ssh|git\\+http|git\\+https)?:\\/\\//.test(x);\n", "};\n", "\n", "exports.isPathRelative = function (x) {\n", " return x.charAt(0) !== '/';\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" return /^(git|git\\+ssh|git\\+http|git\\+https|https|http)?:\\/\\//.test(x);\n"], "file_path": "tools/utils/utils.js", "type": "replace", "edit_start_line_idx": 500}, "file": "node_modules\n", "file_path": "packages/boilerplate-generator-tests/.npm/package/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.0001662125432631001, 0.0001662125432631001, 0.0001662125432631001, 0.0001662125432631001, 0.0]} {"hunk": {"id": 3, "code_window": ["\n", "exports.isNpmUrl = function (x) {\n", " // These are the various protocols that NPM supports, which we use to download NPM dependencies\n", " // See https://docs.npmjs.com/files/package.json#git-urls-as-dependencies\n", " return exports.isUrlWithSha(x) || /^(git|git\\+ssh|git\\+http|git\\+https)?:\\/\\//.test(x);\n", "};\n", "\n", "exports.isPathRelative = function (x) {\n", " return x.charAt(0) !== '/';\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" return /^(git|git\\+ssh|git\\+http|git\\+https|https|http)?:\\/\\//.test(x);\n"], "file_path": "tools/utils/utils.js", "type": "replace", "edit_start_line_idx": 500}, "file": "Package.describe({\n summary: \"Dictionary data structure allowing non-string keys\",\n version: '1.1.0'\n});\n\nPackage.onUse(function (api) {\n api.use('ecmascript');\n api.use('ejson');\n api.mainModule('id-map.js');\n api.export('IdMap');\n});\n", "file_path": "packages/id-map/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.0002145407343050465, 0.00019044244254473597, 0.00016634415078442544, 0.00019044244254473597, 2.409829176031053e-05]} {"hunk": {"id": 3, "code_window": ["\n", "exports.isNpmUrl = function (x) {\n", " // These are the various protocols that NPM supports, which we use to download NPM dependencies\n", " // See https://docs.npmjs.com/files/package.json#git-urls-as-dependencies\n", " return exports.isUrlWithSha(x) || /^(git|git\\+ssh|git\\+http|git\\+https)?:\\/\\//.test(x);\n", "};\n", "\n", "exports.isPathRelative = function (x) {\n", " return x.charAt(0) !== '/';\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" return /^(git|git\\+ssh|git\\+http|git\\+https|https|http)?:\\/\\//.test(x);\n"], "file_path": "tools/utils/utils.js", "type": "replace", "edit_start_line_idx": 500}, "file": "# jquery\n[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/jquery) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/jquery)\n***\n\n[jQuery](http://jquery.com/) is a fast and concise JavaScript\nLibrary that simplifies HTML document traversing, event handling,\nanimating, and Ajax interactions for rapid web development.\n\nThe `jquery` package adds the jQuery library to the client JavaScript\nbundle. It has no effect on the server.\n\nThis package is automatically included in every new Meteor app by `meteor create`.\n\nIn addition to the `jquery` package, Meteor provides several jQuery\nplugins as separate packages. These include:\n\n* [`jquery-waypoints`](http://imakewebthings.com/jquery-waypoints/)\n", "file_path": "packages/jquery/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/16b74e5c0cfab46093f7c7e1ec338844f90121c4", "dependency_score": [0.00016483974468428642, 0.00016353491810150445, 0.00016223007696680725, 0.00016353491810150445, 1.3048338587395847e-06]} {"hunk": {"id": 0, "code_window": ["#!/bin/bash\n", "\n", "BUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n", "\n", "# OS Check. Put here because here is where we download the precompiled\n", "# bundles that are arch specific.\n", "UNAME=$(uname)\n", "if [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["BUNDLE_VERSION=0.4.39\n"], "file_path": "meteor", "type": "replace", "edit_start_line_idx": 2}, "file": "// This file exists because it is the file in the tool that is not automatically\n// transpiled by Babel\n\nrequire('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n\n// Install a global ES6-compliant Promise constructor that knows how to\n// run all its callbacks in Fibers.\nglobal.Promise = require(\"meteor-promise\");\n\n// Include helpers from NPM so that the compiler doesn't need to add boilerplate\n// at the top of every file\nrequire(\"meteor-babel\").installRuntime();\n\n// Installs source map support with a hook to add functions to look for source\n// maps in custom places\nrequire('./source-map-retriever-stack.js');\n\n// Run the Meteor command line tool\nrequire('./main.js');\n", "file_path": "tools/main-transpile-wrapper.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00016944193339440972, 0.00016684102592989802, 0.0001642401039134711, 0.00016684102592989802, 2.6009147404693067e-06]} {"hunk": {"id": 0, "code_window": ["#!/bin/bash\n", "\n", "BUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n", "\n", "# OS Check. Put here because here is where we download the precompiled\n", "# bundles that are arch specific.\n", "UNAME=$(uname)\n", "if [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["BUNDLE_VERSION=0.4.39\n"], "file_path": "meteor", "type": "replace", "edit_start_line_idx": 2}, "file": "none\n", "file_path": "tools/tests/apps/failover-test/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00016922137001529336, 0.00016922137001529336, 0.00016922137001529336, 0.00016922137001529336, 0.0]} {"hunk": {"id": 0, "code_window": ["#!/bin/bash\n", "\n", "BUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n", "\n", "# OS Check. Put here because here is where we download the precompiled\n", "# bundles that are arch specific.\n", "UNAME=$(uname)\n", "if [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["BUNDLE_VERSION=0.4.39\n"], "file_path": "meteor", "type": "replace", "edit_start_line_idx": 2}, "file": "/* CSS declarations go here */\n\n\n* { margin: 0; padding: 0 }\n\n#grid td {\n width: 20px;\n height: 20px;\n vertical-align: middle;\n text-align: center;\n}\n\n.color0 { background: #eee; }\n.color1 { background: #d8f; }\n.color2 { background: #8c3; }\n.color3 { background: #39d; }\n.color4 { background: #d96; }\n.color5 { background: #a95; }\n", "file_path": "examples/other/domrange-grid/domrange-grid.css", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017815796309150755, 0.0001730591175146401, 0.00016796027193777263, 0.0001730591175146401, 5.098845576867461e-06]} {"hunk": {"id": 0, "code_window": ["#!/bin/bash\n", "\n", "BUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n", "\n", "# OS Check. Put here because here is where we download the precompiled\n", "# bundles that are arch specific.\n", "UNAME=$(uname)\n", "if [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["BUNDLE_VERSION=0.4.39\n"], "file_path": "meteor", "type": "replace", "edit_start_line_idx": 2}, "file": "var _ = require('underscore');\nvar packageClient = require('./package-client.js');\nvar watch = require('./watch.js');\nvar archinfo = require('./archinfo.js');\nvar isopack = require('./isopack.js');\nvar buildmessage = require('./buildmessage.js');\nvar tropohouse = require('./tropohouse.js');\nvar files = require('./files.js');\nvar utils = require('./utils.js');\nvar catalog = require('./catalog.js');\nvar PackageSource = require('./package-source.js');\nvar VersionParser = require('./package-version-parser.js');\n\n// LocalCatalog represents packages located in the application's\n// package directory, other package directories specified via an\n// environment variable, and core packages in the repo if meteor is\n// being run from a git checkout.\nvar LocalCatalog = function (options) {\n var self = this;\n options = options || {};\n\n // Package server data. Maps package name to a {packageSource, packageRecord,\n // versionRecord} object.\n self.packages = {};\n\n self.initialized = false;\n\n // Local directories to search for package source trees\n self.localPackageSearchDirs = null;\n\n // Package source trees added explicitly through a directory (not through a\n // parent search directory). We mainly use this to allow the user to run\n // test-packages against a package in a specific directory.\n self.explicitlyAddedLocalPackageDirs = [];\n\n // All packages found either by localPackageSearchDirs or\n // explicitlyAddedLocalPackageDirs. There is a hierarchy of packages, as\n // detailed below and there can only be one local version of a package at a\n // time. This refers to the package by the specific package directory that we\n // need to process.\n self.effectiveLocalPackageDirs = [];\n\n // A WatchSet that detects when the set of packages and their locations\n // changes. ie, the listings of 'packages' directories, and the contents of\n // package.js files underneath. It does NOT track the rest of the source of\n // the packages: that wouldn't be helpful to the runner since it would be too\n // coarse to tell if a change is client-only or not. (But any change to the\n // layout of where packages live counts as a non-client-only change.)\n self.packageLocationWatchSet = new watch.WatchSet;\n\n self._nextId = 1;\n};\n\n_.extend(LocalCatalog.prototype, {\n toString: function () {\n var self = this;\n return \"LocalCatalog [localPackageSearchDirs=\"\n + self.localPackageSearchDirs + \"]\";\n },\n\n // Initialize the Catalog. This must be called before any other\n // Catalog function.\n\n // options:\n // - localPackageSearchDirs: an array of paths on local disk, that contain\n // subdirectories, that each contain a source tree for a package that\n // should override the packages on the package server. For example, if\n // there is a package 'foo' that we find through localPackageSearchDirs,\n // then we will ignore all versions of 'foo' that we find through the\n // package server. Directories that don't exist (or paths that aren't\n // directories) will be silently ignored.\n // - explicitlyAddedLocalPackageDirs: an array of paths which THEMSELVES\n // are package source trees. Takes precedence over packages found\n // via localPackageSearchDirs.\n // - buildingIsopackets: true if we are building isopackets\n initialize: function (options) {\n var self = this;\n buildmessage.assertInCapture();\n\n options = options || {};\n\n self.localPackageSearchDirs = _.map(\n options.localPackageSearchDirs, function (p) {\n return files.pathResolve(p);\n });\n self.explicitlyAddedLocalPackageDirs = _.map(\n options.explicitlyAddedLocalPackageDirs, function (p) {\n return files.pathResolve(p);\n });\n\n self._computeEffectiveLocalPackages();\n self._loadLocalPackages(options.buildingIsopackets);\n self.initialized = true;\n },\n\n // Throw if the catalog's self.initialized value has not been set to true.\n _requireInitialized: function () {\n var self = this;\n\n if (! self.initialized)\n throw new Error(\"catalog not initialized yet?\");\n },\n\n // Return an array with the names of all of the packages that we know about,\n // in no particular order.\n getAllPackageNames: function (options) {\n var self = this;\n self._requireInitialized();\n\n return _.keys(self.packages);\n },\n\n // Return an array with the names of all of the non-test packages that we know\n // about, in no particular order.\n getAllNonTestPackageNames: function (options) {\n var self = this;\n self._requireInitialized();\n\n var ret = [];\n _.each(self.packages, function (record, name) {\n record.versionRecord.isTest || ret.push(name);\n });\n return ret;\n },\n\n // Returns general (non-version-specific) information about a\n // package, or null if there is no such package.\n getPackage: function (name, options) {\n var self = this;\n self._requireInitialized();\n options = options || {};\n\n if (!_.has(self.packages, name))\n return null;\n return self.packages[name].packageRecord;\n },\n\n // Given a package, returns an array of the versions available (ie, the one\n // version we have, or an empty array).\n getSortedVersions: function (name) {\n var self = this;\n self._requireInitialized();\n\n if (!_.has(self.packages, name))\n return [];\n return [self.packages[name].versionRecord.version];\n },\n\n // Given a package, returns an array of the version records available (ie, the\n // one version we have, or an empty array).\n getSortedVersionRecords: function (name) {\n var self = this;\n self._requireInitialized();\n\n if (!_.has(self.packages, name))\n return [];\n return [self.packages[name].versionRecord];\n },\n\n // Return information about a particular version of a package, or\n // null if there is no such package or version.\n getVersion: function (name, version) {\n var self = this;\n self._requireInitialized();\n\n if (!_.has(self.packages, name))\n return null;\n var versionRecord = self.packages[name].versionRecord;\n if (versionRecord.version !== version)\n return null;\n return versionRecord;\n },\n\n // As getVersion, but returns info on the latest version of the\n // package, or null if the package doesn't exist or has no versions.\n getLatestVersion: function (name) {\n var self = this;\n\n if (!_.has(self.packages, name))\n return null;\n return self.packages[name].versionRecord;\n },\n\n getVersionBySourceRoot: function (sourceRoot) {\n var self = this;\n var packageObj = _.find(self.packages, function (p) {\n return p.packageSource.sourceRoot === sourceRoot;\n });\n if (! packageObj)\n return null;\n return packageObj.versionRecord;\n },\n\n // Compute self.effectiveLocalPackageDirs from self.localPackageSearchDirs and\n // self.explicitlyAddedLocalPackageDirs.\n _computeEffectiveLocalPackages: function () {\n var self = this;\n buildmessage.assertInCapture();\n\n self.effectiveLocalPackageDirs = [];\n\n buildmessage.enterJob(\"looking for packages\", function () {\n _.each(self.explicitlyAddedLocalPackageDirs, function (explicitDir) {\n var packageJs = watch.readAndWatchFile(\n self.packageLocationWatchSet,\n files.pathJoin(explicitDir, 'package.js'));\n // We asked specifically for this directory, but it has no package!\n if (packageJs === null) {\n buildmessage.error(\"package has no package.js file\", {\n file: explicitDir\n });\n return; // recover by ignoring\n }\n self.effectiveLocalPackageDirs.push(explicitDir);\n });\n\n _.each(self.localPackageSearchDirs, function (searchDir) {\n var possiblePackageDirs = watch.readAndWatchDirectory(\n self.packageLocationWatchSet, {\n absPath: searchDir,\n include: [/\\/$/]\n });\n // Not a directory? Ignore.\n if (possiblePackageDirs === null)\n return;\n\n _.each(possiblePackageDirs, function (subdir) {\n // readAndWatchDirectory adds a slash to the end of directory names to\n // differentiate them from filenames. Remove it.\n subdir = subdir.substr(0, subdir.length - 1);\n var absPackageDir = files.pathJoin(searchDir, subdir);\n\n // Consider a directory to be a package source tree if it contains\n // 'package.js'. (We used to support isopacks in\n // localPackageSearchDirs, but no longer.)\n var packageJs = watch.readAndWatchFile(\n self.packageLocationWatchSet,\n files.pathJoin(absPackageDir, 'package.js'));\n if (packageJs !== null) {\n // Let earlier package directories override later package\n // directories.\n\n // We don't know the name of the package, so we can't deal with\n // duplicates yet. We are going to have to rely on the fact that we\n // are putting these in in order, to be processed in order.\n self.effectiveLocalPackageDirs.push(absPackageDir);\n }\n });\n });\n });\n },\n\n _loadLocalPackages: function (buildingIsopackets) {\n var self = this;\n buildmessage.assertInCapture();\n\n // Load the package source from a directory. We don't know the names of our\n // local packages until we do this.\n //\n // THIS MUST BE RUN IN LOAD ORDER. Let's say that we have two directories\n // for mongo-livedata. The first one processed by this function will be\n // canonical. The second one will be ignored.\n //\n // (note: this is the behavior that we want for overriding things in\n // checkout. It is not clear that you get good UX if you have two packages\n // with the same name in your app. We don't check that.)\n var initSourceFromDir = function (packageDir, definiteName) {\n var packageSource = new PackageSource;\n buildmessage.enterJob({\n title: \"reading package from `\" + packageDir + \"`\",\n rootPath: packageDir\n }, function () {\n var initFromPackageDirOptions = {\n buildingIsopackets: !! buildingIsopackets\n };\n // If we specified a name, then we know what we want to get and should\n // pass that into the options. Otherwise, we will use the 'name'\n // attribute from package-source.js.\n if (definiteName) {\n initFromPackageDirOptions.name = definiteName;\n }\n packageSource.initFromPackageDir(packageDir, initFromPackageDirOptions);\n if (buildmessage.jobHasMessages())\n return; // recover by ignoring\n\n // Now that we have initialized the package from package.js, we know its\n // name.\n var name = packageSource.name;\n\n // We should only have one package dir for each name; in this case, we\n // are going to take the first one we get (since we preserved the order\n // in which we loaded local package dirs when running this function.)\n if (_.has(self.packages, name))\n return;\n\n self.packages[name] = {\n packageSource: packageSource,\n packageRecord: {\n _id: \"PID\" + self._nextId++,\n name: name,\n maintainers: null,\n lastUpdated: null\n },\n versionRecord: {\n _id: \"VID\" + self._nextId++,\n packageName: name,\n testName: packageSource.testName,\n version: packageSource.version,\n publishedBy: null,\n description: packageSource.metadata.summary,\n git: packageSource.metadata.git,\n dependencies: packageSource.getDependencyMetadata(),\n source: null,\n lastUpdated: null,\n published: null,\n isTest: packageSource.isTest,\n debugOnly: packageSource.debugOnly,\n containsPlugins: packageSource.containsPlugins()\n }\n };\n\n // If this is NOT a test package AND it has tests (tests will be\n // marked as test packages by package source, so we will not recurse\n // infinitely), then process that too.\n if (!packageSource.isTest && packageSource.testName) {\n initSourceFromDir(packageSource.sourceRoot, packageSource.testName);\n }\n });\n };\n\n // Load the package sources for packages and their tests into\n // self.packages.\n //\n // XXX We should make this work with parallel: true; right now it seems to\n // hit node problems.\n buildmessage.forkJoin(\n { 'title': 'initializing packages', parallel: false },\n self.effectiveLocalPackageDirs,\n function (dir) {\n initSourceFromDir(dir);\n });\n },\n\n getPackageSource: function (name) {\n var self = this;\n if (! _.has(self.packages, name))\n return null;\n return self.packages[name].packageSource;\n }\n});\n\nexports.LocalCatalog = LocalCatalog;\n", "file_path": "tools/catalog-local.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.0003674793697427958, 0.00017850942094810307, 0.00016449399117846042, 0.0001680493587628007, 3.593510700738989e-05]} {"hunk": {"id": 1, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-server-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "#!/bin/bash\n\nBUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n\n# OS Check. Put here because here is where we download the precompiled\n# bundles that are arch specific.\nUNAME=$(uname)\nif [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n echo \"Sorry, this OS is not supported.\"\n exit 1\nfi\n\nif [ \"$UNAME\" = \"Darwin\" ] ; then\n if [ \"i386\" != \"$(uname -p)\" -o \"1\" != \"$(sysctl -n hw.cpu64bit_capable 2>/dev/null || echo 0)\" ] ; then\n\n # Can't just test uname -m = x86_64, because Snow Leopard can\n # return other values.\n echo \"Only 64-bit Intel processors are supported at this time.\"\n exit 1\n fi\n ARCH=\"x86_64\"\nelif [ \"$UNAME\" = \"Linux\" ] ; then\n ARCH=\"$(uname -m)\"\n if [ \"$ARCH\" != \"i686\" -a \"$ARCH\" != \"x86_64\" ] ; then\n echo \"Unsupported architecture: $ARCH\"\n echo \"Meteor only supports i686 and x86_64 for now.\"\n exit 1\n fi\nfi\nPLATFORM=\"${UNAME}_${ARCH}\"\n\n# Find the script dir, following symlinks. Note that symlink can be relative or\n# absolute. Too bad 'readlink -f' and 'realpath' (the command-line program) are\n# not portable. We don't stress about infinite loops or bad links, because the\n# OS has already resolved this symlink chain once in order to actually run the\n# shell script.\nORIG_DIR=\"$(pwd)\"\nSCRIPT=\"$0\"\nwhile true; do\n # The symlink might be relative, so we have to actually cd to the right place\n # each time in order to resolve it.\n cd \"$(dirname \"$SCRIPT\")\"\n if [ ! -L \"$(basename \"$SCRIPT\")\" ]; then\n SCRIPT_DIR=\"$(pwd -P)\"\n break\n fi\n SCRIPT=\"$(readlink \"$(basename \"$SCRIPT\")\")\"\ndone\ncd \"$ORIG_DIR\"\n\n\n\nfunction install_dev_bundle {\n set -e\n trap \"echo Failed to install dependency kit.\" EXIT\n\n TARBALL=\"dev_bundle_${PLATFORM}_${BUNDLE_VERSION}.tar.gz\"\n BUNDLE_TMPDIR=\"$SCRIPT_DIR/dev_bundle.xxx\"\n\n rm -rf \"$BUNDLE_TMPDIR\"\n mkdir \"$BUNDLE_TMPDIR\"\n\n # duplicated in scripts/windows/download-dev-bundle.ps1:\n DEV_BUNDLE_URL_ROOT=\"https://d3sqy0vbqsdhku.cloudfront.net/\"\n # If you set $USE_TEST_DEV_BUNDLE_SERVER then we will download\n # dev bundles copied by copy-dev-bundle-from-jenkins.sh without --prod.\n # It still only does this if the version number has changed\n # (setting it won't cause it to automatically delete a prod dev bundle).\n if [ -n \"$USE_TEST_DEV_BUNDLE_SERVER\" ] ; then\n DEV_BUNDLE_URL_ROOT=\"https://s3.amazonaws.com/com.meteor.static/test/\"\n fi\n\n if [ -f \"$SCRIPT_DIR/$TARBALL\" ] ; then\n echo \"Skipping download and installing kit from $SCRIPT_DIR/$TARBALL\" >&2\n tar -xzf \"$SCRIPT_DIR/$TARBALL\" -C \"$BUNDLE_TMPDIR\"\n elif [ -n \"$SAVE_DEV_BUNDLE_TARBALL\" ] ; then\n # URL duplicated in tools/server/target.sh.in\n curl -# \"$DEV_BUNDLE_URL_ROOT$TARBALL\" >\"$SCRIPT_DIR/$TARBALL\"\n tar -xzf \"$SCRIPT_DIR/$TARBALL\" -C \"$BUNDLE_TMPDIR\"\n else\n curl -# \"$DEV_BUNDLE_URL_ROOT$TARBALL\" | tar -xzf - -C \"$BUNDLE_TMPDIR\"\n fi\n\n test -x \"${BUNDLE_TMPDIR}/bin/node\" # bomb out if it didn't work, eg no net\n\n # Delete old dev bundle and rename the new one on top of it.\n rm -rf \"$SCRIPT_DIR/dev_bundle\"\n mv \"$BUNDLE_TMPDIR\" \"$SCRIPT_DIR/dev_bundle\"\n\n echo \"Installed dependency kit v${BUNDLE_VERSION} in dev_bundle.\" >&2\n echo >&2\n\n trap - EXIT\n set +e\n}\n\n\nif [ -d \"$SCRIPT_DIR/.git\" ] || [ -f \"$SCRIPT_DIR/.git\" ]; then\n # In a checkout.\n if [ ! -d \"$SCRIPT_DIR/dev_bundle\" ] ; then\n echo \"It's the first time you've run Meteor from a git checkout.\" >&2\n echo \"I will download a kit containing all of Meteor's dependencies.\" >&2\n install_dev_bundle\n elif [ ! -f \"$SCRIPT_DIR/dev_bundle/.bundle_version.txt\" ] ||\n grep -qvx \"$BUNDLE_VERSION\" \"$SCRIPT_DIR/dev_bundle/.bundle_version.txt\" ; then\n echo \"Your dependency kit is out of date. I will download the new one.\" >&2\n install_dev_bundle\n fi\n\n export BABEL_CACHE_DIR=\"$SCRIPT_DIR/.babel-cache\"\nfi\n\nDEV_BUNDLE=\"$SCRIPT_DIR/dev_bundle\"\nMETEOR=\"$SCRIPT_DIR/tools/main-transpile-wrapper.js\"\n\n\n# Bump our file descriptor ulimit as high as it will go. This is a\n# temporary workaround for dependancy watching holding open too many\n# files: https://app.asana.com/0/364581412985/472479912325\nif [ \"$(ulimit -n)\" != \"unlimited\" ] ; then\n ulimit -n 16384 > /dev/null 2>&1 || \\\n ulimit -n 8192 > /dev/null 2>&1 || \\\n ulimit -n 4096 > /dev/null 2>&1 || \\\n ulimit -n 2048 > /dev/null 2>&1 || \\\n ulimit -n 1024 > /dev/null 2>&1 || \\\n ulimit -n 512 > /dev/null 2>&1\nfi\n\n# We used to set $NODE_PATH here to include the node_modules from the dev\n# bundle, but now we just get them from the symlink at tools/node_modules. This\n# is better because node_modules directories found via the ancestor walk from\n# the script take precedence over $NODE_PATH; it used to be that users would\n# screw up their meteor installs by have a ~/node_modules\n\nexec \"$DEV_BUNDLE/bin/node\" \"$METEOR\" \"$@\"\n", "file_path": "meteor", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00020539821707643569, 0.00017107788880821317, 0.00016356042760889977, 0.0001684988383203745, 9.903935278998688e-06]} {"hunk": {"id": 1, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-server-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "// Like _.isArray, but doesn't regard polyfilled Uint8Arrays on old browsers as\n// arrays.\n// XXX maybe this should be EJSON.isArray\nisArray = function (x) {\n return _.isArray(x) && !EJSON.isBinary(x);\n};\n\n// XXX maybe this should be EJSON.isObject, though EJSON doesn't know about\n// RegExp\n// XXX note that _type(undefined) === 3!!!!\nisPlainObject = LocalCollection._isPlainObject = function (x) {\n return x && LocalCollection._f._type(x) === 3;\n};\n\nisIndexable = function (x) {\n return isArray(x) || isPlainObject(x);\n};\n\n// Returns true if this is an object with at least one key and all keys begin\n// with $. Unless inconsistentOK is set, throws if some keys begin with $ and\n// others don't.\nisOperatorObject = function (valueSelector, inconsistentOK) {\n if (!isPlainObject(valueSelector))\n return false;\n\n var theseAreOperators = undefined;\n _.each(valueSelector, function (value, selKey) {\n var thisIsOperator = selKey.substr(0, 1) === '$';\n if (theseAreOperators === undefined) {\n theseAreOperators = thisIsOperator;\n } else if (theseAreOperators !== thisIsOperator) {\n if (!inconsistentOK)\n throw new Error(\"Inconsistent operator: \" +\n JSON.stringify(valueSelector));\n theseAreOperators = false;\n }\n });\n return !!theseAreOperators; // {} has no operators\n};\n\n\n// string can be converted to integer\nisNumericKey = function (s) {\n return /^[0-9]+$/.test(s);\n};\n", "file_path": "packages/minimongo/helpers.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.0001746202469803393, 0.00017042508989106864, 0.0001665661984588951, 0.0001700410939520225, 2.634033990034368e-06]} {"hunk": {"id": 1, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-server-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": ".overlay.share {\n .wrapper-camera {\n .position(absolute, auto, 0, 0, 0, 100%);\n text-align: center;\n\n .btn-camera {\n margin-bottom: .5rem;\n }\n .subtext-camera {\n .font-s2;\n color: @color-medium;\n margin-bottom: .75rem;\n }\n }\n\n .bg-image {\n //.position(absolute, 3rem, 0, 0, 0, 100%, 50%);\n position: relative;\n margin-top: 3rem;\n height: 50%;\n }\n\n .form-share {\n .background-image(linear-gradient(top, rgba(255,255,255,.9), rgba(255,255,255,1) 10%, @color-empty 100%));\n .position(absolute, auto, 0, 0, 0, 100%);\n .transform(translate3d(0,0,0));// Gpu rendering\n min-height: 50%;\n padding-bottom: 3rem;\n\n .form-group {\n .display(flex);\n .flex-wrap(wrap);\n\n margin-bottom: 3rem;\n\n .avatar,\n .message-share {\n .flex(1);\n }\n .message-share {\n width: 100%;\n }\n\n .avatar {\n height: 2.5rem;\n width: 2.5rem;\n max-width: 2.5rem;\n float: left;\n margin-left: 1rem;\n margin-top: 1rem;\n }\n\n .message-share {\n height: 12em;\n resize: none;\n }\n }\n\n .wrapper-checkbox {\n .position(absolute, auto, auto, 3rem, auto, 100%, 3rem);\n border-top: 1px solid @color-rare;\n border-bottom: 1px solid @color-rare;\n\n .checkbox { padding: 1rem; }\n }\n }\n\n .btn-primary { .position(absolute, auto, 0, 0, 0, 100%); }\n}", "file_path": "examples/localmarket/client/templates/share-overlay.import.less", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017756946908775717, 0.00017578878032509238, 0.00017238406871911138, 0.00017599728016648442, 1.7813983959058532e-06]} {"hunk": {"id": 1, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-server-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "#!/bin/bash\n\n# Get the path to this script in SCRIPT_DIR, preserving cwd\nORIG_DIR=$(pwd)\ncd \"$(dirname \"$0\")\"\nSCRIPT_DIR=$(pwd -P)\ncd \"$ORIG_DIR\"\n\n# Find the top of the tools tree (not to be confused with the 'tools'\n# directory in that tree)\nTOOLS_DIR=\"$SCRIPT_DIR/../../..\"\n\n# Find our binary dependencies (node).\nDEV_BUNDLE=\"$TOOLS_DIR/dev_bundle\"\n\n# Have at it!\nexport NODE_PATH=\"$DEV_BUNDLE/lib/node_modules\"\nexec \"$DEV_BUNDLE/bin/node\" \"$SCRIPT_DIR/fake-mongod.js\" \"$@\"\n", "file_path": "tools/tests/fake-mongod/fake-mongod", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017059782112482935, 0.00016918493201956153, 0.00016777202836237848, 0.00016918493201956153, 1.412896381225437e-06]} {"hunk": {"id": 2, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-babel\": \"0.2.2\",\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"0.3.2\",\n", " \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "#!/bin/bash\n\nBUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n\n# OS Check. Put here because here is where we download the precompiled\n# bundles that are arch specific.\nUNAME=$(uname)\nif [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n echo \"Sorry, this OS is not supported.\"\n exit 1\nfi\n\nif [ \"$UNAME\" = \"Darwin\" ] ; then\n if [ \"i386\" != \"$(uname -p)\" -o \"1\" != \"$(sysctl -n hw.cpu64bit_capable 2>/dev/null || echo 0)\" ] ; then\n\n # Can't just test uname -m = x86_64, because Snow Leopard can\n # return other values.\n echo \"Only 64-bit Intel processors are supported at this time.\"\n exit 1\n fi\n ARCH=\"x86_64\"\nelif [ \"$UNAME\" = \"Linux\" ] ; then\n ARCH=\"$(uname -m)\"\n if [ \"$ARCH\" != \"i686\" -a \"$ARCH\" != \"x86_64\" ] ; then\n echo \"Unsupported architecture: $ARCH\"\n echo \"Meteor only supports i686 and x86_64 for now.\"\n exit 1\n fi\nfi\nPLATFORM=\"${UNAME}_${ARCH}\"\n\n# Find the script dir, following symlinks. Note that symlink can be relative or\n# absolute. Too bad 'readlink -f' and 'realpath' (the command-line program) are\n# not portable. We don't stress about infinite loops or bad links, because the\n# OS has already resolved this symlink chain once in order to actually run the\n# shell script.\nORIG_DIR=\"$(pwd)\"\nSCRIPT=\"$0\"\nwhile true; do\n # The symlink might be relative, so we have to actually cd to the right place\n # each time in order to resolve it.\n cd \"$(dirname \"$SCRIPT\")\"\n if [ ! -L \"$(basename \"$SCRIPT\")\" ]; then\n SCRIPT_DIR=\"$(pwd -P)\"\n break\n fi\n SCRIPT=\"$(readlink \"$(basename \"$SCRIPT\")\")\"\ndone\ncd \"$ORIG_DIR\"\n\n\n\nfunction install_dev_bundle {\n set -e\n trap \"echo Failed to install dependency kit.\" EXIT\n\n TARBALL=\"dev_bundle_${PLATFORM}_${BUNDLE_VERSION}.tar.gz\"\n BUNDLE_TMPDIR=\"$SCRIPT_DIR/dev_bundle.xxx\"\n\n rm -rf \"$BUNDLE_TMPDIR\"\n mkdir \"$BUNDLE_TMPDIR\"\n\n # duplicated in scripts/windows/download-dev-bundle.ps1:\n DEV_BUNDLE_URL_ROOT=\"https://d3sqy0vbqsdhku.cloudfront.net/\"\n # If you set $USE_TEST_DEV_BUNDLE_SERVER then we will download\n # dev bundles copied by copy-dev-bundle-from-jenkins.sh without --prod.\n # It still only does this if the version number has changed\n # (setting it won't cause it to automatically delete a prod dev bundle).\n if [ -n \"$USE_TEST_DEV_BUNDLE_SERVER\" ] ; then\n DEV_BUNDLE_URL_ROOT=\"https://s3.amazonaws.com/com.meteor.static/test/\"\n fi\n\n if [ -f \"$SCRIPT_DIR/$TARBALL\" ] ; then\n echo \"Skipping download and installing kit from $SCRIPT_DIR/$TARBALL\" >&2\n tar -xzf \"$SCRIPT_DIR/$TARBALL\" -C \"$BUNDLE_TMPDIR\"\n elif [ -n \"$SAVE_DEV_BUNDLE_TARBALL\" ] ; then\n # URL duplicated in tools/server/target.sh.in\n curl -# \"$DEV_BUNDLE_URL_ROOT$TARBALL\" >\"$SCRIPT_DIR/$TARBALL\"\n tar -xzf \"$SCRIPT_DIR/$TARBALL\" -C \"$BUNDLE_TMPDIR\"\n else\n curl -# \"$DEV_BUNDLE_URL_ROOT$TARBALL\" | tar -xzf - -C \"$BUNDLE_TMPDIR\"\n fi\n\n test -x \"${BUNDLE_TMPDIR}/bin/node\" # bomb out if it didn't work, eg no net\n\n # Delete old dev bundle and rename the new one on top of it.\n rm -rf \"$SCRIPT_DIR/dev_bundle\"\n mv \"$BUNDLE_TMPDIR\" \"$SCRIPT_DIR/dev_bundle\"\n\n echo \"Installed dependency kit v${BUNDLE_VERSION} in dev_bundle.\" >&2\n echo >&2\n\n trap - EXIT\n set +e\n}\n\n\nif [ -d \"$SCRIPT_DIR/.git\" ] || [ -f \"$SCRIPT_DIR/.git\" ]; then\n # In a checkout.\n if [ ! -d \"$SCRIPT_DIR/dev_bundle\" ] ; then\n echo \"It's the first time you've run Meteor from a git checkout.\" >&2\n echo \"I will download a kit containing all of Meteor's dependencies.\" >&2\n install_dev_bundle\n elif [ ! -f \"$SCRIPT_DIR/dev_bundle/.bundle_version.txt\" ] ||\n grep -qvx \"$BUNDLE_VERSION\" \"$SCRIPT_DIR/dev_bundle/.bundle_version.txt\" ; then\n echo \"Your dependency kit is out of date. I will download the new one.\" >&2\n install_dev_bundle\n fi\n\n export BABEL_CACHE_DIR=\"$SCRIPT_DIR/.babel-cache\"\nfi\n\nDEV_BUNDLE=\"$SCRIPT_DIR/dev_bundle\"\nMETEOR=\"$SCRIPT_DIR/tools/main-transpile-wrapper.js\"\n\n\n# Bump our file descriptor ulimit as high as it will go. This is a\n# temporary workaround for dependancy watching holding open too many\n# files: https://app.asana.com/0/364581412985/472479912325\nif [ \"$(ulimit -n)\" != \"unlimited\" ] ; then\n ulimit -n 16384 > /dev/null 2>&1 || \\\n ulimit -n 8192 > /dev/null 2>&1 || \\\n ulimit -n 4096 > /dev/null 2>&1 || \\\n ulimit -n 2048 > /dev/null 2>&1 || \\\n ulimit -n 1024 > /dev/null 2>&1 || \\\n ulimit -n 512 > /dev/null 2>&1\nfi\n\n# We used to set $NODE_PATH here to include the node_modules from the dev\n# bundle, but now we just get them from the symlink at tools/node_modules. This\n# is better because node_modules directories found via the ancestor walk from\n# the script take precedence over $NODE_PATH; it used to be that users would\n# screw up their meteor installs by have a ~/node_modules\n\nexec \"$DEV_BUNDLE/bin/node\" \"$METEOR\" \"$@\"\n", "file_path": "meteor", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00018012260261457413, 0.0001697757834335789, 0.00016391716781072319, 0.0001683259615674615, 4.532275397650665e-06]} {"hunk": {"id": 2, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-babel\": \"0.2.2\",\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"0.3.2\",\n", " \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "var CurrentFoo = new Meteor.EnvironmentVariable;\n\nTinytest.add(\"environment - dynamic variables\", function (test) {\n test.equal(CurrentFoo.get(), undefined);\n\n CurrentFoo.withValue(17, function () {\n test.equal(CurrentFoo.get(), 17);\n\n CurrentFoo.withValue(22, function () {\n test.equal(CurrentFoo.get(), 22);\n });\n\n test.equal(CurrentFoo.get(), 17);\n });\n\n test.equal(CurrentFoo.get(), undefined);\n});\n\nTinytest.add(\"environment - bindEnvironment\", function (test) {\n var raised_f;\n\n var f = CurrentFoo.withValue(17, function () {\n return Meteor.bindEnvironment(function (flag) {\n test.equal(CurrentFoo.get(), 17);\n if (flag)\n throw \"test\";\n return 12;\n }, function (e) {\n test.equal(CurrentFoo.get(), 17);\n raised_f = e;\n });\n });\n\n var test_f = function () {\n raised_f = null;\n\n test.equal(f(false), 12);\n test.equal(raised_f, null);\n\n test.equal(f(true), undefined);\n test.equal(raised_f, \"test\");\n };\n\n // At top level\n\n test.equal(CurrentFoo.get(), undefined);\n test_f();\n\n // Inside a withValue\n\n CurrentFoo.withValue(22, function () {\n test.equal(CurrentFoo.get(), 22);\n test_f();\n test.equal(CurrentFoo.get(), 22);\n });\n\n test.equal(CurrentFoo.get(), undefined);\n\n // Multiple environment-bound functions on the stack (in the nodejs\n // implementation, this needs to avoid creating additional fibers)\n\n var raised_g;\n\n var g = CurrentFoo.withValue(99, function () {\n return Meteor.bindEnvironment(function (flag) {\n test.equal(CurrentFoo.get(), 99);\n\n if (flag)\n throw \"trial\";\n\n test_f();\n return 88;\n }, function (e) {\n test.equal(CurrentFoo.get(), 99);\n raised_g = e;\n });\n });\n\n var test_g = function () {\n raised_g = null;\n\n test.equal(g(false), 88);\n test.equal(raised_g, null);\n\n test.equal(g(true), undefined);\n test.equal(raised_g, \"trial\");\n };\n\n test_g();\n\n CurrentFoo.withValue(77, function () {\n test.equal(CurrentFoo.get(), 77);\n test_g();\n test.equal(CurrentFoo.get(), 77);\n });\n\n test.equal(CurrentFoo.get(), undefined);\n});\n\nTinytest.addAsync(\"environment - bare bindEnvironment\",\n function (test, onComplete) {\n // this will have to create a fiber in nodejs\n CurrentFoo.withValue(68, function () {\n var f = Meteor.bindEnvironment(function () {\n test.equal(CurrentFoo.get(), 68);\n onComplete();\n }, function () {});\n\n setTimeout(f, 0);\n });\n});\n", "file_path": "packages/meteor/dynamics_test.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00020182131265755743, 0.00017783889779821038, 0.000171100371517241, 0.000176090223249048, 7.4288900577812456e-06]} {"hunk": {"id": 2, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-babel\": \"0.2.2\",\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"0.3.2\",\n", " \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "This is an internal Meteor package.", "file_path": "packages/meyerweb-reset/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017722135817166418, 0.00017722135817166418, 0.00017722135817166418, 0.00017722135817166418, 0.0]} {"hunk": {"id": 2, "code_window": [" version: \"0.0.0\",\n", " dependencies: {\n", " fibers: fibersVersion,\n", " \"meteor-babel\": \"0.2.2\",\n", " \"meteor-promise\": \"0.2.3\",\n", " // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done\n", " // in the package too) because we should consider using lodash instead\n", " // (and there are backwards-incompatible changes either way).\n", " underscore: \"1.5.2\",\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" \"meteor-babel\": \"0.3.2\",\n", " \"meteor-promise\": \"0.2.4\",\n"], "file_path": "scripts/dev-bundle-tool-package.js", "type": "replace", "edit_start_line_idx": 23}, "file": "Package.describe({\n name: \"~package-name~\", // replaced via `Sandbox.prototype.createPackage`\n summary: 'This is a pre-release version of this package!',\n version: '1.3.0-rc.1',\n git: 'www.github.com/fake-user/meteor',\n documentation: null\n});\n", "file_path": "tools/tests/packages/package-for-show/package-rc-version.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00016560080985073, 0.00016560080985073, 0.00016560080985073, 0.00016560080985073, 0.0]} {"hunk": {"id": 3, "code_window": [" if (path === \"tools/main-transpile-wrapper.js\" || path === \"tools/source-map-retriever-stack.js\") {\n", " inputFileContents = inputFileContents.replace(/.+#RemoveInProd.+/, \"\");\n", " }\n", "\n", " var transpiled = babel.compile(inputFileContents, _.extend(babel.getDefaultOptions(), {\n", " filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var babelOptions = babel.getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/main-transpile-wrapper.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " });\n", "\n", " _.extend(babelOptions, {\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "#!/bin/bash\n\nBUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins\n\n# OS Check. Put here because here is where we download the precompiled\n# bundles that are arch specific.\nUNAME=$(uname)\nif [ \"$UNAME\" != \"Linux\" -a \"$UNAME\" != \"Darwin\" ] ; then\n echo \"Sorry, this OS is not supported.\"\n exit 1\nfi\n\nif [ \"$UNAME\" = \"Darwin\" ] ; then\n if [ \"i386\" != \"$(uname -p)\" -o \"1\" != \"$(sysctl -n hw.cpu64bit_capable 2>/dev/null || echo 0)\" ] ; then\n\n # Can't just test uname -m = x86_64, because Snow Leopard can\n # return other values.\n echo \"Only 64-bit Intel processors are supported at this time.\"\n exit 1\n fi\n ARCH=\"x86_64\"\nelif [ \"$UNAME\" = \"Linux\" ] ; then\n ARCH=\"$(uname -m)\"\n if [ \"$ARCH\" != \"i686\" -a \"$ARCH\" != \"x86_64\" ] ; then\n echo \"Unsupported architecture: $ARCH\"\n echo \"Meteor only supports i686 and x86_64 for now.\"\n exit 1\n fi\nfi\nPLATFORM=\"${UNAME}_${ARCH}\"\n\n# Find the script dir, following symlinks. Note that symlink can be relative or\n# absolute. Too bad 'readlink -f' and 'realpath' (the command-line program) are\n# not portable. We don't stress about infinite loops or bad links, because the\n# OS has already resolved this symlink chain once in order to actually run the\n# shell script.\nORIG_DIR=\"$(pwd)\"\nSCRIPT=\"$0\"\nwhile true; do\n # The symlink might be relative, so we have to actually cd to the right place\n # each time in order to resolve it.\n cd \"$(dirname \"$SCRIPT\")\"\n if [ ! -L \"$(basename \"$SCRIPT\")\" ]; then\n SCRIPT_DIR=\"$(pwd -P)\"\n break\n fi\n SCRIPT=\"$(readlink \"$(basename \"$SCRIPT\")\")\"\ndone\ncd \"$ORIG_DIR\"\n\n\n\nfunction install_dev_bundle {\n set -e\n trap \"echo Failed to install dependency kit.\" EXIT\n\n TARBALL=\"dev_bundle_${PLATFORM}_${BUNDLE_VERSION}.tar.gz\"\n BUNDLE_TMPDIR=\"$SCRIPT_DIR/dev_bundle.xxx\"\n\n rm -rf \"$BUNDLE_TMPDIR\"\n mkdir \"$BUNDLE_TMPDIR\"\n\n # duplicated in scripts/windows/download-dev-bundle.ps1:\n DEV_BUNDLE_URL_ROOT=\"https://d3sqy0vbqsdhku.cloudfront.net/\"\n # If you set $USE_TEST_DEV_BUNDLE_SERVER then we will download\n # dev bundles copied by copy-dev-bundle-from-jenkins.sh without --prod.\n # It still only does this if the version number has changed\n # (setting it won't cause it to automatically delete a prod dev bundle).\n if [ -n \"$USE_TEST_DEV_BUNDLE_SERVER\" ] ; then\n DEV_BUNDLE_URL_ROOT=\"https://s3.amazonaws.com/com.meteor.static/test/\"\n fi\n\n if [ -f \"$SCRIPT_DIR/$TARBALL\" ] ; then\n echo \"Skipping download and installing kit from $SCRIPT_DIR/$TARBALL\" >&2\n tar -xzf \"$SCRIPT_DIR/$TARBALL\" -C \"$BUNDLE_TMPDIR\"\n elif [ -n \"$SAVE_DEV_BUNDLE_TARBALL\" ] ; then\n # URL duplicated in tools/server/target.sh.in\n curl -# \"$DEV_BUNDLE_URL_ROOT$TARBALL\" >\"$SCRIPT_DIR/$TARBALL\"\n tar -xzf \"$SCRIPT_DIR/$TARBALL\" -C \"$BUNDLE_TMPDIR\"\n else\n curl -# \"$DEV_BUNDLE_URL_ROOT$TARBALL\" | tar -xzf - -C \"$BUNDLE_TMPDIR\"\n fi\n\n test -x \"${BUNDLE_TMPDIR}/bin/node\" # bomb out if it didn't work, eg no net\n\n # Delete old dev bundle and rename the new one on top of it.\n rm -rf \"$SCRIPT_DIR/dev_bundle\"\n mv \"$BUNDLE_TMPDIR\" \"$SCRIPT_DIR/dev_bundle\"\n\n echo \"Installed dependency kit v${BUNDLE_VERSION} in dev_bundle.\" >&2\n echo >&2\n\n trap - EXIT\n set +e\n}\n\n\nif [ -d \"$SCRIPT_DIR/.git\" ] || [ -f \"$SCRIPT_DIR/.git\" ]; then\n # In a checkout.\n if [ ! -d \"$SCRIPT_DIR/dev_bundle\" ] ; then\n echo \"It's the first time you've run Meteor from a git checkout.\" >&2\n echo \"I will download a kit containing all of Meteor's dependencies.\" >&2\n install_dev_bundle\n elif [ ! -f \"$SCRIPT_DIR/dev_bundle/.bundle_version.txt\" ] ||\n grep -qvx \"$BUNDLE_VERSION\" \"$SCRIPT_DIR/dev_bundle/.bundle_version.txt\" ; then\n echo \"Your dependency kit is out of date. I will download the new one.\" >&2\n install_dev_bundle\n fi\n\n export BABEL_CACHE_DIR=\"$SCRIPT_DIR/.babel-cache\"\nfi\n\nDEV_BUNDLE=\"$SCRIPT_DIR/dev_bundle\"\nMETEOR=\"$SCRIPT_DIR/tools/main-transpile-wrapper.js\"\n\n\n# Bump our file descriptor ulimit as high as it will go. This is a\n# temporary workaround for dependancy watching holding open too many\n# files: https://app.asana.com/0/364581412985/472479912325\nif [ \"$(ulimit -n)\" != \"unlimited\" ] ; then\n ulimit -n 16384 > /dev/null 2>&1 || \\\n ulimit -n 8192 > /dev/null 2>&1 || \\\n ulimit -n 4096 > /dev/null 2>&1 || \\\n ulimit -n 2048 > /dev/null 2>&1 || \\\n ulimit -n 1024 > /dev/null 2>&1 || \\\n ulimit -n 512 > /dev/null 2>&1\nfi\n\n# We used to set $NODE_PATH here to include the node_modules from the dev\n# bundle, but now we just get them from the symlink at tools/node_modules. This\n# is better because node_modules directories found via the ancestor walk from\n# the script take precedence over $NODE_PATH; it used to be that users would\n# screw up their meteor installs by have a ~/node_modules\n\nexec \"$DEV_BUNDLE/bin/node\" \"$METEOR\" \"$@\"\n", "file_path": "meteor", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00025999301578849554, 0.0001766601053532213, 0.00016352675447706133, 0.00017164804739877582, 2.3322432753047906e-05]} {"hunk": {"id": 3, "code_window": [" if (path === \"tools/main-transpile-wrapper.js\" || path === \"tools/source-map-retriever-stack.js\") {\n", " inputFileContents = inputFileContents.replace(/.+#RemoveInProd.+/, \"\");\n", " }\n", "\n", " var transpiled = babel.compile(inputFileContents, _.extend(babel.getDefaultOptions(), {\n", " filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var babelOptions = babel.getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/main-transpile-wrapper.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " });\n", "\n", " _.extend(babelOptions, {\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "0.6.0\n", "file_path": "examples/unfinished/azrael/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017169116472359747, 0.00017169116472359747, 0.00017169116472359747, 0.00017169116472359747, 0.0]} {"hunk": {"id": 3, "code_window": [" if (path === \"tools/main-transpile-wrapper.js\" || path === \"tools/source-map-retriever-stack.js\") {\n", " inputFileContents = inputFileContents.replace(/.+#RemoveInProd.+/, \"\");\n", " }\n", "\n", " var transpiled = babel.compile(inputFileContents, _.extend(babel.getDefaultOptions(), {\n", " filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var babelOptions = babel.getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/main-transpile-wrapper.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " });\n", "\n", " _.extend(babelOptions, {\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "/* This file is only loaded on Cordova-bundled apps and is used only in case\n * autoupdate package is used.\n * It checks if File plugin is installed and a newer version of the app code can\n * be found on persistent storage. In that case those files are dynamically\n * added to the page.\n * Otherwise a normal app code is loaded (shipped with the app initially).\n */\n\n(function () {\n var DEBUG_TAG = 'METEOR CORDOVA DEBUG (meteor_cordova_loader.js) ';\n var log = function (msg) {\n console.log(DEBUG_TAG + msg);\n };\n var uriToPath = function (uri) {\n return decodeURI(uri).replace(/^file:\\/\\//g, '');\n };\n var readFile = function (url, cb) {\n window.resolveLocalFileSystemURL(url, function (fileEntry) {\n var success = function (file) {\n var reader = new FileReader();\n reader.onloadend = function (evt) {\n var result = evt.target.result;\n cb(null, result);\n };\n reader.onerror = fail;\n reader.readAsText(file);\n };\n var fail = function (evt) {\n cb(new Error(\"Failed to load entry: \" + url), null);\n };\n fileEntry.file(success, fail);\n },\n // error callback\n function (err) { cb(new Error(\"Failed to resolve entry: \" + url), null);\n });\n };\n\n var loadTries = 0;\n var loadFromLocation = function (location) {\n var cordovaRoot =\n uriToPath(window.location.href).replace(/\\/index.html$/, '/');\n\n var httpd = cordova && cordova.plugins && cordova.plugins.CordovaUpdate;\n\n var retry = function () {\n loadTries++;\n if (loadTries > 10) {\n // XXX: If this means the app fails, we should probably do exponential backoff\n // or at least show a message\n log('Failed to start the server (too many retries)');\n } else {\n log('Starting the server (retry #' + loadTries + ')');\n loadFromLocation(location);\n }\n };\n\n httpd.startServer({\n 'www_root' : location,\n 'cordovajs_root': cordovaRoot\n }, function (url) {\n // go to the new proxy url\n log(\"Loading from url: \" + url);\n window.location = url;\n }, function (error) {\n // failed to start a server, is port already in use?\n log(\"Failed to start the server: \" + error);\n retry();\n });\n };\n\n // Fallback to the bundled assets from the disk. If an error is passed as an\n // argument, then there was a problem reading from the manifest files. If\n // no error is passed, then we simply do not have any new versions.\n var fallback = function (err) {\n if (err) {\n log(\"Couldn't load from the manifest, falling back to the bundled assets.\");\n } else {\n log('No new versions saved to disk.');\n }\n var location = cordova.file.applicationDirectory + 'www/application/';\n location = uriToPath(location);\n\n loadFromLocation(location);\n };\n\n var loadVersion = function (version, localPathPrefix) {\n var versionPrefix = localPathPrefix + version + '/';\n var location = uriToPath(versionPrefix);\n loadFromLocation(location);\n };\n\n var loadApp = function (localPathPrefix) {\n readFile(localPathPrefix + 'version', function (err, version) {\n if (err) {\n log(\"Error reading version file \" + err);\n fallback(err);\n return;\n }\n\n loadVersion(version, localPathPrefix);\n });\n };\n\n document.addEventListener(\"deviceready\", function () {\n var startLoading = function () {\n if (! cordova.file) {\n // If the plugin didn't actually load, try again later.\n // See a larger comment with details in\n // packages/meteor/startup_client.js\n setTimeout(startLoading, 20);\n return;\n }\n\n var localPathPrefix = cordova.file.dataDirectory + 'meteor/';\n loadApp(localPathPrefix);\n };\n\n startLoading();\n }, false);\n})();\n\n", "file_path": "tools/client/meteor_cordova_loader.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017383611702825874, 0.0001696275285212323, 0.0001607319136383012, 0.000170100451214239, 3.479055067145964e-06]} {"hunk": {"id": 3, "code_window": [" if (path === \"tools/main-transpile-wrapper.js\" || path === \"tools/source-map-retriever-stack.js\") {\n", " inputFileContents = inputFileContents.replace(/.+#RemoveInProd.+/, \"\");\n", " }\n", "\n", " var transpiled = babel.compile(inputFileContents, _.extend(babel.getDefaultOptions(), {\n", " filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var babelOptions = babel.getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/main-transpile-wrapper.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " });\n", "\n", " _.extend(babelOptions, {\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1000}, "file": "body {\n margin: 0px;\n background-color: #f4f4f4;\n font-family: Helvetica, Arial, sans-serif;\n}\n\n/* base styles */\n\ninput {\n height: 50px;\n width: 300px;\n font-size: 2em;\n border: 2px solid black;\n padding: 5px;\n}\n\nbutton {\n position: relative;\n bottom: 3px;\n margin: 10px;\n height: 50px;\n background-color:#E6EFC2;\n border:1px solid #dedede;\n font-weight:bold;\n cursor:pointer;\n font-size: 1.5em;\n}\n\nbutton:hover {\n background-color:#D6DFb2;\n border:1px solid #C6D880;\n}\n\nbutton:active {\n background-color:#529214;\n border:1px solid #529214;\n color:#fff;\n}\n\n/*******/\n\n#main {\n margin: 20px;\n}\n\n#left {\n float: left;\n width: 40%;\n}\n\n#right {\n float: left;\n width: 50%;\n}\n\n#clock {\n width: 100%;\n height: 100px;\n text-align: center;\n font-size: 3em;\n}\n\n#board {\n margin: auto;\n border:4px solid #999999;\n border-radius: 4px;\n -moz-border-radius: 4px;\n padding:2px;\n\n width:400px;\n height:400px;\n background-color:#999999;\n}\n\n.square {\n cursor: pointer;\n width:84px;\n height:84px;\n border:4px solid #eeeee8;\n border-radius: 4px;\n -moz-border-radius: 4px;\n margin: 4px;\n float:left;\n text-align: center;\n background-color:#eeeee8;\n font-size: 65px;\n}\n\n.square.last_in_path {\n color: #ff0000;\n}\n\n.square.in_path {\n color: #990000;\n}\n\n#login {\n margin: 100px auto;\n text-align: center;\n}\n\n#login .error {\n color: red;\n}\n\n#lobby {\n margin: 100px auto;\n text-align: center;\n}\n\n#postgame {\n height: 100px;\n text-align: center;\n}\n\n#scratchpad {\n height: 100px;\n}\n\n#scratchpad input {\n width: 70%;\n}\n\n#scratchpad h1 {\n float: left;\n}\n\n#scores {\n float: left;\n width: 100%;\n background-color: #eeeee8;\n border: 1px solid black;\n padding: 0.5em;\n}\n\n#scores .player {\n float: left;\n width: 100%;\n}\n\n#scores .header {\n font-size: 1.25em;\n}\n\n#scores .unnamed {\n color: #444;\n font-style: italic;\n}\n\n#scores .winner {\n background-color: yellow;\n}\n\n#scores .winner_text {\n float: right;\n}\n\n#scores .word {\n float: left;\n font-size: 1.25em;\n padding: 0.25em;\n margin: 0.5em;\n border: 1px solid #030;\n}\n\n#scores .word.good {\n background-color: #0a0;\n}\n\n#scores .word.bad {\n text-decoration: line-through;\n}\n\n#scores .word span.score {\n width: 1em;\n}\n\n#scores .word.bad span.score {\n background-image: 'circle-ball-dark-antialiased.gif';\n}\n", "file_path": "examples/other/wordplay/client/wordplay.css", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.0001780806778697297, 0.00017284374916926026, 0.00016358787252102047, 0.00017300518811680377, 3.3248823001486016e-06]} {"hunk": {"id": 4, "code_window": [" filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n", " sourceMaps: true\n", " }));\n", "\n", " var sourceMapUrlComment = \"//# sourceMappingURL=\" + files.pathBasename(path + \".map\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" sourceMap: true\n", " });\n", "\n", " var transpiled = babel.compile(inputFileContents, babelOptions);\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1004}, "file": "// This file exists because it is the file in the tool that is not automatically\n// transpiled by Babel\n\nrequire('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n\n// Install a global ES6-compliant Promise constructor that knows how to\n// run all its callbacks in Fibers.\nglobal.Promise = require(\"meteor-promise\");\n\n// Include helpers from NPM so that the compiler doesn't need to add boilerplate\n// at the top of every file\nrequire(\"meteor-babel\").installRuntime();\n\n// Installs source map support with a hook to add functions to look for source\n// maps in custom places\nrequire('./source-map-retriever-stack.js');\n\n// Run the Meteor command line tool\nrequire('./main.js');\n", "file_path": "tools/main-transpile-wrapper.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00024940152070485055, 0.00020525998843368143, 0.0001611184561625123, 0.00020525998843368143, 4.4141532271169126e-05]} {"hunk": {"id": 4, "code_window": [" filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n", " sourceMaps: true\n", " }));\n", "\n", " var sourceMapUrlComment = \"//# sourceMappingURL=\" + files.pathBasename(path + \".map\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" sourceMap: true\n", " });\n", "\n", " var transpiled = babel.compile(inputFileContents, babelOptions);\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1004}, "file": ".build*\n", "file_path": "packages/minifiers/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017578949336893857, 0.00017578949336893857, 0.00017578949336893857, 0.00017578949336893857, 0.0]} {"hunk": {"id": 4, "code_window": [" filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n", " sourceMaps: true\n", " }));\n", "\n", " var sourceMapUrlComment = \"//# sourceMappingURL=\" + files.pathBasename(path + \".map\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" sourceMap: true\n", " });\n", "\n", " var transpiled = babel.compile(inputFileContents, babelOptions);\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1004}, "file": " {\n \"params\": {\n \"numCollections\": 1,\n \"maxAgeSeconds\": 60,\n \"insertsPerSecond\": 100,\n \"updatesPerSecond\": 100,\n \"removesPerSecond\": 10,\n \"documentSize\": 128,\n \"documentNumFields\": 2\n }\n}\n", "file_path": "examples/unfinished/benchmark/scenarios/scale100.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017819720960687846, 0.00017724941426422447, 0.00017630161892157048, 0.00017724941426422447, 9.477953426539898e-07]} {"hunk": {"id": 4, "code_window": [" filename: path,\n", " sourceFileName: \"/\" + path,\n", " sourceMapName: path + \".map\",\n", " sourceMaps: true\n", " }));\n", "\n", " var sourceMapUrlComment = \"//# sourceMappingURL=\" + files.pathBasename(path + \".map\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep"], "after_edit": [" sourceMap: true\n", " });\n", "\n", " var transpiled = babel.compile(inputFileContents, babelOptions);\n"], "file_path": "tools/isopack.js", "type": "replace", "edit_start_line_idx": 1004}, "file": "bla\n", "file_path": "tools/tests/apps/hot-code-push-test/hot-code-push-test.html", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017456630303058773, 0.00017456630303058773, 0.00017456630303058773, 0.00017456630303058773, 0.0]} {"hunk": {"id": 5, "code_window": ["// This file exists because it is the file in the tool that is not automatically\n", "// transpiled by Babel\n", "\n", "require('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n", "\n", "// Install a global ES6-compliant Promise constructor that knows how to\n", "// run all its callbacks in Fibers.\n", "global.Promise = require(\"meteor-promise\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["function babelRegister() {\n", " require('meteor-babel/register')({\n", " babelOptions: require('meteor-babel').getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/isopack.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " })\n", " });\n", "}\n", "\n", "babelRegister(); // #RemoveInProd this line is removed in isopack.js\n"], "file_path": "tools/main-transpile-wrapper.js", "type": "replace", "edit_start_line_idx": 3}, "file": "// This file exists because it is the file in the tool that is not automatically\n// transpiled by Babel\n\nrequire('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n\n// Install a global ES6-compliant Promise constructor that knows how to\n// run all its callbacks in Fibers.\nglobal.Promise = require(\"meteor-promise\");\n\n// Include helpers from NPM so that the compiler doesn't need to add boilerplate\n// at the top of every file\nrequire(\"meteor-babel\").installRuntime();\n\n// Installs source map support with a hook to add functions to look for source\n// maps in custom places\nrequire('./source-map-retriever-stack.js');\n\n// Run the Meteor command line tool\nrequire('./main.js');\n", "file_path": "tools/main-transpile-wrapper.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.9981375932693481, 0.5023438930511475, 0.006550171412527561, 0.5023438930511475, 0.4957937002182007]} {"hunk": {"id": 5, "code_window": ["// This file exists because it is the file in the tool that is not automatically\n", "// transpiled by Babel\n", "\n", "require('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n", "\n", "// Install a global ES6-compliant Promise constructor that knows how to\n", "// run all its callbacks in Fibers.\n", "global.Promise = require(\"meteor-promise\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["function babelRegister() {\n", " require('meteor-babel/register')({\n", " babelOptions: require('meteor-babel').getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/isopack.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " })\n", " });\n", "}\n", "\n", "babelRegister(); // #RemoveInProd this line is removed in isopack.js\n"], "file_path": "tools/main-transpile-wrapper.js", "type": "replace", "edit_start_line_idx": 3}, "file": "/**\n * @summary Generate an absolute URL pointing to the application. The server reads from the `ROOT_URL` environment variable to determine where it is running. This is taken care of automatically for apps deployed with `meteor deploy`, but must be provided when using `meteor build`.\n * @locus Anywhere\n * @param {String} [path] A path to append to the root URL. Do not include a leading \"`/`\".\n * @param {Object} [options]\n * @param {Boolean} options.secure Create an HTTPS URL.\n * @param {Boolean} options.replaceLocalhost Replace localhost with 127.0.0.1. Useful for services that don't recognize localhost as a domain name.\n * @param {String} options.rootUrl Override the default ROOT_URL from the server environment. For example: \"`http://foo.example.com`\"\n */\nMeteor.absoluteUrl = function (path, options) {\n // path is optional\n if (!options && typeof path === 'object') {\n options = path;\n path = undefined;\n }\n // merge options with defaults\n options = _.extend({}, Meteor.absoluteUrl.defaultOptions, options || {});\n\n var url = options.rootUrl;\n if (!url)\n throw new Error(\"Must pass options.rootUrl or set ROOT_URL in the server environment\");\n\n if (!/^http[s]?:\\/\\//i.test(url)) // url starts with 'http://' or 'https://'\n url = 'http://' + url; // we will later fix to https if options.secure is set\n\n if (!/\\/$/.test(url)) // url ends with '/'\n url += '/';\n\n if (path)\n url += path;\n\n // turn http to https if secure option is set, and we're not talking\n // to localhost.\n if (options.secure &&\n /^http:/.test(url) && // url starts with 'http:'\n !/http:\\/\\/localhost[:\\/]/.test(url) && // doesn't match localhost\n !/http:\\/\\/127\\.0\\.0\\.1[:\\/]/.test(url)) // or 127.0.0.1\n url = url.replace(/^http:/, 'https:');\n\n if (options.replaceLocalhost)\n url = url.replace(/^http:\\/\\/localhost([:\\/].*)/, 'http://127.0.0.1$1');\n\n return url;\n};\n\n// allow later packages to override default options\nMeteor.absoluteUrl.defaultOptions = { };\nif (typeof __meteor_runtime_config__ === \"object\" &&\n __meteor_runtime_config__.ROOT_URL)\n Meteor.absoluteUrl.defaultOptions.rootUrl = __meteor_runtime_config__.ROOT_URL;\n\n\nMeteor._relativeToSiteRootUrl = function (link) {\n if (typeof __meteor_runtime_config__ === \"object\" &&\n link.substr(0, 1) === \"/\")\n link = (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX || \"\") + link;\n return link;\n};\n", "file_path": "packages/meteor/url_common.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.0003954100247938186, 0.000219534951611422, 0.00016209849854931235, 0.00016829065862111747, 8.538334805052727e-05]} {"hunk": {"id": 5, "code_window": ["// This file exists because it is the file in the tool that is not automatically\n", "// transpiled by Babel\n", "\n", "require('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n", "\n", "// Install a global ES6-compliant Promise constructor that knows how to\n", "// run all its callbacks in Fibers.\n", "global.Promise = require(\"meteor-promise\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["function babelRegister() {\n", " require('meteor-babel/register')({\n", " babelOptions: require('meteor-babel').getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/isopack.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " })\n", " });\n", "}\n", "\n", "babelRegister(); // #RemoveInProd this line is removed in isopack.js\n"], "file_path": "tools/main-transpile-wrapper.js", "type": "replace", "edit_start_line_idx": 3}, "file": "====================================================================\nFor the license for Meteor itself, see LICENSE.txt in the root of\nthe repository. This file contains the licenses for externally\nmaintained libraries.\n====================================================================\n\n\n\n----------\nnan: https://github.com/rvagg/nan\n----------\n\nCopyright 2013, NAN contributors:\n - Rod Vagg \n - Benjamin Byholm \n - Trevor Norris \n - Nathan Rajlich \n - Brett Lawson \n - Ben Noordhuis \n(the \"Original Author\")\nAll rights reserved.\n\nMIT +no-false-attribs License\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nDistributions of all or part of the Software intended to be used\nby the recipients as they would use the unmodified Software,\ncontaining modifications that substantially alter, remove, or\ndisable functionality of the Software, outside of the documented\nconfiguration mechanisms provided by the Software, shall be\nmodified such that the Original Author's bug reporting email\naddresses and urls are either replaced with the contact information\nof the parties responsible for the changes, or removed entirely.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\n\nExcept where noted, this license applies to any and all software\nprograms and associated documentation files created by the\nOriginal Author, when distributed with the Software.\n", "file_path": "LICENSES/nan.txt", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.00017540925182402134, 0.00017199043941218406, 0.0001656788372201845, 0.00017261854372918606, 3.431602863201988e-06]} {"hunk": {"id": 5, "code_window": ["// This file exists because it is the file in the tool that is not automatically\n", "// transpiled by Babel\n", "\n", "require('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js\n", "\n", "// Install a global ES6-compliant Promise constructor that knows how to\n", "// run all its callbacks in Fibers.\n", "global.Promise = require(\"meteor-promise\");\n", "\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": ["function babelRegister() {\n", " require('meteor-babel/register')({\n", " babelOptions: require('meteor-babel').getDefaultOptions({\n", " // These feature flags must be kept in sync with the babelOptions\n", " // used in tools/isopack.js.\n", " modules: true,\n", " meteorAsyncAwait: true\n", " })\n", " });\n", "}\n", "\n", "babelRegister(); // #RemoveInProd this line is removed in isopack.js\n"], "file_path": "tools/main-transpile-wrapper.js", "type": "replace", "edit_start_line_idx": 3}, "file": "Package.describe({\n summary: \"Wrapper around the bcrypt npm package\",\n version: '0.7.8_2',\n documentation: null\n});\n\nNpm.depends({\n bcrypt: '0.7.8'\n});\n\nPackage.onUse(function (api) {\n api.export('NpmModuleBcrypt', 'server');\n api.addFiles('wrapper.js', 'server');\n});\n", "file_path": "packages/non-core/npm-bcrypt/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/46b33db9030ddfa11c081e990e2970c5839933ed", "dependency_score": [0.0001724421017570421, 0.00016977961058728397, 0.00016711711941752583, 0.00016977961058728397, 2.662491169758141e-06]} {"hunk": {"id": 0, "code_window": [" }\n", " });\n", "\n", " files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" // JSHint has a particular format for defining globals. `false` means that the\n", " // global is not allowed to be redefined. `true` means it is allowed to be\n", " // redefined. Since the passed imports are probably not great for definition,\n", " // mark them as false.\n", " var predefinedGlobals = {};\n", " globals.forEach(function (symbol) {\n", " predefinedGlobals[symbol] = false;\n", " });\n", "\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "add", "edit_start_line_idx": 40}, "file": "var _ = require('underscore');\n\nvar archinfo = require('./archinfo.js');\nvar buildmessage = require('./buildmessage.js');\nvar bundler = require('./bundler.js');\nvar isopack = require('./isopack.js');\nvar isopackets = require('./isopackets.js');\nvar linker = require('./linker.js');\nvar meteorNpm = require('./meteor-npm.js');\nvar watch = require('./watch.js');\nvar Console = require('./console.js').Console;\nvar files = require('./files.js');\nvar colonConverter = require('./colon-converter.js');\nvar linterPluginModule = require('./linter-plugin.js');\n\nvar compiler = exports;\n\n// Whenever you change anything about the code that generates isopacks, bump\n// this version number. The idea is that the \"format\" field of the isopack\n// JSON file only changes when the actual specified structure of the\n// isopack/unibuild changes, but this version (which is build-tool-specific)\n// can change when the the contents (not structure) of the built output\n// changes. So eg, if we improve the linker's static analysis, this should be\n// bumped.\n//\n// You should also update this whenever you update any of the packages used\n// directly by the isopack creation process (eg js-analyze) since they do not\n// end up as watched dependencies. (At least for now, packages only used in\n// target creation (eg minifiers) don't require you to update BUILT_BY, though\n// you will need to quit and rerun \"meteor run\".)\ncompiler.BUILT_BY = 'meteor/16';\n\n// This is a list of all possible architectures that a build can target. (Client\n// is expanded into 'web.browser' and 'web.cordova')\ncompiler.ALL_ARCHES = [ \"os\", \"web.browser\", \"web.cordova\" ];\n\ncompiler.compile = function (packageSource, options) {\n buildmessage.assertInCapture();\n\n var packageMap = options.packageMap;\n var isopackCache = options.isopackCache;\n var includeCordovaUnibuild = options.includeCordovaUnibuild;\n\n var pluginWatchSet = packageSource.pluginWatchSet.clone();\n var plugins = {};\n\n var pluginProviderPackageNames = {};\n\n // Build plugins\n _.each(packageSource.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + packageSource.name + \"`\",\n rootPath: packageSource.sourceRoot\n }, function () {\n // XXX we should probably also pass options.noLineNumbers into\n // buildJsImage so it can pass it back to its call to\n // compiler.compile\n var buildResult = bundler.buildJsImage({\n name: info.name,\n packageMap: packageMap,\n isopackCache: isopackCache,\n use: info.use,\n sourceRoot: packageSource.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: files.pathResolve(\n files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))\n });\n // Add this plugin's dependencies to our \"plugin dependency\"\n // WatchSet. buildResult.watchSet will end up being the merged\n // watchSets of all of the unibuilds of the plugin -- plugins have\n // only one unibuild and this should end up essentially being just\n // the source files of the plugin.\n //\n // Note that we do this even on error, so that you can fix the error\n // and have the runner restart.\n pluginWatchSet.merge(buildResult.watchSet);\n\n if (buildmessage.jobHasMessages())\n return;\n\n _.each(buildResult.usedPackageNames, function (packageName) {\n pluginProviderPackageNames[packageName] = true;\n });\n\n // Register the built plugin's code.\n if (!_.has(plugins, info.name))\n plugins[info.name] = {};\n plugins[info.name][buildResult.image.arch] = buildResult.image;\n });\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n //\n // Go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any (sub)dependencies. This\n // process also runs mostly safely multiple times in parallel (which\n // could happen if you have two apps running locally using the same\n // package).\n //\n // We run this even if we have no dependencies, because we might\n // need to delete dependencies we used to have.\n var isPortable = true;\n var nodeModulesPath = null;\n if (packageSource.npmCacheDirectory) {\n if (meteorNpm.updateDependencies(packageSource.name,\n packageSource.npmCacheDirectory,\n packageSource.npmDependencies)) {\n nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,\n 'node_modules');\n if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))\n isPortable = false;\n }\n }\n\n var isopk = new isopack.Isopack;\n isopk.initFromOptions({\n name: packageSource.name,\n metadata: packageSource.metadata,\n version: packageSource.version,\n isTest: packageSource.isTest,\n plugins: plugins,\n pluginWatchSet: pluginWatchSet,\n cordovaDependencies: packageSource.cordovaDependencies,\n npmDiscards: packageSource.npmDiscards,\n includeTool: packageSource.includeTool,\n debugOnly: packageSource.debugOnly\n });\n\n _.each(packageSource.architectures, function (unibuild) {\n if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)\n return;\n\n var unibuildResult = compileUnibuild({\n isopack: isopk,\n sourceArch: unibuild,\n isopackCache: isopackCache,\n nodeModulesPath: nodeModulesPath,\n isPortable: isPortable,\n noLineNumbers: options.noLineNumbers\n });\n _.extend(pluginProviderPackageNames,\n unibuildResult.pluginProviderPackageNames);\n });\n\n if (options.includePluginProviderPackageMap) {\n isopk.setPluginProviderPackageMap(\n packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));\n }\n\n return isopk;\n};\n\n// options.sourceArch is a SourceArch to compile. Process all source files\n// through the appropriate handlers and run the prelink phase on any resulting\n// JavaScript. Create a new Unibuild and add it to options.isopack.\n//\n// Returns a list of source files that were used in the compilation.\nvar compileUnibuild = function (options) {\n buildmessage.assertInCapture();\n\n var isopk = options.isopack;\n var inputSourceArch = options.sourceArch;\n var isopackCache = options.isopackCache;\n var nodeModulesPath = options.nodeModulesPath;\n var isPortable = options.isPortable;\n var noLineNumbers = options.noLineNumbers;\n\n var isApp = ! inputSourceArch.pkg.name;\n var resources = [];\n var js = [];\n var pluginProviderPackageNames = {};\n // The current package always is a plugin provider. (This also means we no\n // longer need a buildOfPath entry in buildinfo.json.)\n pluginProviderPackageNames[isopk.name] = true;\n var watchSet = inputSourceArch.watchSet.clone();\n\n // *** Determine and load active plugins\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't have\n // a special \"use\" role anymore. it's not totally clear to me what\n // the correct behavior should be -- we need to resolve whether we\n // think about extensions as being global to a package or particular\n // to a unibuild.\n\n // (there's also some weirdness here with handling implies, because\n // the implies field is on the target unibuild, but we really only care\n // about packages.)\n var activePluginPackages = [isopk];\n\n // We don't use plugins from weak dependencies, because the ability\n // to compile a certain type of file shouldn't depend on whether or\n // not some unrelated package in the target has a dependency. And we\n // skip unordered dependencies, because it's not going to work to\n // have circular build-time dependencies.\n //\n // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,\n // templating from standard-app-packages).\n //\n // We pass archinfo.host here, not self.arch, because it may be more specific,\n // and because plugins always have to run on the host architecture.\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: archinfo.host(),\n isopackCache: isopackCache,\n skipUnordered: true\n // implicitly skip weak deps by not specifying acceptableWeakPackages option\n }, function (unibuild) {\n if (unibuild.pkg.name === isopk.name)\n return;\n pluginProviderPackageNames[unibuild.pkg.name] = true;\n // If other package is built from source, then we need to rebuild this\n // package if any file in the other package that could define a plugin\n // changes.\n watchSet.merge(unibuild.pkg.pluginWatchSet);\n\n if (_.isEmpty(unibuild.pkg.plugins))\n return;\n activePluginPackages.push(unibuild.pkg);\n });\n\n activePluginPackages = _.uniq(activePluginPackages);\n\n // *** Assemble the list of source file handlers from the plugins\n // XXX BBP redoc\n var allHandlersWithPkgs = {};\n var compilerPluginsByExtension = {};\n var linterPluginsByExtension = {};\n var sourceExtensions = {}; // maps source extensions to isTemplate\n\n sourceExtensions['js'] = false;\n allHandlersWithPkgs['js'] = {\n pkgName: null /* native handler */,\n handler: function (compileStep) {\n // This is a hardcoded handler for *.js files. Since plugins\n // are written in JavaScript we have to start somewhere.\n\n var options = {\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n _hash: compileStep._hash\n };\n\n if (compileStep.fileOptions.hasOwnProperty(\"bare\")) {\n options.bare = compileStep.fileOptions.bare;\n } else if (compileStep.fileOptions.hasOwnProperty(\"raw\")) {\n // XXX eventually get rid of backward-compatibility \"raw\" name\n // XXX COMPAT WITH 0.6.4\n options.bare = compileStep.fileOptions.raw;\n }\n\n compileStep.addJavaScript(options);\n }\n };\n\n _.each(activePluginPackages, function (otherPkg) {\n otherPkg.ensurePluginsInitialized();\n\n // Iterate over the legacy source handlers.\n _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {\n // XXX comparing function text here seems wrong.\n if (_.has(allHandlersWithPkgs, ext) &&\n allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n return;\n }\n // Is this handler only registered for, say, \"web\", and we're building,\n // say, \"os\"?\n if (sourceHandler.archMatching &&\n !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {\n return;\n }\n allHandlersWithPkgs[ext] = {\n pkgName: otherPkg.name,\n handler: sourceHandler.handler\n };\n sourceExtensions[ext] = !!sourceHandler.isTemplate;\n });\n\n // Iterate over the compiler plugins.\n _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {\n _.each(compilerPlugin.extensions, function (ext) {\n if (_.has(allHandlersWithPkgs, ext) ||\n _.has(compilerPluginsByExtension, ext)) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first one we found.\n return;\n }\n compilerPluginsByExtension[ext] = compilerPlugin;\n sourceExtensions[ext] = compilerPlugin.isTemplate;\n });\n });\n\n // Iterate over the linters\n _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n _.each(linterPlugin.extensions, function (ext) {\n linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n linterPluginsByExtension[ext].push(linterPlugin);\n });\n });\n });\n\n // *** Determine source files\n // Note: sourceExtensions does not include leading dots\n // Note: the getSourcesFunc function isn't expected to add its\n // source files to watchSet; rather, the watchSet is for other\n // things that the getSourcesFunc consulted (such as directory\n // listings or, in some hypothetical universe, control files) to\n // determine its source files.\n var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);\n\n if (nodeModulesPath) {\n // If this slice has node modules, we should consider the shrinkwrap file\n // to be part of its inputs. (This is a little racy because there's no\n // guarantee that what we read here is precisely the version that's used,\n // but it's better than nothing at all.)\n //\n // Note that this also means that npm modules used by plugins will get\n // this npm-shrinkwrap.json in their pluginDependencies (including for all\n // packages that depend on us)! This is good: this means that a tweak to\n // an indirect dependency of the coffee-script npm module used by the\n // coffeescript package will correctly cause packages with *.coffee files\n // to be rebuilt.\n var shrinkwrapPath = nodeModulesPath.replace(\n /node_modules$/, 'npm-shrinkwrap.json');\n watch.readAndWatchFile(watchSet, shrinkwrapPath);\n }\n\n // *** Process each source file\n var addAsset = function (contents, relPath, hash) {\n // XXX hack\n if (! inputSourceArch.pkg.name)\n relPath = relPath.replace(/^(private|public)\\//, '');\n\n resources.push({\n type: \"asset\",\n data: contents,\n path: relPath,\n servePath: colonConverter.convert(\n files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),\n hash: hash\n });\n };\n\n var convertSourceMapPaths = function (sourcemap, f) {\n if (! sourcemap) {\n // Don't try to convert it if it doesn't exist\n return sourcemap;\n }\n\n var srcmap = JSON.parse(sourcemap);\n srcmap.sources = _.map(srcmap.sources, f);\n return JSON.stringify(srcmap);\n };\n\n var wrappedSourceItems = _.map(sourceItems, function (source) {\n var fileWatchSet = new watch.WatchSet;\n // readAndWatchFileWithHash returns an object carrying a buffer with the\n // file-contents. The buffer contains the original data of the file (no EOL\n // transforms from the tools/files.js part).\n // We don't put this into the unibuild's watchSet immediately since we want\n // to avoid putting it there if it turns out not to be relevant to our\n // arch.\n var absPath = files.pathResolve(\n inputSourceArch.pkg.sourceRoot, source.relPath);\n var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);\n\n Console.nudge(true);\n\n return {\n relPath: source.relPath,\n watchset: fileWatchSet,\n contents: file.contents,\n hash: file.hash,\n source: source,\n 'package': isopk.name\n };\n });\n\n runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n\n _.each(wrappedSourceItems, function (wrappedSource) {\n var source = wrappedSource.source;\n var relPath = source.relPath;\n var fileOptions = _.clone(source.fileOptions) || {};\n var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);\n var filename = files.pathBasename(relPath);\n var contents = wrappedSource.contents;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n\n Console.nudge(true);\n\n if (contents === null) {\n // It really sucks to put this check here, since this isn't publish\n // code...\n if (source.relPath.match(/:/)) {\n buildmessage.error(\n \"Couldn't build this package on Windows due to the following file \" +\n \"with a colon -- \" + source.relPath + \". Please rename and \" +\n \"and re-publish the package.\");\n } else {\n buildmessage.error(\"File not found: \" + source.relPath);\n }\n\n // recover by ignoring (but still watching the file)\n watchSet.merge(fileWatchSet);\n return;\n }\n\n // Find the handler for source files with this extension.\n var handler = null;\n var isBuildPluginSource = false;\n if (! fileOptions.isAsset) {\n var parts = filename.split('.');\n // don't use iteration functions, so we can return/break\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(compilerPluginsByExtension, extension)) {\n var compilerPlugin = compilerPluginsByExtension[extension];\n if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {\n // This file is for a compiler plugin but not for this arch. Skip\n // it, and don't even watch it. (eg, skip CSS preprocessor files on\n // the server.)\n return;\n }\n isBuildPluginSource = true;\n break;\n }\n if (_.has(allHandlersWithPkgs, extension)) {\n handler = allHandlersWithPkgs[extension].handler;\n break;\n }\n }\n }\n\n // OK, this is relevant to this arch, so watch it.\n watchSet.merge(fileWatchSet);\n\n if (isBuildPluginSource) {\n // This is source used by a new-style compiler plugin; it will be fully\n // processed later in the bundler.\n resources.push({\n type: \"source\",\n data: contents,\n path: relPath,\n hash: hash\n });\n return;\n }\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n addAsset(contents, relPath, hash);\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript).\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - pathForSourceMap: If this file is to be included in a source map,\n // this is the name you should use for it in the map.\n // - rootOutputPath: on web targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-web targets\n // - fileOptions: any options passed to \"api.addFiles\"; for\n // use by the plugin. The built-in \"js\" plugin uses the \"bare\"\n // option for files that shouldn't be wrapped in a closure.\n // - declaredExports: An array of symbols exported by this unibuild, or null\n // if it may not export any symbols (eg, test unibuilds). This is used by\n // CoffeeScript to ensure that it doesn't close over those symbols, eg.\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // Web targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\",\n // sourceMap: \"stringified json sourcemap\"})\n // Web targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // bare: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. \"bare\" means to not wrap the file in\n // a closure, so that its vars are shared with other files\n // in the module.\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Add a file to serve as-is over HTTP (web targets) or\n // to include as-is in the bundle (os targets).\n // This time `data` is a Buffer rather than a string. For\n // web targets, it will be served at the exact path you\n // request (concatenated with rootOutputPath). For server\n // targets, the file can be retrieved by passing path to\n // Assets.getText or Assets.getBinary.\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces). sourcePath,\n // line, column, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'web'\n // vs 'os') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific unibuild will be emitted only if\n // there are native node modules). Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force unibuilds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n\n /**\n * The comments for this class aren't used to generate docs right now.\n * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers\n * @class CompileStep\n * @summary The object passed into Plugin.registerSourceHandler\n * @global\n */\n var compileStep = {\n\n /**\n * @summary The total number of bytes in the input file.\n * @memberOf CompileStep\n * @instance\n * @type {Integer}\n */\n inputSize: contents.length,\n\n /**\n * @summary The filename and relative path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n inputPath: files.convertToOSPath(relPath, true),\n\n /**\n * @summary The filename and absolute path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n fullInputPath: files.convertToOSPath(absPath),\n\n // The below is used in the less and stylus packages... so it should be\n // public API.\n _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..\n\n // Used for one optimization. Don't rely on this otherwise.\n _hash: hash,\n\n // XXX duplicates _pathForSourceMap() in linker\n /**\n * @summary If you are generating a sourcemap for the compiled file, use\n * this path for the original file in the sourcemap.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n pathForSourceMap: files.convertToOSPath(\n inputSourceArch.pkg.name ? inputSourceArch.pkg.name + \"/\" + relPath :\n files.pathBasename(relPath), true),\n\n // null if this is an app. intended to be used for the sources\n // dictionary for source maps.\n /**\n * @summary The name of the package in which the file being built exists.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n packageName: inputSourceArch.pkg.name,\n\n /**\n * @summary On web targets, this will be the root URL prepended\n * to the paths you pick for your output files. For example,\n * it could be \"/packages/my-package\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n rootOutputPath: files.convertToOSPath(\n inputSourceArch.pkg.serveRoot, true),\n\n /**\n * @summary The architecture for which we are building. Can be \"os\",\n * \"web.browser\", or \"web.cordova\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n arch: inputSourceArch.arch,\n\n /**\n * @deprecated in 0.9.4\n * This is a duplicate API of the above, we don't need it.\n */\n archMatches: function (pattern) {\n return archinfo.matches(inputSourceArch.arch, pattern);\n },\n\n /**\n * @summary Any options passed to \"api.addFiles\".\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n fileOptions: fileOptions,\n\n /**\n * @summary The list of exports that the current package has defined.\n * Can be used to treat those symbols differently during compilation.\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n\n /**\n * @summary Read from the input file. If `n` is specified, returns the\n * next `n` bytes of the file as a Buffer. XXX not sure if this actually\n * returns a String sometimes...\n * @param {Integer} [n] The number of bytes to return.\n * @instance\n * @memberOf CompileStep\n * @returns {Buffer}\n */\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n\n /**\n * @summary Works in web targets only. Add markup to the `head` or `body`\n * section of the document.\n * @param {Object} options\n * @param {String} options.section Which section of the document should\n * be appended to. Can only be \"head\" or \"body\".\n * @param {String} options.data The content to append.\n * @memberOf CompileStep\n * @instance\n */\n addHtml: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"web targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')\n });\n },\n\n /**\n * @deprecated in 0.9.4\n */\n appendDocument: function (options) {\n this.addHtml(options);\n },\n\n /**\n * @summary Web targets only. Add a stylesheet to the document.\n * @param {Object} options\n * @param {String} path The requested path for the added CSS, may not be\n * satisfied if there are path conflicts.\n * @param {String} data The content of the stylesheet that should be\n * added.\n * @param {String} sourceMap A stringified JSON sourcemap, in case the\n * stylesheet was generated from a different file.\n * @memberOf CompileStep\n * @instance\n */\n addStylesheet: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"web targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n refreshable: true,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),\n servePath: colonConverter.convert(\n files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true))),\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath)\n });\n },\n\n /**\n * @summary Add JavaScript code. The code added will only see the\n * namespaces imported by this package as runtime dependencies using\n * ['api.use'](#PackageAPI-use). If the file being compiled was added\n * with the bare flag, the resulting JavaScript won't be wrapped in a\n * closure.\n * @param {Object} options\n * @param {String} options.path The path at which the JavaScript file\n * should be inserted, may not be honored in case of path conflicts.\n * @param {String} options.data The code to be added.\n * @param {String} options.sourcePath The path that will be used in\n * any error messages generated by this file, e.g. `foo.js:4:1: error`.\n * @memberOf CompileStep\n * @instance\n */\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n\n // By default, use fileOptions for the `bare` option but also allow\n // overriding it with the options\n var bare = fileOptions.bare;\n if (options.hasOwnProperty(\"bare\")) {\n bare = options.bare;\n }\n\n js.push({\n source: files.convertToStandardLineEndings(options.data),\n sourcePath: files.convertToStandardPath(options.sourcePath, true),\n servePath: files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true)),\n bare: !! bare,\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath),\n sourceHash: options._hash\n });\n },\n\n /**\n * @summary Add a file to serve as-is to the browser or to include on\n * the browser, depending on the target. On the web, it will be served\n * at the exact path requested. For server targets, it can be retrieved\n * using `Assets.getText` or `Assets.getBinary`.\n * @param {Object} options\n * @param {String} path The path at which to serve the asset.\n * @param {Buffer|String} data The data that should be placed in\n * the file.\n * @memberOf CompileStep\n * @instance\n */\n addAsset: function (options) {\n if (! (options.data instanceof Buffer)) {\n if (_.isString(options.data)) {\n options.data = new Buffer(options.data);\n } else {\n throw new Error(\"'data' option to addAsset must be a Buffer or String.\");\n }\n }\n\n addAsset(options.data, files.convertToStandardPath(options.path, true));\n },\n\n /**\n * @summary Display a build error.\n * @param {Object} options\n * @param {String} message The error message to display.\n * @param {String} [sourcePath] The path to display in the error message.\n * @param {Integer} line The line number to display in the error message.\n * @param {String} func The function name to display in the error message.\n * @memberOf CompileStep\n * @instance\n */\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // *** Run Phase 1 link\n\n // Load jsAnalyze from the js-analyze package... unless we are the\n // js-analyze package, in which case never mind. (The js-analyze package's\n // default unibuild is not allowed to depend on anything!)\n var jsAnalyze = null;\n if (! _.isEmpty(js) && inputSourceArch.pkg.name !== \"js-analyze\") {\n jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;\n }\n\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n // I was confused about this, so I am leaving a comment -- the\n // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.\n // XXX: If we change this, we can get rid of source arch names!\n combinedServePath: isApp ? null :\n \"/packages/\" + colonConverter.convert(\n inputSourceArch.pkg.name +\n (inputSourceArch.kind === \"main\" ? \"\" : (\":\" + inputSourceArch.kind)) +\n \".js\"),\n name: inputSourceArch.pkg.name || null,\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n jsAnalyze: jsAnalyze,\n noLineNumbers: noLineNumbers\n });\n\n // *** Determine captured variables\n var packageVariables = [];\n var packageVariableNames = {};\n _.each(inputSourceArch.declaredExports, function (symbol) {\n if (_.has(packageVariableNames, symbol.name))\n return;\n packageVariables.push({\n name: symbol.name,\n export: symbol.testOnly? \"tests\" : true\n });\n packageVariableNames[symbol.name] = true;\n });\n _.each(results.assignedVariables, function (name) {\n if (_.has(packageVariableNames, name))\n return;\n packageVariables.push({\n name: name\n });\n packageVariableNames[name] = true;\n });\n\n // *** Consider npm dependencies and portability\n var arch = inputSourceArch.arch;\n if (arch === \"os\" && ! isPortable) {\n // Contains non-portable compiled npm modules, so set arch correctly\n arch = archinfo.host();\n }\n if (! archinfo.matches(arch, \"os\")) {\n // npm modules only work on server architectures\n nodeModulesPath = undefined;\n }\n\n // *** Output unibuild object\n isopk.addUnibuild({\n kind: inputSourceArch.kind,\n arch: arch,\n uses: inputSourceArch.uses,\n implies: inputSourceArch.implies,\n watchSet: watchSet,\n nodeModulesPath: nodeModulesPath,\n prelinkFiles: results.files,\n packageVariables: packageVariables,\n resources: resources\n });\n\n return {\n pluginProviderPackageNames: pluginProviderPackageNames\n };\n};\n\nvar runLinters = function (\n inputSourceArch,\n isopackCache,\n wrappedSourceItems,\n linterPluginsByExtension) {\n // For linters, figure out what are the global imports from other packages\n // that we use directly, or are implied.\n var globalImports = ['Package', 'Assets', 'Npm'];\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: inputSourceArch.arch,\n isopackCache: isopackCache,\n skipUnordered: true,\n skipDebugOnly: true\n }, function (unibuild) {\n if (unibuild.pkg.name === inputSourceArch.pkg.name)\n return;\n _.each(unibuild.packageVariables, function (symbol) {\n if (symbol.export === true)\n globalImports.push(symbol.name);\n });\n });\n\n // For each file choose the longest extension handled by linters.\n var longestMatchingExt = {};\n _.each(wrappedSourceItems, function (wrappedSource) {\n var filename = files.pathBasename(wrappedSource.relPath);\n var parts = filename.split('.');\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(linterPluginsByExtension, extension)) {\n longestMatchingExt[wrappedSource.relPath] = extension;\n break;\n }\n }\n });\n\n // Run linters on files.\n _.each(linterPluginsByExtension, function (linters, ext) {\n var sourcesToLint = [];\n _.each(wrappedSourceItems, function (wrappedSource) {\n var relPath = wrappedSource.relPath;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n var source = wrappedSource.source;\n\n // only run linters matching the longest handled extension\n if (longestMatchingExt[relPath] !== ext)\n return;\n\n sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));\n });\n\n _.each(linters, function (linterDef) {\n // skip linters not relevant to the arch we are compiling for\n if (! linterDef.relevantForArch(inputSourceArch.arch))\n return;\n\n var linter = linterDef.instantiatePlugin();\n buildmessage.enterJob({\n title: \"linting files with \" + linterDef.isopack.name\n }, function () {\n try {\n var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));\n markedLinter(sourcesToLint, globalImports);\n } catch (e) {\n buildmessage.exception(e);\n }\n });\n });\n });\n};\n\n// Iterates over each in options.dependencies as well as unibuilds implied by\n// them. The packages in question need to already be built and in\n// options.isopackCache.\ncompiler.eachUsedUnibuild = function (\n options, callback) {\n buildmessage.assertInCapture();\n var dependencies = options.dependencies;\n var arch = options.arch;\n var isopackCache = options.isopackCache;\n\n var acceptableWeakPackages = options.acceptableWeakPackages || {};\n\n var processedUnibuildId = {};\n var usesToProcess = [];\n _.each(dependencies, function (use) {\n if (options.skipUnordered && use.unordered)\n return;\n if (use.weak && !_.has(acceptableWeakPackages, use.package))\n return;\n usesToProcess.push(use);\n });\n\n while (! _.isEmpty(usesToProcess)) {\n var use = usesToProcess.shift();\n\n var usedPackage = isopackCache.getIsopack(use.package);\n\n // Ignore this package if we were told to skip debug-only packages and it is\n // debug-only.\n if (usedPackage.debugOnly && options.skipDebugOnly)\n continue;\n\n var unibuild = usedPackage.getUnibuildAtArch(arch);\n if (!unibuild) {\n // The package exists but there's no unibuild for us. A buildmessage has\n // already been issued. Recover by skipping.\n continue;\n }\n\n if (_.has(processedUnibuildId, unibuild.id))\n continue;\n processedUnibuildId[unibuild.id] = true;\n\n callback(unibuild, {\n unordered: !!use.unordered,\n weak: !!use.weak\n });\n\n _.each(unibuild.implies, function (implied) {\n usesToProcess.push(implied);\n });\n }\n};\n", "file_path": "tools/compiler.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.9945318698883057, 0.05856352671980858, 0.00016292907821480185, 0.00023929655435495079, 0.19957692921161652]} {"hunk": {"id": 0, "code_window": [" }\n", " });\n", "\n", " files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" // JSHint has a particular format for defining globals. `false` means that the\n", " // global is not allowed to be redefined. `true` means it is allowed to be\n", " // redefined. Since the passed imports are probably not great for definition,\n", " // mark them as false.\n", " var predefinedGlobals = {};\n", " globals.forEach(function (symbol) {\n", " predefinedGlobals[symbol] = false;\n", " });\n", "\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "add", "edit_start_line_idx": 40}, "file": "var ERRORS_KEY = 'signinErrors';\n\nTemplate.signin.onCreated(function() {\n Session.set(ERRORS_KEY, {});\n});\n\nTemplate.signin.helpers({\n errorMessages: function() {\n return _.values(Session.get(ERRORS_KEY));\n },\n errorClass: function(key) {\n return Session.get(ERRORS_KEY)[key] && 'error';\n }\n});\n\nTemplate.signin.events({\n 'submit': function(event, template) {\n event.preventDefault();\n \n var email = template.$('[name=email]').val();\n var password = template.$('[name=password]').val();\n \n var errors = {};\n\n if (! email) {\n errors.email = 'Email is required';\n }\n\n if (! password) {\n errors.password = 'Password is required';\n }\n \n Session.set(ERRORS_KEY, errors);\n if (_.keys(errors).length) {\n return;\n }\n \n Meteor.loginWithPassword(email, password, function(error) {\n if (error) {\n return Session.set(ERRORS_KEY, {'none': error.reason});\n }\n \n Router.go('home');\n });\n }\n});\n", "file_path": "examples/todos/client/templates/auth-signin.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001867237879196182, 0.00017131589993368834, 0.00016629403398837894, 0.0001673349179327488, 7.77936202212004e-06]} {"hunk": {"id": 0, "code_window": [" }\n", " });\n", "\n", " files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" // JSHint has a particular format for defining globals. `false` means that the\n", " // global is not allowed to be redefined. `true` means it is allowed to be\n", " // redefined. Since the passed imports are probably not great for definition,\n", " // mark them as false.\n", " var predefinedGlobals = {};\n", " globals.forEach(function (symbol) {\n", " predefinedGlobals[symbol] = false;\n", " });\n", "\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "add", "edit_start_line_idx": 40}, "file": "Package.onUse(function(api) {\n api.use('first-unordered', {unordered: true});\n});\n", "file_path": "tools/tests/apps/circular-deps/packages/second-unordered/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00016964011592790484, 0.00016964011592790484, 0.00016964011592790484, 0.00016964011592790484, 0.0]} {"hunk": {"id": 0, "code_window": [" }\n", " });\n", "\n", " files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n"], "labels": ["keep", "keep", "add", "keep", "keep", "keep"], "after_edit": [" // JSHint has a particular format for defining globals. `false` means that the\n", " // global is not allowed to be redefined. `true` means it is allowed to be\n", " // redefined. Since the passed imports are probably not great for definition,\n", " // mark them as false.\n", " var predefinedGlobals = {};\n", " globals.forEach(function (symbol) {\n", " predefinedGlobals[symbol] = false;\n", " });\n", "\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "add", "edit_start_line_idx": 40}, "file": "var _ = require('underscore');\nvar files = require('./files.js');\nvar utils = require('./utils.js');\nvar parseStack = require('./parse-stack.js');\nvar release = require('./release.js');\nvar catalog = require('./catalog.js');\nvar archinfo = require('./archinfo.js');\nvar Future = require('fibers/future');\nvar isopackets = require(\"./isopackets.js\");\nvar config = require('./config.js');\nvar buildmessage = require('./buildmessage.js');\nvar util = require('util');\nvar child_process = require('child_process');\nvar webdriver = require('browserstack-webdriver');\nvar phantomjs = require('phantomjs');\nvar catalogRemote = require('./catalog-remote.js');\nvar Console = require('./console.js').Console;\nvar tropohouseModule = require('./tropohouse.js');\nvar packageMapModule = require('./package-map.js');\nvar isopackCacheModule = require('./isopack-cache.js');\n\n// Exception representing a test failure\nvar TestFailure = function (reason, details) {\n var self = this;\n self.reason = reason;\n self.details = details || {};\n self.stack = (new Error).stack;\n};\n\n// Use this to decorate functions that throw TestFailure. Decorate the\n// first function that should not be included in the call stack shown\n// to the user.\nvar markStack = function (f) {\n return parseStack.markTop(f);\n};\n\n// Call from a test to throw a TestFailure exception and bail out of the test\nvar fail = markStack(function (reason) {\n throw new TestFailure(reason);\n});\n\n// Call from a test to assert that 'actual' is equal to 'expected',\n// with 'actual' being the value that the test got and 'expected'\n// being the expected value\nvar expectEqual = markStack(function (actual, expected) {\n var Package = isopackets.load('ejson');\n if (! Package.ejson.EJSON.equals(actual, expected)) {\n throw new TestFailure(\"not-equal\", {\n expected: expected,\n actual: actual\n });\n }\n});\n\n// Call from a test to assert that 'actual' is truthy.\nvar expectTrue = markStack(function (actual) {\n if (! actual) {\n throw new TestFailure('not-true');\n }\n});\n// Call from a test to assert that 'actual' is falsey.\nvar expectFalse = markStack(function (actual) {\n if (actual) {\n throw new TestFailure('not-false');\n }\n});\n\nvar expectThrows = markStack(function (f) {\n var threw = false;\n try {\n f();\n } catch (e) {\n threw = true;\n }\n\n if (! threw)\n throw new TestFailure(\"expected-exception\");\n});\n\n// Execute a command synchronously, discarding stderr.\nvar execFileSync = function (binary, args, opts) {\n return Future.wrap(function(cb) {\n var cb2 = function(err, stdout, stderr) { cb(err, stdout); };\n child_process.execFile(binary, args, opts, cb2);\n })().wait();\n};\n\nvar doOrThrow = function (f) {\n var ret;\n var messages = buildmessage.capture(function () {\n ret = f();\n });\n if (messages.hasMessages()) {\n throw Error(messages.formatMessages());\n }\n return ret;\n};\n\n// Our current strategy for running tests that need warehouses is to build all\n// packages from the checkout into this temporary tropohouse directory, and for\n// each test that need a fake warehouse, copy the built packages into the\n// test-specific warehouse directory. This isn't particularly fast, but it'll\n// do for now. We build the packages during the first test that needs them.\nvar builtPackageTropohouseDir = null;\nvar tropohouseLocalCatalog = null;\nvar tropohouseIsopackCache = null;\n\n// Let's build a minimal set of packages that's enough to get self-test\n// working. (And that doesn't need us to download any Atmosphere packages.)\nvar ROOT_PACKAGES_TO_BUILD_IN_SANDBOX = [\n // We need the tool in order to run from the fake warehouse at all.\n \"meteor-tool\",\n // We need the packages in the skeleton app in order to test 'meteor create'.\n \"meteor-platform\", \"autopublish\", \"insecure\"\n];\n\nvar setUpBuiltPackageTropohouse = function () {\n if (builtPackageTropohouseDir)\n return;\n builtPackageTropohouseDir = files.mkdtemp('built-package-tropohouse');\n\n if (config.getPackagesDirectoryName() !== 'packages')\n throw Error(\"running self-test with METEOR_PACKAGE_SERVER_URL set?\");\n\n var tropohouse = new tropohouseModule.Tropohouse(builtPackageTropohouseDir);\n tropohouseLocalCatalog = newSelfTestCatalog();\n var versions = {};\n _.each(\n tropohouseLocalCatalog.getAllNonTestPackageNames(),\n function (packageName) {\n versions[packageName] =\n tropohouseLocalCatalog.getLatestVersion(packageName).version;\n });\n var packageMap = new packageMapModule.PackageMap(versions, {\n localCatalog: tropohouseLocalCatalog\n });\n // Make an isopack cache that doesn't automatically save isopacks to disk and\n // has no access to versioned packages.\n tropohouseIsopackCache = new isopackCacheModule.IsopackCache({\n packageMap: packageMap,\n includeCordovaUnibuild: true\n });\n doOrThrow(function () {\n buildmessage.enterJob(\"building self-test packages\", function () {\n // Build the packages into the in-memory IsopackCache.\n tropohouseIsopackCache.buildLocalPackages(\n ROOT_PACKAGES_TO_BUILD_IN_SANDBOX);\n });\n });\n\n // Save all the isopacks into builtPackageTropohouseDir/packages. (Note that\n // we are always putting them into the default 'packages' (assuming\n // $METEOR_PACKAGE_SERVER_URL is not set in the self-test process itself) even\n // though some tests will want them to be under\n // 'packages-for-server/test-packages'; we'll fix this in _makeWarehouse.\n tropohouseIsopackCache.eachBuiltIsopack(function (name, isopack) {\n tropohouse._saveIsopack(isopack, name);\n });\n};\n\nvar newSelfTestCatalog = function () {\n if (! files.inCheckout())\n throw Error(\"Only can build packages from a checkout\");\n\n var catalogLocal = require('./catalog-local.js');\n var selfTestCatalog = new catalogLocal.LocalCatalog;\n var messages = buildmessage.capture(\n { title: \"scanning local core packages\" },\n function () {\n // When building a fake warehouse from a checkout, we use local packages,\n // but *ONLY THOSE FROM THE CHECKOUT*: not app packages or $PACKAGE_DIRS\n // packages. One side effect of this: we really really expect them to all\n // build, and we're fine with dying if they don't (there's no worries\n // about needing to springboard).\n selfTestCatalog.initialize({\n localPackageSearchDirs: [files.pathJoin(\n files.getCurrentToolsDir(), 'packages')]\n });\n });\n if (messages.hasMessages()) {\n Console.arrowError(\"Errors while scanning core packages:\");\n Console.printMessages(messages);\n throw new Error(\"scan failed?\");\n }\n return selfTestCatalog;\n};\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Matcher\n///////////////////////////////////////////////////////////////////////////////\n\n// Handles the job of waiting until text is seen that matches a\n// regular expression.\n\nvar Matcher = function (run) {\n var self = this;\n self.buf = \"\";\n self.ended = false;\n self.matchPattern = null;\n self.matchFuture = null;\n self.matchStrict = null;\n self.run = run; // used only to set a field on exceptions\n};\n\n_.extend(Matcher.prototype, {\n write: function (data) {\n var self = this;\n self.buf += data;\n self._tryMatch();\n },\n\n match: function (pattern, timeout, strict) {\n var self = this;\n if (self.matchFuture)\n throw new Error(\"already have a match pending?\");\n self.matchPattern = pattern;\n self.matchStrict = strict;\n var f = self.matchFuture = new Future;\n self._tryMatch(); // could clear self.matchFuture\n\n var timer = null;\n if (timeout) {\n timer = setTimeout(function () {\n self.matchPattern = null;\n self.matchStrict = null;\n self.matchFuture = null;\n f['throw'](new TestFailure('match-timeout', { run: self.run }));\n }, timeout * 1000);\n }\n\n try {\n return f.wait();\n } finally {\n if (timer)\n clearTimeout(timer);\n }\n },\n\n end: function () {\n var self = this;\n self.ended = true;\n self._tryMatch();\n },\n\n matchEmpty: function () {\n var self = this;\n\n if (self.buf.length > 0) {\n Console.info(\"Extra junk is :\", self.buf);\n throw new TestFailure('junk-at-end', { run: self.run });\n }\n },\n\n _tryMatch: function () {\n var self = this;\n\n var f = self.matchFuture;\n if (! f)\n return;\n\n var ret = null;\n\n if (self.matchPattern instanceof RegExp) {\n var m = self.buf.match(self.matchPattern);\n if (m) {\n if (self.matchStrict && m.index !== 0) {\n self.matchFuture = null;\n self.matchStrict = null;\n self.matchPattern = null;\n Console.info(\"Extra junk is: \", self.buf.substr(0, m.index));\n f['throw'](new TestFailure(\n 'junk-before', { run: self.run, pattern: self.matchPattern }));\n return;\n }\n ret = m;\n self.buf = self.buf.slice(m.index + m[0].length);\n }\n } else {\n var i = self.buf.indexOf(self.matchPattern);\n if (i !== -1) {\n if (self.matchStrict && i !== 0) {\n self.matchFuture = null;\n self.matchStrict = null;\n self.matchPattern = null;\n Console.info(\"Extra junk is: \", self.buf.substr(0, i));\n f['throw'](new TestFailure('junk-before',\n { run: self.run, pattern: self.matchPattern }));\n return;\n }\n ret = self.matchPattern;\n self.buf = self.buf.slice(i + self.matchPattern.length);\n }\n }\n\n if (ret !== null) {\n self.matchFuture = null;\n self.matchStrict = null;\n self.matchPattern = null;\n f['return'](ret);\n return;\n }\n\n if (self.ended) {\n var failure = new TestFailure('no-match', { run: self.run,\n pattern: self.matchPattern });\n self.matchFuture = null;\n self.matchStrict = null;\n self.matchPattern = null;\n f['throw'](failure);\n return;\n }\n }\n});\n\n\n///////////////////////////////////////////////////////////////////////////////\n// OutputLog\n///////////////////////////////////////////////////////////////////////////////\n\n// Maintains a line-by-line merged log of multiple output channels\n// (eg, stdout and stderr).\n\nvar OutputLog = function (run) {\n var self = this;\n\n // each entry is an object with keys 'channel', 'text', and if it is\n // the last entry and there was no newline terminator, 'bare'\n self.lines = [];\n\n // map from a channel name to an object representing a partially\n // read line of text on that channel. That object has keys 'text'\n // (text read), 'offset' (cursor position, equal to text.length\n // unless a '\\r' has been read).\n self.buffers = {};\n\n // a Run, exclusively for inclusion in exceptions\n self.run = run;\n};\n\n_.extend(OutputLog.prototype, {\n write: function (channel, text) {\n var self = this;\n\n if (! _.has(self.buffers, 'channel'))\n self.buffers[channel] = { text: '', offset: 0};\n var b = self.buffers[channel];\n\n while (text.length) {\n var m = text.match(/^[^\\n\\r]+/);\n if (m) {\n // A run of non-control characters.\n b.text = b.text.substr(0, b.offset) +\n m[0] + b.text.substr(b.offset + m[0].length);\n b.offset += m[0].length;\n text = text.substr(m[0].length);\n continue;\n }\n\n if (text[0] === '\\r') {\n b.offset = 0;\n text = text.substr(1);\n continue;\n }\n\n if (text[0] === '\\n') {\n self.lines.push({ channel: channel, text: b.text });\n b.text = '';\n b.offset = 0;\n text = text.substr(1);\n continue;\n }\n\n throw new Error(\"conditions should have been exhaustive?\");\n }\n },\n\n end: function () {\n var self = this;\n\n _.each(_.keys(self.buffers), function (channel) {\n if (self.buffers[channel].text.length) {\n self.lines.push({ channel: channel,\n text: self.buffers[channel].text,\n bare: true });\n self.buffers[channel] = { text: '', offset: 0};\n }\n });\n },\n\n forbid: function (pattern, channel) {\n var self = this;\n _.each(self.lines, function (line) {\n if (channel && channel !== line.channel)\n return;\n\n var match = (pattern instanceof RegExp) ?\n (line.text.match(pattern)) : (line.text.indexOf(pattern) !== -1);\n if (match)\n throw new TestFailure('forbidden-string-present', { run: self.run });\n });\n },\n\n get: function () {\n var self = this;\n return self.lines;\n }\n});\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Sandbox\n///////////////////////////////////////////////////////////////////////////////\n\n// Represents an install of the tool. Creating this creates a private\n// sandbox with its own state, separate from the state of the current\n// meteor install or checkout, from the user's homedir, and from the\n// state of any other sandbox. It also creates an empty directory\n// which will be, by default, the cwd for runs created inside the\n// sandbox (you can change this with the cd() method).\n//\n// This will throw TestFailure if it has to build packages to set up\n// the sandbox and the build fails. So, only call it from inside\n// tests.\n//\n// options:\n// - warehouse: set to sandbox the warehouse too. If you don't do\n// this, the tests are run in the same context (checkout or\n// warehouse) as the actual copy of meteor you're running (the\n// meteor in 'meteor self-test'. This may only be set when you're\n// running 'meteor self-test' from a checkout. If it is set, it\n// should look something like this:\n// {\n// version1: { tools: 'tools1', notices: (...) },\n// version2: { tools: 'tools2', upgraders: [\"a\"],\n// notices: (...), latest: true }\n// }\n// This would set up a simulated warehouse with two releases in it,\n// one called 'version1' and having a tools version of 'tools1', and\n// similarly with 'version2'/'tools2', with the latter being marked\n// as the latest release, and the latter also having a single\n// upgrader named \"a\". The releases are made by building the\n// checkout into a release, and are identical except for their\n// version names. If you pass 'notices' (which is optional), set it\n// to the verbatim contents of the notices.json file for the\n// release, as an object.\n// - fakeMongo: if set, set an environment variable that causes our\n// 'fake-mongod' stub process to be started instead of 'mongod'. The\n// tellMongo method then becomes available on Runs for controlling\n// the stub.\n// - clients\n// - browserstack: true if browserstack clients should be used\n// - port: the port that the clients should run on\n\nvar Sandbox = function (options) {\n var self = this;\n // default options\n options = _.extend({ clients: {} }, options);\n\n self.root = files.mkdtemp();\n self.warehouse = null;\n\n self.home = files.pathJoin(self.root, 'home');\n files.mkdir(self.home, 0755);\n self.cwd = self.home;\n self.env = {};\n self.fakeMongo = options.fakeMongo;\n\n // By default, tests use the package server that this meteor binary is built\n // with. If a test is tagged 'test-package-server', it uses the test\n // server. Tests that publish packages should have this flag; tests that\n // assume that the release's packages can be found on the server should not.\n // Note that this only affects subprocess meteor runs, not direct invocation\n // of packageClient!\n if (_.contains(runningTest.tags, 'test-package-server')) {\n if (_.has(options, 'warehouse')) {\n // test-package-server and warehouse are basically two different ways of\n // sort of faking out the package system for tests. test-package-server\n // means \"use a specific production test server\"; warehouse means \"use\n // some fake files we put on disk and never sync\" (see _makeEnv where the\n // offline flag is set). Combining them doesn't make sense: either you\n // don't sync, in which case you don't see the stuff you published, or you\n // do sync, and suddenly the mock catalog we built is overridden by\n // test-package-server.\n // XXX we should just run servers locally instead of either of these\n // strategies\n throw Error(\"test-package-server and warehouse cannot be combined\");\n }\n\n self.set('METEOR_PACKAGE_SERVER_URL', exports.testPackageServerUrl);\n }\n\n if (_.has(options, 'warehouse')) {\n if (!files.inCheckout())\n throw Error(\"make only use a fake warehouse in a checkout\");\n self.warehouse = files.pathJoin(self.root, 'tropohouse');\n self._makeWarehouse(options.warehouse);\n }\n\n self.clients = [new PhantomClient({\n host: 'localhost',\n port: options.clients.port || 3000\n })];\n\n if (options.clients && options.clients.browserstack) {\n var browsers = [\n { browserName: 'firefox' },\n { browserName: 'chrome' },\n { browserName: 'internet explorer',\n browserVersion: '11' },\n { browserName: 'internet explorer',\n browserVersion: '8',\n timeout: 60 },\n { browserName: 'safari' },\n { browserName: 'android' }\n ];\n\n _.each(browsers, function (browser) {\n self.clients.push(new BrowserStackClient({\n host: 'localhost',\n port: 3000,\n browserName: browser.browserName,\n browserVersion: browser.browserVersion,\n timeout: browser.timeout\n }));\n });\n }\n\n var meteorScript = process.platform === \"win32\" ? \"meteor.bat\" : \"meteor\";\n\n // Figure out the 'meteor' to run\n if (self.warehouse)\n self.execPath = files.pathJoin(self.warehouse, meteorScript);\n else\n self.execPath = files.pathJoin(files.getCurrentToolsDir(), meteorScript);\n};\n\n_.extend(Sandbox.prototype, {\n // Create a new test run of the tool in this sandbox.\n run: function (/* arguments */) {\n var self = this;\n\n return new Run(self.execPath, {\n sandbox: self,\n args: _.toArray(arguments),\n cwd: self.cwd,\n env: self._makeEnv(),\n fakeMongo: self.fakeMongo\n });\n },\n\n // Tests a set of clients with the argument function. Each call to f(run)\n // instantiates a Run with a different client.\n // Use:\n // sandbox.testWithAllClients(function (run) {\n // // pre-connection checks\n // run.connectClient();\n // // post-connection checks\n // });\n testWithAllClients: function (f) {\n var self = this;\n var argsArray = _.compact(_.toArray(arguments).slice(1));\n\n console.log(\"running test with \" + self.clients.length + \" client(s).\");\n\n _.each(self.clients, function (client) {\n console.log(\"testing with \" + client.name + \"...\");\n var run = new Run(self.execPath, {\n sandbox: self,\n args: argsArray,\n cwd: self.cwd,\n env: self._makeEnv(),\n fakeMongo: self.fakeMongo,\n client: client\n });\n run.baseTimeout = client.timeout;\n f(run);\n });\n },\n\n // Copy an app from a template into the current directory in the\n // sandbox. 'to' is the subdirectory to put the app in, and\n // 'template' is a subdirectory of tools/tests/apps to copy.\n //\n // Note that the arguments are the opposite order from 'cp'. That\n // seems more intuitive to me -- if you disagree, my apologies.\n //\n // For example:\n // s.createApp('myapp', 'empty');\n // s.cd('myapp');\n createApp: function (to, template, options) {\n var self = this;\n options = options || {};\n files.cp_r(files.pathJoin(files.convertToStandardPath(__dirname), 'tests',\n 'apps', template),\n files.pathJoin(self.cwd, to),\n { ignore: [/^local$/] });\n // If the test isn't explicitly managing a mock warehouse, ensure that apps\n // run with our release by default.\n if (options.release) {\n self.write(files.pathJoin(to, '.meteor/release'), options.release);\n } else if (!self.warehouse && release.current.isProperRelease()) {\n self.write(files.pathJoin(to, '.meteor/release'), release.current.name);\n }\n\n if (options.dontPrepareApp)\n return;\n\n // Prepare the app (ie, build or download packages). We give this a nice\n // long timeout, which allows the next command to not need a bloated\n // timeout. (meteor create does this anyway.)\n self.cd(to, function () {\n var run = self.run(\"--prepare-app\");\n // XXX Can we cache the output of running this once somewhere, so that\n // multiple calls to createApp with the same template get the same cache?\n // This is a little tricky because isopack-buildinfo.json uses absolute\n // paths.\n run.waitSecs(20);\n run.expectExit(0);\n });\n },\n\n // Same as createApp, but with a package.\n //\n // @param packageDir {String} The directory in which to create the package\n // @param packageName {String} The package name to create. This string will\n // replace all appearances of ~package-name~\n // in any package*.js files in the template\n // @param template {String} The package template to use. Found as a\n // subdirectory in tests/packages/\n //\n // For example:\n // s.createPackage('me_mypack', me:mypack', 'empty');\n // s.cd('me_mypack');\n createPackage: function (packageDir, packageName, template) {\n var self = this;\n var packagePath = files.pathJoin(self.cwd, packageDir);\n var templatePackagePath = files.pathJoin(\n files.convertToStandardPath(__dirname), 'tests', 'packages', template);\n files.cp_r(templatePackagePath, packagePath);\n\n _.each(files.readdir(packagePath), function (file) {\n if (file.match(/^package.*\\.js$/)) {\n var packageJsFile = files.pathJoin(packagePath, file);\n files.writeFile(\n packageJsFile,\n files.readFile(packageJsFile, \"utf8\")\n .replace(\"~package-name~\", packageName));\n }\n });\n },\n\n // Change the cwd to be used for subsequent runs. For example:\n // s.run('create', 'myapp').expectExit(0);\n // s.cd('myapp');\n // s.run('add', 'somepackage') ...\n // If you provide a callback, it will invoke the callback and then\n // change the cwd back to the previous value. eg:\n // s.cd('app1', function () {\n // s.run('add', 'somepackage');\n // });\n // s.cd('app2', function () {\n // s.run('add', 'somepackage');\n // });\n cd: function (relativePath, callback) {\n var self = this;\n var previous = self.cwd;\n self.cwd = files.pathResolve(self.cwd, relativePath);\n if (callback) {\n callback();\n self.cwd = previous;\n }\n },\n\n // Set an environment variable for subsequent runs.\n set: function (name, value) {\n var self = this;\n self.env[name] = value;\n },\n\n // Undo set().\n unset: function (name) {\n var self = this;\n delete self.env[name];\n },\n\n // Write to a file in the sandbox, overwriting its current contents\n // if any. 'filename' is a path intepreted relative to the Sandbox's\n // cwd. 'contents' is a string (utf8 is assumed).\n write: function (filename, contents) {\n var self = this;\n files.writeFile(files.pathJoin(self.cwd, filename), contents, 'utf8');\n },\n\n // Reads a file in the sandbox as a utf8 string. 'filename' is a\n // path intepreted relative to the Sandbox's cwd. Returns null if\n // file does not exist.\n read: function (filename) {\n var self = this;\n var file = files.pathJoin(self.cwd, filename);\n if (!files.exists(file))\n return null;\n else\n return files.readFile(files.pathJoin(self.cwd, filename), 'utf8');\n },\n\n // Copy the contents of one file to another. In these series of tests, we often\n // want to switch contents of package.js files. It is more legible to copy in\n // the backup file rather than trying to write into it manually.\n cp: function(from, to) {\n var self = this;\n var contents = self.read(from);\n if (!contents) {\n throw new Error(\"File \" + from + \" does not exist.\");\n };\n self.write(to, contents);\n },\n\n // Delete a file in the sandbox. 'filename' is as in write().\n unlink: function (filename) {\n var self = this;\n files.unlink(files.pathJoin(self.cwd, filename));\n },\n\n // Make a directory in the sandbox. 'filename' is as in write().\n mkdir: function (dirname) {\n var self = this;\n var dirPath = files.pathJoin(self.cwd, dirname);\n if (! files.exists(dirPath)) {\n files.mkdir(dirPath);\n }\n },\n\n // Rename something in the sandbox. 'oldName' and 'newName' are as in write().\n rename: function (oldName, newName) {\n var self = this;\n files.rename(files.pathJoin(self.cwd, oldName),\n files.pathJoin(self.cwd, newName));\n },\n\n // Return the current contents of .meteorsession in the sandbox.\n readSessionFile: function () {\n var self = this;\n return files.readFile(files.pathJoin(self.root, '.meteorsession'), 'utf8');\n },\n\n // Overwrite .meteorsession in the sandbox with 'contents'. You\n // could use this in conjunction with readSessionFile to save and\n // restore authentication states.\n writeSessionFile: function (contents) {\n var self = this;\n return files.writeFile(files.pathJoin(self.root, '.meteorsession'),\n contents, 'utf8');\n },\n\n _makeEnv: function () {\n var self = this;\n var env = _.clone(self.env);\n env.METEOR_SESSION_FILE = files.convertToOSPath(\n files.pathJoin(self.root, '.meteorsession'));\n\n if (self.warehouse) {\n // Tell it where the warehouse lives.\n env.METEOR_WAREHOUSE_DIR = files.convertToOSPath(self.warehouse);\n\n // Don't ever try to refresh the stub catalog we made.\n env.METEOR_OFFLINE_CATALOG = \"t\";\n }\n\n // By default (ie, with no mock warehouse and no --release arg) we should be\n // testing the actual release this is built in, so we pretend that it is the\n // latest release.\n if (!self.warehouse && release.current.isProperRelease())\n env.METEOR_TEST_LATEST_RELEASE = release.current.name;\n return env;\n },\n\n // Writes a stub warehouse (really a tropohouse) to the directory\n // self.warehouse. This warehouse only contains a meteor-tool package and some\n // releases containing that tool only (and no packages).\n //\n // packageServerUrl indicates which package server we think we are using. Use\n // the default, if we do not pass this in; you should pass it in any case that\n // you will be specifying $METEOR_PACKAGE_SERVER_URL in the environment of a\n // command you are running in this sandbox.\n _makeWarehouse: function (releases) {\n var self = this;\n\n // Ensure we have a tropohouse to copy stuff out of.\n setUpBuiltPackageTropohouse();\n\n var serverUrl = self.env.METEOR_PACKAGE_SERVER_URL;\n var packagesDirectoryName = config.getPackagesDirectoryName(serverUrl);\n files.cp_r(files.pathJoin(builtPackageTropohouseDir, 'packages'),\n files.pathJoin(self.warehouse, packagesDirectoryName),\n { preserveSymlinks: true });\n\n var stubCatalog = {\n syncToken: {},\n formatVersion: \"1.0\",\n collections: {\n packages: [],\n versions: [],\n builds: [],\n releaseTracks: [],\n releaseVersions: []\n }\n };\n\n var packageVersions = {};\n var toolPackageVersion = null;\n\n tropohouseIsopackCache.eachBuiltIsopack(function (packageName, isopack) {\n var packageRec = tropohouseLocalCatalog.getPackage(packageName);\n if (! packageRec)\n throw Error(\"no package record for \" + packageName);\n stubCatalog.collections.packages.push(packageRec);\n\n var versionRec = tropohouseLocalCatalog.getLatestVersion(packageName);\n if (! versionRec)\n throw Error(\"no version record for \" + packageName);\n stubCatalog.collections.versions.push(versionRec);\n\n stubCatalog.collections.builds.push({\n buildArchitectures: isopack.buildArchitectures(),\n versionId: versionRec._id,\n _id: utils.randomToken()\n });\n\n if (packageName === \"meteor-tool\") {\n toolPackageVersion = versionRec.version;\n } else {\n packageVersions[packageName] = versionRec.version;\n }\n });\n\n if (! toolPackageVersion)\n throw Error(\"no meteor-tool?\");\n\n stubCatalog.collections.releaseTracks.push({\n name: catalog.DEFAULT_TRACK,\n _id: utils.randomToken()\n });\n\n // Now create each requested release.\n _.each(releases, function (configuration, releaseName) {\n // Release info\n stubCatalog.collections.releaseVersions.push({\n track: catalog.DEFAULT_TRACK,\n _id: Math.random().toString(),\n version: releaseName,\n orderKey: releaseName,\n description: \"test release \" + releaseName,\n recommended: !!configuration.recommended,\n tool: configuration.tool || \"meteor-tool@\" + toolPackageVersion,\n packages: packageVersions\n });\n });\n\n var dataFile = config.getPackageStorage({\n root: self.warehouse,\n serverUrl: serverUrl\n });\n self.warehouseOfficialCatalog = new catalogRemote.RemoteCatalog();\n self.warehouseOfficialCatalog.initialize({\n packageStorage: dataFile\n });\n self.warehouseOfficialCatalog.insertData(stubCatalog);\n\n // And a cherry on top\n // XXX this is hacky\n files.linkToMeteorScript(\n files.pathJoin(self.warehouse, packagesDirectoryName, \"meteor-tool\", toolPackageVersion,\n 'mt-' + archinfo.host(), 'meteor'),\n files.pathJoin(self.warehouse, 'meteor'));\n }\n});\n\n///////////////////////////////////////////////////////////////////////////////\n// Client\n///////////////////////////////////////////////////////////////////////////////\n\nvar Client = function (options) {\n var self = this;\n\n self.host = options.host;\n self.port = options.port;\n self.url = \"http://\" + self.host + \":\" + self.port + '/' +\n (Math.random() * 0x100000000 + 1).toString(36);\n self.timeout = options.timeout || 40;\n\n if (! self.connect || ! self.stop) {\n console.log(\"Missing methods in subclass of Client.\");\n }\n};\n\n// PhantomClient\nvar PhantomClient = function (options) {\n var self = this;\n Client.apply(this, arguments);\n\n self.name = \"phantomjs\";\n self.process = null;\n\n self._logError = true;\n};\n\nutil.inherits(PhantomClient, Client);\n\n_.extend(PhantomClient.prototype, {\n connect: function () {\n var self = this;\n\n var phantomPath = phantomjs.path;\n\n var scriptPath = files.pathJoin(files.getCurrentToolsDir(), \"tools\",\n \"phantom\", \"open-url.js\");\n self.process = child_process.execFile(phantomPath, [\"--load-images=no\",\n files.convertToOSPath(scriptPath), self.url],\n {}, function (error, stdout, stderr) {\n if (self._logError && error) {\n console.log(\"PhantomJS exited with error \", error, \"\\nstdout:\\n\", stdout, \"\\nstderr:\\n\", stderr);\n }\n });\n },\n\n stop: function() {\n var self = this;\n // Suppress the expected SIGTERM exit 'failure'\n self._logError = false;\n self.process && self.process.kill();\n self.process = null;\n }\n});\n\n// BrowserStackClient\nvar browserStackKey = null;\n\nvar BrowserStackClient = function (options) {\n var self = this;\n Client.apply(this, arguments);\n\n self.tunnelProcess = null;\n self.driver = null;\n\n self.browserName = options.browserName;\n self.browserVersion = options.browserVersion;\n\n self.name = \"BrowserStack - \" + self.browserName;\n if (self.browserVersion) {\n self.name += \" \" + self.browserVersion;\n }\n};\n\nutil.inherits(BrowserStackClient, Client);\n\n_.extend(BrowserStackClient.prototype, {\n connect: function () {\n var self = this;\n\n // memoize the key\n if (browserStackKey === null)\n browserStackKey = self._getBrowserStackKey();\n if (! browserStackKey)\n throw new Error(\"BrowserStack key not found. Ensure that you \" +\n \"have installed your S3 credentials.\");\n\n var capabilities = {\n 'browserName' : self.browserName,\n 'browserstack.user' : 'meteor',\n 'browserstack.local' : 'true',\n 'browserstack.key' : browserStackKey\n };\n\n if (self.browserVersion) {\n capabilities.browserVersion = self.browserVersion;\n }\n\n self._launchBrowserStackTunnel(function (error) {\n if (error)\n throw error;\n\n self.driver = new webdriver.Builder().\n usingServer('http://hub.browserstack.com/wd/hub').\n withCapabilities(capabilities).\n build();\n self.driver.get(self.url);\n });\n },\n\n stop: function() {\n var self = this;\n self.tunnelProcess && self.tunnelProcess.kill();\n self.tunnelProcess = null;\n\n self.driver && self.driver.quit();\n self.driver = null;\n },\n\n _getBrowserStackKey: function () {\n var outputDir = files.pathJoin(files.mkdtemp(), \"key\");\n\n try {\n execFileSync(\"s3cmd\", [\"get\",\n \"s3://meteor-browserstack-keys/browserstack-key\",\n outputDir\n ]);\n\n return files.readFile(outputDir, \"utf8\").trim();\n } catch (e) {\n return null;\n }\n },\n\n _launchBrowserStackTunnel: function (callback) {\n var self = this;\n var browserStackPath =\n files.pathJoin(files.getDevBundle(), 'bin', 'BrowserStackLocal');\n files.chmod(browserStackPath, 0755);\n\n var args = [\n browserStackPath,\n browserStackKey,\n [self.host, self.port, 0].join(','),\n // Disable Live Testing and Screenshots, just test with Automate.\n '-onlyAutomate',\n // Do not wait for the server to be ready to spawn the process.\n '-skipCheck'\n ];\n self.tunnelProcess = child_process.execFile(\n '/bin/bash',\n ['-c', args.join(' ')]\n );\n\n // Called when the SSH tunnel is established.\n self.tunnelProcess.stdout.on('data', function(data) {\n if (data.toString().match(/You can now access your local server/))\n callback();\n });\n }\n});\n\n///////////////////////////////////////////////////////////////////////////////\n// Run\n///////////////////////////////////////////////////////////////////////////////\n\n// Represents a test run of the tool (except we also use it in\n// tests/old.js to run Node scripts). Typically created through the\n// run() method on Sandbox, but can also be created directly, say if\n// you want to do something other than invoke the 'meteor' command in\n// a nice sandbox.\n//\n// Options: args, cwd, env\n//\n// The 'execPath' argument and the 'cwd' option are assumed to be standard\n// paths.\n//\n// Arguments in the 'args' option are not assumed to be standard paths, so\n// calling any of the 'files.*' methods on them is not safe.\nvar Run = function (execPath, options) {\n var self = this;\n\n self.execPath = execPath;\n self.cwd = options.cwd || files.convertToStandardPath(process.cwd());\n // default env variables\n self.env = _.extend({ SELFTEST: \"t\", METEOR_NO_WORDWRAP: \"t\" }, options.env);\n self._args = [];\n self.proc = null;\n self.baseTimeout = 20;\n self.extraTime = 0;\n self.client = options.client;\n\n self.stdoutMatcher = new Matcher(self);\n self.stderrMatcher = new Matcher(self);\n self.outputLog = new OutputLog(self);\n\n self.exitStatus = undefined; // 'null' means failed rather than exited\n self.exitFutures = [];\n\n var opts = options.args || [];\n self.args.apply(self, opts || []);\n\n self.fakeMongoPort = null;\n self.fakeMongoConnection = null;\n if (options.fakeMongo) {\n self.fakeMongoPort = require('./utils.js').randomPort();\n self.env.METEOR_TEST_FAKE_MONGOD_CONTROL_PORT = self.fakeMongoPort;\n }\n\n runningTest.onCleanup(function () {\n self._stopWithoutWaiting();\n });\n};\n\n_.extend(Run.prototype, {\n // Set command-line arguments. This may be called multiple times as\n // long as the run has not yet started (the run starts after the\n // first call to a function that requires it, like match()).\n //\n // Pass as many arguments as you want. Non-object values will be\n // cast to string, and object values will be treated as maps from\n // option names to values.\n args: function (/* arguments */) {\n var self = this;\n\n if (self.proc)\n throw new Error(\"already started?\");\n\n _.each(_.toArray(arguments), function (a) {\n if (typeof a !== \"object\") {\n self._args.push('' + a);\n } else {\n _.each(a, function (value, key) {\n self._args.push(\"--\" + key);\n self._args.push('' + value);\n });\n }\n });\n },\n\n connectClient: function () {\n var self = this;\n if (! self.client)\n throw new Error(\"Must create Run with a client to use connectClient().\");\n\n self._ensureStarted();\n self.client.connect();\n },\n\n _exited: function (status) {\n var self = this;\n\n if (self.exitStatus !== undefined)\n throw new Error(\"already exited?\");\n\n self.client && self.client.stop();\n\n self.exitStatus = status;\n var exitFutures = self.exitFutures;\n self.exitFutures = null;\n _.each(exitFutures, function (f) {\n f['return']();\n });\n\n self.stdoutMatcher.end();\n self.stderrMatcher.end();\n },\n\n _ensureStarted: function () {\n var self = this;\n\n if (self.proc)\n return;\n\n var env = _.clone(process.env);\n _.extend(env, self.env);\n\n self.proc = child_process.spawn(files.convertToOSPath(self.execPath),\n self._args, {\n cwd: files.convertToOSPath(self.cwd),\n env: env\n });\n\n self.proc.on('close', function (code, signal) {\n if (self.exitStatus === undefined)\n self._exited({ code: code, signal: signal });\n });\n\n self.proc.on('exit', function (code, signal) {\n if (self.exitStatus === undefined)\n self._exited({ code: code, signal: signal });\n });\n\n self.proc.on('error', function (err) {\n if (self.exitStatus === undefined)\n self._exited(null);\n });\n\n self.proc.stdout.setEncoding('utf8');\n self.proc.stdout.on('data', function (data) {\n self.outputLog.write('stdout', data);\n self.stdoutMatcher.write(data);\n });\n\n self.proc.stderr.setEncoding('utf8');\n self.proc.stderr.on('data', function (data) {\n self.outputLog.write('stderr', data);\n self.stderrMatcher.write(data);\n });\n },\n\n // Wait until we get text on stdout that matches 'pattern', which\n // may be a regular expression or a string. Consume stdout up to\n // that point. If this pattern does not appear after a timeout (or\n // the program exits before emitting the pattern), fail.\n match: markStack(function (pattern, _strict) {\n var self = this;\n self._ensureStarted();\n\n var timeout = self.baseTimeout + self.extraTime;\n timeout *= utils.timeoutScaleFactor;\n self.extraTime = 0;\n return self.stdoutMatcher.match(pattern, timeout, _strict);\n }),\n\n // As expect(), but for stderr instead of stdout.\n matchErr: markStack(function (pattern, _strict) {\n var self = this;\n self._ensureStarted();\n\n var timeout = self.baseTimeout + self.extraTime;\n timeout *= utils.timeoutScaleFactor;\n self.extraTime = 0;\n return self.stderrMatcher.match(pattern, timeout, _strict);\n }),\n\n // Like match(), but won't skip ahead looking for a match. It must\n // follow immediately after the last thing we matched or read.\n read: markStack(function (pattern) {\n return this.match(pattern, true);\n }),\n\n // As read(), but for stderr instead of stdout.\n readErr: markStack(function (pattern) {\n return this.matchErr(pattern, true);\n }),\n\n // Assert that 'pattern' (again, a regexp or string) has not\n // occurred on stdout at any point so far in this run. Currently\n // this works on complete lines, so unlike match() and read(),\n // 'pattern' cannot span multiple lines, and furthermore if it is\n // called before the end of the program, it may not see text on a\n // partially read line. We could lift these restrictions easily, but\n // there may not be any benefit since the usual way to use this is\n // to call it after expectExit or expectEnd.\n //\n // Example:\n // run = s.run(\"--help\");\n // run.expectExit(1); // <<-- improtant to actually run the command\n // run.forbidErr(\"unwanted string\"); // <<-- important to run **after** the\n // // command ran the process.\n forbid: markStack(function (pattern) {\n this._ensureStarted();\n this.outputLog.forbid(pattern, 'stdout');\n }),\n\n // As forbid(), but for stderr instead of stdout.\n forbidErr: markStack(function (pattern) {\n this._ensureStarted();\n this.outputLog.forbid(pattern, 'stderr');\n }),\n\n // Combination of forbid() and forbidErr(). Forbids the pattern on\n // both stdout and stderr.\n forbidAll: markStack(function (pattern) {\n this._ensureStarted();\n this.outputLog.forbid(pattern);\n }),\n\n // Expect the program to exit without anything further being\n // printed on either stdout or stderr.\n expectEnd: markStack(function () {\n var self = this;\n self._ensureStarted();\n\n var timeout = self.baseTimeout + self.extraTime;\n timeout *= utils.timeoutScaleFactor;\n self.extraTime = 0;\n self.expectExit();\n\n self.stdoutMatcher.matchEmpty();\n self.stderrMatcher.matchEmpty();\n }),\n\n // Expect the program to exit with the given (numeric) exit\n // status. Fail if the process exits with a different code, or if\n // the process does not exit after a timeout. You can also omit the\n // argument to simply wait for the program to exit.\n expectExit: markStack(function (code) {\n var self = this;\n self._ensureStarted();\n\n if (self.exitStatus === undefined) {\n var timeout = self.baseTimeout + self.extraTime;\n timeout *= utils.timeoutScaleFactor;\n self.extraTime = 0;\n\n var fut = new Future;\n self.exitFutures.push(fut);\n var timer = setTimeout(function () {\n self.exitFutures = _.without(self.exitFutures, fut);\n fut['throw'](new TestFailure('exit-timeout', { run: self }));\n }, timeout * 1000);\n\n try {\n fut.wait();\n } finally {\n clearTimeout(timer);\n }\n }\n\n if (! self.exitStatus)\n throw new TestFailure('spawn-failure', { run: self });\n if (code !== undefined && self.exitStatus.code !== code) {\n throw new TestFailure('wrong-exit-code', {\n expected: { code: code },\n actual: self.exitStatus,\n run: self\n });\n }\n }),\n\n // Extend the timeout for the next operation by 'secs' seconds.\n waitSecs: function (secs) {\n var self = this;\n self.extraTime += secs;\n },\n\n // Send 'string' to the program on its stdin.\n write: function (string) {\n var self = this;\n self._ensureStarted();\n self.proc.stdin.write(string);\n },\n\n // Kill the program and then wait for it to actually exit.\n stop: markStack(function () {\n var self = this;\n if (self.exitStatus === undefined) {\n self._ensureStarted();\n self.client && self.client.stop();\n self._killProcess();\n self.expectExit();\n }\n }),\n\n // Like stop, but doesn't wait for it to exit.\n _stopWithoutWaiting: function () {\n var self = this;\n if (self.exitStatus === undefined && self.proc) {\n self.client && self.client.stop();\n self._killProcess();\n }\n },\n\n // Kills the running process and it's child processes\n _killProcess: function () {\n if (!this.proc)\n throw new Error(\"Unexpected: `this.proc` undefined when calling _killProcess\");\n\n if (process.platform === \"win32\") {\n // looks like in Windows `self.proc.kill()` doesn't kill child\n // processes.\n utils.execFileSync(\"taskkill\", [\"/pid\", this.proc.pid, '/f', '/t']);\n } else {\n this.proc.kill();\n }\n },\n\n // If the fakeMongo option was set, sent a command to the stub\n // mongod. Available commands currently are:\n //\n // - { stdout: \"xyz\" } to make fake-mongod write \"xyz\" to stdout\n // - { stderr: \"xyz\" } likewise for stderr\n // - { exit: 123 } to make fake-mongod exit with code 123\n //\n // Blocks until a connection to fake-mongod can be\n // established. Throws a TestFailure if it cannot be established.\n tellMongo: markStack(function (command) {\n var self = this;\n\n if (! self.fakeMongoPort)\n throw new Error(\"fakeMongo option on sandbox must be set\");\n\n self._ensureStarted();\n\n // If it's the first time we've called tellMongo on this sandbox,\n // open a connection to fake-mongod. Wait up to 10 seconds for it\n // to accept the connection, retrying every 100ms.\n //\n // XXX we never clean up this connection. Hopefully once\n // fake-mongod has dropped its end of the connection, and we hold\n // no reference to our end, it will get gc'd. If not, that's not\n // great, but it probably doesn't actually create any practical\n // problems since this is only for testing.\n if (! self.fakeMongoConnection) {\n var net = require('net');\n\n var lastStartTime = 0;\n for (var attempts = 0; ! self.fakeMongoConnection && attempts < 100;\n attempts ++) {\n // Throttle attempts to one every 100ms\n utils.sleepMs((lastStartTime + 100) - (+ new Date));\n lastStartTime = +(new Date);\n\n // Use an anonymous function so that each iteration of the\n // loop gets its own values of 'fut' and 'conn'.\n (function () {\n var fut = new Future;\n var conn = net.connect(self.fakeMongoPort, function () {\n if (fut)\n fut['return'](true);\n });\n conn.setNoDelay();\n conn.on('error', function () {\n if (fut)\n fut['return'](false);\n });\n setTimeout(function () {\n if (fut)\n fut['return'](false); // 100ms connection timeout\n }, 100);\n\n // This is all arranged so that if a previous attempt\n // belatedly succeeds, somehow, we ignore it.\n if (fut.wait())\n self.fakeMongoConnection = conn;\n fut = null;\n })();\n }\n\n if (! self.fakeMongoConnection)\n throw new TestFailure(\"mongo-not-running\", { run: self });\n }\n\n self.fakeMongoConnection.write(JSON.stringify(command) + \"\\n\");\n // If we told it to exit, then we should close our end and connect again if\n // asked to send more.\n if (command.exit) {\n self.fakeMongoConnection.end();\n self.fakeMongoConnection = null;\n }\n })\n});\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Defining tests\n///////////////////////////////////////////////////////////////////////////////\n\nvar Test = function (options) {\n var self = this;\n self.name = options.name;\n self.file = options.file;\n self.fileHash = options.fileHash;\n self.tags = options.tags || [];\n self.f = options.func;\n self.cleanupHandlers = [];\n};\n\n_.extend(Test.prototype, {\n onCleanup: function (cleanupHandler) {\n this.cleanupHandlers.push(cleanupHandler);\n },\n cleanup: function () {\n var self = this;\n _.each(self.cleanupHandlers, function (cleanupHandler) {\n cleanupHandler();\n });\n self.cleanupHandlers = [];\n }\n});\n\nvar allTests = null;\nvar fileBeingLoaded = null;\nvar fileBeingLoadedHash = null;\nvar runningTest = null;\nvar getAllTests = function () {\n if (allTests)\n return allTests;\n allTests = [];\n\n // Load all files in the 'tests' directory that end in .js. They\n // are supposed to then call define() to register their tests.\n var testdir = files.pathJoin(__dirname, 'tests');\n var filenames = files.readdir(testdir);\n _.each(filenames, function (n) {\n if (! n.match(/^[^.].*\\.js$/)) // ends in '.js', doesn't start with '.'\n return;\n try {\n if (fileBeingLoaded)\n throw new Error(\"called recursively?\");\n fileBeingLoaded = files.pathBasename(n, '.js');\n\n var fullPath = files.pathJoin(testdir, n);\n var contents = files.readFile(fullPath, 'utf8');\n fileBeingLoadedHash =\n require('crypto').createHash('sha1').update(contents).digest('hex');\n\n require(files.pathJoin(testdir, n));\n } finally {\n fileBeingLoaded = null;\n fileBeingLoadedHash = null;\n }\n });\n\n return allTests;\n};\n\nvar define = function (name, tagsList, f) {\n if (typeof tagsList === \"function\") {\n // tagsList is optional\n f = tagsList;\n tagsList = [];\n }\n\n var tags = tagsList.slice();\n tags.sort();\n\n allTests.push(new Test({\n name: name,\n tags: tags,\n file: fileBeingLoaded,\n fileHash: fileBeingLoadedHash,\n func: f\n }));\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Choosing tests\n///////////////////////////////////////////////////////////////////////////////\n\nvar tagDescriptions = {\n checkout: 'can only run from checkouts',\n net: 'require an internet connection',\n slow: 'take quite a long time; use --slow to include',\n cordova: 'requires Cordova support in tool (eg not on Windows)',\n windows: 'runs only on Windows',\n // these are pseudo-tags, assigned to tests when you specify\n // --changed, --file, or a pattern argument\n unchanged: 'unchanged since last pass',\n 'non-matching': \"don't match specified pattern\",\n 'in other files': \"\"\n};\n\n// Returns a TestList object representing a filtered list of tests,\n// according to the options given (which are based closely on the\n// command-line arguments). Used as the first step of both listTests\n// and runTests.\n//\n// Options: testRegexp, fileRegexp, onlyChanged, offline, includeSlowTests\nvar getFilteredTests = function (options) {\n options = options || {};\n\n var allTests = getAllTests();\n\n if (allTests.length) {\n var testState = readTestState();\n\n // Add pseudo-tags 'non-matching', 'unchanged', and 'in other files'\n // (but only so that we can then skip tests with those tags)\n allTests = allTests.map(function (test) {\n var newTags = [];\n\n if (options.fileRegexp && ! options.fileRegexp.test(test.file)) {\n newTags.push('in other files');\n } else if (options.testRegexp && ! options.testRegexp.test(test.name)) {\n newTags.push('non-matching');\n } else if (options.onlyChanged &&\n test.fileHash === testState.lastPassedHashes[test.file]) {\n newTags.push('unchanged');\n }\n\n if (! newTags.length) {\n return test;\n }\n\n return _.extend({}, test, { tags: test.tags.concat(newTags) });\n });\n }\n\n // (order of tags is significant to the \"skip counts\" that are displayed)\n var tagsToSkip = [];\n if (options.fileRegexp) {\n tagsToSkip.push('in other files');\n }\n if (options.testRegexp) {\n tagsToSkip.push('non-matching');\n }\n if (options.onlyChanged) {\n tagsToSkip.push('unchanged');\n }\n if (! files.inCheckout()) {\n tagsToSkip.push('checkout');\n }\n if (options.offline) {\n tagsToSkip.push('net');\n }\n if (! options.includeSlowTests) {\n tagsToSkip.push('slow');\n }\n\n if (process.platform === \"win32\") {\n tagsToSkip.push(\"cordova\");\n tagsToSkip.push(\"yet-unsolved-windows-failure\");\n } else {\n tagsToSkip.push(\"windows\");\n }\n\n return new TestList(allTests, tagsToSkip, testState);\n};\n\n// A TestList is the result of getFilteredTests. It holds the original\n// list of all tests, the filtered list, and stats on how many tests\n// were skipped (see generateSkipReport).\n//\n// TestList also has code to save the hashes of files where all tests\n// ran and passed (for the `--changed` option). If a testState is\n// provided, the notifyFailed and saveTestState can be used to modify\n// the testState appropriately and write it out.\nvar TestList = function (allTests, tagsToSkip, testState) {\n tagsToSkip = (tagsToSkip || []);\n testState = (testState || null); // optional\n\n var self = this;\n self.allTests = allTests;\n self.skippedTags = tagsToSkip;\n self.skipCounts = {};\n self.testState = testState;\n\n _.each(tagsToSkip, function (tag) {\n self.skipCounts[tag] = 0;\n });\n\n self.fileInfo = {}; // path -> {hash, hasSkips, hasFailures}\n\n self.filteredTests = _.filter(allTests, function (test) {\n\n if (! self.fileInfo[test.file]) {\n self.fileInfo[test.file] = {\n hash: test.fileHash,\n hasSkips: false,\n hasFailures: false\n };\n }\n var fileInfo = self.fileInfo[test.file];\n\n // We look for tagsToSkip *in order*, and when we decide to\n // skip a test, we don't keep looking at more tags, and we don't\n // add the test to any further \"skip counts\".\n return !_.any(tagsToSkip, function (tag) {\n if (_.contains(test.tags, tag)) {\n self.skipCounts[tag]++;\n fileInfo.hasSkips = true;\n return true;\n } else {\n return false;\n }\n });\n });\n};\n\n// Mark a test's file as having failures. This prevents\n// saveTestState from saving its hash as a potentially\n// \"unchanged\" file to be skipped in a future run.\nTestList.prototype.notifyFailed = function (test) {\n this.fileInfo[test.file].hasFailures = true;\n};\n\n// If this TestList was constructed with a testState,\n// modify it and write it out based on which tests\n// were skipped and which tests had failures.\nTestList.prototype.saveTestState = function () {\n var self = this;\n var testState = self.testState;\n if (! (testState && self.filteredTests.length)) {\n return;\n }\n\n _.each(self.fileInfo, function (info, f) {\n if (info.hasFailures) {\n delete testState.lastPassedHashes[f];\n } else if (! info.hasSkips) {\n testState.lastPassedHashes[f] = info.hash;\n }\n });\n\n writeTestState(testState);\n};\n\n// Return a string like \"Skipped 1 foo test\\nSkipped 5 bar tests\\n\"\nTestList.prototype.generateSkipReport = function () {\n var self = this;\n var result = '';\n\n _.each(self.skippedTags, function (tag) {\n var count = self.skipCounts[tag];\n if (count) {\n var noun = \"test\" + (count > 1 ? \"s\" : \"\"); // \"test\" or \"tests\"\n // \"non-matching tests\" or \"tests in other files\"\n var nounPhrase = (/ /.test(tag) ?\n (noun + \" \" + tag) : (tag + \" \" + noun));\n // \" (foo)\" or \"\"\n var parenthetical = (tagDescriptions[tag] ? \" (\" +\n tagDescriptions[tag] + \")\" : '');\n result += (\"Skipped \" + count + \" \" + nounPhrase + parenthetical + '\\n');\n }\n });\n\n return result;\n};\n\nvar getTestStateFilePath = function () {\n return files.pathJoin(files.getHomeDir(), '.meteortest');\n};\n\nvar readTestState = function () {\n var testStateFile = getTestStateFilePath();\n var testState;\n if (files.exists(testStateFile))\n testState = JSON.parse(files.readFile(testStateFile, 'utf8'));\n if (! testState || testState.version !== 1)\n testState = { version: 1, lastPassedHashes: {} };\n return testState;\n};\n\nvar writeTestState = function (testState) {\n var testStateFile = getTestStateFilePath();\n files.writeFile(testStateFile, JSON.stringify(testState), 'utf8');\n};\n\n// Same options as getFilteredTests. Writes to stdout and stderr.\nvar listTests = function (options) {\n var testList = getFilteredTests(options);\n\n if (! testList.allTests.length) {\n Console.error(\"No tests defined.\\n\");\n return;\n }\n\n _.each(_.groupBy(testList.filteredTests, 'file'), function (tests, file) {\n Console.rawInfo(file + ':\\n');\n _.each(tests, function (test) {\n Console.rawInfo(' - ' + test.name +\n (test.tags.length ? ' [' + test.tags.join(' ') + ']'\n : '') + '\\n');\n });\n });\n\n Console.error();\n Console.error(testList.filteredTests.length + \" tests listed.\");\n Console.error(testList.generateSkipReport());\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Running tests\n///////////////////////////////////////////////////////////////////////////////\n\n// options: onlyChanged, offline, includeSlowTests, historyLines, testRegexp,\n// fileRegexp,\n// clients:\n// - browserstack (need s3cmd credentials)\nvar runTests = function (options) {\n var testList = getFilteredTests(options);\n\n if (! testList.allTests.length) {\n Console.error(\"No tests defined.\");\n return 0;\n }\n\n var totalRun = 0;\n var failedTests = [];\n\n _.each(testList.filteredTests, function (test) {\n totalRun++;\n Console.error(test.file + \": \" + test.name + \" ... \");\n\n var failure = null;\n try {\n runningTest = test;\n var startTime = +(new Date);\n test.f(options);\n } catch (e) {\n failure = e;\n } finally {\n runningTest = null;\n test.cleanup();\n }\n\n if (failure) {\n Console.error(\"... fail!\", Console.options({ indent: 2 }));\n failedTests.push(test);\n testList.notifyFailed(test);\n\n if (failure instanceof TestFailure) {\n var frames = parseStack.parse(failure);\n var relpath = files.pathRelative(files.getCurrentToolsDir(),\n frames[0].file);\n Console.rawError(\" => \" + failure.reason + \" at \" +\n relpath + \":\" + frames[0].line + \"\\n\");\n if (failure.reason === 'no-match' || failure.reason === 'junk-before') {\n Console.arrowError(\"Pattern: \" + failure.details.pattern, 2);\n }\n if (failure.reason === \"wrong-exit-code\") {\n var s = function (status) {\n return status.signal || ('' + status.code) || \"???\";\n };\n\n Console.rawError(\n \" => \" + \"Expected: \" + s(failure.details.expected) +\n \"; actual: \" + s(failure.details.actual) + \"\\n\");\n }\n if (failure.reason === 'expected-exception') {\n }\n if (failure.reason === 'not-equal') {\n Console.rawError(\n \" => \" + \"Expected: \" + JSON.stringify(failure.details.expected) +\n \"; actual: \" + JSON.stringify(failure.details.actual) + \"\\n\");\n }\n\n if (failure.details.run) {\n failure.details.run.outputLog.end();\n var lines = failure.details.run.outputLog.get();\n if (! lines.length) {\n Console.arrowError(\"No output\", 2);\n } else {\n var historyLines = options.historyLines || 100;\n\n Console.arrowError(\"Last \" + historyLines + \" lines:\", 2);\n _.each(lines.slice(-historyLines), function (line) {\n Console.rawError(\" \" +\n (line.channel === \"stderr\" ? \"2| \" : \"1| \") +\n line.text +\n (line.bare ? \"%\" : \"\") + \"\\n\");\n });\n }\n }\n\n if (failure.details.messages) {\n Console.arrowError(\"Errors while building:\", 2);\n Console.rawError(failure.details.messages.formatMessages() + \"\\n\");\n }\n } else {\n Console.rawError(\" => Test threw exception: \" + failure.stack + \"\\n\");\n }\n } else {\n var durationMs = +(new Date) - startTime;\n Console.error(\n \"... ok (\" + durationMs + \" ms)\",\n Console.options({ indent: 2 }));\n }\n });\n\n testList.saveTestState();\n\n if (totalRun > 0)\n Console.error();\n\n Console.error(testList.generateSkipReport());\n\n if (testList.filteredTests.length === 0) {\n Console.error(\"No tests run.\");\n return 0;\n } else if (failedTests.length === 0) {\n var disclaimers = '';\n if (testList.filteredTests.length < testList.allTests.length)\n disclaimers += \" other\";\n Console.error(\"All\" + disclaimers + \" tests passed.\");\n return 0;\n } else {\n var failureCount = failedTests.length;\n Console.error(failureCount + \" failure\" +\n (failureCount > 1 ? \"s\" : \"\") + \":\");\n _.each(failedTests, function (test) {\n Console.rawError(\" - \" + test.file + \": \" + test.name + \"\\n\");\n });\n return 1;\n }\n};\n\n// To create self-tests:\n//\n// Create a new .js file in the tests directory. It will be picked\n// up automatically.\n//\n// Start your file with something like:\n// var selftest = require('../selftest.js');\n// var Sandbox = selftest.Sandbox;\n//\n// Define tests with:\n// selftest.define(\"test-name\", ['tag1', 'tag2'], function () {\n// ...\n// });\n//\n// The tags are used to group tests. Currently used tags:\n// - 'checkout': should only be run when we're running from a\n// checkout as opposed to a released copy.\n// - 'net': test requires an internet connection. Not going to work\n// if you're on a plane; will be skipped if we appear to be\n// offline unless run with 'self-test --force-online'.\n// - 'slow': test is slow enough that you don't want to run it\n// except on purpose. Won't run unless you say 'self-test --slow'.\n//\n// If you don't want to set any tags, you can omit that parameter\n// entirely.\n//\n// Inside your test function, first create a Sandbox object, then call\n// the run() method on the sandbox to set up a new run of meteor with\n// arguments of your choice, and then use functions like match(),\n// write(), and expectExit() to script that run.\n\n_.extend(exports, {\n runTests: runTests,\n listTests: listTests,\n markStack: markStack,\n define: define,\n Sandbox: Sandbox,\n Run: Run,\n fail: fail,\n expectEqual: expectEqual,\n expectThrows: expectThrows,\n expectTrue: expectTrue,\n expectFalse: expectFalse,\n execFileSync: execFileSync,\n doOrThrow: doOrThrow,\n testPackageServerUrl: config.getTestPackageServerUrl()\n});\n", "file_path": "tools/selftest.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.9934412240982056, 0.07861772179603577, 0.00016256565868388861, 0.00016865275392774493, 0.23228229582309723]} {"hunk": {"id": 1, "code_window": [" files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n", " if (! jshint(file.getContentsAsString(), conf, globals)) {\n", " jshint.errors.forEach(function (error) {\n", " file.error({\n", " message: error.reason,\n", " line: error.line,\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" if (! jshint(file.getContentsAsString(), conf, predefinedGlobals)) {\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "replace", "edit_start_line_idx": 43}, "file": "var _ = require('underscore');\n\nvar archinfo = require('./archinfo.js');\nvar buildmessage = require('./buildmessage.js');\nvar bundler = require('./bundler.js');\nvar isopack = require('./isopack.js');\nvar isopackets = require('./isopackets.js');\nvar linker = require('./linker.js');\nvar meteorNpm = require('./meteor-npm.js');\nvar watch = require('./watch.js');\nvar Console = require('./console.js').Console;\nvar files = require('./files.js');\nvar colonConverter = require('./colon-converter.js');\nvar linterPluginModule = require('./linter-plugin.js');\n\nvar compiler = exports;\n\n// Whenever you change anything about the code that generates isopacks, bump\n// this version number. The idea is that the \"format\" field of the isopack\n// JSON file only changes when the actual specified structure of the\n// isopack/unibuild changes, but this version (which is build-tool-specific)\n// can change when the the contents (not structure) of the built output\n// changes. So eg, if we improve the linker's static analysis, this should be\n// bumped.\n//\n// You should also update this whenever you update any of the packages used\n// directly by the isopack creation process (eg js-analyze) since they do not\n// end up as watched dependencies. (At least for now, packages only used in\n// target creation (eg minifiers) don't require you to update BUILT_BY, though\n// you will need to quit and rerun \"meteor run\".)\ncompiler.BUILT_BY = 'meteor/16';\n\n// This is a list of all possible architectures that a build can target. (Client\n// is expanded into 'web.browser' and 'web.cordova')\ncompiler.ALL_ARCHES = [ \"os\", \"web.browser\", \"web.cordova\" ];\n\ncompiler.compile = function (packageSource, options) {\n buildmessage.assertInCapture();\n\n var packageMap = options.packageMap;\n var isopackCache = options.isopackCache;\n var includeCordovaUnibuild = options.includeCordovaUnibuild;\n\n var pluginWatchSet = packageSource.pluginWatchSet.clone();\n var plugins = {};\n\n var pluginProviderPackageNames = {};\n\n // Build plugins\n _.each(packageSource.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + packageSource.name + \"`\",\n rootPath: packageSource.sourceRoot\n }, function () {\n // XXX we should probably also pass options.noLineNumbers into\n // buildJsImage so it can pass it back to its call to\n // compiler.compile\n var buildResult = bundler.buildJsImage({\n name: info.name,\n packageMap: packageMap,\n isopackCache: isopackCache,\n use: info.use,\n sourceRoot: packageSource.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: files.pathResolve(\n files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))\n });\n // Add this plugin's dependencies to our \"plugin dependency\"\n // WatchSet. buildResult.watchSet will end up being the merged\n // watchSets of all of the unibuilds of the plugin -- plugins have\n // only one unibuild and this should end up essentially being just\n // the source files of the plugin.\n //\n // Note that we do this even on error, so that you can fix the error\n // and have the runner restart.\n pluginWatchSet.merge(buildResult.watchSet);\n\n if (buildmessage.jobHasMessages())\n return;\n\n _.each(buildResult.usedPackageNames, function (packageName) {\n pluginProviderPackageNames[packageName] = true;\n });\n\n // Register the built plugin's code.\n if (!_.has(plugins, info.name))\n plugins[info.name] = {};\n plugins[info.name][buildResult.image.arch] = buildResult.image;\n });\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n //\n // Go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any (sub)dependencies. This\n // process also runs mostly safely multiple times in parallel (which\n // could happen if you have two apps running locally using the same\n // package).\n //\n // We run this even if we have no dependencies, because we might\n // need to delete dependencies we used to have.\n var isPortable = true;\n var nodeModulesPath = null;\n if (packageSource.npmCacheDirectory) {\n if (meteorNpm.updateDependencies(packageSource.name,\n packageSource.npmCacheDirectory,\n packageSource.npmDependencies)) {\n nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,\n 'node_modules');\n if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))\n isPortable = false;\n }\n }\n\n var isopk = new isopack.Isopack;\n isopk.initFromOptions({\n name: packageSource.name,\n metadata: packageSource.metadata,\n version: packageSource.version,\n isTest: packageSource.isTest,\n plugins: plugins,\n pluginWatchSet: pluginWatchSet,\n cordovaDependencies: packageSource.cordovaDependencies,\n npmDiscards: packageSource.npmDiscards,\n includeTool: packageSource.includeTool,\n debugOnly: packageSource.debugOnly\n });\n\n _.each(packageSource.architectures, function (unibuild) {\n if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)\n return;\n\n var unibuildResult = compileUnibuild({\n isopack: isopk,\n sourceArch: unibuild,\n isopackCache: isopackCache,\n nodeModulesPath: nodeModulesPath,\n isPortable: isPortable,\n noLineNumbers: options.noLineNumbers\n });\n _.extend(pluginProviderPackageNames,\n unibuildResult.pluginProviderPackageNames);\n });\n\n if (options.includePluginProviderPackageMap) {\n isopk.setPluginProviderPackageMap(\n packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));\n }\n\n return isopk;\n};\n\n// options.sourceArch is a SourceArch to compile. Process all source files\n// through the appropriate handlers and run the prelink phase on any resulting\n// JavaScript. Create a new Unibuild and add it to options.isopack.\n//\n// Returns a list of source files that were used in the compilation.\nvar compileUnibuild = function (options) {\n buildmessage.assertInCapture();\n\n var isopk = options.isopack;\n var inputSourceArch = options.sourceArch;\n var isopackCache = options.isopackCache;\n var nodeModulesPath = options.nodeModulesPath;\n var isPortable = options.isPortable;\n var noLineNumbers = options.noLineNumbers;\n\n var isApp = ! inputSourceArch.pkg.name;\n var resources = [];\n var js = [];\n var pluginProviderPackageNames = {};\n // The current package always is a plugin provider. (This also means we no\n // longer need a buildOfPath entry in buildinfo.json.)\n pluginProviderPackageNames[isopk.name] = true;\n var watchSet = inputSourceArch.watchSet.clone();\n\n // *** Determine and load active plugins\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't have\n // a special \"use\" role anymore. it's not totally clear to me what\n // the correct behavior should be -- we need to resolve whether we\n // think about extensions as being global to a package or particular\n // to a unibuild.\n\n // (there's also some weirdness here with handling implies, because\n // the implies field is on the target unibuild, but we really only care\n // about packages.)\n var activePluginPackages = [isopk];\n\n // We don't use plugins from weak dependencies, because the ability\n // to compile a certain type of file shouldn't depend on whether or\n // not some unrelated package in the target has a dependency. And we\n // skip unordered dependencies, because it's not going to work to\n // have circular build-time dependencies.\n //\n // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,\n // templating from standard-app-packages).\n //\n // We pass archinfo.host here, not self.arch, because it may be more specific,\n // and because plugins always have to run on the host architecture.\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: archinfo.host(),\n isopackCache: isopackCache,\n skipUnordered: true\n // implicitly skip weak deps by not specifying acceptableWeakPackages option\n }, function (unibuild) {\n if (unibuild.pkg.name === isopk.name)\n return;\n pluginProviderPackageNames[unibuild.pkg.name] = true;\n // If other package is built from source, then we need to rebuild this\n // package if any file in the other package that could define a plugin\n // changes.\n watchSet.merge(unibuild.pkg.pluginWatchSet);\n\n if (_.isEmpty(unibuild.pkg.plugins))\n return;\n activePluginPackages.push(unibuild.pkg);\n });\n\n activePluginPackages = _.uniq(activePluginPackages);\n\n // *** Assemble the list of source file handlers from the plugins\n // XXX BBP redoc\n var allHandlersWithPkgs = {};\n var compilerPluginsByExtension = {};\n var linterPluginsByExtension = {};\n var sourceExtensions = {}; // maps source extensions to isTemplate\n\n sourceExtensions['js'] = false;\n allHandlersWithPkgs['js'] = {\n pkgName: null /* native handler */,\n handler: function (compileStep) {\n // This is a hardcoded handler for *.js files. Since plugins\n // are written in JavaScript we have to start somewhere.\n\n var options = {\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n _hash: compileStep._hash\n };\n\n if (compileStep.fileOptions.hasOwnProperty(\"bare\")) {\n options.bare = compileStep.fileOptions.bare;\n } else if (compileStep.fileOptions.hasOwnProperty(\"raw\")) {\n // XXX eventually get rid of backward-compatibility \"raw\" name\n // XXX COMPAT WITH 0.6.4\n options.bare = compileStep.fileOptions.raw;\n }\n\n compileStep.addJavaScript(options);\n }\n };\n\n _.each(activePluginPackages, function (otherPkg) {\n otherPkg.ensurePluginsInitialized();\n\n // Iterate over the legacy source handlers.\n _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {\n // XXX comparing function text here seems wrong.\n if (_.has(allHandlersWithPkgs, ext) &&\n allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n return;\n }\n // Is this handler only registered for, say, \"web\", and we're building,\n // say, \"os\"?\n if (sourceHandler.archMatching &&\n !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {\n return;\n }\n allHandlersWithPkgs[ext] = {\n pkgName: otherPkg.name,\n handler: sourceHandler.handler\n };\n sourceExtensions[ext] = !!sourceHandler.isTemplate;\n });\n\n // Iterate over the compiler plugins.\n _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {\n _.each(compilerPlugin.extensions, function (ext) {\n if (_.has(allHandlersWithPkgs, ext) ||\n _.has(compilerPluginsByExtension, ext)) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first one we found.\n return;\n }\n compilerPluginsByExtension[ext] = compilerPlugin;\n sourceExtensions[ext] = compilerPlugin.isTemplate;\n });\n });\n\n // Iterate over the linters\n _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n _.each(linterPlugin.extensions, function (ext) {\n linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n linterPluginsByExtension[ext].push(linterPlugin);\n });\n });\n });\n\n // *** Determine source files\n // Note: sourceExtensions does not include leading dots\n // Note: the getSourcesFunc function isn't expected to add its\n // source files to watchSet; rather, the watchSet is for other\n // things that the getSourcesFunc consulted (such as directory\n // listings or, in some hypothetical universe, control files) to\n // determine its source files.\n var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);\n\n if (nodeModulesPath) {\n // If this slice has node modules, we should consider the shrinkwrap file\n // to be part of its inputs. (This is a little racy because there's no\n // guarantee that what we read here is precisely the version that's used,\n // but it's better than nothing at all.)\n //\n // Note that this also means that npm modules used by plugins will get\n // this npm-shrinkwrap.json in their pluginDependencies (including for all\n // packages that depend on us)! This is good: this means that a tweak to\n // an indirect dependency of the coffee-script npm module used by the\n // coffeescript package will correctly cause packages with *.coffee files\n // to be rebuilt.\n var shrinkwrapPath = nodeModulesPath.replace(\n /node_modules$/, 'npm-shrinkwrap.json');\n watch.readAndWatchFile(watchSet, shrinkwrapPath);\n }\n\n // *** Process each source file\n var addAsset = function (contents, relPath, hash) {\n // XXX hack\n if (! inputSourceArch.pkg.name)\n relPath = relPath.replace(/^(private|public)\\//, '');\n\n resources.push({\n type: \"asset\",\n data: contents,\n path: relPath,\n servePath: colonConverter.convert(\n files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),\n hash: hash\n });\n };\n\n var convertSourceMapPaths = function (sourcemap, f) {\n if (! sourcemap) {\n // Don't try to convert it if it doesn't exist\n return sourcemap;\n }\n\n var srcmap = JSON.parse(sourcemap);\n srcmap.sources = _.map(srcmap.sources, f);\n return JSON.stringify(srcmap);\n };\n\n var wrappedSourceItems = _.map(sourceItems, function (source) {\n var fileWatchSet = new watch.WatchSet;\n // readAndWatchFileWithHash returns an object carrying a buffer with the\n // file-contents. The buffer contains the original data of the file (no EOL\n // transforms from the tools/files.js part).\n // We don't put this into the unibuild's watchSet immediately since we want\n // to avoid putting it there if it turns out not to be relevant to our\n // arch.\n var absPath = files.pathResolve(\n inputSourceArch.pkg.sourceRoot, source.relPath);\n var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);\n\n Console.nudge(true);\n\n return {\n relPath: source.relPath,\n watchset: fileWatchSet,\n contents: file.contents,\n hash: file.hash,\n source: source,\n 'package': isopk.name\n };\n });\n\n runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n\n _.each(wrappedSourceItems, function (wrappedSource) {\n var source = wrappedSource.source;\n var relPath = source.relPath;\n var fileOptions = _.clone(source.fileOptions) || {};\n var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);\n var filename = files.pathBasename(relPath);\n var contents = wrappedSource.contents;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n\n Console.nudge(true);\n\n if (contents === null) {\n // It really sucks to put this check here, since this isn't publish\n // code...\n if (source.relPath.match(/:/)) {\n buildmessage.error(\n \"Couldn't build this package on Windows due to the following file \" +\n \"with a colon -- \" + source.relPath + \". Please rename and \" +\n \"and re-publish the package.\");\n } else {\n buildmessage.error(\"File not found: \" + source.relPath);\n }\n\n // recover by ignoring (but still watching the file)\n watchSet.merge(fileWatchSet);\n return;\n }\n\n // Find the handler for source files with this extension.\n var handler = null;\n var isBuildPluginSource = false;\n if (! fileOptions.isAsset) {\n var parts = filename.split('.');\n // don't use iteration functions, so we can return/break\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(compilerPluginsByExtension, extension)) {\n var compilerPlugin = compilerPluginsByExtension[extension];\n if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {\n // This file is for a compiler plugin but not for this arch. Skip\n // it, and don't even watch it. (eg, skip CSS preprocessor files on\n // the server.)\n return;\n }\n isBuildPluginSource = true;\n break;\n }\n if (_.has(allHandlersWithPkgs, extension)) {\n handler = allHandlersWithPkgs[extension].handler;\n break;\n }\n }\n }\n\n // OK, this is relevant to this arch, so watch it.\n watchSet.merge(fileWatchSet);\n\n if (isBuildPluginSource) {\n // This is source used by a new-style compiler plugin; it will be fully\n // processed later in the bundler.\n resources.push({\n type: \"source\",\n data: contents,\n path: relPath,\n hash: hash\n });\n return;\n }\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n addAsset(contents, relPath, hash);\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript).\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - pathForSourceMap: If this file is to be included in a source map,\n // this is the name you should use for it in the map.\n // - rootOutputPath: on web targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-web targets\n // - fileOptions: any options passed to \"api.addFiles\"; for\n // use by the plugin. The built-in \"js\" plugin uses the \"bare\"\n // option for files that shouldn't be wrapped in a closure.\n // - declaredExports: An array of symbols exported by this unibuild, or null\n // if it may not export any symbols (eg, test unibuilds). This is used by\n // CoffeeScript to ensure that it doesn't close over those symbols, eg.\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // Web targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\",\n // sourceMap: \"stringified json sourcemap\"})\n // Web targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // bare: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. \"bare\" means to not wrap the file in\n // a closure, so that its vars are shared with other files\n // in the module.\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Add a file to serve as-is over HTTP (web targets) or\n // to include as-is in the bundle (os targets).\n // This time `data` is a Buffer rather than a string. For\n // web targets, it will be served at the exact path you\n // request (concatenated with rootOutputPath). For server\n // targets, the file can be retrieved by passing path to\n // Assets.getText or Assets.getBinary.\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces). sourcePath,\n // line, column, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'web'\n // vs 'os') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific unibuild will be emitted only if\n // there are native node modules). Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force unibuilds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n\n /**\n * The comments for this class aren't used to generate docs right now.\n * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers\n * @class CompileStep\n * @summary The object passed into Plugin.registerSourceHandler\n * @global\n */\n var compileStep = {\n\n /**\n * @summary The total number of bytes in the input file.\n * @memberOf CompileStep\n * @instance\n * @type {Integer}\n */\n inputSize: contents.length,\n\n /**\n * @summary The filename and relative path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n inputPath: files.convertToOSPath(relPath, true),\n\n /**\n * @summary The filename and absolute path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n fullInputPath: files.convertToOSPath(absPath),\n\n // The below is used in the less and stylus packages... so it should be\n // public API.\n _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..\n\n // Used for one optimization. Don't rely on this otherwise.\n _hash: hash,\n\n // XXX duplicates _pathForSourceMap() in linker\n /**\n * @summary If you are generating a sourcemap for the compiled file, use\n * this path for the original file in the sourcemap.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n pathForSourceMap: files.convertToOSPath(\n inputSourceArch.pkg.name ? inputSourceArch.pkg.name + \"/\" + relPath :\n files.pathBasename(relPath), true),\n\n // null if this is an app. intended to be used for the sources\n // dictionary for source maps.\n /**\n * @summary The name of the package in which the file being built exists.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n packageName: inputSourceArch.pkg.name,\n\n /**\n * @summary On web targets, this will be the root URL prepended\n * to the paths you pick for your output files. For example,\n * it could be \"/packages/my-package\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n rootOutputPath: files.convertToOSPath(\n inputSourceArch.pkg.serveRoot, true),\n\n /**\n * @summary The architecture for which we are building. Can be \"os\",\n * \"web.browser\", or \"web.cordova\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n arch: inputSourceArch.arch,\n\n /**\n * @deprecated in 0.9.4\n * This is a duplicate API of the above, we don't need it.\n */\n archMatches: function (pattern) {\n return archinfo.matches(inputSourceArch.arch, pattern);\n },\n\n /**\n * @summary Any options passed to \"api.addFiles\".\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n fileOptions: fileOptions,\n\n /**\n * @summary The list of exports that the current package has defined.\n * Can be used to treat those symbols differently during compilation.\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n\n /**\n * @summary Read from the input file. If `n` is specified, returns the\n * next `n` bytes of the file as a Buffer. XXX not sure if this actually\n * returns a String sometimes...\n * @param {Integer} [n] The number of bytes to return.\n * @instance\n * @memberOf CompileStep\n * @returns {Buffer}\n */\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n\n /**\n * @summary Works in web targets only. Add markup to the `head` or `body`\n * section of the document.\n * @param {Object} options\n * @param {String} options.section Which section of the document should\n * be appended to. Can only be \"head\" or \"body\".\n * @param {String} options.data The content to append.\n * @memberOf CompileStep\n * @instance\n */\n addHtml: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"web targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')\n });\n },\n\n /**\n * @deprecated in 0.9.4\n */\n appendDocument: function (options) {\n this.addHtml(options);\n },\n\n /**\n * @summary Web targets only. Add a stylesheet to the document.\n * @param {Object} options\n * @param {String} path The requested path for the added CSS, may not be\n * satisfied if there are path conflicts.\n * @param {String} data The content of the stylesheet that should be\n * added.\n * @param {String} sourceMap A stringified JSON sourcemap, in case the\n * stylesheet was generated from a different file.\n * @memberOf CompileStep\n * @instance\n */\n addStylesheet: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"web targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n refreshable: true,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),\n servePath: colonConverter.convert(\n files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true))),\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath)\n });\n },\n\n /**\n * @summary Add JavaScript code. The code added will only see the\n * namespaces imported by this package as runtime dependencies using\n * ['api.use'](#PackageAPI-use). If the file being compiled was added\n * with the bare flag, the resulting JavaScript won't be wrapped in a\n * closure.\n * @param {Object} options\n * @param {String} options.path The path at which the JavaScript file\n * should be inserted, may not be honored in case of path conflicts.\n * @param {String} options.data The code to be added.\n * @param {String} options.sourcePath The path that will be used in\n * any error messages generated by this file, e.g. `foo.js:4:1: error`.\n * @memberOf CompileStep\n * @instance\n */\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n\n // By default, use fileOptions for the `bare` option but also allow\n // overriding it with the options\n var bare = fileOptions.bare;\n if (options.hasOwnProperty(\"bare\")) {\n bare = options.bare;\n }\n\n js.push({\n source: files.convertToStandardLineEndings(options.data),\n sourcePath: files.convertToStandardPath(options.sourcePath, true),\n servePath: files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true)),\n bare: !! bare,\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath),\n sourceHash: options._hash\n });\n },\n\n /**\n * @summary Add a file to serve as-is to the browser or to include on\n * the browser, depending on the target. On the web, it will be served\n * at the exact path requested. For server targets, it can be retrieved\n * using `Assets.getText` or `Assets.getBinary`.\n * @param {Object} options\n * @param {String} path The path at which to serve the asset.\n * @param {Buffer|String} data The data that should be placed in\n * the file.\n * @memberOf CompileStep\n * @instance\n */\n addAsset: function (options) {\n if (! (options.data instanceof Buffer)) {\n if (_.isString(options.data)) {\n options.data = new Buffer(options.data);\n } else {\n throw new Error(\"'data' option to addAsset must be a Buffer or String.\");\n }\n }\n\n addAsset(options.data, files.convertToStandardPath(options.path, true));\n },\n\n /**\n * @summary Display a build error.\n * @param {Object} options\n * @param {String} message The error message to display.\n * @param {String} [sourcePath] The path to display in the error message.\n * @param {Integer} line The line number to display in the error message.\n * @param {String} func The function name to display in the error message.\n * @memberOf CompileStep\n * @instance\n */\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // *** Run Phase 1 link\n\n // Load jsAnalyze from the js-analyze package... unless we are the\n // js-analyze package, in which case never mind. (The js-analyze package's\n // default unibuild is not allowed to depend on anything!)\n var jsAnalyze = null;\n if (! _.isEmpty(js) && inputSourceArch.pkg.name !== \"js-analyze\") {\n jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;\n }\n\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n // I was confused about this, so I am leaving a comment -- the\n // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.\n // XXX: If we change this, we can get rid of source arch names!\n combinedServePath: isApp ? null :\n \"/packages/\" + colonConverter.convert(\n inputSourceArch.pkg.name +\n (inputSourceArch.kind === \"main\" ? \"\" : (\":\" + inputSourceArch.kind)) +\n \".js\"),\n name: inputSourceArch.pkg.name || null,\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n jsAnalyze: jsAnalyze,\n noLineNumbers: noLineNumbers\n });\n\n // *** Determine captured variables\n var packageVariables = [];\n var packageVariableNames = {};\n _.each(inputSourceArch.declaredExports, function (symbol) {\n if (_.has(packageVariableNames, symbol.name))\n return;\n packageVariables.push({\n name: symbol.name,\n export: symbol.testOnly? \"tests\" : true\n });\n packageVariableNames[symbol.name] = true;\n });\n _.each(results.assignedVariables, function (name) {\n if (_.has(packageVariableNames, name))\n return;\n packageVariables.push({\n name: name\n });\n packageVariableNames[name] = true;\n });\n\n // *** Consider npm dependencies and portability\n var arch = inputSourceArch.arch;\n if (arch === \"os\" && ! isPortable) {\n // Contains non-portable compiled npm modules, so set arch correctly\n arch = archinfo.host();\n }\n if (! archinfo.matches(arch, \"os\")) {\n // npm modules only work on server architectures\n nodeModulesPath = undefined;\n }\n\n // *** Output unibuild object\n isopk.addUnibuild({\n kind: inputSourceArch.kind,\n arch: arch,\n uses: inputSourceArch.uses,\n implies: inputSourceArch.implies,\n watchSet: watchSet,\n nodeModulesPath: nodeModulesPath,\n prelinkFiles: results.files,\n packageVariables: packageVariables,\n resources: resources\n });\n\n return {\n pluginProviderPackageNames: pluginProviderPackageNames\n };\n};\n\nvar runLinters = function (\n inputSourceArch,\n isopackCache,\n wrappedSourceItems,\n linterPluginsByExtension) {\n // For linters, figure out what are the global imports from other packages\n // that we use directly, or are implied.\n var globalImports = ['Package', 'Assets', 'Npm'];\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: inputSourceArch.arch,\n isopackCache: isopackCache,\n skipUnordered: true,\n skipDebugOnly: true\n }, function (unibuild) {\n if (unibuild.pkg.name === inputSourceArch.pkg.name)\n return;\n _.each(unibuild.packageVariables, function (symbol) {\n if (symbol.export === true)\n globalImports.push(symbol.name);\n });\n });\n\n // For each file choose the longest extension handled by linters.\n var longestMatchingExt = {};\n _.each(wrappedSourceItems, function (wrappedSource) {\n var filename = files.pathBasename(wrappedSource.relPath);\n var parts = filename.split('.');\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(linterPluginsByExtension, extension)) {\n longestMatchingExt[wrappedSource.relPath] = extension;\n break;\n }\n }\n });\n\n // Run linters on files.\n _.each(linterPluginsByExtension, function (linters, ext) {\n var sourcesToLint = [];\n _.each(wrappedSourceItems, function (wrappedSource) {\n var relPath = wrappedSource.relPath;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n var source = wrappedSource.source;\n\n // only run linters matching the longest handled extension\n if (longestMatchingExt[relPath] !== ext)\n return;\n\n sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));\n });\n\n _.each(linters, function (linterDef) {\n // skip linters not relevant to the arch we are compiling for\n if (! linterDef.relevantForArch(inputSourceArch.arch))\n return;\n\n var linter = linterDef.instantiatePlugin();\n buildmessage.enterJob({\n title: \"linting files with \" + linterDef.isopack.name\n }, function () {\n try {\n var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));\n markedLinter(sourcesToLint, globalImports);\n } catch (e) {\n buildmessage.exception(e);\n }\n });\n });\n });\n};\n\n// Iterates over each in options.dependencies as well as unibuilds implied by\n// them. The packages in question need to already be built and in\n// options.isopackCache.\ncompiler.eachUsedUnibuild = function (\n options, callback) {\n buildmessage.assertInCapture();\n var dependencies = options.dependencies;\n var arch = options.arch;\n var isopackCache = options.isopackCache;\n\n var acceptableWeakPackages = options.acceptableWeakPackages || {};\n\n var processedUnibuildId = {};\n var usesToProcess = [];\n _.each(dependencies, function (use) {\n if (options.skipUnordered && use.unordered)\n return;\n if (use.weak && !_.has(acceptableWeakPackages, use.package))\n return;\n usesToProcess.push(use);\n });\n\n while (! _.isEmpty(usesToProcess)) {\n var use = usesToProcess.shift();\n\n var usedPackage = isopackCache.getIsopack(use.package);\n\n // Ignore this package if we were told to skip debug-only packages and it is\n // debug-only.\n if (usedPackage.debugOnly && options.skipDebugOnly)\n continue;\n\n var unibuild = usedPackage.getUnibuildAtArch(arch);\n if (!unibuild) {\n // The package exists but there's no unibuild for us. A buildmessage has\n // already been issued. Recover by skipping.\n continue;\n }\n\n if (_.has(processedUnibuildId, unibuild.id))\n continue;\n processedUnibuildId[unibuild.id] = true;\n\n callback(unibuild, {\n unordered: !!use.unordered,\n weak: !!use.weak\n });\n\n _.each(unibuild.implies, function (implied) {\n usesToProcess.push(implied);\n });\n }\n};\n", "file_path": "tools/compiler.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.005822021048516035, 0.00035082269459962845, 0.00016164840781129897, 0.00017291746917180717, 0.0007686741300858557]} {"hunk": {"id": 1, "code_window": [" files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n", " if (! jshint(file.getContentsAsString(), conf, globals)) {\n", " jshint.errors.forEach(function (error) {\n", " file.error({\n", " message: error.reason,\n", " line: error.line,\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" if (! jshint(file.getContentsAsString(), conf, predefinedGlobals)) {\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "replace", "edit_start_line_idx": 43}, "file": "Template.configureLoginServiceDialogForMeetup.helpers({\n siteUrl: function () {\n return Meteor.absoluteUrl();\n }\n});\n\nTemplate.configureLoginServiceDialogForMeetup.fields = function () {\n return [\n {property: 'clientId', label: 'Key'},\n {property: 'secret', label: 'Secret'}\n ];\n};\n", "file_path": "packages/meetup/meetup_configure.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00016952870646491647, 0.00016921432688832283, 0.00016889993275981396, 0.00016921432688832283, 3.1438685255125165e-07]} {"hunk": {"id": 1, "code_window": [" files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n", " if (! jshint(file.getContentsAsString(), conf, globals)) {\n", " jshint.errors.forEach(function (error) {\n", " file.error({\n", " message: error.reason,\n", " line: error.line,\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" if (! jshint(file.getContentsAsString(), conf, predefinedGlobals)) {\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "replace", "edit_start_line_idx": 43}, "file": "# Meteor packages used by this project, one per line.\n#\n# 'meteor add' and 'meteor remove' will edit this file for you,\n# but you can also edit it by hand.\n\nmeteor-platform\nunderscore\n", "file_path": "tools/tests/apps/ddp-heartbeat/.meteor/packages", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001644935255171731, 0.0001644935255171731, 0.0001644935255171731, 0.0001644935255171731, 0.0]} {"hunk": {"id": 1, "code_window": [" files.forEach(function (file) {\n", " if (file.getBasename() === '.jshintrc')\n", " return;\n", " if (! jshint(file.getContentsAsString(), conf, globals)) {\n", " jshint.errors.forEach(function (error) {\n", " file.error({\n", " message: error.reason,\n", " line: error.line,\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep"], "after_edit": [" if (! jshint(file.getContentsAsString(), conf, predefinedGlobals)) {\n"], "file_path": "packages/jshint/plugin/lint-jshint.js", "type": "replace", "edit_start_line_idx": 43}, "file": ".build*\n", "file_path": "packages/browser-policy-common/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00017160589050035924, 0.00017160589050035924, 0.00017160589050035924, 0.00017160589050035924, 0.0]} {"hunk": {"id": 2, "code_window": [" // XXX BBP redoc\n", " var allHandlersWithPkgs = {};\n", " var compilerPluginsByExtension = {};\n", " var linterPluginsByExtension = {};\n", " var sourceExtensions = {}; // maps source extensions to isTemplate\n", "\n", " sourceExtensions['js'] = false;\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var allLinters = [];\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 234}, "file": "var util = Npm.require('util');\nvar Future = Npm.require('fibers/future');\nvar path = Npm.require('path');\nvar jshint = Npm.require('jshint').JSHINT;\n\nPlugin.registerLinter({\n extensions: [\"jshintrc\", \"js\"],\n}, function () {\n var linter = new JsHintLinter();\n return linter;\n});\n\nfunction JsHintLinter () {};\n\nJsHintLinter.prototype.processFilesForTarget = function (files, globals) {\n var conf = {\n undef: true,\n unused: true,\n node: true,\n browser: true\n };\n\n files.forEach(function (file) {\n // find the config file\n if (file.getBasename() === '.jshintrc') {\n var confStr = file.getContentsAsString();\n try {\n conf = JSON.parse(confStr);\n } catch (err) {\n file.error({ message: \"Failed to parse .jshint file, not a valid JSON: \" + err.message });\n }\n return;\n }\n // require configuration file to be called '.jshintrc'\n if (path.extname(file.getBasename()) !== '.js') {\n file.error({ message: \"Unrecognized configuration file name. Configuration file should be called .jshintrc\" });\n return;\n }\n });\n\n files.forEach(function (file) {\n if (file.getBasename() === '.jshintrc')\n return;\n if (! jshint(file.getContentsAsString(), conf, globals)) {\n jshint.errors.forEach(function (error) {\n file.error({\n message: error.reason,\n line: error.line,\n column: error.character\n });\n });\n }\n });\n};\n\n\n", "file_path": "packages/jshint/plugin/lint-jshint.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.000175887907971628, 0.0001718668354442343, 0.0001676959072938189, 0.00017187438788823783, 2.3946242890815483e-06]} {"hunk": {"id": 2, "code_window": [" // XXX BBP redoc\n", " var allHandlersWithPkgs = {};\n", " var compilerPluginsByExtension = {};\n", " var linterPluginsByExtension = {};\n", " var sourceExtensions = {}; // maps source extensions to isTemplate\n", "\n", " sourceExtensions['js'] = false;\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var allLinters = [];\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 234}, "file": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n\n# User-specific files\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio)\n*.userprefs\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\nbuild/\nbld/\n[Bb]in/\n[Oo]bj/\n\n# Visual Studo 2015 cache/options directory\n.vs/\n\n# MSTest test Results\n[Tt]est[Rr]esult*/\n[Bb]uild[Ll]og.*\n\n# NUNIT\n*.VisualState.xml\nTestResult.xml\n\n# Build Results of an ATL Project\n[Dd]ebugPS/\n[Rr]eleasePS/\ndlldata.c\n\n*_i.c\n*_p.c\n*_i.h\n*.ilk\n*.meta\n*.obj\n*.pch\n*.pdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.tmp_proj\n*.log\n*.vspscc\n*.vssscc\n.builds\n*.pidb\n*.svclog\n*.scc\n\n# Chutzpah Test files\n_Chutzpah*\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opensdf\n*.sdf\n*.cachefile\n\n# Visual Studio profiler\n*.psess\n*.vsp\n*.vspx\n\n# TFS 2012 Local Workspace\n$tf/\n\n# Guidance Automation Toolkit\n*.gpState\n\n# ReSharper is a .NET coding add-in\n_ReSharper*/\n*.[Rr]e[Ss]harper\n*.DotSettings.user\n\n# JustCode is a .NET coding addin-in\n.JustCode\n\n# TeamCity is a build add-in\n_TeamCity*\n\n# DotCover is a Code Coverage Tool\n*.dotCover\n\n# NCrunch\n_NCrunch_*\n.*crunch*.local.xml\n\n# MightyMoose\n*.mm.*\nAutoTest.Net/\n\n# Web workbench (sass)\n.sass-cache/\n\n# Installshield output folder\n[Ee]xpress/\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish/\n\n# Publish Web Output\n*.[Pp]ublish.xml\n*.azurePubxml\n# TODO: Comment the next line if you want to checkin your web deploy settings \n# but database connection strings (with potential passwords) will be unencrypted\n*.pubxml\n*.publishproj\n\n# NuGet Packages\n*.nupkg\n# The packages folder can be ignored because of Package Restore\n**/packages/*\n# except build/, which is used as an MSBuild target.\n!**/packages/build/\n# Uncomment if necessary however generally it will be regenerated when needed\n#!**/packages/repositories.config\n\n# Windows Azure Build Output\ncsx/\n*.build.csdef\n\n# Windows Store app package directory\nAppPackages/\n\n# Others\n*.[Cc]ache\nClientBin/\n[Ss]tyle[Cc]op.*\n~$*\n*~\n*.dbmdl\n*.dbproj.schemaview\n*.pfx\n*.publishsettings\nnode_modules/\nbower_components/\n\n# RIA/Silverlight projects\nGenerated_Code/\n\n# Backup & report files from converting an old project file\n# to a newer Visual Studio version. Backup files are not needed,\n# because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\nUpgradeLog*.htm\n\n# SQL Server files\n*.mdf\n*.ldf\n\n# Business Intelligence projects\n*.rdl.data\n*.bim.layout\n*.bim_*.settings\n\n# Microsoft Fakes\nFakesAssemblies/\n\n# Node.js Tools for Visual Studio\n.ntvs_analysis.dat\n\n# Visual Studio 6 build log\n*.plg\n\n# Visual Studio 6 workspace options file\n*.opt\n", "file_path": "scripts/windows/installer/WiXHelper/.gitignore", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00017524173017591238, 0.0001706349867163226, 0.00016522291116416454, 0.00017106137238442898, 2.7904495709663024e-06]} {"hunk": {"id": 2, "code_window": [" // XXX BBP redoc\n", " var allHandlersWithPkgs = {};\n", " var compilerPluginsByExtension = {};\n", " var linterPluginsByExtension = {};\n", " var sourceExtensions = {}; // maps source extensions to isTemplate\n", "\n", " sourceExtensions['js'] = false;\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var allLinters = [];\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 234}, "file": "// The HTTP proxy is primarily so we can use localhost:3000 with OAuth,\n// on devices which don't run a webserver e.g. Android / iOS\n// This is a generic HTTP proxy, like a mini-Squid\n// (whereas run-proxy.js is just for our app)\nvar _ = require('underscore');\nvar Future = require('fibers/future');\nvar runLog = require('./run-log.js');\nvar url = require('url');\n\n// options: listenPort, listenHost, onFailure\nvar HttpProxy = function (options) {\n var self = this;\n\n self.listenPort = options.listenPort;\n self.listenHost = options.listenHost;\n\n self.onFailure = options.onFailure || function () {};\n\n self.mode = \"proxy\";\n self.httpQueue = []; // keys: req, res\n self.websocketQueue = []; // keys: req, socket, head\n self.connectQueue = []; // keys: req, socket, head\n\n self.proxy = null;\n self.server = null;\n};\n\n_.extend(HttpProxy.prototype, {\n // Start the proxy server, block (yield) until it is ready to go\n // (actively listening on outer and proxying to inner), and then\n // return.\n start: function () {\n var self = this;\n\n if (self.server)\n throw new Error(\"already running?\");\n\n self.started = false;\n\n var http = require('http');\n var net = require('net');\n var httpProxy = require('http-proxy');\n\n self.proxy = httpProxy.createProxyServer({\n // agent is required to handle keep-alive, and http-proxy 1.0 is a little\n // buggy without it: https://github.com/nodejitsu/node-http-proxy/pull/488\n agent: new http.Agent({ maxSockets: 1000 }),\n xfwd: false //true\n });\n\n var server = self.server = http.createServer(function (req, res) {\n // Normal HTTP request\n self.httpQueue.push({ req: req, res: res });\n self._tryHandleConnections();\n });\n\n self.server.on('connect', function (req, socket, head) {\n self.connectQueue.push({ req: req, socket: socket, head: head });\n self._tryHandleConnections();\n });\n\n self.server.on('upgrade', function (req, socket, head) {\n // Websocket connection\n self.websocketQueue.push({ req: req, socket: socket, head: head });\n self._tryHandleConnections();\n });\n\n var fut = new Future;\n self.server.on('error', function (err) {\n if (err.code === 'EADDRINUSE') {\n var port = self.listenPort;\n runLog.log(\n \"HTTP proxy server can't listen on port \" + port + \". \\n\" +\n \"If something else is using port \" + port + \", you can\\n\" +\n \"specify an alternative port with --http-proxy-port .\");\n } else if (self.listenHost &&\n (err.code === 'ENOTFOUND' || err.code === 'EADDRNOTAVAIL')) {\n // This handles the case of \"entered a DNS name that's unknown\"\n // (ENOTFOUND from getaddrinfo) and \"entered some random IP that we\n // can't bind to\" (EADDRNOTAVAIL from listen).\n runLog.log(\n \"Can't listen on host \" + self.listenHost +\n \" (\" + err.code + \" from \" + err.syscall + \").\");\n } else {\n runLog.log('' + err);\n }\n self.onFailure();\n // Allow start() to return.\n fut.isResolved() || fut['return']();\n });\n\n // Don't crash if the app doesn't respond; instead return an error\n // immediately.\n self.proxy.on('error', function (err, req, resOrSocket) {\n if (resOrSocket instanceof http.ServerResponse) {\n resOrSocket.writeHead(503, {\n 'Content-Type': 'text/plain'\n });\n resOrSocket.end('Unexpected error.');\n } else if (resOrSocket instanceof net.Socket) {\n resOrSocket.end();\n }\n });\n\n self.server.listen(self.listenPort, self.listenHost || '0.0.0.0', function () {\n if (self.server) {\n self.started = true;\n } else {\n // stop() got called while we were invoking listen! Close the server (we\n // still have the var server). The rest of the cleanup shouldn't be\n // necessary.\n server.close();\n }\n fut.isResolved() || fut['return']();\n });\n\n fut.wait();\n },\n\n // Idempotent.\n stop: function () {\n var self = this;\n\n if (! self.server)\n return;\n\n if (! self.started) {\n // This probably means that we failed to listen. However, there could be a\n // race condition and we could be in the middle of starting to listen! In\n // that case, the listen callback will notice that we nulled out server\n // here.\n self.server = null;\n return;\n }\n\n // This stops listening but allows existing connections to\n // complete gracefully.\n self.server.close();\n self.server = null;\n\n // It doesn't seem to be necessary to do anything special to\n // destroy an httpProxy proxyserver object.\n self.proxy = null;\n\n // Drop any held connections.\n _.each(self.httpQueue, function (c) {\n c.res.statusCode = 500;\n c.res.end();\n });\n self.httpQueue = [];\n\n _.each(self.websocketQueue, function (c) {\n c.socket.destroy();\n });\n self.websocketQueue = [];\n\n _.each(self.connectQueue, function (c) {\n c.socket.destroy();\n });\n self.connectQueue = [];\n\n self.mode = \"hold\";\n },\n\n _tryHandleConnections: function () {\n var self = this;\n\n while (self.httpQueue.length) {\n if (self.mode !== \"proxy\")\n break;\n\n var c = self.httpQueue.shift();\n var req = c.req;\n var targetUrl = req.url;\n runLog.log(\"Proxy request: \" + req.method + \" \" +req.url);\n var newUrl = req.url\n self.proxy.web(c.req, c.res, {\n target: targetUrl\n });\n }\n\n while (self.websocketQueue.length) {\n if (self.mode !== \"proxy\")\n break;\n\n var c = self.websocketQueue.shift();\n var req = c.req;\n var targetUrl = req.url;\n runLog.log(\"Proxy request (websocket): \" + req.method + \" \" +req.url);\n self.proxy.ws(c.req, c.socket, c.head, {\n target: targetUrl\n });\n }\n\n while (self.connectQueue.length) {\n if (self.mode !== \"proxy\")\n break;\n\n var c = self.connectQueue.shift();\n runLog.log(\"Proxy request (connect): \" + c.req.method + \" \" + c.req.url);\n proxyConnectMethod(c.req, c.socket, c.head);\n }\n },\n\n // The proxy can be in one of three modes:\n // - \"proxy\": connections are proxied\n //\n // The initial mode is \"proxy\".\n setMode: function (mode) {\n var self = this;\n self.mode = mode;\n self._tryHandleConnections();\n }\n});\n\n\n\n// This is what http-proxy does\n// XXX: We should submit connect support upstream\nvar setupSocket = function(socket) {\n socket.setTimeout(0);\n socket.setNoDelay(true);\n\n socket.setKeepAlive(true, 0);\n\n return socket;\n};\n\n\nvar proxyConnectMethod = function (req, socket, options, head, server, clb) {\n if (req.method !== 'CONNECT') {\n socket.destroy();\n return true;\n }\n\n var tokens = req.url.split(':');\n\n if (tokens.length != 2) {\n runLog.log(\"Bad request: \" + req.url);\n socket.destroy();\n return true;\n }\n\n var host = tokens[0];\n var port = tokens[1];\n\n if (port != 443) {\n runLog.log(\"Blocking request to non-443 port: \" + req.url);\n socket.destroy();\n return true;\n }\n\n setupSocket(socket);\n\n // XXX: Needed?\n // if (head && head.length) socket.unshift(head);\n\n var net = require('net');\n var proxySocket = net.createConnection(port, host);\n setupSocket(proxySocket);\n\n socket.on('error', function (err) {\n runLog.log(\"Error on socket: \" + err);\n proxySocket.end();\n });\n proxySocket.on('error', function (err) {\n runLog.log(\"Error on proxySocket: \" + err);\n socket.end();\n });\n\n proxySocket.on('connect', function(connect) {\n runLog.log(\"Connection established to \" + host + \":\" + port);\n socket.write(\"HTTP/1.0 200 Connection established\\n\\n\");\n socket.pipe(proxySocket);\n proxySocket.pipe(socket);\n });\n};\n\n\nexports.HttpProxy = HttpProxy;\n", "file_path": "tools/run-httpproxy.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00017516255320515484, 0.0001711875229375437, 0.0001657344400882721, 0.00017180154100060463, 2.5120791633526096e-06]} {"hunk": {"id": 2, "code_window": [" // XXX BBP redoc\n", " var allHandlersWithPkgs = {};\n", " var compilerPluginsByExtension = {};\n", " var linterPluginsByExtension = {};\n", " var sourceExtensions = {}; // maps source extensions to isTemplate\n", "\n", " sourceExtensions['js'] = false;\n"], "labels": ["keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var allLinters = [];\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 234}, "file": "@menu-width: 270px;\n@column: 5.55555%;\n\nbody {\n .position(absolute, 0, 0, 0, 0);\n background-color: #315481;\n .background-image( linear-gradient(top, #315481, #918e82 100%) );\n background-repeat: no-repeat;\n background-attachment: fixed;\n}\n\n#container {\n .position(absolute, 0, 0, 0, 0);\n\n @media screen and (min-width: 60em) {\n left: @column;\n right: @column;\n }\n\n @media screen and (min-width: 80em) {\n left: 2*@column;\n right: 2*@column;\n }\n\n // Hide anything offscreen\n overflow: hidden;\n}\n\n#menu {\n .position(absolute, 0, 0, 0, 0, @menu-width);\n}\n\n#content-container {\n .position(absolute, 0, 0, 0, 0);\n .transition(all 200ms ease-out);\n .transform(translate3d(0, 0, 0));\n background: @color-tertiary;\n opacity: 1;\n\n @media screen and (min-width: 40em) {\n left: @menu-width;\n }\n\n .content-scrollable {\n .position(absolute, 0, 0, 0, 0);\n .transform(translate3d(0, 0, 0));\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n }\n\n // Toggle menu on mobile\n .menu-open & {\n .transform(translate3d(@menu-width, 0, 0));\n opacity: .85;\n left: 0;\n\n @media screen and (min-width: 40em) {\n // Show menu on desktop, negate .menu-open\n .transform(translate3d(0, 0, 0)); //reset transform and use position properties instead\n opacity: 1;\n left: @menu-width;\n }\n }\n}\n\n// Transparent screen to prevent interactions on content when menu is open\n.content-overlay {\n .position(absolute, 0, 0, 0, 0);\n cursor: pointer;\n\n .menu-open & {\n .transform(translate3d(@menu-width, 0, 0));\n z-index: 1;\n }\n\n // Hide overlay on desktop\n @media screen and (min-width: 40em) { display: none; }\n}", "file_path": "examples/todos/client/stylesheets/globals/layout.import.less", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001762974279699847, 0.00017394534370396286, 0.00016954469901975244, 0.0001742886088322848, 1.8937583945444203e-06]} {"hunk": {"id": 3, "code_window": [" sourceExtensions[ext] = compilerPlugin.isTemplate;\n", " });\n", " });\n", "\n", " // Iterate over the linters\n", " _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 312}, "file": "var _ = require('underscore');\n\nvar archinfo = require('./archinfo.js');\nvar buildmessage = require('./buildmessage.js');\nvar bundler = require('./bundler.js');\nvar isopack = require('./isopack.js');\nvar isopackets = require('./isopackets.js');\nvar linker = require('./linker.js');\nvar meteorNpm = require('./meteor-npm.js');\nvar watch = require('./watch.js');\nvar Console = require('./console.js').Console;\nvar files = require('./files.js');\nvar colonConverter = require('./colon-converter.js');\nvar linterPluginModule = require('./linter-plugin.js');\n\nvar compiler = exports;\n\n// Whenever you change anything about the code that generates isopacks, bump\n// this version number. The idea is that the \"format\" field of the isopack\n// JSON file only changes when the actual specified structure of the\n// isopack/unibuild changes, but this version (which is build-tool-specific)\n// can change when the the contents (not structure) of the built output\n// changes. So eg, if we improve the linker's static analysis, this should be\n// bumped.\n//\n// You should also update this whenever you update any of the packages used\n// directly by the isopack creation process (eg js-analyze) since they do not\n// end up as watched dependencies. (At least for now, packages only used in\n// target creation (eg minifiers) don't require you to update BUILT_BY, though\n// you will need to quit and rerun \"meteor run\".)\ncompiler.BUILT_BY = 'meteor/16';\n\n// This is a list of all possible architectures that a build can target. (Client\n// is expanded into 'web.browser' and 'web.cordova')\ncompiler.ALL_ARCHES = [ \"os\", \"web.browser\", \"web.cordova\" ];\n\ncompiler.compile = function (packageSource, options) {\n buildmessage.assertInCapture();\n\n var packageMap = options.packageMap;\n var isopackCache = options.isopackCache;\n var includeCordovaUnibuild = options.includeCordovaUnibuild;\n\n var pluginWatchSet = packageSource.pluginWatchSet.clone();\n var plugins = {};\n\n var pluginProviderPackageNames = {};\n\n // Build plugins\n _.each(packageSource.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + packageSource.name + \"`\",\n rootPath: packageSource.sourceRoot\n }, function () {\n // XXX we should probably also pass options.noLineNumbers into\n // buildJsImage so it can pass it back to its call to\n // compiler.compile\n var buildResult = bundler.buildJsImage({\n name: info.name,\n packageMap: packageMap,\n isopackCache: isopackCache,\n use: info.use,\n sourceRoot: packageSource.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: files.pathResolve(\n files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))\n });\n // Add this plugin's dependencies to our \"plugin dependency\"\n // WatchSet. buildResult.watchSet will end up being the merged\n // watchSets of all of the unibuilds of the plugin -- plugins have\n // only one unibuild and this should end up essentially being just\n // the source files of the plugin.\n //\n // Note that we do this even on error, so that you can fix the error\n // and have the runner restart.\n pluginWatchSet.merge(buildResult.watchSet);\n\n if (buildmessage.jobHasMessages())\n return;\n\n _.each(buildResult.usedPackageNames, function (packageName) {\n pluginProviderPackageNames[packageName] = true;\n });\n\n // Register the built plugin's code.\n if (!_.has(plugins, info.name))\n plugins[info.name] = {};\n plugins[info.name][buildResult.image.arch] = buildResult.image;\n });\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n //\n // Go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any (sub)dependencies. This\n // process also runs mostly safely multiple times in parallel (which\n // could happen if you have two apps running locally using the same\n // package).\n //\n // We run this even if we have no dependencies, because we might\n // need to delete dependencies we used to have.\n var isPortable = true;\n var nodeModulesPath = null;\n if (packageSource.npmCacheDirectory) {\n if (meteorNpm.updateDependencies(packageSource.name,\n packageSource.npmCacheDirectory,\n packageSource.npmDependencies)) {\n nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,\n 'node_modules');\n if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))\n isPortable = false;\n }\n }\n\n var isopk = new isopack.Isopack;\n isopk.initFromOptions({\n name: packageSource.name,\n metadata: packageSource.metadata,\n version: packageSource.version,\n isTest: packageSource.isTest,\n plugins: plugins,\n pluginWatchSet: pluginWatchSet,\n cordovaDependencies: packageSource.cordovaDependencies,\n npmDiscards: packageSource.npmDiscards,\n includeTool: packageSource.includeTool,\n debugOnly: packageSource.debugOnly\n });\n\n _.each(packageSource.architectures, function (unibuild) {\n if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)\n return;\n\n var unibuildResult = compileUnibuild({\n isopack: isopk,\n sourceArch: unibuild,\n isopackCache: isopackCache,\n nodeModulesPath: nodeModulesPath,\n isPortable: isPortable,\n noLineNumbers: options.noLineNumbers\n });\n _.extend(pluginProviderPackageNames,\n unibuildResult.pluginProviderPackageNames);\n });\n\n if (options.includePluginProviderPackageMap) {\n isopk.setPluginProviderPackageMap(\n packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));\n }\n\n return isopk;\n};\n\n// options.sourceArch is a SourceArch to compile. Process all source files\n// through the appropriate handlers and run the prelink phase on any resulting\n// JavaScript. Create a new Unibuild and add it to options.isopack.\n//\n// Returns a list of source files that were used in the compilation.\nvar compileUnibuild = function (options) {\n buildmessage.assertInCapture();\n\n var isopk = options.isopack;\n var inputSourceArch = options.sourceArch;\n var isopackCache = options.isopackCache;\n var nodeModulesPath = options.nodeModulesPath;\n var isPortable = options.isPortable;\n var noLineNumbers = options.noLineNumbers;\n\n var isApp = ! inputSourceArch.pkg.name;\n var resources = [];\n var js = [];\n var pluginProviderPackageNames = {};\n // The current package always is a plugin provider. (This also means we no\n // longer need a buildOfPath entry in buildinfo.json.)\n pluginProviderPackageNames[isopk.name] = true;\n var watchSet = inputSourceArch.watchSet.clone();\n\n // *** Determine and load active plugins\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't have\n // a special \"use\" role anymore. it's not totally clear to me what\n // the correct behavior should be -- we need to resolve whether we\n // think about extensions as being global to a package or particular\n // to a unibuild.\n\n // (there's also some weirdness here with handling implies, because\n // the implies field is on the target unibuild, but we really only care\n // about packages.)\n var activePluginPackages = [isopk];\n\n // We don't use plugins from weak dependencies, because the ability\n // to compile a certain type of file shouldn't depend on whether or\n // not some unrelated package in the target has a dependency. And we\n // skip unordered dependencies, because it's not going to work to\n // have circular build-time dependencies.\n //\n // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,\n // templating from standard-app-packages).\n //\n // We pass archinfo.host here, not self.arch, because it may be more specific,\n // and because plugins always have to run on the host architecture.\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: archinfo.host(),\n isopackCache: isopackCache,\n skipUnordered: true\n // implicitly skip weak deps by not specifying acceptableWeakPackages option\n }, function (unibuild) {\n if (unibuild.pkg.name === isopk.name)\n return;\n pluginProviderPackageNames[unibuild.pkg.name] = true;\n // If other package is built from source, then we need to rebuild this\n // package if any file in the other package that could define a plugin\n // changes.\n watchSet.merge(unibuild.pkg.pluginWatchSet);\n\n if (_.isEmpty(unibuild.pkg.plugins))\n return;\n activePluginPackages.push(unibuild.pkg);\n });\n\n activePluginPackages = _.uniq(activePluginPackages);\n\n // *** Assemble the list of source file handlers from the plugins\n // XXX BBP redoc\n var allHandlersWithPkgs = {};\n var compilerPluginsByExtension = {};\n var linterPluginsByExtension = {};\n var sourceExtensions = {}; // maps source extensions to isTemplate\n\n sourceExtensions['js'] = false;\n allHandlersWithPkgs['js'] = {\n pkgName: null /* native handler */,\n handler: function (compileStep) {\n // This is a hardcoded handler for *.js files. Since plugins\n // are written in JavaScript we have to start somewhere.\n\n var options = {\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n _hash: compileStep._hash\n };\n\n if (compileStep.fileOptions.hasOwnProperty(\"bare\")) {\n options.bare = compileStep.fileOptions.bare;\n } else if (compileStep.fileOptions.hasOwnProperty(\"raw\")) {\n // XXX eventually get rid of backward-compatibility \"raw\" name\n // XXX COMPAT WITH 0.6.4\n options.bare = compileStep.fileOptions.raw;\n }\n\n compileStep.addJavaScript(options);\n }\n };\n\n _.each(activePluginPackages, function (otherPkg) {\n otherPkg.ensurePluginsInitialized();\n\n // Iterate over the legacy source handlers.\n _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {\n // XXX comparing function text here seems wrong.\n if (_.has(allHandlersWithPkgs, ext) &&\n allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n return;\n }\n // Is this handler only registered for, say, \"web\", and we're building,\n // say, \"os\"?\n if (sourceHandler.archMatching &&\n !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {\n return;\n }\n allHandlersWithPkgs[ext] = {\n pkgName: otherPkg.name,\n handler: sourceHandler.handler\n };\n sourceExtensions[ext] = !!sourceHandler.isTemplate;\n });\n\n // Iterate over the compiler plugins.\n _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {\n _.each(compilerPlugin.extensions, function (ext) {\n if (_.has(allHandlersWithPkgs, ext) ||\n _.has(compilerPluginsByExtension, ext)) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first one we found.\n return;\n }\n compilerPluginsByExtension[ext] = compilerPlugin;\n sourceExtensions[ext] = compilerPlugin.isTemplate;\n });\n });\n\n // Iterate over the linters\n _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n _.each(linterPlugin.extensions, function (ext) {\n linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n linterPluginsByExtension[ext].push(linterPlugin);\n });\n });\n });\n\n // *** Determine source files\n // Note: sourceExtensions does not include leading dots\n // Note: the getSourcesFunc function isn't expected to add its\n // source files to watchSet; rather, the watchSet is for other\n // things that the getSourcesFunc consulted (such as directory\n // listings or, in some hypothetical universe, control files) to\n // determine its source files.\n var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);\n\n if (nodeModulesPath) {\n // If this slice has node modules, we should consider the shrinkwrap file\n // to be part of its inputs. (This is a little racy because there's no\n // guarantee that what we read here is precisely the version that's used,\n // but it's better than nothing at all.)\n //\n // Note that this also means that npm modules used by plugins will get\n // this npm-shrinkwrap.json in their pluginDependencies (including for all\n // packages that depend on us)! This is good: this means that a tweak to\n // an indirect dependency of the coffee-script npm module used by the\n // coffeescript package will correctly cause packages with *.coffee files\n // to be rebuilt.\n var shrinkwrapPath = nodeModulesPath.replace(\n /node_modules$/, 'npm-shrinkwrap.json');\n watch.readAndWatchFile(watchSet, shrinkwrapPath);\n }\n\n // *** Process each source file\n var addAsset = function (contents, relPath, hash) {\n // XXX hack\n if (! inputSourceArch.pkg.name)\n relPath = relPath.replace(/^(private|public)\\//, '');\n\n resources.push({\n type: \"asset\",\n data: contents,\n path: relPath,\n servePath: colonConverter.convert(\n files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),\n hash: hash\n });\n };\n\n var convertSourceMapPaths = function (sourcemap, f) {\n if (! sourcemap) {\n // Don't try to convert it if it doesn't exist\n return sourcemap;\n }\n\n var srcmap = JSON.parse(sourcemap);\n srcmap.sources = _.map(srcmap.sources, f);\n return JSON.stringify(srcmap);\n };\n\n var wrappedSourceItems = _.map(sourceItems, function (source) {\n var fileWatchSet = new watch.WatchSet;\n // readAndWatchFileWithHash returns an object carrying a buffer with the\n // file-contents. The buffer contains the original data of the file (no EOL\n // transforms from the tools/files.js part).\n // We don't put this into the unibuild's watchSet immediately since we want\n // to avoid putting it there if it turns out not to be relevant to our\n // arch.\n var absPath = files.pathResolve(\n inputSourceArch.pkg.sourceRoot, source.relPath);\n var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);\n\n Console.nudge(true);\n\n return {\n relPath: source.relPath,\n watchset: fileWatchSet,\n contents: file.contents,\n hash: file.hash,\n source: source,\n 'package': isopk.name\n };\n });\n\n runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n\n _.each(wrappedSourceItems, function (wrappedSource) {\n var source = wrappedSource.source;\n var relPath = source.relPath;\n var fileOptions = _.clone(source.fileOptions) || {};\n var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);\n var filename = files.pathBasename(relPath);\n var contents = wrappedSource.contents;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n\n Console.nudge(true);\n\n if (contents === null) {\n // It really sucks to put this check here, since this isn't publish\n // code...\n if (source.relPath.match(/:/)) {\n buildmessage.error(\n \"Couldn't build this package on Windows due to the following file \" +\n \"with a colon -- \" + source.relPath + \". Please rename and \" +\n \"and re-publish the package.\");\n } else {\n buildmessage.error(\"File not found: \" + source.relPath);\n }\n\n // recover by ignoring (but still watching the file)\n watchSet.merge(fileWatchSet);\n return;\n }\n\n // Find the handler for source files with this extension.\n var handler = null;\n var isBuildPluginSource = false;\n if (! fileOptions.isAsset) {\n var parts = filename.split('.');\n // don't use iteration functions, so we can return/break\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(compilerPluginsByExtension, extension)) {\n var compilerPlugin = compilerPluginsByExtension[extension];\n if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {\n // This file is for a compiler plugin but not for this arch. Skip\n // it, and don't even watch it. (eg, skip CSS preprocessor files on\n // the server.)\n return;\n }\n isBuildPluginSource = true;\n break;\n }\n if (_.has(allHandlersWithPkgs, extension)) {\n handler = allHandlersWithPkgs[extension].handler;\n break;\n }\n }\n }\n\n // OK, this is relevant to this arch, so watch it.\n watchSet.merge(fileWatchSet);\n\n if (isBuildPluginSource) {\n // This is source used by a new-style compiler plugin; it will be fully\n // processed later in the bundler.\n resources.push({\n type: \"source\",\n data: contents,\n path: relPath,\n hash: hash\n });\n return;\n }\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n addAsset(contents, relPath, hash);\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript).\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - pathForSourceMap: If this file is to be included in a source map,\n // this is the name you should use for it in the map.\n // - rootOutputPath: on web targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-web targets\n // - fileOptions: any options passed to \"api.addFiles\"; for\n // use by the plugin. The built-in \"js\" plugin uses the \"bare\"\n // option for files that shouldn't be wrapped in a closure.\n // - declaredExports: An array of symbols exported by this unibuild, or null\n // if it may not export any symbols (eg, test unibuilds). This is used by\n // CoffeeScript to ensure that it doesn't close over those symbols, eg.\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // Web targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\",\n // sourceMap: \"stringified json sourcemap\"})\n // Web targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // bare: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. \"bare\" means to not wrap the file in\n // a closure, so that its vars are shared with other files\n // in the module.\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Add a file to serve as-is over HTTP (web targets) or\n // to include as-is in the bundle (os targets).\n // This time `data` is a Buffer rather than a string. For\n // web targets, it will be served at the exact path you\n // request (concatenated with rootOutputPath). For server\n // targets, the file can be retrieved by passing path to\n // Assets.getText or Assets.getBinary.\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces). sourcePath,\n // line, column, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'web'\n // vs 'os') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific unibuild will be emitted only if\n // there are native node modules). Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force unibuilds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n\n /**\n * The comments for this class aren't used to generate docs right now.\n * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers\n * @class CompileStep\n * @summary The object passed into Plugin.registerSourceHandler\n * @global\n */\n var compileStep = {\n\n /**\n * @summary The total number of bytes in the input file.\n * @memberOf CompileStep\n * @instance\n * @type {Integer}\n */\n inputSize: contents.length,\n\n /**\n * @summary The filename and relative path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n inputPath: files.convertToOSPath(relPath, true),\n\n /**\n * @summary The filename and absolute path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n fullInputPath: files.convertToOSPath(absPath),\n\n // The below is used in the less and stylus packages... so it should be\n // public API.\n _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..\n\n // Used for one optimization. Don't rely on this otherwise.\n _hash: hash,\n\n // XXX duplicates _pathForSourceMap() in linker\n /**\n * @summary If you are generating a sourcemap for the compiled file, use\n * this path for the original file in the sourcemap.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n pathForSourceMap: files.convertToOSPath(\n inputSourceArch.pkg.name ? inputSourceArch.pkg.name + \"/\" + relPath :\n files.pathBasename(relPath), true),\n\n // null if this is an app. intended to be used for the sources\n // dictionary for source maps.\n /**\n * @summary The name of the package in which the file being built exists.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n packageName: inputSourceArch.pkg.name,\n\n /**\n * @summary On web targets, this will be the root URL prepended\n * to the paths you pick for your output files. For example,\n * it could be \"/packages/my-package\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n rootOutputPath: files.convertToOSPath(\n inputSourceArch.pkg.serveRoot, true),\n\n /**\n * @summary The architecture for which we are building. Can be \"os\",\n * \"web.browser\", or \"web.cordova\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n arch: inputSourceArch.arch,\n\n /**\n * @deprecated in 0.9.4\n * This is a duplicate API of the above, we don't need it.\n */\n archMatches: function (pattern) {\n return archinfo.matches(inputSourceArch.arch, pattern);\n },\n\n /**\n * @summary Any options passed to \"api.addFiles\".\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n fileOptions: fileOptions,\n\n /**\n * @summary The list of exports that the current package has defined.\n * Can be used to treat those symbols differently during compilation.\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n\n /**\n * @summary Read from the input file. If `n` is specified, returns the\n * next `n` bytes of the file as a Buffer. XXX not sure if this actually\n * returns a String sometimes...\n * @param {Integer} [n] The number of bytes to return.\n * @instance\n * @memberOf CompileStep\n * @returns {Buffer}\n */\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n\n /**\n * @summary Works in web targets only. Add markup to the `head` or `body`\n * section of the document.\n * @param {Object} options\n * @param {String} options.section Which section of the document should\n * be appended to. Can only be \"head\" or \"body\".\n * @param {String} options.data The content to append.\n * @memberOf CompileStep\n * @instance\n */\n addHtml: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"web targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')\n });\n },\n\n /**\n * @deprecated in 0.9.4\n */\n appendDocument: function (options) {\n this.addHtml(options);\n },\n\n /**\n * @summary Web targets only. Add a stylesheet to the document.\n * @param {Object} options\n * @param {String} path The requested path for the added CSS, may not be\n * satisfied if there are path conflicts.\n * @param {String} data The content of the stylesheet that should be\n * added.\n * @param {String} sourceMap A stringified JSON sourcemap, in case the\n * stylesheet was generated from a different file.\n * @memberOf CompileStep\n * @instance\n */\n addStylesheet: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"web targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n refreshable: true,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),\n servePath: colonConverter.convert(\n files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true))),\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath)\n });\n },\n\n /**\n * @summary Add JavaScript code. The code added will only see the\n * namespaces imported by this package as runtime dependencies using\n * ['api.use'](#PackageAPI-use). If the file being compiled was added\n * with the bare flag, the resulting JavaScript won't be wrapped in a\n * closure.\n * @param {Object} options\n * @param {String} options.path The path at which the JavaScript file\n * should be inserted, may not be honored in case of path conflicts.\n * @param {String} options.data The code to be added.\n * @param {String} options.sourcePath The path that will be used in\n * any error messages generated by this file, e.g. `foo.js:4:1: error`.\n * @memberOf CompileStep\n * @instance\n */\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n\n // By default, use fileOptions for the `bare` option but also allow\n // overriding it with the options\n var bare = fileOptions.bare;\n if (options.hasOwnProperty(\"bare\")) {\n bare = options.bare;\n }\n\n js.push({\n source: files.convertToStandardLineEndings(options.data),\n sourcePath: files.convertToStandardPath(options.sourcePath, true),\n servePath: files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true)),\n bare: !! bare,\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath),\n sourceHash: options._hash\n });\n },\n\n /**\n * @summary Add a file to serve as-is to the browser or to include on\n * the browser, depending on the target. On the web, it will be served\n * at the exact path requested. For server targets, it can be retrieved\n * using `Assets.getText` or `Assets.getBinary`.\n * @param {Object} options\n * @param {String} path The path at which to serve the asset.\n * @param {Buffer|String} data The data that should be placed in\n * the file.\n * @memberOf CompileStep\n * @instance\n */\n addAsset: function (options) {\n if (! (options.data instanceof Buffer)) {\n if (_.isString(options.data)) {\n options.data = new Buffer(options.data);\n } else {\n throw new Error(\"'data' option to addAsset must be a Buffer or String.\");\n }\n }\n\n addAsset(options.data, files.convertToStandardPath(options.path, true));\n },\n\n /**\n * @summary Display a build error.\n * @param {Object} options\n * @param {String} message The error message to display.\n * @param {String} [sourcePath] The path to display in the error message.\n * @param {Integer} line The line number to display in the error message.\n * @param {String} func The function name to display in the error message.\n * @memberOf CompileStep\n * @instance\n */\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // *** Run Phase 1 link\n\n // Load jsAnalyze from the js-analyze package... unless we are the\n // js-analyze package, in which case never mind. (The js-analyze package's\n // default unibuild is not allowed to depend on anything!)\n var jsAnalyze = null;\n if (! _.isEmpty(js) && inputSourceArch.pkg.name !== \"js-analyze\") {\n jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;\n }\n\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n // I was confused about this, so I am leaving a comment -- the\n // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.\n // XXX: If we change this, we can get rid of source arch names!\n combinedServePath: isApp ? null :\n \"/packages/\" + colonConverter.convert(\n inputSourceArch.pkg.name +\n (inputSourceArch.kind === \"main\" ? \"\" : (\":\" + inputSourceArch.kind)) +\n \".js\"),\n name: inputSourceArch.pkg.name || null,\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n jsAnalyze: jsAnalyze,\n noLineNumbers: noLineNumbers\n });\n\n // *** Determine captured variables\n var packageVariables = [];\n var packageVariableNames = {};\n _.each(inputSourceArch.declaredExports, function (symbol) {\n if (_.has(packageVariableNames, symbol.name))\n return;\n packageVariables.push({\n name: symbol.name,\n export: symbol.testOnly? \"tests\" : true\n });\n packageVariableNames[symbol.name] = true;\n });\n _.each(results.assignedVariables, function (name) {\n if (_.has(packageVariableNames, name))\n return;\n packageVariables.push({\n name: name\n });\n packageVariableNames[name] = true;\n });\n\n // *** Consider npm dependencies and portability\n var arch = inputSourceArch.arch;\n if (arch === \"os\" && ! isPortable) {\n // Contains non-portable compiled npm modules, so set arch correctly\n arch = archinfo.host();\n }\n if (! archinfo.matches(arch, \"os\")) {\n // npm modules only work on server architectures\n nodeModulesPath = undefined;\n }\n\n // *** Output unibuild object\n isopk.addUnibuild({\n kind: inputSourceArch.kind,\n arch: arch,\n uses: inputSourceArch.uses,\n implies: inputSourceArch.implies,\n watchSet: watchSet,\n nodeModulesPath: nodeModulesPath,\n prelinkFiles: results.files,\n packageVariables: packageVariables,\n resources: resources\n });\n\n return {\n pluginProviderPackageNames: pluginProviderPackageNames\n };\n};\n\nvar runLinters = function (\n inputSourceArch,\n isopackCache,\n wrappedSourceItems,\n linterPluginsByExtension) {\n // For linters, figure out what are the global imports from other packages\n // that we use directly, or are implied.\n var globalImports = ['Package', 'Assets', 'Npm'];\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: inputSourceArch.arch,\n isopackCache: isopackCache,\n skipUnordered: true,\n skipDebugOnly: true\n }, function (unibuild) {\n if (unibuild.pkg.name === inputSourceArch.pkg.name)\n return;\n _.each(unibuild.packageVariables, function (symbol) {\n if (symbol.export === true)\n globalImports.push(symbol.name);\n });\n });\n\n // For each file choose the longest extension handled by linters.\n var longestMatchingExt = {};\n _.each(wrappedSourceItems, function (wrappedSource) {\n var filename = files.pathBasename(wrappedSource.relPath);\n var parts = filename.split('.');\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(linterPluginsByExtension, extension)) {\n longestMatchingExt[wrappedSource.relPath] = extension;\n break;\n }\n }\n });\n\n // Run linters on files.\n _.each(linterPluginsByExtension, function (linters, ext) {\n var sourcesToLint = [];\n _.each(wrappedSourceItems, function (wrappedSource) {\n var relPath = wrappedSource.relPath;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n var source = wrappedSource.source;\n\n // only run linters matching the longest handled extension\n if (longestMatchingExt[relPath] !== ext)\n return;\n\n sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));\n });\n\n _.each(linters, function (linterDef) {\n // skip linters not relevant to the arch we are compiling for\n if (! linterDef.relevantForArch(inputSourceArch.arch))\n return;\n\n var linter = linterDef.instantiatePlugin();\n buildmessage.enterJob({\n title: \"linting files with \" + linterDef.isopack.name\n }, function () {\n try {\n var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));\n markedLinter(sourcesToLint, globalImports);\n } catch (e) {\n buildmessage.exception(e);\n }\n });\n });\n });\n};\n\n// Iterates over each in options.dependencies as well as unibuilds implied by\n// them. The packages in question need to already be built and in\n// options.isopackCache.\ncompiler.eachUsedUnibuild = function (\n options, callback) {\n buildmessage.assertInCapture();\n var dependencies = options.dependencies;\n var arch = options.arch;\n var isopackCache = options.isopackCache;\n\n var acceptableWeakPackages = options.acceptableWeakPackages || {};\n\n var processedUnibuildId = {};\n var usesToProcess = [];\n _.each(dependencies, function (use) {\n if (options.skipUnordered && use.unordered)\n return;\n if (use.weak && !_.has(acceptableWeakPackages, use.package))\n return;\n usesToProcess.push(use);\n });\n\n while (! _.isEmpty(usesToProcess)) {\n var use = usesToProcess.shift();\n\n var usedPackage = isopackCache.getIsopack(use.package);\n\n // Ignore this package if we were told to skip debug-only packages and it is\n // debug-only.\n if (usedPackage.debugOnly && options.skipDebugOnly)\n continue;\n\n var unibuild = usedPackage.getUnibuildAtArch(arch);\n if (!unibuild) {\n // The package exists but there's no unibuild for us. A buildmessage has\n // already been issued. Recover by skipping.\n continue;\n }\n\n if (_.has(processedUnibuildId, unibuild.id))\n continue;\n processedUnibuildId[unibuild.id] = true;\n\n callback(unibuild, {\n unordered: !!use.unordered,\n weak: !!use.weak\n });\n\n _.each(unibuild.implies, function (implied) {\n usesToProcess.push(implied);\n });\n }\n};\n", "file_path": "tools/compiler.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.9928494691848755, 0.01970374956727028, 0.0001594721688888967, 0.00017180587747134268, 0.1333291083574295]} {"hunk": {"id": 3, "code_window": [" sourceExtensions[ext] = compilerPlugin.isTemplate;\n", " });\n", " });\n", "\n", " // Iterate over the linters\n", " _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 312}, "file": "#pragma once\n//-------------------------------------------------------------------------------------------------\n// \n// Copyright (c) 2004, Outercurve Foundation.\n// This software is released under Microsoft Reciprocal License (MS-RL).\n// The license and further copyright text can be found in the file\n// LICENSE.TXT at the root directory of the distribution.\n// \n// \n// \n// Header for utility layer that provides standard support for asserts, exit macros\n// \n//-------------------------------------------------------------------------------------------------\n\n#define DAPI __stdcall\n#define DAPIV __cdecl // used only for functions taking variable length arguments\n\n#define DAPI_(type) EXTERN_C type DAPI\n#define DAPIV_(type) EXTERN_C type DAPIV\n\n\n// enums\nenum REPORT_LEVEL\n{\n REPORT_NONE, // turns off report (only valid for XXXSetLevel())\n REPORT_WARNING, // written if want only warnings or reporting is on in general\n REPORT_STANDARD, // written if reporting is on\n REPORT_VERBOSE, // written only if verbose reporting is on\n REPORT_DEBUG, // reporting useful when debugging code\n REPORT_ERROR, // always gets reported, but can never be specified\n};\n\n// asserts and traces\ntypedef BOOL (DAPI *DUTIL_ASSERTDISPLAYFUNCTION)(__in_z LPCSTR sz);\n\nextern \"C\" void DAPI Dutil_SetAssertModule(__in HMODULE hAssertModule);\nextern \"C\" void DAPI Dutil_SetAssertDisplayFunction(__in DUTIL_ASSERTDISPLAYFUNCTION pfn);\nextern \"C\" void DAPI Dutil_Assert(__in_z LPCSTR szFile, __in int iLine);\nextern \"C\" void DAPI Dutil_AssertSz(__in_z LPCSTR szFile, __in int iLine, __in_z LPCSTR szMsg);\n\nextern \"C\" void DAPI Dutil_TraceSetLevel(__in REPORT_LEVEL ll, __in BOOL fTraceFilenames);\nextern \"C\" REPORT_LEVEL DAPI Dutil_TraceGetLevel();\nextern \"C\" void __cdecl Dutil_Trace(__in_z LPCSTR szFile, __in int iLine, __in REPORT_LEVEL rl, __in_z __format_string LPCSTR szMessage, ...);\nextern \"C\" void __cdecl Dutil_TraceError(__in_z LPCSTR szFile, __in int iLine, __in REPORT_LEVEL rl, __in HRESULT hr, __in_z __format_string LPCSTR szMessage, ...);\nextern \"C\" void DAPI Dutil_RootFailure(__in_z LPCSTR szFile, __in int iLine, __in HRESULT hrError);\n\n#ifdef DEBUG\n\n#define AssertSetModule(m) (void)Dutil_SetAssertModule(m)\n#define AssertSetDisplayFunction(pfn) (void)Dutil_SetAssertDisplayFunction(pfn)\n#define Assert(f) ((f) ? (void)0 : (void)Dutil_Assert(__FILE__, __LINE__))\n#define AssertSz(f, sz) ((f) ? (void)0 : (void)Dutil_AssertSz(__FILE__, __LINE__, sz))\n\n#define TraceSetLevel(l, f) (void)Dutil_TraceSetLevel(l, f)\n#define TraceGetLevel() (REPORT_LEVEL)Dutil_TraceGetLevel()\n#define Trace(l, f) (void)Dutil_Trace(__FILE__, __LINE__, l, f, NULL)\n#define Trace1(l, f, s) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s)\n#define Trace2(l, f, s, t) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s, t)\n#define Trace3(l, f, s, t, u) (void)Dutil_Trace(__FILE__, __LINE__, l, f, s, t, u)\n\n#define TraceError(x, f) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, NULL)\n#define TraceError1(x, f, s) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s)\n#define TraceError2(x, f, s, t) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s, t)\n#define TraceError3(x, f, s, t, u) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_ERROR, x, f, s, t, u)\n\n#define TraceErrorDebug(x, f) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, NULL)\n#define TraceErrorDebug1(x, f, s) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s)\n#define TraceErrorDebug2(x, f, s, t) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s, t)\n#define TraceErrorDebug3(x, f, s, t, u) (void)Dutil_TraceError(__FILE__, __LINE__, REPORT_DEBUG, x, f, s, t, u)\n\n#else // !DEBUG\n\n#define AssertSetModule(m)\n#define AssertSetDisplayFunction(pfn)\n#define Assert(f)\n#define AssertSz(f, sz)\n\n#define TraceSetLevel(l, f)\n#define Trace(l, f)\n#define Trace1(l, f, s)\n#define Trace2(l, f, s, t)\n#define Trace3(l, f, s, t, u)\n\n#define TraceError(x, f)\n#define TraceError1(x, f, s)\n#define TraceError2(x, f, s, t)\n#define TraceError3(x, f, s, t, u)\n\n#define TraceErrorDebug(x, f)\n#define TraceErrorDebug1(x, f, s)\n#define TraceErrorDebug2(x, f, s, t)\n#define TraceErrorDebug3(x, f, s, t, u)\n\n#endif // DEBUG\n\n\n// ExitTrace can be overriden\n#ifndef ExitTrace\n#define ExitTrace TraceError\n#endif\n#ifndef ExitTrace1\n#define ExitTrace1 TraceError1\n#endif\n#ifndef ExitTrace2\n#define ExitTrace2 TraceError2\n#endif\n#ifndef ExitTrace3\n#define ExitTrace3 TraceError3\n#endif\n\n// Exit macros\n#define ExitFunction() { goto LExit; }\n#define ExitFunction1(x) { x; goto LExit; }\n\n#define ExitOnLastError(x, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; } }\n#define ExitOnLastError1(x, f, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; } }\n#define ExitOnLastError2(x, f, s, t) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; } }\n\n#define ExitOnLastErrorDebugTrace(x, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug(x, s); goto LExit; } }\n#define ExitOnLastErrorDebugTrace1(x, f, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug1(x, f, s); goto LExit; } }\n#define ExitOnLastErrorDebugTrace2(x, f, s, t) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug2(x, f, s, t); goto LExit; } }\n\n#define ExitWithLastError(x, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }\n#define ExitWithLastError1(x, f, s) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }\n#define ExitWithLastError2(x, f, s, t) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }\n#define ExitWithLastError3(x, f, s, t, u) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace3(x, f, s, t, u); goto LExit; }\n\n#define ExitOnFailure(x, s) if (FAILED(x)) { ExitTrace(x, s); goto LExit; }\n#define ExitOnFailure1(x, f, s) if (FAILED(x)) { ExitTrace1(x, f, s); goto LExit; }\n#define ExitOnFailure2(x, f, s, t) if (FAILED(x)) { ExitTrace2(x, f, s, t); goto LExit; }\n#define ExitOnFailure3(x, f, s, t, u) if (FAILED(x)) { ExitTrace3(x, f, s, t, u); goto LExit; }\n\n#define ExitOnRootFailure(x, s) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }\n#define ExitOnRootFailure1(x, f, s) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }\n#define ExitOnRootFailure2(x, f, s, t) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }\n#define ExitOnRootFailure3(x, f, s, t, u) if (FAILED(x)) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace3(x, f, s, t, u); goto LExit; }\n\n#define ExitOnFailureDebugTrace(x, s) if (FAILED(x)) { TraceErrorDebug(x, s); goto LExit; }\n#define ExitOnFailureDebugTrace1(x, f, s) if (FAILED(x)) { TraceErrorDebug1(x, f, s); goto LExit; }\n#define ExitOnFailureDebugTrace2(x, f, s, t) if (FAILED(x)) { TraceErrorDebug2(x, f, s, t); goto LExit; }\n#define ExitOnFailureDebugTrace3(x, f, s, t, u) if (FAILED(x)) { TraceErrorDebug3(x, f, s, t, u); goto LExit; }\n\n#define ExitOnNull(p, x, e, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }\n#define ExitOnNull1(p, x, e, f, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }\n#define ExitOnNull2(p, x, e, f, s, t) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }\n\n#define ExitOnNullWithLastError(p, x, s) if (NULL == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }\n#define ExitOnNullWithLastError1(p, x, f, s) if (NULL == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }\n\n#define ExitOnNullDebugTrace(p, x, e, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug(x, s); goto LExit; }\n#define ExitOnNullDebugTrace1(p, x, e, f, s) if (NULL == p) { x = e; Dutil_RootFailure(__FILE__, __LINE__, x); TraceErrorDebug1(x, f, s); goto LExit; }\n\n#define ExitOnInvalidHandleWithLastError(p, x, s) if (INVALID_HANDLE_VALUE == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }\n#define ExitOnInvalidHandleWithLastError1(p, x, f, s) if (INVALID_HANDLE_VALUE == p) { DWORD Dutil_er = ::GetLastError(); x = HRESULT_FROM_WIN32(Dutil_er); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }\n\n#define ExitOnWin32Error(e, x, s) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace(x, s); goto LExit; }\n#define ExitOnWin32Error1(e, x, f, s) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace1(x, f, s); goto LExit; }\n#define ExitOnWin32Error2(e, x, f, s, t) if (ERROR_SUCCESS != e) { x = HRESULT_FROM_WIN32(e); if (!FAILED(x)) { x = E_FAIL; } Dutil_RootFailure(__FILE__, __LINE__, x); ExitTrace2(x, f, s, t); goto LExit; }\n\n// release macros\n#define ReleaseObject(x) if (x) { x->Release(); }\n#define ReleaseObjectArray(prg, cel) if (prg) { for (DWORD Dutil_ReleaseObjectArrayIndex = 0; Dutil_ReleaseObjectArrayIndex < cel; ++Dutil_ReleaseObjectArrayIndex) { ReleaseObject(prg[Dutil_ReleaseObjectArrayIndex]); } ReleaseMem(prg); }\n#define ReleaseVariant(x) { ::VariantClear(&x); }\n#define ReleaseNullObject(x) if (x) { (x)->Release(); x = NULL; }\n#define ReleaseCertificate(x) if (x) { ::CertFreeCertificateContext(x); x=NULL; }\n#define ReleaseHandle(x) if (x) { ::CloseHandle(x); x = NULL; }\n\n\n// useful defines and macros\n#define Unused(x) ((void)x)\n\n#ifndef countof\n#if 1\n#define countof(ary) (sizeof(ary) / sizeof(ary[0]))\n#else\n#ifndef __cplusplus\n#define countof(ary) (sizeof(ary) / sizeof(ary[0]))\n#else\ntemplate static char countofVerify(void const *, T) throw() { return 0; }\ntemplate static void countofVerify(T *const, T *const *) throw() {};\n#define countof(arr) (sizeof(countofVerify(arr,&(arr))) * sizeof(arr)/sizeof(*(arr)))\n#endif\n#endif\n#endif\n\n#define roundup(x, n) roundup_typed(x, n, DWORD)\n#define roundup_typed(x, n, t) (((t)(x) + ((t)(n) - 1)) & ~((t)(n) - 1))\n\n#define HRESULT_FROM_RPC(x) ((HRESULT) ((x) | FACILITY_RPC))\n\n#ifndef MAXSIZE_T\n#define MAXSIZE_T ((SIZE_T)~((SIZE_T)0))\n#endif\n\ntypedef const BYTE* LPCBYTE;\n\n#define E_FILENOTFOUND HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)\n#define E_PATHNOTFOUND HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)\n#define E_INVALIDDATA HRESULT_FROM_WIN32(ERROR_INVALID_DATA)\n#define E_INVALIDSTATE HRESULT_FROM_WIN32(ERROR_INVALID_STATE)\n#define E_INSUFFICIENT_BUFFER HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)\n#define E_MOREDATA HRESULT_FROM_WIN32(ERROR_MORE_DATA)\n#define E_NOMOREITEMS HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)\n#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)\n#define E_MODNOTFOUND HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)\n#define E_BADCONFIGURATION HRESULT_FROM_WIN32(ERROR_BAD_CONFIGURATION)\n\n#define AddRefAndRelease(x) { x->AddRef(); x->Release(); }\n\n#define MAKEDWORD(lo, hi) ((DWORD)MAKELONG(lo, hi))\n#define MAKEQWORDVERSION(mj, mi, b, r) (((DWORD64)MAKELONG(r, b)) | (((DWORD64)MAKELONG(mi, mj)) << 32))\n\n// other functions\nextern \"C\" HRESULT DAPI LoadSystemLibrary(__in_z LPCWSTR wzModuleName, __out HMODULE *phModule);\nextern \"C\" HRESULT DAPI LoadSystemLibraryWithPath(__in_z LPCWSTR wzModuleName, __out HMODULE *phModule, __deref_out_z_opt LPWSTR* psczPath);\n", "file_path": "scripts/windows/installer/WiXSDK/inc/dutil.h", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00047560923849232495, 0.00020720026805065572, 0.00016425293870270252, 0.0001750678929965943, 8.032656478462741e-05]} {"hunk": {"id": 3, "code_window": [" sourceExtensions[ext] = compilerPlugin.isTemplate;\n", " });\n", " });\n", "\n", " // Iterate over the linters\n", " _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 312}, "file": "{\n \"dependencies\": {\n \"node-aes-gcm\": {\n \"version\": \"0.1.3\"\n }\n }\n}\n", "file_path": "packages/non-core/npm-node-aes-gcm/.npm/package/npm-shrinkwrap.json", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00017732074775267392, 0.00017732074775267392, 0.00017732074775267392, 0.00017732074775267392, 0.0]} {"hunk": {"id": 3, "code_window": [" sourceExtensions[ext] = compilerPlugin.isTemplate;\n", " });\n", " });\n", "\n", " // Iterate over the linters\n", " _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n"], "labels": ["keep", "keep", "keep", "keep", "replace", "keep"], "after_edit": [], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 312}, "file": "# weibo\n\nAn implementation of the Weibo OAuth flow. See the [project\npage](https://www.meteor.com/accounts) on Meteor Accounts for more\ndetails.", "file_path": "packages/weibo/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00016876551671884954, 0.00016876551671884954, 0.00016876551671884954, 0.00016876551671884954, 0.0]} {"hunk": {"id": 4, "code_window": [" _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n", " _.each(linterPlugin.extensions, function (ext) {\n", " linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n", " linterPluginsByExtension[ext].push(linterPlugin);\n", " });\n", " });\n", " });\n", "\n", " // *** Determine source files\n", " // Note: sourceExtensions does not include leading dots\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" allLinters.push(linterPlugin);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 314}, "file": "var util = Npm.require('util');\nvar Future = Npm.require('fibers/future');\nvar path = Npm.require('path');\nvar jshint = Npm.require('jshint').JSHINT;\n\nPlugin.registerLinter({\n extensions: [\"jshintrc\", \"js\"],\n}, function () {\n var linter = new JsHintLinter();\n return linter;\n});\n\nfunction JsHintLinter () {};\n\nJsHintLinter.prototype.processFilesForTarget = function (files, globals) {\n var conf = {\n undef: true,\n unused: true,\n node: true,\n browser: true\n };\n\n files.forEach(function (file) {\n // find the config file\n if (file.getBasename() === '.jshintrc') {\n var confStr = file.getContentsAsString();\n try {\n conf = JSON.parse(confStr);\n } catch (err) {\n file.error({ message: \"Failed to parse .jshint file, not a valid JSON: \" + err.message });\n }\n return;\n }\n // require configuration file to be called '.jshintrc'\n if (path.extname(file.getBasename()) !== '.js') {\n file.error({ message: \"Unrecognized configuration file name. Configuration file should be called .jshintrc\" });\n return;\n }\n });\n\n files.forEach(function (file) {\n if (file.getBasename() === '.jshintrc')\n return;\n if (! jshint(file.getContentsAsString(), conf, globals)) {\n jshint.errors.forEach(function (error) {\n file.error({\n message: error.reason,\n line: error.line,\n column: error.character\n });\n });\n }\n });\n};\n\n\n", "file_path": "packages/jshint/plugin/lint-jshint.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0002031217300100252, 0.00017333963478449732, 0.00016327637422364205, 0.00016825525381136686, 1.3461154594551772e-05]} {"hunk": {"id": 4, "code_window": [" _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n", " _.each(linterPlugin.extensions, function (ext) {\n", " linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n", " linterPluginsByExtension[ext].push(linterPlugin);\n", " });\n", " });\n", " });\n", "\n", " // *** Determine source files\n", " // Note: sourceExtensions does not include leading dots\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" allLinters.push(linterPlugin);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 314}, "file": "accounts-base@1.2.0\naccounts-password@1.1.1\nautoupdate@1.2.1\nbase64@1.0.3\nbinary-heap@1.0.3\nblaze@2.1.2\nblaze-tools@1.0.3\nboilerplate-generator@1.0.3\ncallback-hook@1.0.3\ncheck@1.0.5\nddp@1.1.0\ndeps@1.0.7\nejson@1.0.6\nemail@1.0.6\nfastclick@1.0.3\ngeojson-utils@1.0.3\nhtml-tools@1.0.4\nhtmljs@1.0.4\nhttp@1.1.0\nid-map@1.0.3\ninsecure@1.0.3\niron:core@0.3.4\niron:dynamic-template@0.4.1\niron:layout@0.4.1\niron:router@0.9.4\njquery@1.11.3_2\njson@1.0.3\nlaunch-screen@1.0.2\nless@1.0.14\nlivedata@1.0.13\nlocalstorage@1.0.3\nlogging@1.0.7\nmeteor@1.1.6\nmeteor-platform@1.2.2\nminifiers@1.1.5\nminimongo@1.0.8\nmobile-status-bar@1.0.3\nmongo@1.1.0\nnpm-bcrypt@0.7.8_2\nobserve-sequence@1.0.6\nordered-dict@1.0.3\nrandom@1.0.3\nreactive-dict@1.1.0\nreactive-var@1.0.5\nreload@1.1.3\nretry@1.0.3\nroutepolicy@1.0.5\nservice-configuration@1.0.4\nsession@1.1.0\nsha@1.0.3\nspacebars@1.0.6\nspacebars-compiler@1.0.6\nsrp@1.0.3\ntemplating@1.1.1\ntracker@1.0.7\nui@1.0.6\nunderscore@1.0.3\nurl@1.0.4\nwebapp@1.2.0\nwebapp-hashing@1.0.3\n", "file_path": "examples/todos/.meteor/versions", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001754989061737433, 0.00017267100338358432, 0.00017062205006368458, 0.00017268744704779238, 1.4362657339006546e-06]} {"hunk": {"id": 4, "code_window": [" _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n", " _.each(linterPlugin.extensions, function (ext) {\n", " linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n", " linterPluginsByExtension[ext].push(linterPlugin);\n", " });\n", " });\n", " });\n", "\n", " // *** Determine source files\n", " // Note: sourceExtensions does not include leading dots\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" allLinters.push(linterPlugin);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 314}, "file": "This is an internal Meteor package.", "file_path": "packages/boilerplate-generator/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00016661924018990248, 0.00016661924018990248, 0.00016661924018990248, 0.00016661924018990248, 0.0]} {"hunk": {"id": 4, "code_window": [" _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n", " _.each(linterPlugin.extensions, function (ext) {\n", " linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n", " linterPluginsByExtension[ext].push(linterPlugin);\n", " });\n", " });\n", " });\n", "\n", " // *** Determine source files\n", " // Note: sourceExtensions does not include leading dots\n"], "labels": ["keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" allLinters.push(linterPlugin);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 314}, "file": "Package.describe({\n summary: \"Deprecated: Use the 'blaze' package\",\n version: '1.0.6'\n});\n\nPackage.onUse(function (api) {\n api.use('blaze');\n api.imply('blaze');\n\n // XXX COMPAT WITH PACKAGES BUILT FOR 0.9.0.\n //\n // (in particular, packages that have a weak dependency on this\n // package, since then exported symbols live on the\n // `Package.ui` object)\n api.export(['Blaze', 'UI', 'Handlebars']);\n});\n", "file_path": "packages/ui/package.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001727323979139328, 0.00017123341967817396, 0.00016973444144241512, 0.00017123341967817396, 1.498978235758841e-06]} {"hunk": {"id": 5, "code_window": [" source: source,\n", " 'package': isopk.name\n", " };\n", " });\n", "\n", " runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n", "\n", " _.each(wrappedSourceItems, function (wrappedSource) {\n", " var source = wrappedSource.source;\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" runLinters(inputSourceArch, isopackCache, wrappedSourceItems, allLinters);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 398}, "file": "var _ = require('underscore');\n\nvar archinfo = require('./archinfo.js');\nvar buildmessage = require('./buildmessage.js');\nvar bundler = require('./bundler.js');\nvar isopack = require('./isopack.js');\nvar isopackets = require('./isopackets.js');\nvar linker = require('./linker.js');\nvar meteorNpm = require('./meteor-npm.js');\nvar watch = require('./watch.js');\nvar Console = require('./console.js').Console;\nvar files = require('./files.js');\nvar colonConverter = require('./colon-converter.js');\nvar linterPluginModule = require('./linter-plugin.js');\n\nvar compiler = exports;\n\n// Whenever you change anything about the code that generates isopacks, bump\n// this version number. The idea is that the \"format\" field of the isopack\n// JSON file only changes when the actual specified structure of the\n// isopack/unibuild changes, but this version (which is build-tool-specific)\n// can change when the the contents (not structure) of the built output\n// changes. So eg, if we improve the linker's static analysis, this should be\n// bumped.\n//\n// You should also update this whenever you update any of the packages used\n// directly by the isopack creation process (eg js-analyze) since they do not\n// end up as watched dependencies. (At least for now, packages only used in\n// target creation (eg minifiers) don't require you to update BUILT_BY, though\n// you will need to quit and rerun \"meteor run\".)\ncompiler.BUILT_BY = 'meteor/16';\n\n// This is a list of all possible architectures that a build can target. (Client\n// is expanded into 'web.browser' and 'web.cordova')\ncompiler.ALL_ARCHES = [ \"os\", \"web.browser\", \"web.cordova\" ];\n\ncompiler.compile = function (packageSource, options) {\n buildmessage.assertInCapture();\n\n var packageMap = options.packageMap;\n var isopackCache = options.isopackCache;\n var includeCordovaUnibuild = options.includeCordovaUnibuild;\n\n var pluginWatchSet = packageSource.pluginWatchSet.clone();\n var plugins = {};\n\n var pluginProviderPackageNames = {};\n\n // Build plugins\n _.each(packageSource.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + packageSource.name + \"`\",\n rootPath: packageSource.sourceRoot\n }, function () {\n // XXX we should probably also pass options.noLineNumbers into\n // buildJsImage so it can pass it back to its call to\n // compiler.compile\n var buildResult = bundler.buildJsImage({\n name: info.name,\n packageMap: packageMap,\n isopackCache: isopackCache,\n use: info.use,\n sourceRoot: packageSource.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: files.pathResolve(\n files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))\n });\n // Add this plugin's dependencies to our \"plugin dependency\"\n // WatchSet. buildResult.watchSet will end up being the merged\n // watchSets of all of the unibuilds of the plugin -- plugins have\n // only one unibuild and this should end up essentially being just\n // the source files of the plugin.\n //\n // Note that we do this even on error, so that you can fix the error\n // and have the runner restart.\n pluginWatchSet.merge(buildResult.watchSet);\n\n if (buildmessage.jobHasMessages())\n return;\n\n _.each(buildResult.usedPackageNames, function (packageName) {\n pluginProviderPackageNames[packageName] = true;\n });\n\n // Register the built plugin's code.\n if (!_.has(plugins, info.name))\n plugins[info.name] = {};\n plugins[info.name][buildResult.image.arch] = buildResult.image;\n });\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n //\n // Go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any (sub)dependencies. This\n // process also runs mostly safely multiple times in parallel (which\n // could happen if you have two apps running locally using the same\n // package).\n //\n // We run this even if we have no dependencies, because we might\n // need to delete dependencies we used to have.\n var isPortable = true;\n var nodeModulesPath = null;\n if (packageSource.npmCacheDirectory) {\n if (meteorNpm.updateDependencies(packageSource.name,\n packageSource.npmCacheDirectory,\n packageSource.npmDependencies)) {\n nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,\n 'node_modules');\n if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))\n isPortable = false;\n }\n }\n\n var isopk = new isopack.Isopack;\n isopk.initFromOptions({\n name: packageSource.name,\n metadata: packageSource.metadata,\n version: packageSource.version,\n isTest: packageSource.isTest,\n plugins: plugins,\n pluginWatchSet: pluginWatchSet,\n cordovaDependencies: packageSource.cordovaDependencies,\n npmDiscards: packageSource.npmDiscards,\n includeTool: packageSource.includeTool,\n debugOnly: packageSource.debugOnly\n });\n\n _.each(packageSource.architectures, function (unibuild) {\n if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)\n return;\n\n var unibuildResult = compileUnibuild({\n isopack: isopk,\n sourceArch: unibuild,\n isopackCache: isopackCache,\n nodeModulesPath: nodeModulesPath,\n isPortable: isPortable,\n noLineNumbers: options.noLineNumbers\n });\n _.extend(pluginProviderPackageNames,\n unibuildResult.pluginProviderPackageNames);\n });\n\n if (options.includePluginProviderPackageMap) {\n isopk.setPluginProviderPackageMap(\n packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));\n }\n\n return isopk;\n};\n\n// options.sourceArch is a SourceArch to compile. Process all source files\n// through the appropriate handlers and run the prelink phase on any resulting\n// JavaScript. Create a new Unibuild and add it to options.isopack.\n//\n// Returns a list of source files that were used in the compilation.\nvar compileUnibuild = function (options) {\n buildmessage.assertInCapture();\n\n var isopk = options.isopack;\n var inputSourceArch = options.sourceArch;\n var isopackCache = options.isopackCache;\n var nodeModulesPath = options.nodeModulesPath;\n var isPortable = options.isPortable;\n var noLineNumbers = options.noLineNumbers;\n\n var isApp = ! inputSourceArch.pkg.name;\n var resources = [];\n var js = [];\n var pluginProviderPackageNames = {};\n // The current package always is a plugin provider. (This also means we no\n // longer need a buildOfPath entry in buildinfo.json.)\n pluginProviderPackageNames[isopk.name] = true;\n var watchSet = inputSourceArch.watchSet.clone();\n\n // *** Determine and load active plugins\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't have\n // a special \"use\" role anymore. it's not totally clear to me what\n // the correct behavior should be -- we need to resolve whether we\n // think about extensions as being global to a package or particular\n // to a unibuild.\n\n // (there's also some weirdness here with handling implies, because\n // the implies field is on the target unibuild, but we really only care\n // about packages.)\n var activePluginPackages = [isopk];\n\n // We don't use plugins from weak dependencies, because the ability\n // to compile a certain type of file shouldn't depend on whether or\n // not some unrelated package in the target has a dependency. And we\n // skip unordered dependencies, because it's not going to work to\n // have circular build-time dependencies.\n //\n // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,\n // templating from standard-app-packages).\n //\n // We pass archinfo.host here, not self.arch, because it may be more specific,\n // and because plugins always have to run on the host architecture.\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: archinfo.host(),\n isopackCache: isopackCache,\n skipUnordered: true\n // implicitly skip weak deps by not specifying acceptableWeakPackages option\n }, function (unibuild) {\n if (unibuild.pkg.name === isopk.name)\n return;\n pluginProviderPackageNames[unibuild.pkg.name] = true;\n // If other package is built from source, then we need to rebuild this\n // package if any file in the other package that could define a plugin\n // changes.\n watchSet.merge(unibuild.pkg.pluginWatchSet);\n\n if (_.isEmpty(unibuild.pkg.plugins))\n return;\n activePluginPackages.push(unibuild.pkg);\n });\n\n activePluginPackages = _.uniq(activePluginPackages);\n\n // *** Assemble the list of source file handlers from the plugins\n // XXX BBP redoc\n var allHandlersWithPkgs = {};\n var compilerPluginsByExtension = {};\n var linterPluginsByExtension = {};\n var sourceExtensions = {}; // maps source extensions to isTemplate\n\n sourceExtensions['js'] = false;\n allHandlersWithPkgs['js'] = {\n pkgName: null /* native handler */,\n handler: function (compileStep) {\n // This is a hardcoded handler for *.js files. Since plugins\n // are written in JavaScript we have to start somewhere.\n\n var options = {\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n _hash: compileStep._hash\n };\n\n if (compileStep.fileOptions.hasOwnProperty(\"bare\")) {\n options.bare = compileStep.fileOptions.bare;\n } else if (compileStep.fileOptions.hasOwnProperty(\"raw\")) {\n // XXX eventually get rid of backward-compatibility \"raw\" name\n // XXX COMPAT WITH 0.6.4\n options.bare = compileStep.fileOptions.raw;\n }\n\n compileStep.addJavaScript(options);\n }\n };\n\n _.each(activePluginPackages, function (otherPkg) {\n otherPkg.ensurePluginsInitialized();\n\n // Iterate over the legacy source handlers.\n _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {\n // XXX comparing function text here seems wrong.\n if (_.has(allHandlersWithPkgs, ext) &&\n allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n return;\n }\n // Is this handler only registered for, say, \"web\", and we're building,\n // say, \"os\"?\n if (sourceHandler.archMatching &&\n !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {\n return;\n }\n allHandlersWithPkgs[ext] = {\n pkgName: otherPkg.name,\n handler: sourceHandler.handler\n };\n sourceExtensions[ext] = !!sourceHandler.isTemplate;\n });\n\n // Iterate over the compiler plugins.\n _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {\n _.each(compilerPlugin.extensions, function (ext) {\n if (_.has(allHandlersWithPkgs, ext) ||\n _.has(compilerPluginsByExtension, ext)) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first one we found.\n return;\n }\n compilerPluginsByExtension[ext] = compilerPlugin;\n sourceExtensions[ext] = compilerPlugin.isTemplate;\n });\n });\n\n // Iterate over the linters\n _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n _.each(linterPlugin.extensions, function (ext) {\n linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n linterPluginsByExtension[ext].push(linterPlugin);\n });\n });\n });\n\n // *** Determine source files\n // Note: sourceExtensions does not include leading dots\n // Note: the getSourcesFunc function isn't expected to add its\n // source files to watchSet; rather, the watchSet is for other\n // things that the getSourcesFunc consulted (such as directory\n // listings or, in some hypothetical universe, control files) to\n // determine its source files.\n var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);\n\n if (nodeModulesPath) {\n // If this slice has node modules, we should consider the shrinkwrap file\n // to be part of its inputs. (This is a little racy because there's no\n // guarantee that what we read here is precisely the version that's used,\n // but it's better than nothing at all.)\n //\n // Note that this also means that npm modules used by plugins will get\n // this npm-shrinkwrap.json in their pluginDependencies (including for all\n // packages that depend on us)! This is good: this means that a tweak to\n // an indirect dependency of the coffee-script npm module used by the\n // coffeescript package will correctly cause packages with *.coffee files\n // to be rebuilt.\n var shrinkwrapPath = nodeModulesPath.replace(\n /node_modules$/, 'npm-shrinkwrap.json');\n watch.readAndWatchFile(watchSet, shrinkwrapPath);\n }\n\n // *** Process each source file\n var addAsset = function (contents, relPath, hash) {\n // XXX hack\n if (! inputSourceArch.pkg.name)\n relPath = relPath.replace(/^(private|public)\\//, '');\n\n resources.push({\n type: \"asset\",\n data: contents,\n path: relPath,\n servePath: colonConverter.convert(\n files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),\n hash: hash\n });\n };\n\n var convertSourceMapPaths = function (sourcemap, f) {\n if (! sourcemap) {\n // Don't try to convert it if it doesn't exist\n return sourcemap;\n }\n\n var srcmap = JSON.parse(sourcemap);\n srcmap.sources = _.map(srcmap.sources, f);\n return JSON.stringify(srcmap);\n };\n\n var wrappedSourceItems = _.map(sourceItems, function (source) {\n var fileWatchSet = new watch.WatchSet;\n // readAndWatchFileWithHash returns an object carrying a buffer with the\n // file-contents. The buffer contains the original data of the file (no EOL\n // transforms from the tools/files.js part).\n // We don't put this into the unibuild's watchSet immediately since we want\n // to avoid putting it there if it turns out not to be relevant to our\n // arch.\n var absPath = files.pathResolve(\n inputSourceArch.pkg.sourceRoot, source.relPath);\n var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);\n\n Console.nudge(true);\n\n return {\n relPath: source.relPath,\n watchset: fileWatchSet,\n contents: file.contents,\n hash: file.hash,\n source: source,\n 'package': isopk.name\n };\n });\n\n runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n\n _.each(wrappedSourceItems, function (wrappedSource) {\n var source = wrappedSource.source;\n var relPath = source.relPath;\n var fileOptions = _.clone(source.fileOptions) || {};\n var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);\n var filename = files.pathBasename(relPath);\n var contents = wrappedSource.contents;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n\n Console.nudge(true);\n\n if (contents === null) {\n // It really sucks to put this check here, since this isn't publish\n // code...\n if (source.relPath.match(/:/)) {\n buildmessage.error(\n \"Couldn't build this package on Windows due to the following file \" +\n \"with a colon -- \" + source.relPath + \". Please rename and \" +\n \"and re-publish the package.\");\n } else {\n buildmessage.error(\"File not found: \" + source.relPath);\n }\n\n // recover by ignoring (but still watching the file)\n watchSet.merge(fileWatchSet);\n return;\n }\n\n // Find the handler for source files with this extension.\n var handler = null;\n var isBuildPluginSource = false;\n if (! fileOptions.isAsset) {\n var parts = filename.split('.');\n // don't use iteration functions, so we can return/break\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(compilerPluginsByExtension, extension)) {\n var compilerPlugin = compilerPluginsByExtension[extension];\n if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {\n // This file is for a compiler plugin but not for this arch. Skip\n // it, and don't even watch it. (eg, skip CSS preprocessor files on\n // the server.)\n return;\n }\n isBuildPluginSource = true;\n break;\n }\n if (_.has(allHandlersWithPkgs, extension)) {\n handler = allHandlersWithPkgs[extension].handler;\n break;\n }\n }\n }\n\n // OK, this is relevant to this arch, so watch it.\n watchSet.merge(fileWatchSet);\n\n if (isBuildPluginSource) {\n // This is source used by a new-style compiler plugin; it will be fully\n // processed later in the bundler.\n resources.push({\n type: \"source\",\n data: contents,\n path: relPath,\n hash: hash\n });\n return;\n }\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n addAsset(contents, relPath, hash);\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript).\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - pathForSourceMap: If this file is to be included in a source map,\n // this is the name you should use for it in the map.\n // - rootOutputPath: on web targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-web targets\n // - fileOptions: any options passed to \"api.addFiles\"; for\n // use by the plugin. The built-in \"js\" plugin uses the \"bare\"\n // option for files that shouldn't be wrapped in a closure.\n // - declaredExports: An array of symbols exported by this unibuild, or null\n // if it may not export any symbols (eg, test unibuilds). This is used by\n // CoffeeScript to ensure that it doesn't close over those symbols, eg.\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // Web targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\",\n // sourceMap: \"stringified json sourcemap\"})\n // Web targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // bare: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. \"bare\" means to not wrap the file in\n // a closure, so that its vars are shared with other files\n // in the module.\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Add a file to serve as-is over HTTP (web targets) or\n // to include as-is in the bundle (os targets).\n // This time `data` is a Buffer rather than a string. For\n // web targets, it will be served at the exact path you\n // request (concatenated with rootOutputPath). For server\n // targets, the file can be retrieved by passing path to\n // Assets.getText or Assets.getBinary.\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces). sourcePath,\n // line, column, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'web'\n // vs 'os') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific unibuild will be emitted only if\n // there are native node modules). Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force unibuilds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n\n /**\n * The comments for this class aren't used to generate docs right now.\n * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers\n * @class CompileStep\n * @summary The object passed into Plugin.registerSourceHandler\n * @global\n */\n var compileStep = {\n\n /**\n * @summary The total number of bytes in the input file.\n * @memberOf CompileStep\n * @instance\n * @type {Integer}\n */\n inputSize: contents.length,\n\n /**\n * @summary The filename and relative path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n inputPath: files.convertToOSPath(relPath, true),\n\n /**\n * @summary The filename and absolute path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n fullInputPath: files.convertToOSPath(absPath),\n\n // The below is used in the less and stylus packages... so it should be\n // public API.\n _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..\n\n // Used for one optimization. Don't rely on this otherwise.\n _hash: hash,\n\n // XXX duplicates _pathForSourceMap() in linker\n /**\n * @summary If you are generating a sourcemap for the compiled file, use\n * this path for the original file in the sourcemap.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n pathForSourceMap: files.convertToOSPath(\n inputSourceArch.pkg.name ? inputSourceArch.pkg.name + \"/\" + relPath :\n files.pathBasename(relPath), true),\n\n // null if this is an app. intended to be used for the sources\n // dictionary for source maps.\n /**\n * @summary The name of the package in which the file being built exists.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n packageName: inputSourceArch.pkg.name,\n\n /**\n * @summary On web targets, this will be the root URL prepended\n * to the paths you pick for your output files. For example,\n * it could be \"/packages/my-package\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n rootOutputPath: files.convertToOSPath(\n inputSourceArch.pkg.serveRoot, true),\n\n /**\n * @summary The architecture for which we are building. Can be \"os\",\n * \"web.browser\", or \"web.cordova\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n arch: inputSourceArch.arch,\n\n /**\n * @deprecated in 0.9.4\n * This is a duplicate API of the above, we don't need it.\n */\n archMatches: function (pattern) {\n return archinfo.matches(inputSourceArch.arch, pattern);\n },\n\n /**\n * @summary Any options passed to \"api.addFiles\".\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n fileOptions: fileOptions,\n\n /**\n * @summary The list of exports that the current package has defined.\n * Can be used to treat those symbols differently during compilation.\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n\n /**\n * @summary Read from the input file. If `n` is specified, returns the\n * next `n` bytes of the file as a Buffer. XXX not sure if this actually\n * returns a String sometimes...\n * @param {Integer} [n] The number of bytes to return.\n * @instance\n * @memberOf CompileStep\n * @returns {Buffer}\n */\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n\n /**\n * @summary Works in web targets only. Add markup to the `head` or `body`\n * section of the document.\n * @param {Object} options\n * @param {String} options.section Which section of the document should\n * be appended to. Can only be \"head\" or \"body\".\n * @param {String} options.data The content to append.\n * @memberOf CompileStep\n * @instance\n */\n addHtml: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"web targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')\n });\n },\n\n /**\n * @deprecated in 0.9.4\n */\n appendDocument: function (options) {\n this.addHtml(options);\n },\n\n /**\n * @summary Web targets only. Add a stylesheet to the document.\n * @param {Object} options\n * @param {String} path The requested path for the added CSS, may not be\n * satisfied if there are path conflicts.\n * @param {String} data The content of the stylesheet that should be\n * added.\n * @param {String} sourceMap A stringified JSON sourcemap, in case the\n * stylesheet was generated from a different file.\n * @memberOf CompileStep\n * @instance\n */\n addStylesheet: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"web targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n refreshable: true,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),\n servePath: colonConverter.convert(\n files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true))),\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath)\n });\n },\n\n /**\n * @summary Add JavaScript code. The code added will only see the\n * namespaces imported by this package as runtime dependencies using\n * ['api.use'](#PackageAPI-use). If the file being compiled was added\n * with the bare flag, the resulting JavaScript won't be wrapped in a\n * closure.\n * @param {Object} options\n * @param {String} options.path The path at which the JavaScript file\n * should be inserted, may not be honored in case of path conflicts.\n * @param {String} options.data The code to be added.\n * @param {String} options.sourcePath The path that will be used in\n * any error messages generated by this file, e.g. `foo.js:4:1: error`.\n * @memberOf CompileStep\n * @instance\n */\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n\n // By default, use fileOptions for the `bare` option but also allow\n // overriding it with the options\n var bare = fileOptions.bare;\n if (options.hasOwnProperty(\"bare\")) {\n bare = options.bare;\n }\n\n js.push({\n source: files.convertToStandardLineEndings(options.data),\n sourcePath: files.convertToStandardPath(options.sourcePath, true),\n servePath: files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true)),\n bare: !! bare,\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath),\n sourceHash: options._hash\n });\n },\n\n /**\n * @summary Add a file to serve as-is to the browser or to include on\n * the browser, depending on the target. On the web, it will be served\n * at the exact path requested. For server targets, it can be retrieved\n * using `Assets.getText` or `Assets.getBinary`.\n * @param {Object} options\n * @param {String} path The path at which to serve the asset.\n * @param {Buffer|String} data The data that should be placed in\n * the file.\n * @memberOf CompileStep\n * @instance\n */\n addAsset: function (options) {\n if (! (options.data instanceof Buffer)) {\n if (_.isString(options.data)) {\n options.data = new Buffer(options.data);\n } else {\n throw new Error(\"'data' option to addAsset must be a Buffer or String.\");\n }\n }\n\n addAsset(options.data, files.convertToStandardPath(options.path, true));\n },\n\n /**\n * @summary Display a build error.\n * @param {Object} options\n * @param {String} message The error message to display.\n * @param {String} [sourcePath] The path to display in the error message.\n * @param {Integer} line The line number to display in the error message.\n * @param {String} func The function name to display in the error message.\n * @memberOf CompileStep\n * @instance\n */\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // *** Run Phase 1 link\n\n // Load jsAnalyze from the js-analyze package... unless we are the\n // js-analyze package, in which case never mind. (The js-analyze package's\n // default unibuild is not allowed to depend on anything!)\n var jsAnalyze = null;\n if (! _.isEmpty(js) && inputSourceArch.pkg.name !== \"js-analyze\") {\n jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;\n }\n\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n // I was confused about this, so I am leaving a comment -- the\n // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.\n // XXX: If we change this, we can get rid of source arch names!\n combinedServePath: isApp ? null :\n \"/packages/\" + colonConverter.convert(\n inputSourceArch.pkg.name +\n (inputSourceArch.kind === \"main\" ? \"\" : (\":\" + inputSourceArch.kind)) +\n \".js\"),\n name: inputSourceArch.pkg.name || null,\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n jsAnalyze: jsAnalyze,\n noLineNumbers: noLineNumbers\n });\n\n // *** Determine captured variables\n var packageVariables = [];\n var packageVariableNames = {};\n _.each(inputSourceArch.declaredExports, function (symbol) {\n if (_.has(packageVariableNames, symbol.name))\n return;\n packageVariables.push({\n name: symbol.name,\n export: symbol.testOnly? \"tests\" : true\n });\n packageVariableNames[symbol.name] = true;\n });\n _.each(results.assignedVariables, function (name) {\n if (_.has(packageVariableNames, name))\n return;\n packageVariables.push({\n name: name\n });\n packageVariableNames[name] = true;\n });\n\n // *** Consider npm dependencies and portability\n var arch = inputSourceArch.arch;\n if (arch === \"os\" && ! isPortable) {\n // Contains non-portable compiled npm modules, so set arch correctly\n arch = archinfo.host();\n }\n if (! archinfo.matches(arch, \"os\")) {\n // npm modules only work on server architectures\n nodeModulesPath = undefined;\n }\n\n // *** Output unibuild object\n isopk.addUnibuild({\n kind: inputSourceArch.kind,\n arch: arch,\n uses: inputSourceArch.uses,\n implies: inputSourceArch.implies,\n watchSet: watchSet,\n nodeModulesPath: nodeModulesPath,\n prelinkFiles: results.files,\n packageVariables: packageVariables,\n resources: resources\n });\n\n return {\n pluginProviderPackageNames: pluginProviderPackageNames\n };\n};\n\nvar runLinters = function (\n inputSourceArch,\n isopackCache,\n wrappedSourceItems,\n linterPluginsByExtension) {\n // For linters, figure out what are the global imports from other packages\n // that we use directly, or are implied.\n var globalImports = ['Package', 'Assets', 'Npm'];\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: inputSourceArch.arch,\n isopackCache: isopackCache,\n skipUnordered: true,\n skipDebugOnly: true\n }, function (unibuild) {\n if (unibuild.pkg.name === inputSourceArch.pkg.name)\n return;\n _.each(unibuild.packageVariables, function (symbol) {\n if (symbol.export === true)\n globalImports.push(symbol.name);\n });\n });\n\n // For each file choose the longest extension handled by linters.\n var longestMatchingExt = {};\n _.each(wrappedSourceItems, function (wrappedSource) {\n var filename = files.pathBasename(wrappedSource.relPath);\n var parts = filename.split('.');\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(linterPluginsByExtension, extension)) {\n longestMatchingExt[wrappedSource.relPath] = extension;\n break;\n }\n }\n });\n\n // Run linters on files.\n _.each(linterPluginsByExtension, function (linters, ext) {\n var sourcesToLint = [];\n _.each(wrappedSourceItems, function (wrappedSource) {\n var relPath = wrappedSource.relPath;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n var source = wrappedSource.source;\n\n // only run linters matching the longest handled extension\n if (longestMatchingExt[relPath] !== ext)\n return;\n\n sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));\n });\n\n _.each(linters, function (linterDef) {\n // skip linters not relevant to the arch we are compiling for\n if (! linterDef.relevantForArch(inputSourceArch.arch))\n return;\n\n var linter = linterDef.instantiatePlugin();\n buildmessage.enterJob({\n title: \"linting files with \" + linterDef.isopack.name\n }, function () {\n try {\n var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));\n markedLinter(sourcesToLint, globalImports);\n } catch (e) {\n buildmessage.exception(e);\n }\n });\n });\n });\n};\n\n// Iterates over each in options.dependencies as well as unibuilds implied by\n// them. The packages in question need to already be built and in\n// options.isopackCache.\ncompiler.eachUsedUnibuild = function (\n options, callback) {\n buildmessage.assertInCapture();\n var dependencies = options.dependencies;\n var arch = options.arch;\n var isopackCache = options.isopackCache;\n\n var acceptableWeakPackages = options.acceptableWeakPackages || {};\n\n var processedUnibuildId = {};\n var usesToProcess = [];\n _.each(dependencies, function (use) {\n if (options.skipUnordered && use.unordered)\n return;\n if (use.weak && !_.has(acceptableWeakPackages, use.package))\n return;\n usesToProcess.push(use);\n });\n\n while (! _.isEmpty(usesToProcess)) {\n var use = usesToProcess.shift();\n\n var usedPackage = isopackCache.getIsopack(use.package);\n\n // Ignore this package if we were told to skip debug-only packages and it is\n // debug-only.\n if (usedPackage.debugOnly && options.skipDebugOnly)\n continue;\n\n var unibuild = usedPackage.getUnibuildAtArch(arch);\n if (!unibuild) {\n // The package exists but there's no unibuild for us. A buildmessage has\n // already been issued. Recover by skipping.\n continue;\n }\n\n if (_.has(processedUnibuildId, unibuild.id))\n continue;\n processedUnibuildId[unibuild.id] = true;\n\n callback(unibuild, {\n unordered: !!use.unordered,\n weak: !!use.weak\n });\n\n _.each(unibuild.implies, function (implied) {\n usesToProcess.push(implied);\n });\n }\n};\n", "file_path": "tools/compiler.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.9977085590362549, 0.040720369666814804, 0.0001607892627362162, 0.0001778471196303144, 0.18876564502716064]} {"hunk": {"id": 5, "code_window": [" source: source,\n", " 'package': isopk.name\n", " };\n", " });\n", "\n", " runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n", "\n", " _.each(wrappedSourceItems, function (wrappedSource) {\n", " var source = wrappedSource.source;\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" runLinters(inputSourceArch, isopackCache, wrappedSourceItems, allLinters);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 398}, "file": "# Defer in Inactive Tab\n\nTests that `Meteor.defer` works in an inactive tab in iOS Safari.\n\n(`setTimeout` and `setInterval` events aren't delivered to inactive\ntabs in iOS Safari until they become active again).\n\nSadly we have to run the test manually because scripts aren't allowed\nto open windows themselves except in response to user events.\n\nThis test will not run on Chrome for iOS because the storage event is\nnot implemented in that browser. Also doesn't attempt to run on\nversions of IE that don't support `window.addEventListener`.\n", "file_path": "examples/other/defer-in-inactive-tab/README.md", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001713009987724945, 0.00017110318003688008, 0.00017090536130126566, 0.00017110318003688008, 1.9781873561441898e-07]} {"hunk": {"id": 5, "code_window": [" source: source,\n", " 'package': isopk.name\n", " };\n", " });\n", "\n", " runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n", "\n", " _.each(wrappedSourceItems, function (wrappedSource) {\n", " var source = wrappedSource.source;\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" runLinters(inputSourceArch, isopackCache, wrappedSourceItems, allLinters);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 398}, "file": "====================================================================\nFor the license for Meteor itself, see LICENSE.txt in the root of\nthe repository. This file contains the licenses for externally\nmaintained libraries.\n====================================================================\n\n\n\n----------\nMongoDB: http://www.mongodb.org/\n----------\n\nLICENSE\n\n Most MongoDB source files are made available under the terms of the\n GNU Affero General Public License (AGPL). See individual files for\n details.\n\n As an exception, the files in the client/, debian/, rpm/,\n utils/mongoutils, and all subdirectories thereof are made available under\n the terms of the Apache License, version 2.0.\n\nhttp://www.gnu.org/licenses/agpl-3.0.html\nhttp://www.apache.org/licenses/LICENSE-2.0\n\n\nMongoDB uses third-party libraries or other resources that may\nbe distributed under licenses different than the MongoDB software.\n\nIn the event that we accidentally failed to list a required notice,\nplease bring it to our attention through any of the ways detailed here :\n\n mongodb-dev@googlegroups.com\n\nThe attached notices are provided for information only.\n\n\n1) License Notice for Boost\n---------------------------\n\nhttp://www.boost.org/LICENSE_1_0.txt\n\nBoost Software License - Version 1.0 - August 17th, 2003\n\nPermission is hereby granted, free of charge, to any person or organization\nobtaining a copy of the software and accompanying documentation covered by\nthis license (the \"Software\") to use, reproduce, display, distribute,\nexecute, and transmit the Software, and to prepare derivative works of the\nSoftware, and to permit third-parties to whom the Software is furnished to\ndo so, all subject to the following:\n\nThe copyright notices in the Software and this entire statement, including\nthe above license grant, this restriction and the following disclaimer,\nmust be included in all copies of the Software, in whole or in part, and\nall derivative works of the Software, unless such copies or derivative\nworks are solely in the form of machine-executable object code generated by\na source language processor.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\nSHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\nFOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n\n2) License Notice for V8\n-------------------------\n\nhttp://code.google.com/p/v8/source/browse/trunk/LICENSE\n\nThis license applies to all parts of V8 that are not externally\nmaintained libraries. The externally maintained libraries used by V8\nare:\n\n - Jscre, located under third_party/jscre. This code is copyrighted\n by the University of Cambridge and Apple Inc. and released under a\n 2-clause BSD license.\n\n - Dtoa, located under third_party/dtoa. This code is copyrighted by\n David M. Gay and released under an MIT license.\n\n - Strongtalk assembler, the basis of the files assembler-arm-inl.h,\n assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h,\n assembler-ia32.cc, assembler-ia32.h, assembler.cc and assembler.h.\n This code is copyrighted by Sun Microsystems Inc. and released\n under a 3-clause BSD license.\n\nThese libraries have their own licenses; we recommend you read them,\nas their terms may differ from the terms below.\n\nCopyright 2006-2008, Google Inc. All rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n * Neither the name of Google Inc. nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n3) License Notice for PCRE\n--------------------------\n\nhttp://www.pcre.org/licence.txt\n\nPCRE LICENCE\n------------\n\nPCRE is a library of functions to support regular expressions whose syntax\nand semantics are as close as possible to those of the Perl 5 language.\n\nRelease 7 of PCRE is distributed under the terms of the \"BSD\" licence, as\nspecified below. The documentation for PCRE, supplied in the \"doc\"\ndirectory, is distributed under the same terms as the software itself.\n\nThe basic library functions are written in C and are freestanding. Also\nincluded in the distribution is a set of C++ wrapper functions.\n\n\nTHE BASIC LIBRARY FUNCTIONS\n---------------------------\n\nWritten by: Philip Hazel\nEmail local part: ph10\nEmail domain: cam.ac.uk\n\nUniversity of Cambridge Computing Service,\nCambridge, England.\n\nCopyright (c) 1997-2008 University of Cambridge\nAll rights reserved.\n\n\nTHE C++ WRAPPER FUNCTIONS\n-------------------------\n\nContributed by: Google Inc.\n\nCopyright (c) 2007-2008, Google Inc.\nAll rights reserved.\n\n\nTHE \"BSD\" LICENCE\n-----------------\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n * Neither the name of the University of Cambridge nor the name of Google\n Inc. nor the names of their contributors may be used to endorse or\n promote products derived from this software without specific prior\n written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n\n4) License notice for Aladdin MD5\n---------------------------------\n\nCopyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved.\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n\nL. Peter Deutsch\nghost@aladdin.com\n\n5) License notice for Snappy - http://code.google.com/p/snappy/\n---------------------------------\n Copyright 2005 and onwards Google Inc.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following disclaimer\n in the documentation and/or other materials provided with the\n distribution.\n * Neither the name of Google Inc. nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n A light-weight compression algorithm. It is designed for speed of\n compression and decompression, rather than for the utmost in space\n savings.\n\n For getting better compression ratios when you are compressing data\n with long repeated sequences or compressing data that is similar to\n other data, while still compressing fast, you might look at first\n using BMDiff and then compressing the output of BMDiff with\n Snappy.\n\n\n\nEnd\n", "file_path": "LICENSES/MongoDB.txt", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.0001815298746805638, 0.00017312867566943169, 0.00016172749747056514, 0.00017476585344411433, 5.156939096195856e-06]} {"hunk": {"id": 5, "code_window": [" source: source,\n", " 'package': isopk.name\n", " };\n", " });\n", "\n", " runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n", "\n", " _.each(wrappedSourceItems, function (wrappedSource) {\n", " var source = wrappedSource.source;\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" runLinters(inputSourceArch, isopackCache, wrappedSourceItems, allLinters);\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 398}, "file": "0.6.0\n", "file_path": "examples/other/quiescence/.meteor/release", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.000175882873008959, 0.000175882873008959, 0.000175882873008959, 0.000175882873008959, 0.0]} {"hunk": {"id": 6, "code_window": ["\n", "var runLinters = function (\n", " inputSourceArch,\n", " isopackCache,\n", " wrappedSourceItems,\n", " linterPluginsByExtension) {\n", " // For linters, figure out what are the global imports from other packages\n", " // that we use directly, or are implied.\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": [" linters) {\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 954}, "file": "var _ = require('underscore');\n\nvar archinfo = require('./archinfo.js');\nvar buildmessage = require('./buildmessage.js');\nvar bundler = require('./bundler.js');\nvar isopack = require('./isopack.js');\nvar isopackets = require('./isopackets.js');\nvar linker = require('./linker.js');\nvar meteorNpm = require('./meteor-npm.js');\nvar watch = require('./watch.js');\nvar Console = require('./console.js').Console;\nvar files = require('./files.js');\nvar colonConverter = require('./colon-converter.js');\nvar linterPluginModule = require('./linter-plugin.js');\n\nvar compiler = exports;\n\n// Whenever you change anything about the code that generates isopacks, bump\n// this version number. The idea is that the \"format\" field of the isopack\n// JSON file only changes when the actual specified structure of the\n// isopack/unibuild changes, but this version (which is build-tool-specific)\n// can change when the the contents (not structure) of the built output\n// changes. So eg, if we improve the linker's static analysis, this should be\n// bumped.\n//\n// You should also update this whenever you update any of the packages used\n// directly by the isopack creation process (eg js-analyze) since they do not\n// end up as watched dependencies. (At least for now, packages only used in\n// target creation (eg minifiers) don't require you to update BUILT_BY, though\n// you will need to quit and rerun \"meteor run\".)\ncompiler.BUILT_BY = 'meteor/16';\n\n// This is a list of all possible architectures that a build can target. (Client\n// is expanded into 'web.browser' and 'web.cordova')\ncompiler.ALL_ARCHES = [ \"os\", \"web.browser\", \"web.cordova\" ];\n\ncompiler.compile = function (packageSource, options) {\n buildmessage.assertInCapture();\n\n var packageMap = options.packageMap;\n var isopackCache = options.isopackCache;\n var includeCordovaUnibuild = options.includeCordovaUnibuild;\n\n var pluginWatchSet = packageSource.pluginWatchSet.clone();\n var plugins = {};\n\n var pluginProviderPackageNames = {};\n\n // Build plugins\n _.each(packageSource.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + packageSource.name + \"`\",\n rootPath: packageSource.sourceRoot\n }, function () {\n // XXX we should probably also pass options.noLineNumbers into\n // buildJsImage so it can pass it back to its call to\n // compiler.compile\n var buildResult = bundler.buildJsImage({\n name: info.name,\n packageMap: packageMap,\n isopackCache: isopackCache,\n use: info.use,\n sourceRoot: packageSource.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: files.pathResolve(\n files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))\n });\n // Add this plugin's dependencies to our \"plugin dependency\"\n // WatchSet. buildResult.watchSet will end up being the merged\n // watchSets of all of the unibuilds of the plugin -- plugins have\n // only one unibuild and this should end up essentially being just\n // the source files of the plugin.\n //\n // Note that we do this even on error, so that you can fix the error\n // and have the runner restart.\n pluginWatchSet.merge(buildResult.watchSet);\n\n if (buildmessage.jobHasMessages())\n return;\n\n _.each(buildResult.usedPackageNames, function (packageName) {\n pluginProviderPackageNames[packageName] = true;\n });\n\n // Register the built plugin's code.\n if (!_.has(plugins, info.name))\n plugins[info.name] = {};\n plugins[info.name][buildResult.image.arch] = buildResult.image;\n });\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n //\n // Go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any (sub)dependencies. This\n // process also runs mostly safely multiple times in parallel (which\n // could happen if you have two apps running locally using the same\n // package).\n //\n // We run this even if we have no dependencies, because we might\n // need to delete dependencies we used to have.\n var isPortable = true;\n var nodeModulesPath = null;\n if (packageSource.npmCacheDirectory) {\n if (meteorNpm.updateDependencies(packageSource.name,\n packageSource.npmCacheDirectory,\n packageSource.npmDependencies)) {\n nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,\n 'node_modules');\n if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))\n isPortable = false;\n }\n }\n\n var isopk = new isopack.Isopack;\n isopk.initFromOptions({\n name: packageSource.name,\n metadata: packageSource.metadata,\n version: packageSource.version,\n isTest: packageSource.isTest,\n plugins: plugins,\n pluginWatchSet: pluginWatchSet,\n cordovaDependencies: packageSource.cordovaDependencies,\n npmDiscards: packageSource.npmDiscards,\n includeTool: packageSource.includeTool,\n debugOnly: packageSource.debugOnly\n });\n\n _.each(packageSource.architectures, function (unibuild) {\n if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)\n return;\n\n var unibuildResult = compileUnibuild({\n isopack: isopk,\n sourceArch: unibuild,\n isopackCache: isopackCache,\n nodeModulesPath: nodeModulesPath,\n isPortable: isPortable,\n noLineNumbers: options.noLineNumbers\n });\n _.extend(pluginProviderPackageNames,\n unibuildResult.pluginProviderPackageNames);\n });\n\n if (options.includePluginProviderPackageMap) {\n isopk.setPluginProviderPackageMap(\n packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));\n }\n\n return isopk;\n};\n\n// options.sourceArch is a SourceArch to compile. Process all source files\n// through the appropriate handlers and run the prelink phase on any resulting\n// JavaScript. Create a new Unibuild and add it to options.isopack.\n//\n// Returns a list of source files that were used in the compilation.\nvar compileUnibuild = function (options) {\n buildmessage.assertInCapture();\n\n var isopk = options.isopack;\n var inputSourceArch = options.sourceArch;\n var isopackCache = options.isopackCache;\n var nodeModulesPath = options.nodeModulesPath;\n var isPortable = options.isPortable;\n var noLineNumbers = options.noLineNumbers;\n\n var isApp = ! inputSourceArch.pkg.name;\n var resources = [];\n var js = [];\n var pluginProviderPackageNames = {};\n // The current package always is a plugin provider. (This also means we no\n // longer need a buildOfPath entry in buildinfo.json.)\n pluginProviderPackageNames[isopk.name] = true;\n var watchSet = inputSourceArch.watchSet.clone();\n\n // *** Determine and load active plugins\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't have\n // a special \"use\" role anymore. it's not totally clear to me what\n // the correct behavior should be -- we need to resolve whether we\n // think about extensions as being global to a package or particular\n // to a unibuild.\n\n // (there's also some weirdness here with handling implies, because\n // the implies field is on the target unibuild, but we really only care\n // about packages.)\n var activePluginPackages = [isopk];\n\n // We don't use plugins from weak dependencies, because the ability\n // to compile a certain type of file shouldn't depend on whether or\n // not some unrelated package in the target has a dependency. And we\n // skip unordered dependencies, because it's not going to work to\n // have circular build-time dependencies.\n //\n // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,\n // templating from standard-app-packages).\n //\n // We pass archinfo.host here, not self.arch, because it may be more specific,\n // and because plugins always have to run on the host architecture.\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: archinfo.host(),\n isopackCache: isopackCache,\n skipUnordered: true\n // implicitly skip weak deps by not specifying acceptableWeakPackages option\n }, function (unibuild) {\n if (unibuild.pkg.name === isopk.name)\n return;\n pluginProviderPackageNames[unibuild.pkg.name] = true;\n // If other package is built from source, then we need to rebuild this\n // package if any file in the other package that could define a plugin\n // changes.\n watchSet.merge(unibuild.pkg.pluginWatchSet);\n\n if (_.isEmpty(unibuild.pkg.plugins))\n return;\n activePluginPackages.push(unibuild.pkg);\n });\n\n activePluginPackages = _.uniq(activePluginPackages);\n\n // *** Assemble the list of source file handlers from the plugins\n // XXX BBP redoc\n var allHandlersWithPkgs = {};\n var compilerPluginsByExtension = {};\n var linterPluginsByExtension = {};\n var sourceExtensions = {}; // maps source extensions to isTemplate\n\n sourceExtensions['js'] = false;\n allHandlersWithPkgs['js'] = {\n pkgName: null /* native handler */,\n handler: function (compileStep) {\n // This is a hardcoded handler for *.js files. Since plugins\n // are written in JavaScript we have to start somewhere.\n\n var options = {\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n _hash: compileStep._hash\n };\n\n if (compileStep.fileOptions.hasOwnProperty(\"bare\")) {\n options.bare = compileStep.fileOptions.bare;\n } else if (compileStep.fileOptions.hasOwnProperty(\"raw\")) {\n // XXX eventually get rid of backward-compatibility \"raw\" name\n // XXX COMPAT WITH 0.6.4\n options.bare = compileStep.fileOptions.raw;\n }\n\n compileStep.addJavaScript(options);\n }\n };\n\n _.each(activePluginPackages, function (otherPkg) {\n otherPkg.ensurePluginsInitialized();\n\n // Iterate over the legacy source handlers.\n _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {\n // XXX comparing function text here seems wrong.\n if (_.has(allHandlersWithPkgs, ext) &&\n allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n return;\n }\n // Is this handler only registered for, say, \"web\", and we're building,\n // say, \"os\"?\n if (sourceHandler.archMatching &&\n !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {\n return;\n }\n allHandlersWithPkgs[ext] = {\n pkgName: otherPkg.name,\n handler: sourceHandler.handler\n };\n sourceExtensions[ext] = !!sourceHandler.isTemplate;\n });\n\n // Iterate over the compiler plugins.\n _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {\n _.each(compilerPlugin.extensions, function (ext) {\n if (_.has(allHandlersWithPkgs, ext) ||\n _.has(compilerPluginsByExtension, ext)) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first one we found.\n return;\n }\n compilerPluginsByExtension[ext] = compilerPlugin;\n sourceExtensions[ext] = compilerPlugin.isTemplate;\n });\n });\n\n // Iterate over the linters\n _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n _.each(linterPlugin.extensions, function (ext) {\n linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n linterPluginsByExtension[ext].push(linterPlugin);\n });\n });\n });\n\n // *** Determine source files\n // Note: sourceExtensions does not include leading dots\n // Note: the getSourcesFunc function isn't expected to add its\n // source files to watchSet; rather, the watchSet is for other\n // things that the getSourcesFunc consulted (such as directory\n // listings or, in some hypothetical universe, control files) to\n // determine its source files.\n var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);\n\n if (nodeModulesPath) {\n // If this slice has node modules, we should consider the shrinkwrap file\n // to be part of its inputs. (This is a little racy because there's no\n // guarantee that what we read here is precisely the version that's used,\n // but it's better than nothing at all.)\n //\n // Note that this also means that npm modules used by plugins will get\n // this npm-shrinkwrap.json in their pluginDependencies (including for all\n // packages that depend on us)! This is good: this means that a tweak to\n // an indirect dependency of the coffee-script npm module used by the\n // coffeescript package will correctly cause packages with *.coffee files\n // to be rebuilt.\n var shrinkwrapPath = nodeModulesPath.replace(\n /node_modules$/, 'npm-shrinkwrap.json');\n watch.readAndWatchFile(watchSet, shrinkwrapPath);\n }\n\n // *** Process each source file\n var addAsset = function (contents, relPath, hash) {\n // XXX hack\n if (! inputSourceArch.pkg.name)\n relPath = relPath.replace(/^(private|public)\\//, '');\n\n resources.push({\n type: \"asset\",\n data: contents,\n path: relPath,\n servePath: colonConverter.convert(\n files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),\n hash: hash\n });\n };\n\n var convertSourceMapPaths = function (sourcemap, f) {\n if (! sourcemap) {\n // Don't try to convert it if it doesn't exist\n return sourcemap;\n }\n\n var srcmap = JSON.parse(sourcemap);\n srcmap.sources = _.map(srcmap.sources, f);\n return JSON.stringify(srcmap);\n };\n\n var wrappedSourceItems = _.map(sourceItems, function (source) {\n var fileWatchSet = new watch.WatchSet;\n // readAndWatchFileWithHash returns an object carrying a buffer with the\n // file-contents. The buffer contains the original data of the file (no EOL\n // transforms from the tools/files.js part).\n // We don't put this into the unibuild's watchSet immediately since we want\n // to avoid putting it there if it turns out not to be relevant to our\n // arch.\n var absPath = files.pathResolve(\n inputSourceArch.pkg.sourceRoot, source.relPath);\n var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);\n\n Console.nudge(true);\n\n return {\n relPath: source.relPath,\n watchset: fileWatchSet,\n contents: file.contents,\n hash: file.hash,\n source: source,\n 'package': isopk.name\n };\n });\n\n runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n\n _.each(wrappedSourceItems, function (wrappedSource) {\n var source = wrappedSource.source;\n var relPath = source.relPath;\n var fileOptions = _.clone(source.fileOptions) || {};\n var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);\n var filename = files.pathBasename(relPath);\n var contents = wrappedSource.contents;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n\n Console.nudge(true);\n\n if (contents === null) {\n // It really sucks to put this check here, since this isn't publish\n // code...\n if (source.relPath.match(/:/)) {\n buildmessage.error(\n \"Couldn't build this package on Windows due to the following file \" +\n \"with a colon -- \" + source.relPath + \". Please rename and \" +\n \"and re-publish the package.\");\n } else {\n buildmessage.error(\"File not found: \" + source.relPath);\n }\n\n // recover by ignoring (but still watching the file)\n watchSet.merge(fileWatchSet);\n return;\n }\n\n // Find the handler for source files with this extension.\n var handler = null;\n var isBuildPluginSource = false;\n if (! fileOptions.isAsset) {\n var parts = filename.split('.');\n // don't use iteration functions, so we can return/break\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(compilerPluginsByExtension, extension)) {\n var compilerPlugin = compilerPluginsByExtension[extension];\n if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {\n // This file is for a compiler plugin but not for this arch. Skip\n // it, and don't even watch it. (eg, skip CSS preprocessor files on\n // the server.)\n return;\n }\n isBuildPluginSource = true;\n break;\n }\n if (_.has(allHandlersWithPkgs, extension)) {\n handler = allHandlersWithPkgs[extension].handler;\n break;\n }\n }\n }\n\n // OK, this is relevant to this arch, so watch it.\n watchSet.merge(fileWatchSet);\n\n if (isBuildPluginSource) {\n // This is source used by a new-style compiler plugin; it will be fully\n // processed later in the bundler.\n resources.push({\n type: \"source\",\n data: contents,\n path: relPath,\n hash: hash\n });\n return;\n }\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n addAsset(contents, relPath, hash);\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript).\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - pathForSourceMap: If this file is to be included in a source map,\n // this is the name you should use for it in the map.\n // - rootOutputPath: on web targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-web targets\n // - fileOptions: any options passed to \"api.addFiles\"; for\n // use by the plugin. The built-in \"js\" plugin uses the \"bare\"\n // option for files that shouldn't be wrapped in a closure.\n // - declaredExports: An array of symbols exported by this unibuild, or null\n // if it may not export any symbols (eg, test unibuilds). This is used by\n // CoffeeScript to ensure that it doesn't close over those symbols, eg.\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // Web targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\",\n // sourceMap: \"stringified json sourcemap\"})\n // Web targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // bare: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. \"bare\" means to not wrap the file in\n // a closure, so that its vars are shared with other files\n // in the module.\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Add a file to serve as-is over HTTP (web targets) or\n // to include as-is in the bundle (os targets).\n // This time `data` is a Buffer rather than a string. For\n // web targets, it will be served at the exact path you\n // request (concatenated with rootOutputPath). For server\n // targets, the file can be retrieved by passing path to\n // Assets.getText or Assets.getBinary.\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces). sourcePath,\n // line, column, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'web'\n // vs 'os') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific unibuild will be emitted only if\n // there are native node modules). Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force unibuilds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n\n /**\n * The comments for this class aren't used to generate docs right now.\n * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers\n * @class CompileStep\n * @summary The object passed into Plugin.registerSourceHandler\n * @global\n */\n var compileStep = {\n\n /**\n * @summary The total number of bytes in the input file.\n * @memberOf CompileStep\n * @instance\n * @type {Integer}\n */\n inputSize: contents.length,\n\n /**\n * @summary The filename and relative path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n inputPath: files.convertToOSPath(relPath, true),\n\n /**\n * @summary The filename and absolute path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n fullInputPath: files.convertToOSPath(absPath),\n\n // The below is used in the less and stylus packages... so it should be\n // public API.\n _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..\n\n // Used for one optimization. Don't rely on this otherwise.\n _hash: hash,\n\n // XXX duplicates _pathForSourceMap() in linker\n /**\n * @summary If you are generating a sourcemap for the compiled file, use\n * this path for the original file in the sourcemap.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n pathForSourceMap: files.convertToOSPath(\n inputSourceArch.pkg.name ? inputSourceArch.pkg.name + \"/\" + relPath :\n files.pathBasename(relPath), true),\n\n // null if this is an app. intended to be used for the sources\n // dictionary for source maps.\n /**\n * @summary The name of the package in which the file being built exists.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n packageName: inputSourceArch.pkg.name,\n\n /**\n * @summary On web targets, this will be the root URL prepended\n * to the paths you pick for your output files. For example,\n * it could be \"/packages/my-package\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n rootOutputPath: files.convertToOSPath(\n inputSourceArch.pkg.serveRoot, true),\n\n /**\n * @summary The architecture for which we are building. Can be \"os\",\n * \"web.browser\", or \"web.cordova\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n arch: inputSourceArch.arch,\n\n /**\n * @deprecated in 0.9.4\n * This is a duplicate API of the above, we don't need it.\n */\n archMatches: function (pattern) {\n return archinfo.matches(inputSourceArch.arch, pattern);\n },\n\n /**\n * @summary Any options passed to \"api.addFiles\".\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n fileOptions: fileOptions,\n\n /**\n * @summary The list of exports that the current package has defined.\n * Can be used to treat those symbols differently during compilation.\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n\n /**\n * @summary Read from the input file. If `n` is specified, returns the\n * next `n` bytes of the file as a Buffer. XXX not sure if this actually\n * returns a String sometimes...\n * @param {Integer} [n] The number of bytes to return.\n * @instance\n * @memberOf CompileStep\n * @returns {Buffer}\n */\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n\n /**\n * @summary Works in web targets only. Add markup to the `head` or `body`\n * section of the document.\n * @param {Object} options\n * @param {String} options.section Which section of the document should\n * be appended to. Can only be \"head\" or \"body\".\n * @param {String} options.data The content to append.\n * @memberOf CompileStep\n * @instance\n */\n addHtml: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"web targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')\n });\n },\n\n /**\n * @deprecated in 0.9.4\n */\n appendDocument: function (options) {\n this.addHtml(options);\n },\n\n /**\n * @summary Web targets only. Add a stylesheet to the document.\n * @param {Object} options\n * @param {String} path The requested path for the added CSS, may not be\n * satisfied if there are path conflicts.\n * @param {String} data The content of the stylesheet that should be\n * added.\n * @param {String} sourceMap A stringified JSON sourcemap, in case the\n * stylesheet was generated from a different file.\n * @memberOf CompileStep\n * @instance\n */\n addStylesheet: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"web targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n refreshable: true,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),\n servePath: colonConverter.convert(\n files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true))),\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath)\n });\n },\n\n /**\n * @summary Add JavaScript code. The code added will only see the\n * namespaces imported by this package as runtime dependencies using\n * ['api.use'](#PackageAPI-use). If the file being compiled was added\n * with the bare flag, the resulting JavaScript won't be wrapped in a\n * closure.\n * @param {Object} options\n * @param {String} options.path The path at which the JavaScript file\n * should be inserted, may not be honored in case of path conflicts.\n * @param {String} options.data The code to be added.\n * @param {String} options.sourcePath The path that will be used in\n * any error messages generated by this file, e.g. `foo.js:4:1: error`.\n * @memberOf CompileStep\n * @instance\n */\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n\n // By default, use fileOptions for the `bare` option but also allow\n // overriding it with the options\n var bare = fileOptions.bare;\n if (options.hasOwnProperty(\"bare\")) {\n bare = options.bare;\n }\n\n js.push({\n source: files.convertToStandardLineEndings(options.data),\n sourcePath: files.convertToStandardPath(options.sourcePath, true),\n servePath: files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true)),\n bare: !! bare,\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath),\n sourceHash: options._hash\n });\n },\n\n /**\n * @summary Add a file to serve as-is to the browser or to include on\n * the browser, depending on the target. On the web, it will be served\n * at the exact path requested. For server targets, it can be retrieved\n * using `Assets.getText` or `Assets.getBinary`.\n * @param {Object} options\n * @param {String} path The path at which to serve the asset.\n * @param {Buffer|String} data The data that should be placed in\n * the file.\n * @memberOf CompileStep\n * @instance\n */\n addAsset: function (options) {\n if (! (options.data instanceof Buffer)) {\n if (_.isString(options.data)) {\n options.data = new Buffer(options.data);\n } else {\n throw new Error(\"'data' option to addAsset must be a Buffer or String.\");\n }\n }\n\n addAsset(options.data, files.convertToStandardPath(options.path, true));\n },\n\n /**\n * @summary Display a build error.\n * @param {Object} options\n * @param {String} message The error message to display.\n * @param {String} [sourcePath] The path to display in the error message.\n * @param {Integer} line The line number to display in the error message.\n * @param {String} func The function name to display in the error message.\n * @memberOf CompileStep\n * @instance\n */\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // *** Run Phase 1 link\n\n // Load jsAnalyze from the js-analyze package... unless we are the\n // js-analyze package, in which case never mind. (The js-analyze package's\n // default unibuild is not allowed to depend on anything!)\n var jsAnalyze = null;\n if (! _.isEmpty(js) && inputSourceArch.pkg.name !== \"js-analyze\") {\n jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;\n }\n\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n // I was confused about this, so I am leaving a comment -- the\n // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.\n // XXX: If we change this, we can get rid of source arch names!\n combinedServePath: isApp ? null :\n \"/packages/\" + colonConverter.convert(\n inputSourceArch.pkg.name +\n (inputSourceArch.kind === \"main\" ? \"\" : (\":\" + inputSourceArch.kind)) +\n \".js\"),\n name: inputSourceArch.pkg.name || null,\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n jsAnalyze: jsAnalyze,\n noLineNumbers: noLineNumbers\n });\n\n // *** Determine captured variables\n var packageVariables = [];\n var packageVariableNames = {};\n _.each(inputSourceArch.declaredExports, function (symbol) {\n if (_.has(packageVariableNames, symbol.name))\n return;\n packageVariables.push({\n name: symbol.name,\n export: symbol.testOnly? \"tests\" : true\n });\n packageVariableNames[symbol.name] = true;\n });\n _.each(results.assignedVariables, function (name) {\n if (_.has(packageVariableNames, name))\n return;\n packageVariables.push({\n name: name\n });\n packageVariableNames[name] = true;\n });\n\n // *** Consider npm dependencies and portability\n var arch = inputSourceArch.arch;\n if (arch === \"os\" && ! isPortable) {\n // Contains non-portable compiled npm modules, so set arch correctly\n arch = archinfo.host();\n }\n if (! archinfo.matches(arch, \"os\")) {\n // npm modules only work on server architectures\n nodeModulesPath = undefined;\n }\n\n // *** Output unibuild object\n isopk.addUnibuild({\n kind: inputSourceArch.kind,\n arch: arch,\n uses: inputSourceArch.uses,\n implies: inputSourceArch.implies,\n watchSet: watchSet,\n nodeModulesPath: nodeModulesPath,\n prelinkFiles: results.files,\n packageVariables: packageVariables,\n resources: resources\n });\n\n return {\n pluginProviderPackageNames: pluginProviderPackageNames\n };\n};\n\nvar runLinters = function (\n inputSourceArch,\n isopackCache,\n wrappedSourceItems,\n linterPluginsByExtension) {\n // For linters, figure out what are the global imports from other packages\n // that we use directly, or are implied.\n var globalImports = ['Package', 'Assets', 'Npm'];\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: inputSourceArch.arch,\n isopackCache: isopackCache,\n skipUnordered: true,\n skipDebugOnly: true\n }, function (unibuild) {\n if (unibuild.pkg.name === inputSourceArch.pkg.name)\n return;\n _.each(unibuild.packageVariables, function (symbol) {\n if (symbol.export === true)\n globalImports.push(symbol.name);\n });\n });\n\n // For each file choose the longest extension handled by linters.\n var longestMatchingExt = {};\n _.each(wrappedSourceItems, function (wrappedSource) {\n var filename = files.pathBasename(wrappedSource.relPath);\n var parts = filename.split('.');\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(linterPluginsByExtension, extension)) {\n longestMatchingExt[wrappedSource.relPath] = extension;\n break;\n }\n }\n });\n\n // Run linters on files.\n _.each(linterPluginsByExtension, function (linters, ext) {\n var sourcesToLint = [];\n _.each(wrappedSourceItems, function (wrappedSource) {\n var relPath = wrappedSource.relPath;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n var source = wrappedSource.source;\n\n // only run linters matching the longest handled extension\n if (longestMatchingExt[relPath] !== ext)\n return;\n\n sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));\n });\n\n _.each(linters, function (linterDef) {\n // skip linters not relevant to the arch we are compiling for\n if (! linterDef.relevantForArch(inputSourceArch.arch))\n return;\n\n var linter = linterDef.instantiatePlugin();\n buildmessage.enterJob({\n title: \"linting files with \" + linterDef.isopack.name\n }, function () {\n try {\n var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));\n markedLinter(sourcesToLint, globalImports);\n } catch (e) {\n buildmessage.exception(e);\n }\n });\n });\n });\n};\n\n// Iterates over each in options.dependencies as well as unibuilds implied by\n// them. The packages in question need to already be built and in\n// options.isopackCache.\ncompiler.eachUsedUnibuild = function (\n options, callback) {\n buildmessage.assertInCapture();\n var dependencies = options.dependencies;\n var arch = options.arch;\n var isopackCache = options.isopackCache;\n\n var acceptableWeakPackages = options.acceptableWeakPackages || {};\n\n var processedUnibuildId = {};\n var usesToProcess = [];\n _.each(dependencies, function (use) {\n if (options.skipUnordered && use.unordered)\n return;\n if (use.weak && !_.has(acceptableWeakPackages, use.package))\n return;\n usesToProcess.push(use);\n });\n\n while (! _.isEmpty(usesToProcess)) {\n var use = usesToProcess.shift();\n\n var usedPackage = isopackCache.getIsopack(use.package);\n\n // Ignore this package if we were told to skip debug-only packages and it is\n // debug-only.\n if (usedPackage.debugOnly && options.skipDebugOnly)\n continue;\n\n var unibuild = usedPackage.getUnibuildAtArch(arch);\n if (!unibuild) {\n // The package exists but there's no unibuild for us. A buildmessage has\n // already been issued. Recover by skipping.\n continue;\n }\n\n if (_.has(processedUnibuildId, unibuild.id))\n continue;\n processedUnibuildId[unibuild.id] = true;\n\n callback(unibuild, {\n unordered: !!use.unordered,\n weak: !!use.weak\n });\n\n _.each(unibuild.implies, function (implied) {\n usesToProcess.push(implied);\n });\n }\n};\n", "file_path": "tools/compiler.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.999319314956665, 0.2670399844646454, 0.00016299683193210512, 0.00031431129900738597, 0.4232335686683655]} {"hunk": {"id": 6, "code_window": ["\n", "var runLinters = function (\n", " inputSourceArch,\n", " isopackCache,\n", " wrappedSourceItems,\n", " linterPluginsByExtension) {\n", " // For linters, figure out what are the global imports from other packages\n", " // that we use directly, or are implied.\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": [" linters) {\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 954}, "file": "var getNonZeroWeightedTerms = function (costTerms, costWeights) {\n if (typeof costWeights === 'number') {\n return costWeights ? costTerms : [];\n } else {\n var terms = [];\n for (var i = 0; i < costTerms.length; i++) {\n if (costWeights[i]) {\n terms.push(costTerms[i]);\n }\n }\n return terms;\n }\n};\n\n// See comments on minimizeWeightedSum and maximizeWeightedSum.\nvar minMaxWS = function (solver, solution, costTerms, costWeights, options,\n isMin) {\n var curSolution = solution;\n var curCost = curSolution.getWeightedSum(costTerms, costWeights);\n\n var optFormula = options && options.formula;\n var weightedSum = (optFormula || Logic.weightedSum(costTerms, costWeights));\n\n var progress = options && options.progress;\n var strategy = options && options.strategy;\n\n // array of terms with non-zero weights, populated on demand\n var nonZeroTerms = null;\n\n if (isMin && curCost > 0) {\n // try to skip straight to 0 cost, because if it works, it could\n // save us some time\n if (progress) {\n progress('trying', 0);\n }\n var zeroSolution = null;\n nonZeroTerms = getNonZeroWeightedTerms(costTerms, costWeights);\n var zeroSolution = solver.solveAssuming(Logic.not(Logic.or(nonZeroTerms)));\n if (zeroSolution) {\n curSolution = zeroSolution;\n curCost = 0;\n }\n }\n\n if (isMin && strategy === 'bottom-up') {\n for (var trialCost = 1; trialCost < curCost; trialCost++) {\n if (progress) {\n progress('trying', trialCost);\n }\n var costIsTrialCost = Logic.equalBits(\n weightedSum, Logic.constantBits(trialCost));\n var newSolution = solver.solveAssuming(costIsTrialCost);\n if (newSolution) {\n curSolution = newSolution;\n curCost = trialCost;\n break;\n }\n }\n } else if (strategy && strategy !== 'default') {\n throw new Error(\"Bad strategy: \" + strategy);\n } else {\n strategy = 'default';\n }\n\n if (strategy === 'default') {\n // for minimization, count down from current cost. for maximization,\n // count up.\n while (isMin ? curCost > 0 : true) {\n if (progress) {\n progress('improving', curCost);\n }\n var improvement = (isMin ? Logic.lessThan : Logic.greaterThan)(\n weightedSum, Logic.constantBits(curCost));\n var newSolution = solver.solveAssuming(improvement);\n if (! newSolution) {\n break;\n }\n solver.require(improvement);\n curSolution = newSolution;\n curCost = curSolution.getWeightedSum(costTerms, costWeights);\n }\n }\n\n if (isMin && curCost === 0) {\n // express the requirement that the weighted sum be 0 in an efficient\n // way for the solver (all terms with non-zero weights must be 0)\n if (! nonZeroTerms) {\n nonZeroTerms = getNonZeroWeightedTerms(costTerms, costWeights);\n }\n solver.forbid(nonZeroTerms);\n } else {\n solver.require(Logic.equalBits(weightedSum, Logic.constantBits(curCost)));\n }\n\n if (progress) {\n progress('finished', curCost);\n }\n\n return curSolution;\n};\n\n// Minimize (or maximize) the dot product of costTerms and\n// costWeights, and further, require (as in solver.require) that the\n// value of the dot product be equal to the optimum found. Returns a\n// valid solution where this optimum is achieved.\n//\n// `solution` must be a current valid solution as returned from\n// `solve` or `solveAssuming`. It is used as a starting point (to\n// evaluate the current cost).\n//\n// costWeights is an array (of same length as costTerms) or a single\n// WholeNumber.\n//\n// if the caller passes options.formula, it should be the formula\n// Logic.weightedSum(costTerms, costWeights). The optimizer will use\n// this existing formula rather than generating a new one (for\n// efficiency). The optimizer still wants to know the terms and\n// weights, because it is more efficient for it to evaluate the\n// current cost using them directly rather than the formula.\n//\n// options.progress: a function that takes two arguments, to call at\n// particular times during optimization. Called with arguments\n// ('improving', cost) when about to search for a way to improve on\n// `cost`, and called with arguments ('finished', cost) when the\n// optimum is reached. There's also ('trying', cost) when a cost\n// is tried directly (which is usually done with 0 right off the bat).\n//\n// options.strategy: a string hinting how to go about the optimization.\n// the default strategy (option absent or 'default') is to work down\n// from the current cost for minimization or up from the current cost\n// for maximization, and iteratively insist that the cost be made lower\n// if possible. For minimization, the alternate strategy 'bottom-up' is\n// available, which starts at 0 and tries ever higher costs until one\n// works. All strategies first try and see if a cost of 0 is possible.\n\n// (\"costTerms\" is kind of a misnomer since they may be Formulas or Terms.)\nLogic.Solver.prototype.minimizeWeightedSum = function (solution, costTerms,\n costWeights, options) {\n return minMaxWS(this, solution, costTerms, costWeights, options, true);\n};\n\nLogic.Solver.prototype.maximizeWeightedSum = function (solution, costTerms,\n costWeights, options) {\n return minMaxWS(this, solution, costTerms, costWeights, options, false);\n};\n", "file_path": "packages/logic-solver/optimize.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00017651828238740563, 0.00017128317267633975, 0.0001646942546358332, 0.0001721861190162599, 3.630294258982758e-06]} {"hunk": {"id": 6, "code_window": ["\n", "var runLinters = function (\n", " inputSourceArch,\n", " isopackCache,\n", " wrappedSourceItems,\n", " linterPluginsByExtension) {\n", " // For linters, figure out what are the global imports from other packages\n", " // that we use directly, or are implied.\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": [" linters) {\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 954}, "file": "// URL parsing and validation\n// RPC to server (endpoint, arguments)\n// see if RPC requires password\n// prompt for password\n// send RPC with or without password as required\n\nvar qs = require('querystring');\nvar files = require('./files.js');\nvar httpHelpers = require('./http-helpers.js');\nvar buildmessage = require('./buildmessage.js');\nvar config = require('./config.js');\nvar auth = require('./auth.js');\nvar utils = require('./utils.js');\nvar _ = require('underscore');\nvar Future = require('fibers/future');\nvar stats = require('./stats.js');\nvar Console = require('./console.js').Console;\n\n// Make a synchronous RPC to the \"classic\" MDG deploy API. The deploy\n// API has the following contract:\n//\n// - Parameters are always sent in the query string.\n// - A tarball can be sent in the body (when deploying an app).\n// - On success, all calls return HTTP 200. Those that return a value\n// either return a JSON payload or a plaintext payload and the\n// Content-Type header is set appropriately.\n// - On failure, calls return some non-200 HTTP status code and\n// provide a human-readable error message in the body.\n// - URLs are of the form \"/[operation]/[site]\".\n// - Body encodings are always utf8.\n// - Meteor Accounts auth is possible using first-party MDG cookies\n// (rather than OAuth).\n//\n// Options include:\n// - method: GET, POST, or DELETE. default GET\n// - operation: \"info\", \"logs\", \"mongo\", \"deploy\", \"authorized-apps\"\n// - site: site name\n// - expectPayload: an array of key names. if present, then we expect\n// the server to return JSON content on success and to return an\n// object with all of these key names.\n// - expectMessage: if true, then we expect the server to return text\n// content on success.\n// - bodyStream: if provided, a stream to use as the request body\n// - any other parameters accepted by the node 'request' module, for example\n// 'qs' to set query string parameters\n//\n// Waits until server responds, then returns an object with the\n// following keys:\n//\n// - statusCode: HTTP status code, or null if the server couldn't be\n// contacted\n// - payload: if successful, and the server returned a JSON body, the\n// parsed JSON body\n// - message: if successful, and the server returned a text body, the\n// body as a string\n// - errorMessage: if unsuccessful, a human-readable error message,\n// derived from either a transport-level exception, the response\n// body, or a generic 'try again later' message, as appropriate\n\nvar deployRpc = function (options) {\n var genericError = \"Server error (please try again later)\";\n\n options = _.clone(options);\n options.headers = _.clone(options.headers || {});\n if (options.headers.cookie)\n throw new Error(\"sorry, can't combine cookie headers yet\");\n\n // XXX: Reintroduce progress for upload\n try {\n var result = httpHelpers.request(_.extend(options, {\n url: config.getDeployUrl() + '/' + options.operation +\n (options.site ? ('/' + options.site) : ''),\n method: options.method || 'GET',\n bodyStream: options.bodyStream,\n useAuthHeader: true,\n encoding: 'utf8' // Hack, but good enough for the deploy server..\n }));\n } catch (e) {\n return {\n statusCode: null,\n errorMessage: \"Connection error (\" + e.message + \")\"\n };\n }\n\n var response = result.response;\n var body = result.body;\n var ret = { statusCode: response.statusCode };\n\n if (response.statusCode !== 200) {\n ret.errorMessage = body.length > 0 ? body : genericError;\n return ret;\n }\n\n var contentType = response.headers[\"content-type\"] || '';\n if (contentType === \"application/json; charset=utf-8\") {\n try {\n ret.payload = JSON.parse(body);\n } catch (e) {\n ret.errorMessage = genericError;\n return ret;\n }\n } else if (contentType === \"text/plain; charset=utf-8\") {\n ret.message = body;\n }\n\n var hasAllExpectedKeys = _.all(_.map(\n options.expectPayload || [], function (key) {\n return ret.payload && _.has(ret.payload, key);\n }));\n\n if ((options.expectPayload && ! _.has(ret, 'payload')) ||\n (options.expectMessage && ! _.has(ret, 'message')) ||\n ! hasAllExpectedKeys) {\n delete ret.payload;\n delete ret.message;\n\n ret.errorMessage = genericError;\n }\n\n return ret;\n};\n\n// Just like deployRpc, but also presents authentication. It will\n// prompt the user for a password, or use a Meteor Accounts\n// credential, as necessary.\n//\n// Additional options (beyond deployRpc):\n//\n// - preflight: if true, do everything but the actual RPC. The only\n// other necessary option is 'site'. On failure, returns an object\n// with errorMessage (just like deployRpc). On success, returns an\n// object without an errorMessage key and with possible keys\n// 'protection' (value either 'password' or 'account') and\n// 'authorized' (true if the current user is an authorized user on\n// this app).\n// - promptIfAuthFails: if true, then we think we are logged in with the\n// accounts server but our authentication actually fails, then prompt\n// the user to log in with a username and password and then resend the\n// RPC.\nvar authedRpc = function (options) {\n var rpcOptions = _.clone(options);\n var preflight = rpcOptions.preflight;\n delete rpcOptions.preflight;\n\n // Fetch auth info\n var infoResult = deployRpc({\n operation: 'info',\n site: rpcOptions.site,\n expectPayload: []\n });\n\n if (infoResult.statusCode === 401 && rpcOptions.promptIfAuthFails) {\n // Our authentication didn't validate, so prompt the user to log in\n // again, and resend the RPC if the login succeeds.\n var username = Console.readLine({\n prompt: \"Username: \",\n stream: process.stderr\n });\n var loginOptions = {\n username: username,\n suppressErrorMessage: true\n };\n if (auth.doInteractivePasswordLogin(loginOptions)) {\n return authedRpc(options);\n } else {\n return {\n statusCode: 403,\n errorMessage: \"login failed.\"\n };\n }\n }\n\n if (infoResult.statusCode === 404) {\n // Doesn't exist, therefore not protected.\n return preflight ? { } : deployRpc(rpcOptions);\n }\n\n if (infoResult.errorMessage)\n return infoResult;\n var info = infoResult.payload;\n\n if (! _.has(info, 'protection')) {\n // Not protected.\n //\n // XXX should prompt the user to claim the app (only if deploying?)\n return preflight ? { } : deployRpc(rpcOptions);\n }\n\n if (info.protection === \"password\") {\n if (preflight) {\n return { protection: info.protection };\n }\n // Password protected. Read a password, hash it, and include the\n // hashed password as a query parameter when doing the RPC.\n var password;\n password = Console.readLine({\n echo: false,\n prompt: \"Password: \",\n stream: process.stderr\n });\n\n // Hash the password so we never send plaintext over the\n // wire. Doesn't actually make us more secure, but it means we\n // won't leak a user's password, which they might use on other\n // sites too.\n var crypto = require('crypto');\n var hash = crypto.createHash('sha1');\n hash.update('S3krit Salt!');\n hash.update(password);\n password = hash.digest('hex');\n\n rpcOptions = _.clone(rpcOptions);\n rpcOptions.qs = _.clone(rpcOptions.qs || {});\n rpcOptions.qs.password = password;\n\n return deployRpc(rpcOptions);\n }\n\n if (info.protection === \"account\") {\n if (! _.has(info, 'authorized')) {\n // Absence of this implies that we are not an authorized user on\n // this app\n if (preflight) {\n return { protection: info.protection };\n } else {\n return {\n statusCode: null,\n errorMessage: auth.isLoggedIn() ?\n // XXX better error message (probably need to break out of\n // the 'errorMessage printed with brief prefix' pattern)\n \"Not an authorized user on this site\" :\n \"Not logged in\"\n };\n }\n }\n\n // Sweet, we're an authorized user.\n if (preflight) {\n return {\n protection: info.protection,\n authorized: info.authorized\n };\n } else {\n return deployRpc(rpcOptions);\n }\n }\n\n return {\n statusCode: null,\n errorMessage: \"You need a newer version of Meteor to work with this site\"\n };\n};\n\n// When the user is trying to do something with a legacy\n// password-protected app, instruct them to claim it with 'meteor\n// claim'.\nvar printLegacyPasswordMessage = function (site) {\n Console.error(\n \"\\nThis site was deployed with an old version of Meteor that used \" +\n \"site passwords instead of user accounts. Now we have a much better \" +\n \"system, Meteor developer accounts.\");\n Console.error();\n Console.error(\"If this is your site, please claim it into your account with\");\n Console.error(\n Console.command(\"meteor claim \" + site),\n Console.options({ indent: 2 }));\n};\n\n// When the user is trying to do something with an app that they are not\n// authorized for, instruct them to get added via 'meteor authorized\n// --add' or switch accounts.\nvar printUnauthorizedMessage = function () {\n var username = auth.loggedInUsername();\n Console.error(\"Sorry, that site belongs to a different user.\");\n if (username) {\n Console.error(\"You are currently logged in as \" + username + \".\");\n }\n Console.error();\n Console.error(\n \"Either have the site owner use \" +\n Console.command(\"'meteor authorized --add'\") + \" to add you as an \" +\n \"authorized developer for the site, or switch to an authorized account \" +\n \"with \" + Console.command(\"'meteor login'\") + \".\");\n};\n\n// Take a proposed sitename for deploying to. If it looks\n// syntactically good, canonicalize it (this essentially means\n// stripping 'http://' or a trailing '/' if present) and return it. If\n// not, print an error message to stderr and return null.\nvar canonicalizeSite = function (site) {\n // There are actually two different bugs here. One is that the meteor deploy\n // server does not support apps whose total site length is greater than 63\n // (because of how it generates Mongo database names); that can be fixed on\n // the server. After that, this check will be too strong, but we still will\n // want to check that each *component* of the hostname is at most 63\n // characters (url.parse will do something very strange if a component is\n // larger than 63, which is the maximum legal length).\n if (site.length > 63) {\n Console.error(\n \"The maximum hostname length currently supported is 63 characters: \" +\n site + \" is too long. \" +\n \"Please try again with a shorter URL for your site.\");\n return false;\n }\n\n var url = site;\n if (!url.match(':\\/\\/'))\n url = 'http://' + url;\n\n var parsed = require('url').parse(url);\n\n if (! parsed.hostname) {\n Console.info(\n \"Please specify a domain to connect to, such as www.example.com or \" +\n \"http://www.example.com/\");\n return false;\n }\n\n if (parsed.pathname != '/' || parsed.hash || parsed.query) {\n Console.info(\n \"Sorry, Meteor does not yet support specific path URLs, such as \" +\n Console.url(\"http://www.example.com/blog\") + \" . Please specify the root of a domain.\");\n return false;\n }\n\n return parsed.hostname;\n};\n\n// Run the bundler and deploy the result. Print progress\n// messages. Return a command exit code.\n//\n// Options:\n// - projectContext: the ProjectContext for the app\n// - site: site to deploy as\n// - settingsFile: file from which to read deploy settings (undefined\n// to leave unchanged from previous deploy of the app, if any)\n// - recordPackageUsage: (defaults to true) if set to false, don't\n// send information about packages used by this app to the package\n// stats server.\n// - buildOptions: the 'buildOptions' argument to the bundler\nvar bundleAndDeploy = function (options) {\n if (options.recordPackageUsage === undefined)\n options.recordPackageUsage = true;\n\n var site = canonicalizeSite(options.site);\n if (! site)\n return 1;\n\n // We should give a username/password prompt if the user was logged in\n // but the credentials are expired, unless the user is logged in but\n // doesn't have a username (in which case they should hit the email\n // prompt -- a user without a username shouldn't be given a username\n // prompt). There's an edge case where things happen in the following\n // order: user creates account, user sets username, credential expires\n // or is revoked, user comes back to deploy again. In that case,\n // they'll get an email prompt instead of a username prompt because\n // the command-line tool didn't have time to learn about their\n // username before the credential was expired.\n auth.pollForRegistrationCompletion({\n noLogout: true\n });\n var promptIfAuthFails = (auth.loggedInUsername() !== null);\n\n // Check auth up front, rather than after the (potentially lengthy)\n // bundling process.\n var preflight = authedRpc({\n site: site,\n preflight: true,\n promptIfAuthFails: promptIfAuthFails\n });\n\n if (preflight.errorMessage) {\n Console.error(\"Error deploying application: \" + preflight.errorMessage);\n return 1;\n }\n\n if (preflight.protection === \"password\") {\n printLegacyPasswordMessage(site);\n Console.error(\"If it's not your site, please try a different name!\");\n return 1;\n\n } else if (preflight.protection === \"account\" &&\n ! preflight.authorized) {\n printUnauthorizedMessage();\n return 1;\n }\n\n var buildDir = files.mkdtemp('build_tar');\n var bundlePath = files.pathJoin(buildDir, 'bundle');\n\n Console.info('Deploying to ' + site + '.');\n\n var settings = null;\n var messages = buildmessage.capture({\n title: \"preparing to deploy\",\n rootPath: process.cwd()\n }, function () {\n if (options.settingsFile)\n settings = files.getSettings(options.settingsFile);\n });\n\n if (! messages.hasMessages()) {\n var bundler = require('./bundler.js');\n\n var bundleResult = bundler.bundle({\n projectContext: options.projectContext,\n outputPath: bundlePath,\n buildOptions: options.buildOptions\n });\n\n if (bundleResult.errors)\n messages = bundleResult.errors;\n }\n\n if (messages.hasMessages()) {\n Console.info(\"\\nErrors prevented deploying:\");\n Console.info(messages.formatMessages());\n return 1;\n }\n\n if (options.recordPackageUsage) {\n stats.recordPackages({\n what: \"sdk.deploy\",\n projectContext: options.projectContext,\n site: site\n });\n }\n\n var result = buildmessage.enterJob({ title: \"uploading\" }, function () {\n return authedRpc({\n method: 'POST',\n operation: 'deploy',\n site: site,\n qs: settings !== null ? {settings: settings} : {},\n bodyStream: files.createTarGzStream(files.pathJoin(buildDir, 'bundle')),\n expectPayload: ['url'],\n preflightPassword: preflight.preflightPassword\n });\n });\n\n\n if (result.errorMessage) {\n Console.error(\"\\nError deploying application: \" + result.errorMessage);\n return 1;\n }\n\n var deployedAt = require('url').parse(result.payload.url);\n var hostname = deployedAt.hostname;\n\n Console.info('Now serving at http://' + hostname);\n\n if (! hostname.match(/meteor\\.com$/)) {\n var dns = require('dns');\n dns.resolve(hostname, 'CNAME', function (err, cnames) {\n if (err || cnames[0] !== 'origin.meteor.com') {\n dns.resolve(hostname, 'A', function (err, addresses) {\n if (err || addresses[0] !== '107.22.210.133') {\n Console.info('-------------');\n Console.info(\n \"You've deployed to a custom domain.\",\n \"Please be sure to CNAME your hostname\",\n \"to origin.meteor.com, or set an A record to 107.22.210.133.\");\n Console.info('-------------');\n }\n });\n }\n });\n }\n\n return 0;\n};\n\nvar deleteApp = function (site) {\n site = canonicalizeSite(site);\n if (! site)\n return 1;\n\n var result = authedRpc({\n method: 'DELETE',\n operation: 'deploy',\n site: site,\n promptIfAuthFails: true\n });\n\n if (result.errorMessage) {\n Console.error(\"Couldn't delete application: \" + result.errorMessage);\n return 1;\n }\n\n Console.info(\"Deleted.\");\n return 0;\n};\n\n// Helper that does a preflight request to check auth, and prints the\n// appropriate error message if auth fails or if this is a legacy\n// password-protected app. If auth succeeds, then it runs the actual\n// RPC. 'site' and 'operation' are the site and operation for the\n// RPC. 'what' is a string describing the operation, for use in error\n// messages. Returns the result of the RPC if successful, or null\n// otherwise (including if auth failed or if the user is not authorized\n// for this site).\nvar checkAuthThenSendRpc = function (site, operation, what) {\n var preflight = authedRpc({\n operation: operation,\n site: site,\n preflight: true,\n promptIfAuthFails: true\n });\n\n if (preflight.errorMessage) {\n Console.error(\"Couldn't \" + what + \": \" + preflight.errorMessage);\n return null;\n }\n\n if (preflight.protection === \"password\") {\n printLegacyPasswordMessage(site);\n return null;\n } else if (preflight.protection === \"account\" &&\n ! preflight.authorized) {\n if (! auth.isLoggedIn()) {\n // Maybe the user is authorized for this app but not logged in\n // yet, so give them a login prompt.\n var loginResult = auth.doUsernamePasswordLogin({ retry: true });\n if (loginResult) {\n // Once we've logged in, retry the whole operation. We need to\n // do the preflight request again instead of immediately moving\n // on to the real RPC because we don't yet know if the newly\n // logged-in user is authorized for this app, and if they\n // aren't, then we want to print the nice unauthorized error\n // message.\n return checkAuthThenSendRpc(site, operation, what);\n } else {\n // Shouldn't ever get here because we set the retry flag on the\n // login, but just in case.\n Console.error(\n \"\\nYou must be logged in to \" + what + \" for this app. Use \" +\n Console.command(\"'meteor login'\") + \"to log in.\");\n Console.error();\n Console.error(\n \"If you don't have a Meteor developer account yet, you can quickly \" +\n \"create one at www.meteor.com.\");\n return null;\n }\n } else { // User is logged in but not authorized for this app\n Console.error();\n printUnauthorizedMessage();\n return null;\n }\n }\n\n // User is authorized for the app; go ahead and do the actual RPC.\n\n var result = authedRpc({\n operation: operation,\n site: site,\n expectMessage: true,\n promptIfAuthFails: true\n });\n\n if (result.errorMessage) {\n Console.error(\"Couldn't \" + what + \": \" + result.errorMessage);\n return null;\n }\n\n return result;\n};\n\n// On failure, prints a message to stderr and returns null. Otherwise,\n// returns a temporary authenticated Mongo URL allowing access to this\n// site's database.\nvar temporaryMongoUrl = function (site) {\n site = canonicalizeSite(site);\n if (! site)\n // canonicalizeSite printed an error\n return null;\n\n var result = checkAuthThenSendRpc(site, 'mongo', 'open a mongo connection');\n\n if (result !== null) {\n return result.message;\n } else {\n return null;\n }\n};\n\nvar logs = function (site) {\n site = canonicalizeSite(site);\n if (! site)\n return 1;\n\n var result = checkAuthThenSendRpc(site, 'logs', 'view logs');\n\n if (result === null) {\n return 1;\n } else {\n Console.info(result.message);\n auth.maybePrintRegistrationLink({ leadingNewline: true });\n return 0;\n }\n};\n\nvar listAuthorized = function (site) {\n site = canonicalizeSite(site);\n if (! site)\n return 1;\n\n var result = deployRpc({\n operation: 'info',\n site: site,\n expectPayload: []\n });\n if (result.errorMessage) {\n Console.error(\"Couldn't get authorized users list: \" + result.errorMessage);\n return 1;\n }\n var info = result.payload;\n\n if (! _.has(info, 'protection')) {\n Console.info(\"\");\n return 0;\n }\n\n if (info.protection === \"password\") {\n Console.info(\"\");\n return 0;\n }\n\n if (info.protection === \"account\") {\n if (! _.has(info, 'authorized')) {\n Console.error(\"Couldn't get authorized users list: \" +\n \"You are not authorized\");\n return 1;\n }\n\n Console.info((auth.loggedInUsername() || \"\"));\n _.each(info.authorized, function (username) {\n if (username)\n // Current username rules don't let you register anything that we might\n // want to split over multiple lines (ex: containing a space), but we\n // don't want confusion if we ever change some implementation detail.\n Console.rawInfo(username + \"\\n\");\n });\n return 0;\n }\n};\n\n// action is \"add\" or \"remove\"\nvar changeAuthorized = function (site, action, username) {\n site = canonicalizeSite(site);\n if (! site)\n // canonicalizeSite will have already printed an error\n return 1;\n\n var result = authedRpc({\n method: 'POST',\n operation: 'authorized',\n site: site,\n qs: action === \"add\" ? { add: username } : { remove: username },\n promptIfAuthFails: true\n });\n\n if (result.errorMessage) {\n Console.error(\"Couldn't change authorized users: \" + result.errorMessage);\n return 1;\n }\n\n Console.info(site + \": \" +\n (action === \"add\" ? \"added \" : \"removed \")\n + username);\n return 0;\n};\n\nvar claim = function (site) {\n site = canonicalizeSite(site);\n if (! site)\n // canonicalizeSite will have already printed an error\n return 1;\n\n // Check to see if it's even a claimable site, so that we can print\n // a more appropriate message than we'd get if we called authedRpc\n // straight away (at a cost of an extra REST call)\n var infoResult = deployRpc({\n operation: 'info',\n site: site\n });\n if (infoResult.statusCode === 404) {\n Console.error(\n \"There isn't a site deployed at that address. Use \" +\n Console.command(\"'meteor deploy'\") + \" \" +\n \"if you'd like to deploy your app here.\");\n return 1;\n }\n\n if (infoResult.payload && infoResult.payload.protection === \"account\") {\n if (infoResult.payload.authorized)\n Console.error(\"That site already belongs to you.\\n\");\n else\n Console.error(\"Sorry, that site belongs to someone else.\\n\");\n return 1;\n }\n\n if (infoResult.payload &&\n infoResult.payload.protection === \"password\") {\n Console.info(\n \"To claim this site and transfer it to your account, enter the\",\n \"site password one last time.\");\n Console.info();\n }\n\n var result = authedRpc({\n method: 'POST',\n operation: 'claim',\n site: site,\n promptIfAuthFails: true\n });\n\n if (result.errorMessage) {\n auth.pollForRegistrationCompletion();\n if (! auth.loggedInUsername() &&\n auth.registrationUrl()) {\n Console.error(\n \"You need to set a password on your Meteor developer account before\",\n \"you can claim sites. You can do that here in under a minute:\");\n Console.error(Console.url(auth.registrationUrl()));\n Console.error();\n } else {\n Console.error(\"Couldn't claim site: \" + result.errorMessage);\n }\n return 1;\n }\n\n Console.info(site + \": \" + \"successfully transferred to your account.\");\n Console.info();\n Console.info(\"Show authorized users with:\");\n Console.info(\n Console.command(\"meteor authorized \" + site),\n Console.options({ indent: 2 }));\n Console.info();\n Console.info(\"Add authorized users with:\");\n Console.info(\n Console.command(\"meteor authorized \" + site + \" --add \"),\n Console.options({ indent: 2 }));\n Console.info();\n Console.info(\"Remove authorized users with:\");\n Console.info(\n Console.command(\"meteor authorized \" + site + \" --remove \"),\n Console.options({ indent: 2 }));\n Console.info();\n return 0;\n};\n\nvar listSites = function () {\n var result = deployRpc({\n method: \"GET\",\n operation: \"authorized-apps\",\n promptIfAuthFails: true,\n expectPayload: [\"sites\"]\n });\n\n if (result.errorMessage) {\n Console.error(\"Couldn't list sites: \" + result.errorMessage);\n return 1;\n }\n\n if (! result.payload ||\n ! result.payload.sites ||\n ! result.payload.sites.length) {\n Console.info(\"You don't have any sites yet.\");\n } else {\n result.payload.sites.sort();\n _.each(result.payload.sites, function (site) {\n Console.info(site);\n });\n }\n return 0;\n};\n\n\nexports.bundleAndDeploy = bundleAndDeploy;\nexports.deleteApp = deleteApp;\nexports.temporaryMongoUrl = temporaryMongoUrl;\nexports.logs = logs;\nexports.listAuthorized = listAuthorized;\nexports.changeAuthorized = changeAuthorized;\nexports.claim = claim;\nexports.listSites = listSites;\n", "file_path": "tools/deploy.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00019426687504164875, 0.0001725512556731701, 0.00016559212235733867, 0.0001722137094475329, 3.936081611755071e-06]} {"hunk": {"id": 6, "code_window": ["\n", "var runLinters = function (\n", " inputSourceArch,\n", " isopackCache,\n", " wrappedSourceItems,\n", " linterPluginsByExtension) {\n", " // For linters, figure out what are the global imports from other packages\n", " // that we use directly, or are implied.\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep"], "after_edit": [" linters) {\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 954}, "file": "var SPEW = function(str) {\n SPEW.lines.push(str);\n // use counter to signal invalidation\n Session.set(\"SPEW_V\", (Session.get(\"SPEW_V\") || 0)+1);\n};\nSPEW.lines = [];\n\nTemplate.radios.events = {\n 'change input': function(event) {\n //SPEW(\"change \"+event.target.value);\n if (event.target.checked) {\n Session.set(\"current_band\", event.target.value);\n }\n }\n};\n\nTemplate.radios.current_band = function() {\n return Session.get(\"current_band\");\n};\n\nTemplate.radios.band_checked = function(b) {\n return Session.equals(\"current_band\", b) ?\n 'checked=\"checked\"' : '';\n};\n\nTemplate.checkboxes.events = {\n 'change input': function(event) {\n Session.set(\"dst\", event.target.checked);\n }\n};\n\nTemplate.checkboxes.dst_checked = function() {\n return Session.get(\"dst\") ? 'checked=\"checked\"' : '';\n};\n\nTemplate.checkboxes.dst = function() {\n return Session.get(\"dst\") ? 'Yes' : 'No';\n};\n\nTemplate.spew.lines = function() {\n Session.get(\"SPEW_V\");\n return SPEW.lines;\n};\n", "file_path": "examples/unfinished/controls/client/controls.js", "label": 0, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.00017284855130128562, 0.0001670191704761237, 0.00015910824004095048, 0.00016688684991095215, 4.739998985314742e-06]} {"hunk": {"id": 7, "code_window": [" // For linters, figure out what are the global imports from other packages\n", " // that we use directly, or are implied.\n", " var globalImports = ['Package', 'Assets', 'Npm'];\n", " compiler.eachUsedUnibuild({\n", " dependencies: inputSourceArch.uses,\n", " arch: inputSourceArch.arch,\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var globalImports = ['Package'];\n", "\n", " if (archinfo.matches(inputSourceArch.arch, \"os\")) {\n", " globalImports = globalImports.concat(['Npm', 'Assets']);\n", " }\n", "\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 957}, "file": "var _ = require('underscore');\n\nvar archinfo = require('./archinfo.js');\nvar buildmessage = require('./buildmessage.js');\nvar bundler = require('./bundler.js');\nvar isopack = require('./isopack.js');\nvar isopackets = require('./isopackets.js');\nvar linker = require('./linker.js');\nvar meteorNpm = require('./meteor-npm.js');\nvar watch = require('./watch.js');\nvar Console = require('./console.js').Console;\nvar files = require('./files.js');\nvar colonConverter = require('./colon-converter.js');\nvar linterPluginModule = require('./linter-plugin.js');\n\nvar compiler = exports;\n\n// Whenever you change anything about the code that generates isopacks, bump\n// this version number. The idea is that the \"format\" field of the isopack\n// JSON file only changes when the actual specified structure of the\n// isopack/unibuild changes, but this version (which is build-tool-specific)\n// can change when the the contents (not structure) of the built output\n// changes. So eg, if we improve the linker's static analysis, this should be\n// bumped.\n//\n// You should also update this whenever you update any of the packages used\n// directly by the isopack creation process (eg js-analyze) since they do not\n// end up as watched dependencies. (At least for now, packages only used in\n// target creation (eg minifiers) don't require you to update BUILT_BY, though\n// you will need to quit and rerun \"meteor run\".)\ncompiler.BUILT_BY = 'meteor/16';\n\n// This is a list of all possible architectures that a build can target. (Client\n// is expanded into 'web.browser' and 'web.cordova')\ncompiler.ALL_ARCHES = [ \"os\", \"web.browser\", \"web.cordova\" ];\n\ncompiler.compile = function (packageSource, options) {\n buildmessage.assertInCapture();\n\n var packageMap = options.packageMap;\n var isopackCache = options.isopackCache;\n var includeCordovaUnibuild = options.includeCordovaUnibuild;\n\n var pluginWatchSet = packageSource.pluginWatchSet.clone();\n var plugins = {};\n\n var pluginProviderPackageNames = {};\n\n // Build plugins\n _.each(packageSource.pluginInfo, function (info) {\n buildmessage.enterJob({\n title: \"building plugin `\" + info.name +\n \"` in package `\" + packageSource.name + \"`\",\n rootPath: packageSource.sourceRoot\n }, function () {\n // XXX we should probably also pass options.noLineNumbers into\n // buildJsImage so it can pass it back to its call to\n // compiler.compile\n var buildResult = bundler.buildJsImage({\n name: info.name,\n packageMap: packageMap,\n isopackCache: isopackCache,\n use: info.use,\n sourceRoot: packageSource.sourceRoot,\n sources: info.sources,\n npmDependencies: info.npmDependencies,\n // Plugins have their own npm dependencies separate from the\n // rest of the package, so they need their own separate npm\n // shrinkwrap and cache state.\n npmDir: files.pathResolve(\n files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name))\n });\n // Add this plugin's dependencies to our \"plugin dependency\"\n // WatchSet. buildResult.watchSet will end up being the merged\n // watchSets of all of the unibuilds of the plugin -- plugins have\n // only one unibuild and this should end up essentially being just\n // the source files of the plugin.\n //\n // Note that we do this even on error, so that you can fix the error\n // and have the runner restart.\n pluginWatchSet.merge(buildResult.watchSet);\n\n if (buildmessage.jobHasMessages())\n return;\n\n _.each(buildResult.usedPackageNames, function (packageName) {\n pluginProviderPackageNames[packageName] = true;\n });\n\n // Register the built plugin's code.\n if (!_.has(plugins, info.name))\n plugins[info.name] = {};\n plugins[info.name][buildResult.image.arch] = buildResult.image;\n });\n });\n\n // Grab any npm dependencies. Keep them in a cache in the package\n // source directory so we don't have to do this from scratch on\n // every build.\n //\n // Go through a specialized npm dependencies update process,\n // ensuring we don't get new versions of any (sub)dependencies. This\n // process also runs mostly safely multiple times in parallel (which\n // could happen if you have two apps running locally using the same\n // package).\n //\n // We run this even if we have no dependencies, because we might\n // need to delete dependencies we used to have.\n var isPortable = true;\n var nodeModulesPath = null;\n if (packageSource.npmCacheDirectory) {\n if (meteorNpm.updateDependencies(packageSource.name,\n packageSource.npmCacheDirectory,\n packageSource.npmDependencies)) {\n nodeModulesPath = files.pathJoin(packageSource.npmCacheDirectory,\n 'node_modules');\n if (! meteorNpm.dependenciesArePortable(packageSource.npmCacheDirectory))\n isPortable = false;\n }\n }\n\n var isopk = new isopack.Isopack;\n isopk.initFromOptions({\n name: packageSource.name,\n metadata: packageSource.metadata,\n version: packageSource.version,\n isTest: packageSource.isTest,\n plugins: plugins,\n pluginWatchSet: pluginWatchSet,\n cordovaDependencies: packageSource.cordovaDependencies,\n npmDiscards: packageSource.npmDiscards,\n includeTool: packageSource.includeTool,\n debugOnly: packageSource.debugOnly\n });\n\n _.each(packageSource.architectures, function (unibuild) {\n if (unibuild.arch === 'web.cordova' && ! includeCordovaUnibuild)\n return;\n\n var unibuildResult = compileUnibuild({\n isopack: isopk,\n sourceArch: unibuild,\n isopackCache: isopackCache,\n nodeModulesPath: nodeModulesPath,\n isPortable: isPortable,\n noLineNumbers: options.noLineNumbers\n });\n _.extend(pluginProviderPackageNames,\n unibuildResult.pluginProviderPackageNames);\n });\n\n if (options.includePluginProviderPackageMap) {\n isopk.setPluginProviderPackageMap(\n packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames)));\n }\n\n return isopk;\n};\n\n// options.sourceArch is a SourceArch to compile. Process all source files\n// through the appropriate handlers and run the prelink phase on any resulting\n// JavaScript. Create a new Unibuild and add it to options.isopack.\n//\n// Returns a list of source files that were used in the compilation.\nvar compileUnibuild = function (options) {\n buildmessage.assertInCapture();\n\n var isopk = options.isopack;\n var inputSourceArch = options.sourceArch;\n var isopackCache = options.isopackCache;\n var nodeModulesPath = options.nodeModulesPath;\n var isPortable = options.isPortable;\n var noLineNumbers = options.noLineNumbers;\n\n var isApp = ! inputSourceArch.pkg.name;\n var resources = [];\n var js = [];\n var pluginProviderPackageNames = {};\n // The current package always is a plugin provider. (This also means we no\n // longer need a buildOfPath entry in buildinfo.json.)\n pluginProviderPackageNames[isopk.name] = true;\n var watchSet = inputSourceArch.watchSet.clone();\n\n // *** Determine and load active plugins\n\n // XXX we used to include our own extensions only if we were the\n // \"use\" role. now we include them everywhere because we don't have\n // a special \"use\" role anymore. it's not totally clear to me what\n // the correct behavior should be -- we need to resolve whether we\n // think about extensions as being global to a package or particular\n // to a unibuild.\n\n // (there's also some weirdness here with handling implies, because\n // the implies field is on the target unibuild, but we really only care\n // about packages.)\n var activePluginPackages = [isopk];\n\n // We don't use plugins from weak dependencies, because the ability\n // to compile a certain type of file shouldn't depend on whether or\n // not some unrelated package in the target has a dependency. And we\n // skip unordered dependencies, because it's not going to work to\n // have circular build-time dependencies.\n //\n // eachUsedUnibuild takes care of pulling in implied dependencies for us (eg,\n // templating from standard-app-packages).\n //\n // We pass archinfo.host here, not self.arch, because it may be more specific,\n // and because plugins always have to run on the host architecture.\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: archinfo.host(),\n isopackCache: isopackCache,\n skipUnordered: true\n // implicitly skip weak deps by not specifying acceptableWeakPackages option\n }, function (unibuild) {\n if (unibuild.pkg.name === isopk.name)\n return;\n pluginProviderPackageNames[unibuild.pkg.name] = true;\n // If other package is built from source, then we need to rebuild this\n // package if any file in the other package that could define a plugin\n // changes.\n watchSet.merge(unibuild.pkg.pluginWatchSet);\n\n if (_.isEmpty(unibuild.pkg.plugins))\n return;\n activePluginPackages.push(unibuild.pkg);\n });\n\n activePluginPackages = _.uniq(activePluginPackages);\n\n // *** Assemble the list of source file handlers from the plugins\n // XXX BBP redoc\n var allHandlersWithPkgs = {};\n var compilerPluginsByExtension = {};\n var linterPluginsByExtension = {};\n var sourceExtensions = {}; // maps source extensions to isTemplate\n\n sourceExtensions['js'] = false;\n allHandlersWithPkgs['js'] = {\n pkgName: null /* native handler */,\n handler: function (compileStep) {\n // This is a hardcoded handler for *.js files. Since plugins\n // are written in JavaScript we have to start somewhere.\n\n var options = {\n data: compileStep.read().toString('utf8'),\n path: compileStep.inputPath,\n sourcePath: compileStep.inputPath,\n _hash: compileStep._hash\n };\n\n if (compileStep.fileOptions.hasOwnProperty(\"bare\")) {\n options.bare = compileStep.fileOptions.bare;\n } else if (compileStep.fileOptions.hasOwnProperty(\"raw\")) {\n // XXX eventually get rid of backward-compatibility \"raw\" name\n // XXX COMPAT WITH 0.6.4\n options.bare = compileStep.fileOptions.raw;\n }\n\n compileStep.addJavaScript(options);\n }\n };\n\n _.each(activePluginPackages, function (otherPkg) {\n otherPkg.ensurePluginsInitialized();\n\n // Iterate over the legacy source handlers.\n _.each(otherPkg.getSourceHandlers(), function (sourceHandler, ext) {\n // XXX comparing function text here seems wrong.\n if (_.has(allHandlersWithPkgs, ext) &&\n allHandlersWithPkgs[ext].handler.toString() !== sourceHandler.handler.toString()) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first handler we saw\n return;\n }\n // Is this handler only registered for, say, \"web\", and we're building,\n // say, \"os\"?\n if (sourceHandler.archMatching &&\n !archinfo.matches(inputSourceArch.arch, sourceHandler.archMatching)) {\n return;\n }\n allHandlersWithPkgs[ext] = {\n pkgName: otherPkg.name,\n handler: sourceHandler.handler\n };\n sourceExtensions[ext] = !!sourceHandler.isTemplate;\n });\n\n // Iterate over the compiler plugins.\n _.each(otherPkg.sourceProcessors.compiler, function (compilerPlugin, id) {\n _.each(compilerPlugin.extensions, function (ext) {\n if (_.has(allHandlersWithPkgs, ext) ||\n _.has(compilerPluginsByExtension, ext)) {\n buildmessage.error(\n \"conflict: two packages included in \" +\n (inputSourceArch.pkg.name || \"the app\") + \", \" +\n (allHandlersWithPkgs[ext].pkgName || \"the app\") + \" and \" +\n (otherPkg.name || \"the app\") + \", \" +\n \"are both trying to handle .\" + ext);\n // Recover by just going with the first one we found.\n return;\n }\n compilerPluginsByExtension[ext] = compilerPlugin;\n sourceExtensions[ext] = compilerPlugin.isTemplate;\n });\n });\n\n // Iterate over the linters\n _.each(otherPkg.sourceProcessors.linter, function (linterPlugin, id) {\n _.each(linterPlugin.extensions, function (ext) {\n linterPluginsByExtension[ext] = linterPluginsByExtension[ext] || [];\n linterPluginsByExtension[ext].push(linterPlugin);\n });\n });\n });\n\n // *** Determine source files\n // Note: sourceExtensions does not include leading dots\n // Note: the getSourcesFunc function isn't expected to add its\n // source files to watchSet; rather, the watchSet is for other\n // things that the getSourcesFunc consulted (such as directory\n // listings or, in some hypothetical universe, control files) to\n // determine its source files.\n var sourceItems = inputSourceArch.getSourcesFunc(sourceExtensions, watchSet);\n\n if (nodeModulesPath) {\n // If this slice has node modules, we should consider the shrinkwrap file\n // to be part of its inputs. (This is a little racy because there's no\n // guarantee that what we read here is precisely the version that's used,\n // but it's better than nothing at all.)\n //\n // Note that this also means that npm modules used by plugins will get\n // this npm-shrinkwrap.json in their pluginDependencies (including for all\n // packages that depend on us)! This is good: this means that a tweak to\n // an indirect dependency of the coffee-script npm module used by the\n // coffeescript package will correctly cause packages with *.coffee files\n // to be rebuilt.\n var shrinkwrapPath = nodeModulesPath.replace(\n /node_modules$/, 'npm-shrinkwrap.json');\n watch.readAndWatchFile(watchSet, shrinkwrapPath);\n }\n\n // *** Process each source file\n var addAsset = function (contents, relPath, hash) {\n // XXX hack\n if (! inputSourceArch.pkg.name)\n relPath = relPath.replace(/^(private|public)\\//, '');\n\n resources.push({\n type: \"asset\",\n data: contents,\n path: relPath,\n servePath: colonConverter.convert(\n files.pathJoin(inputSourceArch.pkg.serveRoot, relPath)),\n hash: hash\n });\n };\n\n var convertSourceMapPaths = function (sourcemap, f) {\n if (! sourcemap) {\n // Don't try to convert it if it doesn't exist\n return sourcemap;\n }\n\n var srcmap = JSON.parse(sourcemap);\n srcmap.sources = _.map(srcmap.sources, f);\n return JSON.stringify(srcmap);\n };\n\n var wrappedSourceItems = _.map(sourceItems, function (source) {\n var fileWatchSet = new watch.WatchSet;\n // readAndWatchFileWithHash returns an object carrying a buffer with the\n // file-contents. The buffer contains the original data of the file (no EOL\n // transforms from the tools/files.js part).\n // We don't put this into the unibuild's watchSet immediately since we want\n // to avoid putting it there if it turns out not to be relevant to our\n // arch.\n var absPath = files.pathResolve(\n inputSourceArch.pkg.sourceRoot, source.relPath);\n var file = watch.readAndWatchFileWithHash(fileWatchSet, absPath);\n\n Console.nudge(true);\n\n return {\n relPath: source.relPath,\n watchset: fileWatchSet,\n contents: file.contents,\n hash: file.hash,\n source: source,\n 'package': isopk.name\n };\n });\n\n runLinters(inputSourceArch, isopackCache, wrappedSourceItems, linterPluginsByExtension);\n\n _.each(wrappedSourceItems, function (wrappedSource) {\n var source = wrappedSource.source;\n var relPath = source.relPath;\n var fileOptions = _.clone(source.fileOptions) || {};\n var absPath = files.pathResolve(inputSourceArch.pkg.sourceRoot, relPath);\n var filename = files.pathBasename(relPath);\n var contents = wrappedSource.contents;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n\n Console.nudge(true);\n\n if (contents === null) {\n // It really sucks to put this check here, since this isn't publish\n // code...\n if (source.relPath.match(/:/)) {\n buildmessage.error(\n \"Couldn't build this package on Windows due to the following file \" +\n \"with a colon -- \" + source.relPath + \". Please rename and \" +\n \"and re-publish the package.\");\n } else {\n buildmessage.error(\"File not found: \" + source.relPath);\n }\n\n // recover by ignoring (but still watching the file)\n watchSet.merge(fileWatchSet);\n return;\n }\n\n // Find the handler for source files with this extension.\n var handler = null;\n var isBuildPluginSource = false;\n if (! fileOptions.isAsset) {\n var parts = filename.split('.');\n // don't use iteration functions, so we can return/break\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(compilerPluginsByExtension, extension)) {\n var compilerPlugin = compilerPluginsByExtension[extension];\n if (! compilerPlugin.relevantForArch(inputSourceArch.arch)) {\n // This file is for a compiler plugin but not for this arch. Skip\n // it, and don't even watch it. (eg, skip CSS preprocessor files on\n // the server.)\n return;\n }\n isBuildPluginSource = true;\n break;\n }\n if (_.has(allHandlersWithPkgs, extension)) {\n handler = allHandlersWithPkgs[extension].handler;\n break;\n }\n }\n }\n\n // OK, this is relevant to this arch, so watch it.\n watchSet.merge(fileWatchSet);\n\n if (isBuildPluginSource) {\n // This is source used by a new-style compiler plugin; it will be fully\n // processed later in the bundler.\n resources.push({\n type: \"source\",\n data: contents,\n path: relPath,\n hash: hash\n });\n return;\n }\n\n if (! handler) {\n // If we don't have an extension handler, serve this file as a\n // static resource on the client, or ignore it on the server.\n //\n // XXX This is pretty confusing, especially if you've\n // accidentally forgotten a plugin -- revisit?\n addAsset(contents, relPath, hash);\n return;\n }\n\n // This object is called a #CompileStep and it's the interface\n // to plugins that define new source file handlers (eg,\n // Coffeescript).\n //\n // Fields on CompileStep:\n //\n // - arch: the architecture for which we are building\n // - inputSize: total number of bytes in the input file\n // - inputPath: the filename and (relative) path of the input\n // file, eg, \"foo.js\". We don't provide a way to get the full\n // path because you're not supposed to read the file directly\n // off of disk. Instead you should call read(). That way we\n // can ensure that the version of the file that you use is\n // exactly the one that is recorded in the dependency\n // information.\n // - pathForSourceMap: If this file is to be included in a source map,\n // this is the name you should use for it in the map.\n // - rootOutputPath: on web targets, for resources such as\n // stylesheet and static assets, this is the root URL that\n // will get prepended to the paths you pick for your output\n // files so that you get your own namespace, for example\n // '/packages/foo'. null on non-web targets\n // - fileOptions: any options passed to \"api.addFiles\"; for\n // use by the plugin. The built-in \"js\" plugin uses the \"bare\"\n // option for files that shouldn't be wrapped in a closure.\n // - declaredExports: An array of symbols exported by this unibuild, or null\n // if it may not export any symbols (eg, test unibuilds). This is used by\n // CoffeeScript to ensure that it doesn't close over those symbols, eg.\n // - read(n): read from the input file. If n is given it should\n // be an integer, and you will receive the next n bytes of the\n // file as a Buffer. If n is omitted you get the rest of the\n // file.\n // - appendDocument({ section: \"head\", data: \"my markup\" })\n // Browser targets only. Add markup to the \"head\" or \"body\"\n // Web targets only. Add markup to the \"head\" or \"body\"\n // section of the document.\n // - addStylesheet({ path: \"my/stylesheet.css\", data: \"my css\",\n // sourceMap: \"stringified json sourcemap\"})\n // Web targets only. Add a stylesheet to the\n // document. 'path' is a requested URL for the stylesheet that\n // may or may not ultimately be honored. (Meteor will add\n // appropriate tags to cause the stylesheet to be loaded. It\n // will be subject to any stylesheet processing stages in\n // effect, such as minification.)\n // - addJavaScript({ path: \"my/program.js\", data: \"my code\",\n // sourcePath: \"src/my/program.js\",\n // bare: true })\n // Add JavaScript code, which will be namespaced into this\n // package's environment (eg, it will see only the exports of\n // this package's imports), and which will be subject to\n // minification and so forth. Again, 'path' is merely a hint\n // that may or may not be honored. 'sourcePath' is the path\n // that will be used in any error messages generated (eg,\n // \"foo.js:4:1: syntax error\"). It must be present and should\n // be relative to the project root. Typically 'inputPath' will\n // do handsomely. \"bare\" means to not wrap the file in\n // a closure, so that its vars are shared with other files\n // in the module.\n // - addAsset({ path: \"my/image.png\", data: Buffer })\n // Add a file to serve as-is over HTTP (web targets) or\n // to include as-is in the bundle (os targets).\n // This time `data` is a Buffer rather than a string. For\n // web targets, it will be served at the exact path you\n // request (concatenated with rootOutputPath). For server\n // targets, the file can be retrieved by passing path to\n // Assets.getText or Assets.getBinary.\n // - error({ message: \"There's a problem in your source file\",\n // sourcePath: \"src/my/program.ext\", line: 12,\n // column: 20, func: \"doStuff\" })\n // Flag an error -- at a particular location in a source\n // file, if you like (you can even indicate a function name\n // to show in the error, like in stack traces). sourcePath,\n // line, column, and func are all optional.\n //\n // XXX for now, these handlers must only generate portable code\n // (code that isn't dependent on the arch, other than 'web'\n // vs 'os') -- they can look at the arch that is provided\n // but they can't rely on the running on that particular arch\n // (in the end, an arch-specific unibuild will be emitted only if\n // there are native node modules). Obviously this should\n // change. A first step would be a setOutputArch() function\n // analogous to what we do with native node modules, but maybe\n // what we want is the ability to ask the plugin ahead of time\n // how specific it would like to force unibuilds to be.\n //\n // XXX we handle encodings in a rather cavalier way and I\n // suspect we effectively end up assuming utf8. We can do better\n // than that!\n //\n // XXX addAsset probably wants to be able to set MIME type and\n // also control any manifest field we deem relevant (if any)\n //\n // XXX Some handlers process languages that have the concept of\n // include files. These are problematic because we need to\n // somehow instrument them to get the names and hashs of all of\n // the files that they read for dependency tracking purposes. We\n // don't have an API for that yet, so for now we provide a\n // workaround, which is that _fullInputPath contains the full\n // absolute path to the input files, which allows such a plugin\n // to set up its include search path. It's then on its own for\n // registering dependencies (for now..)\n //\n // XXX in the future we should give plugins an easy and clean\n // way to return errors (that could go in an overall list of\n // errors experienced across all files)\n var readOffset = 0;\n\n /**\n * The comments for this class aren't used to generate docs right now.\n * The docs live in the GitHub Wiki at: https://github.com/meteor/meteor/wiki/CompileStep-API-for-Build-Plugin-Source-Handlers\n * @class CompileStep\n * @summary The object passed into Plugin.registerSourceHandler\n * @global\n */\n var compileStep = {\n\n /**\n * @summary The total number of bytes in the input file.\n * @memberOf CompileStep\n * @instance\n * @type {Integer}\n */\n inputSize: contents.length,\n\n /**\n * @summary The filename and relative path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n inputPath: files.convertToOSPath(relPath, true),\n\n /**\n * @summary The filename and absolute path of the input file.\n * Please don't use this filename to read the file from disk, instead\n * use [compileStep.read](CompileStep-read).\n * @type {String}\n * @instance\n * @memberOf CompileStep\n */\n fullInputPath: files.convertToOSPath(absPath),\n\n // The below is used in the less and stylus packages... so it should be\n // public API.\n _fullInputPath: files.convertToOSPath(absPath), // avoid, see above..\n\n // Used for one optimization. Don't rely on this otherwise.\n _hash: hash,\n\n // XXX duplicates _pathForSourceMap() in linker\n /**\n * @summary If you are generating a sourcemap for the compiled file, use\n * this path for the original file in the sourcemap.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n pathForSourceMap: files.convertToOSPath(\n inputSourceArch.pkg.name ? inputSourceArch.pkg.name + \"/\" + relPath :\n files.pathBasename(relPath), true),\n\n // null if this is an app. intended to be used for the sources\n // dictionary for source maps.\n /**\n * @summary The name of the package in which the file being built exists.\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n packageName: inputSourceArch.pkg.name,\n\n /**\n * @summary On web targets, this will be the root URL prepended\n * to the paths you pick for your output files. For example,\n * it could be \"/packages/my-package\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n rootOutputPath: files.convertToOSPath(\n inputSourceArch.pkg.serveRoot, true),\n\n /**\n * @summary The architecture for which we are building. Can be \"os\",\n * \"web.browser\", or \"web.cordova\".\n * @type {String}\n * @memberOf CompileStep\n * @instance\n */\n arch: inputSourceArch.arch,\n\n /**\n * @deprecated in 0.9.4\n * This is a duplicate API of the above, we don't need it.\n */\n archMatches: function (pattern) {\n return archinfo.matches(inputSourceArch.arch, pattern);\n },\n\n /**\n * @summary Any options passed to \"api.addFiles\".\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n fileOptions: fileOptions,\n\n /**\n * @summary The list of exports that the current package has defined.\n * Can be used to treat those symbols differently during compilation.\n * @type {Object}\n * @memberOf CompileStep\n * @instance\n */\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n\n /**\n * @summary Read from the input file. If `n` is specified, returns the\n * next `n` bytes of the file as a Buffer. XXX not sure if this actually\n * returns a String sometimes...\n * @param {Integer} [n] The number of bytes to return.\n * @instance\n * @memberOf CompileStep\n * @returns {Buffer}\n */\n read: function (n) {\n if (n === undefined || readOffset + n > contents.length)\n n = contents.length - readOffset;\n var ret = contents.slice(readOffset, readOffset + n);\n readOffset += n;\n return ret;\n },\n\n /**\n * @summary Works in web targets only. Add markup to the `head` or `body`\n * section of the document.\n * @param {Object} options\n * @param {String} options.section Which section of the document should\n * be appended to. Can only be \"head\" or \"body\".\n * @param {String} options.data The content to append.\n * @memberOf CompileStep\n * @instance\n */\n addHtml: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Document sections can only be emitted to \" +\n \"web targets\");\n if (options.section !== \"head\" && options.section !== \"body\")\n throw new Error(\"'section' must be 'head' or 'body'\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to appendDocument must be a string\");\n resources.push({\n type: options.section,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')\n });\n },\n\n /**\n * @deprecated in 0.9.4\n */\n appendDocument: function (options) {\n this.addHtml(options);\n },\n\n /**\n * @summary Web targets only. Add a stylesheet to the document.\n * @param {Object} options\n * @param {String} path The requested path for the added CSS, may not be\n * satisfied if there are path conflicts.\n * @param {String} data The content of the stylesheet that should be\n * added.\n * @param {String} sourceMap A stringified JSON sourcemap, in case the\n * stylesheet was generated from a different file.\n * @memberOf CompileStep\n * @instance\n */\n addStylesheet: function (options) {\n if (! archinfo.matches(inputSourceArch.arch, \"web\"))\n throw new Error(\"Stylesheets can only be emitted to \" +\n \"web targets\");\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addStylesheet must be a string\");\n resources.push({\n type: \"css\",\n refreshable: true,\n data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),\n servePath: colonConverter.convert(\n files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true))),\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath)\n });\n },\n\n /**\n * @summary Add JavaScript code. The code added will only see the\n * namespaces imported by this package as runtime dependencies using\n * ['api.use'](#PackageAPI-use). If the file being compiled was added\n * with the bare flag, the resulting JavaScript won't be wrapped in a\n * closure.\n * @param {Object} options\n * @param {String} options.path The path at which the JavaScript file\n * should be inserted, may not be honored in case of path conflicts.\n * @param {String} options.data The code to be added.\n * @param {String} options.sourcePath The path that will be used in\n * any error messages generated by this file, e.g. `foo.js:4:1: error`.\n * @memberOf CompileStep\n * @instance\n */\n addJavaScript: function (options) {\n if (typeof options.data !== \"string\")\n throw new Error(\"'data' option to addJavaScript must be a string\");\n if (typeof options.sourcePath !== \"string\")\n throw new Error(\"'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.\");\n\n // By default, use fileOptions for the `bare` option but also allow\n // overriding it with the options\n var bare = fileOptions.bare;\n if (options.hasOwnProperty(\"bare\")) {\n bare = options.bare;\n }\n\n js.push({\n source: files.convertToStandardLineEndings(options.data),\n sourcePath: files.convertToStandardPath(options.sourcePath, true),\n servePath: files.pathJoin(\n inputSourceArch.pkg.serveRoot,\n files.convertToStandardPath(options.path, true)),\n bare: !! bare,\n sourceMap: convertSourceMapPaths(options.sourceMap,\n files.convertToStandardPath),\n sourceHash: options._hash\n });\n },\n\n /**\n * @summary Add a file to serve as-is to the browser or to include on\n * the browser, depending on the target. On the web, it will be served\n * at the exact path requested. For server targets, it can be retrieved\n * using `Assets.getText` or `Assets.getBinary`.\n * @param {Object} options\n * @param {String} path The path at which to serve the asset.\n * @param {Buffer|String} data The data that should be placed in\n * the file.\n * @memberOf CompileStep\n * @instance\n */\n addAsset: function (options) {\n if (! (options.data instanceof Buffer)) {\n if (_.isString(options.data)) {\n options.data = new Buffer(options.data);\n } else {\n throw new Error(\"'data' option to addAsset must be a Buffer or String.\");\n }\n }\n\n addAsset(options.data, files.convertToStandardPath(options.path, true));\n },\n\n /**\n * @summary Display a build error.\n * @param {Object} options\n * @param {String} message The error message to display.\n * @param {String} [sourcePath] The path to display in the error message.\n * @param {Integer} line The line number to display in the error message.\n * @param {String} func The function name to display in the error message.\n * @memberOf CompileStep\n * @instance\n */\n error: function (options) {\n buildmessage.error(options.message || (\"error building \" + relPath), {\n file: options.sourcePath,\n line: options.line ? options.line : undefined,\n column: options.column ? options.column : undefined,\n func: options.func ? options.func : undefined\n });\n }\n };\n\n try {\n (buildmessage.markBoundary(handler))(compileStep);\n } catch (e) {\n e.message = e.message + \" (compiling \" + relPath + \")\";\n buildmessage.exception(e);\n\n // Recover by ignoring this source file (as best we can -- the\n // handler might already have emitted resources)\n }\n });\n\n // *** Run Phase 1 link\n\n // Load jsAnalyze from the js-analyze package... unless we are the\n // js-analyze package, in which case never mind. (The js-analyze package's\n // default unibuild is not allowed to depend on anything!)\n var jsAnalyze = null;\n if (! _.isEmpty(js) && inputSourceArch.pkg.name !== \"js-analyze\") {\n jsAnalyze = isopackets.load('js-analyze')['js-analyze'].JSAnalyze;\n }\n\n var results = linker.prelink({\n inputFiles: js,\n useGlobalNamespace: isApp,\n // I was confused about this, so I am leaving a comment -- the\n // combinedServePath is either [pkgname].js or [pluginName]:plugin.js.\n // XXX: If we change this, we can get rid of source arch names!\n combinedServePath: isApp ? null :\n \"/packages/\" + colonConverter.convert(\n inputSourceArch.pkg.name +\n (inputSourceArch.kind === \"main\" ? \"\" : (\":\" + inputSourceArch.kind)) +\n \".js\"),\n name: inputSourceArch.pkg.name || null,\n declaredExports: _.pluck(inputSourceArch.declaredExports, 'name'),\n jsAnalyze: jsAnalyze,\n noLineNumbers: noLineNumbers\n });\n\n // *** Determine captured variables\n var packageVariables = [];\n var packageVariableNames = {};\n _.each(inputSourceArch.declaredExports, function (symbol) {\n if (_.has(packageVariableNames, symbol.name))\n return;\n packageVariables.push({\n name: symbol.name,\n export: symbol.testOnly? \"tests\" : true\n });\n packageVariableNames[symbol.name] = true;\n });\n _.each(results.assignedVariables, function (name) {\n if (_.has(packageVariableNames, name))\n return;\n packageVariables.push({\n name: name\n });\n packageVariableNames[name] = true;\n });\n\n // *** Consider npm dependencies and portability\n var arch = inputSourceArch.arch;\n if (arch === \"os\" && ! isPortable) {\n // Contains non-portable compiled npm modules, so set arch correctly\n arch = archinfo.host();\n }\n if (! archinfo.matches(arch, \"os\")) {\n // npm modules only work on server architectures\n nodeModulesPath = undefined;\n }\n\n // *** Output unibuild object\n isopk.addUnibuild({\n kind: inputSourceArch.kind,\n arch: arch,\n uses: inputSourceArch.uses,\n implies: inputSourceArch.implies,\n watchSet: watchSet,\n nodeModulesPath: nodeModulesPath,\n prelinkFiles: results.files,\n packageVariables: packageVariables,\n resources: resources\n });\n\n return {\n pluginProviderPackageNames: pluginProviderPackageNames\n };\n};\n\nvar runLinters = function (\n inputSourceArch,\n isopackCache,\n wrappedSourceItems,\n linterPluginsByExtension) {\n // For linters, figure out what are the global imports from other packages\n // that we use directly, or are implied.\n var globalImports = ['Package', 'Assets', 'Npm'];\n compiler.eachUsedUnibuild({\n dependencies: inputSourceArch.uses,\n arch: inputSourceArch.arch,\n isopackCache: isopackCache,\n skipUnordered: true,\n skipDebugOnly: true\n }, function (unibuild) {\n if (unibuild.pkg.name === inputSourceArch.pkg.name)\n return;\n _.each(unibuild.packageVariables, function (symbol) {\n if (symbol.export === true)\n globalImports.push(symbol.name);\n });\n });\n\n // For each file choose the longest extension handled by linters.\n var longestMatchingExt = {};\n _.each(wrappedSourceItems, function (wrappedSource) {\n var filename = files.pathBasename(wrappedSource.relPath);\n var parts = filename.split('.');\n for (var i = 1; i < parts.length; i++) {\n var extension = parts.slice(i).join('.');\n if (_.has(linterPluginsByExtension, extension)) {\n longestMatchingExt[wrappedSource.relPath] = extension;\n break;\n }\n }\n });\n\n // Run linters on files.\n _.each(linterPluginsByExtension, function (linters, ext) {\n var sourcesToLint = [];\n _.each(wrappedSourceItems, function (wrappedSource) {\n var relPath = wrappedSource.relPath;\n var hash = wrappedSource.hash;\n var fileWatchSet = wrappedSource.watchset;\n var source = wrappedSource.source;\n\n // only run linters matching the longest handled extension\n if (longestMatchingExt[relPath] !== ext)\n return;\n\n sourcesToLint.push(new linterPluginModule.LintingFile(wrappedSource));\n });\n\n _.each(linters, function (linterDef) {\n // skip linters not relevant to the arch we are compiling for\n if (! linterDef.relevantForArch(inputSourceArch.arch))\n return;\n\n var linter = linterDef.instantiatePlugin();\n buildmessage.enterJob({\n title: \"linting files with \" + linterDef.isopack.name\n }, function () {\n try {\n var markedLinter = buildmessage.markBoundary(linter.run.bind(linter));\n markedLinter(sourcesToLint, globalImports);\n } catch (e) {\n buildmessage.exception(e);\n }\n });\n });\n });\n};\n\n// Iterates over each in options.dependencies as well as unibuilds implied by\n// them. The packages in question need to already be built and in\n// options.isopackCache.\ncompiler.eachUsedUnibuild = function (\n options, callback) {\n buildmessage.assertInCapture();\n var dependencies = options.dependencies;\n var arch = options.arch;\n var isopackCache = options.isopackCache;\n\n var acceptableWeakPackages = options.acceptableWeakPackages || {};\n\n var processedUnibuildId = {};\n var usesToProcess = [];\n _.each(dependencies, function (use) {\n if (options.skipUnordered && use.unordered)\n return;\n if (use.weak && !_.has(acceptableWeakPackages, use.package))\n return;\n usesToProcess.push(use);\n });\n\n while (! _.isEmpty(usesToProcess)) {\n var use = usesToProcess.shift();\n\n var usedPackage = isopackCache.getIsopack(use.package);\n\n // Ignore this package if we were told to skip debug-only packages and it is\n // debug-only.\n if (usedPackage.debugOnly && options.skipDebugOnly)\n continue;\n\n var unibuild = usedPackage.getUnibuildAtArch(arch);\n if (!unibuild) {\n // The package exists but there's no unibuild for us. A buildmessage has\n // already been issued. Recover by skipping.\n continue;\n }\n\n if (_.has(processedUnibuildId, unibuild.id))\n continue;\n processedUnibuildId[unibuild.id] = true;\n\n callback(unibuild, {\n unordered: !!use.unordered,\n weak: !!use.weak\n });\n\n _.each(unibuild.implies, function (implied) {\n usesToProcess.push(implied);\n });\n }\n};\n", "file_path": "tools/compiler.js", "label": 1, "commit_url": "https://github.com/meteor/meteor/commit/aaa9e606d4836dd1d458975896bcb7be25bc0be7", "dependency_score": [0.9990137815475464, 0.030897926539182663, 0.0001645415322855115, 0.00023548136232420802, 0.16381992399692535]} {"hunk": {"id": 7, "code_window": [" // For linters, figure out what are the global imports from other packages\n", " // that we use directly, or are implied.\n", " var globalImports = ['Package', 'Assets', 'Npm'];\n", " compiler.eachUsedUnibuild({\n", " dependencies: inputSourceArch.uses,\n", " arch: inputSourceArch.arch,\n"], "labels": ["keep", "keep", "replace", "keep", "keep", "keep"], "after_edit": [" var globalImports = ['Package'];\n", "\n", " if (archinfo.matches(inputSourceArch.arch, \"os\")) {\n", " globalImports = globalImports.concat(['Npm', 'Assets']);\n", " }\n", "\n"], "file_path": "tools/compiler.js", "type": "replace", "edit_start_line_idx": 957}, "file": "# html-tools\n\nA lightweight HTML tokenizer and parser which outputs to the HTMLjs\nobject representation. Special hooks allow the syntax to be extended\nto parse an HTML-like template language like Spacebars.\n\n```\nHTMLTools.parseFragment(\"
Hello
World
\")\n\n=> HTML.DIV({'class':'greeting'}, \"Hello\", HTML.BR(), \"World\"))\n```\n\nThis package is used by the Spacebars compiler, which normally only\nruns at bundle time but can also be used at runtime on the client or\nserver.\n\n## Invoking the Parser\n\n`HTMLTools.parseFragment(input, options)` - Takes an input string or Scanner object and returns HTMLjs.\n\nIn the basic case, where no options are passed, `parseFragment` will consume the entire input (the full string or the rest of the Scanner).\n\nThe options are as follows:\n\n#### getTemplateTag\n\nThis option extends the HTML parser to parse template tags such as `{{foo}}`.\n\n`getTemplateTag: function (scanner, templateTagPosition) { ... }` - A function for the parser to call after every HTML token and at various positions within tags. If the function returns an instanceof `HTMLTools.TemplateTag`, it is inserted into the HTMLjs tree at the appropriate location. The constructor is `HTMLTools.TemplateTag(props)`, where props is an object whose properties are copied to the `TemplateTag` instance. You can also call the constructor with no arguments and assign whatever properties you want, or you can subclass `TemplateTag`.\n\nThere are four possible outcomes when `getTemplateTag` is called:\n\n* Not a template tag - Leave the scanner as is, and return `null`. A quick peek at the next character should bail to this case if the start of a template tag is not seen.\n* Bad template tag - Call `scanner.fatal`, which aborts parsing completely. Once the beginning of a template tag is seen, `getTemplateTag` will generally want to commit, and either succeed or fail trying).\n* Good template tag - Advance the scanner to the end of the template tag and return an `HTMLTools.TemplateTag` object.\n* Comment tag - Advance the scanner and return `null`. For example, a Spacebars comment is `{{! foo}}`.\n\nThe `templateTagPosition` argument to `getTemplateTag` is one of:\n\n* `HTMLTools.TEMPLATE_TAG_POSITION.ELEMENT` - At \"element level,\" meaning somewhere an HTML tag could be.\n* `HTMLTools.TEMPLATE_TAG_POSITION.IN_START_TAG` - Inside a start tag, as in `
`, where you might otherwise find `name=value`.\n* `HTMLTools.TEMPLATE_TAG_POSITION.IN_ATTRIBUTE` - Inside the value of an HTML attribute, as in `
`.\n* `HTMLTools.TEMPLATE_TAG_POSITION.IN_RCDATA` - Inside a TEXTAREA or a block helper inside an attribute, where character references are allowed (\"replaced character data\") but not tags.\n* `HTMLTools.TEMPLATE_TAG_POSITION.IN_RAWTEXT` - In a context where character references are not parsed, such as a script tag, style tag, or markdown helper.\n\nIt's completely normal for `getTemplateTag` to invoke `HTMLTools.parseFragment` recursively on the same scanner (see `shouldStop`). If it does so, the same value of `getTemplateTag` must be passed to the second invocation.\n\nAt the moment, template tags must begin with `{`. The parser does not try calling `getTemplateTag` for every character of an HTML document, only at token boundaries, and it knows to always end a token at `{`.\n\n#### textMode\n\nThe `textMode` option, if present, causes the parser to parse text (such as the contents of a `\n

Display a logo on your site in place of blog title

\n \n\n \n\n \n \n \n
\n
\n

Users

\n
\n \n
\n
\n
\n
\n

Invited Users

\n
    \n
  • \n
    \n
    \n

    Some Name

    \n Invitation Sent: 7 hours ago\n
    \n
  • \n
\n
\n
\n
\n

Active Users

\n\n
\n \n
\n
\n\n
    \n
  • \n
    \n \"user\"/\n
    \n
    \n

    Some Name

    \n Last Seen: 7 hours ago\n
    \n Admin\n
  • \n
  • \n
    \n \"user\"/\n
    \n
    \n

    Some Name

    \n Last Seen: 2 days ago\n
    \n Editor\n
  • \n
\n
\n
\n
\n
\n
\n

Appearance

\n
\n
\n
Raw json be here
\n

Active theme: {{json settings.activeTheme}}

\n

Available themes: {{json availableThemes}}

\n

Available plugins: {{json availablePlugins}}

\n
\n
\n
", "file_path": "core/server/views/settings.hbs", "label": 1, "commit_url": "https://github.com/TryGhost/Ghost/commit/3d3d42bd7c659397f69d8522cce2f4f09776078b", "dependency_score": [0.0005843086983077228, 0.0001913788146339357, 0.00016452711133752018, 0.00016838264127727598, 8.507016900693998e-05]} {"hunk": {"id": 0, "code_window": [" handlebars: {\n", " core: {\n", " options: {\n", " namespace: \"JST\",\n", " processName: function (filename) {\n", " filename = filename.replace('./core/client/tpl/', '');\n", " return filename.replace('.hbs', '');\n", " }\n", " },\n", " files: {\n", " \"core/client/tpl/hbs-tpl.js\": \"core/client/tpl/**/*.hbs\"\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" filename = filename.replace('core/client/tpl/', '');\n"], "file_path": "Gruntfile.js", "type": "replace", "edit_start_line_idx": 129}, "file": "var User = require('./user').User,\n Permission = require('./permission').Permission,\n GhostBookshelf = require('./base'),\n Role,\n Roles;\n\nRole = GhostBookshelf.Model.extend({\n tableName: 'roles',\n\n users: function () {\n return this.belongsToMany(User);\n },\n\n permissions: function () {\n return this.belongsToMany(Permission);\n }\n});\n\nRoles = GhostBookshelf.Collection.extend({\n model: Role\n});\n\nmodule.exports = {\n Role: Role,\n Roles: Roles\n};\n", "file_path": "core/server/models/role.js", "label": 0, "commit_url": "https://github.com/TryGhost/Ghost/commit/3d3d42bd7c659397f69d8522cce2f4f09776078b", "dependency_score": [0.00016966406838037074, 0.0001676754473010078, 0.00016571579908486456, 0.00016764650354161859, 1.6120042118927813e-06]} {"hunk": {"id": 0, "code_window": [" handlebars: {\n", " core: {\n", " options: {\n", " namespace: \"JST\",\n", " processName: function (filename) {\n", " filename = filename.replace('./core/client/tpl/', '');\n", " return filename.replace('.hbs', '');\n", " }\n", " },\n", " files: {\n", " \"core/client/tpl/hbs-tpl.js\": \"core/client/tpl/**/*.hbs\"\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" filename = filename.replace('core/client/tpl/', '');\n"], "file_path": "Gruntfile.js", "type": "replace", "edit_start_line_idx": 129}, "file": "/*globals Handlebars, moment\n*/\n(function () {\n \"use strict\";\n Handlebars.registerHelper('dateFormat', function (context, block) {\n var f = block.hash.format || \"MMM Do, YYYY\",\n timeago = block.hash.timeago,\n date;\n if (timeago) {\n date = moment(context).fromNow();\n } else {\n date = moment(context).format(f);\n }\n return date;\n });\n}());\n", "file_path": "core/client/helpers/index.js", "label": 0, "commit_url": "https://github.com/TryGhost/Ghost/commit/3d3d42bd7c659397f69d8522cce2f4f09776078b", "dependency_score": [0.00016605365090072155, 0.00016517232870683074, 0.0001642909919610247, 0.00016517232870683074, 8.813294698484242e-07]} {"hunk": {"id": 0, "code_window": [" handlebars: {\n", " core: {\n", " options: {\n", " namespace: \"JST\",\n", " processName: function (filename) {\n", " filename = filename.replace('./core/client/tpl/', '');\n", " return filename.replace('.hbs', '');\n", " }\n", " },\n", " files: {\n", " \"core/client/tpl/hbs-tpl.js\": \"core/client/tpl/**/*.hbs\"\n"], "labels": ["keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep"], "after_edit": [" filename = filename.replace('core/client/tpl/', '');\n"], "file_path": "Gruntfile.js", "type": "replace", "edit_start_line_idx": 129}, "file": "\n\n\n\n\n\n\n \n\n Ghost\n\n \n \n\n \n \n \n\n \n \n\n \n \n \n\n\n\n\n\n
\n Ghost\n \n
\n\n
\n\n \n\n
\n
\n
\n Published + Featured\n
\n \n
\n
\n
\n

Ut Enim ad Minim Veniam Quis Nostrud Exercitation Ullamco

\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu.

\n\n

This is a Heading 2

\n

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisicing elit, Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

\n\n \"\"\n\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

\n\n
    \n
  • Lorem ipsum dolor sit amet
  • \n
  • Lorem ipsum dolor sit amet
  • \n
  • Lorem ipsum dolor sit amet
  • \n
  • Lorem ipsum dolor sit amet
  • \n
  • Lorem ipsum dolor sit amet
  • \n
\n\n

This is a Heading 3

\n\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

\n\n
    \n
  1. Lorem ipsum dolor sit amet
  2. \n
  3. Lorem ipsum dolor sit amet
  4. \n
  5. Lorem ipsum dolor sit amet
  6. \n
  7. Lorem ipsum dolor sit amet
  8. \n
  9. Lorem ipsum dolor sit amet
  10. \n
\n\n
\n
\n
\n\n
\n\n\n\n\n\n", "file_path": "core/test/html/manage.html", "label": 0, "commit_url": "https://github.com/TryGhost/Ghost/commit/3d3d42bd7c659397f69d8522cce2f4f09776078b", "dependency_score": [0.00017727274098433554, 0.00017123269208241254, 0.0001647273893468082, 0.00017223093891516328, 3.368090119693079e-06]} {"hunk": {"id": 1, "code_window": ["\n", " \n", "\n", "