hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 4, "code_window": [ " if (\n", " this.parentPath.isExpressionStatement() ||\n", " this.parentPath.isLabeledStatement()\n", " ) {\n", " // `replaceWithMultiple` requeues if there's a replacement for this.node,\n", " // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement\n", " // for an ancestor node can be enqueued. Fix #5628 and #5023.\n", " return this.parentPath._insertAfter(nodes, true);\n", " } else if (\n", " this.isNodeType(\"Expression\") ||\n", " (this.parentPath.isForStatement() && this.key === \"init\")\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return this.parentPath.insertAfter(nodes);\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 118 }
import { basename, extname } from "path"; import template from "babel-template"; import * as t from "babel-types"; import transformStrictMode from "babel-plugin-transform-strict-mode"; const buildRequire = template(` require($0); `); const buildExportsModuleDeclaration = template(` Object.defineProperty(exports, "__esModule", { value: true }); `); const buildExportsFrom = template(` Object.defineProperty(exports, $0, { enumerable: true, get: function () { return $1; } }); `); const buildLooseExportsModuleDeclaration = template(` exports.__esModule = true; `); const buildExportsAssignment = template(` exports.$0 = $1; `); const buildExportAll = template(` Object.keys(OBJECT).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return OBJECT[key]; } }); }); `); const THIS_BREAK_KEYS = [ "FunctionExpression", "FunctionDeclaration", "ClassProperty", "ClassMethod", "ObjectMethod", ]; export default function() { const REASSIGN_REMAP_SKIP = Symbol(); const reassignmentVisitor = { ReferencedIdentifier(path) { const name = path.node.name; const remap = this.remaps[name]; if (!remap) return; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; if (path.parentPath.isCallExpression({ callee: path.node })) { path.replaceWith(t.sequenceExpression([t.numericLiteral(0), remap])); } else if (path.isJSXIdentifier() && t.isMemberExpression(remap)) { const { object, property } = remap; path.replaceWith( t.JSXMemberExpression( t.JSXIdentifier(object.name), t.JSXIdentifier(property.name), ), ); } else { path.replaceWith( // Clone the node before inserting it to ensure that different nodes in the AST are represented // by different objects. t.cloneWithoutLoc(remap), ); } this.requeueInParent(path); }, AssignmentExpression(path) { let node = path.node; if (node[REASSIGN_REMAP_SKIP]) return; const left = path.get("left"); if (left.isIdentifier()) { const name = left.node.name; const exports = this.exports[name]; if (!exports) return; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; node[REASSIGN_REMAP_SKIP] = true; for (const reid of exports) { node = buildExportsAssignment(reid, node).expression; } path.replaceWith(node); this.requeueInParent(path); } else if (left.isObjectPattern()) { for (const property of left.node.properties) { const name = property.value.name; const exports = this.exports[name]; if (!exports) continue; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) { return; } node[REASSIGN_REMAP_SKIP] = true; path.insertAfter( buildExportsAssignment(t.identifier(name), t.identifier(name)), ); } } else if (left.isArrayPattern()) { for (const element of left.node.elements) { if (!element) continue; const name = element.name; const exports = this.exports[name]; if (!exports) continue; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) { return; } node[REASSIGN_REMAP_SKIP] = true; path.insertAfter( buildExportsAssignment(t.identifier(name), t.identifier(name)), ); } } }, UpdateExpression(path) { const arg = path.get("argument"); if (!arg.isIdentifier()) return; const name = arg.node.name; const exports = this.exports[name]; if (!exports) return; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; const node = t.assignmentExpression( path.node.operator[0] + "=", arg.node, t.numericLiteral(1), ); if ( (path.parentPath.isExpressionStatement() && !path.isCompletionRecord()) || path.node.prefix ) { path.replaceWith(node); this.requeueInParent(path); return; } const nodes = []; nodes.push(node); let operator; if (path.node.operator === "--") { operator = "+"; } else { // "++" operator = "-"; } nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1))); path.replaceWithMultiple(t.sequenceExpression(nodes)); }, }; return { inherits: transformStrictMode, visitor: { ThisExpression(path, state) { // If other plugins run after this plugin's Program#exit handler, we allow them to // insert top-level `this` values. This allows the AMD and UMD plugins to // function properly. if (this.ranCommonJS) return; if ( state.opts.allowTopLevelThis !== true && !path.findParent(path => THIS_BREAK_KEYS.indexOf(path.type) >= 0) ) { path.replaceWith(path.scope.buildUndefinedNode()); } }, Program: { exit(path) { this.ranCommonJS = true; const strict = !!this.opts.strict; const noInterop = !!this.opts.noInterop; const { scope } = path; // rename these commonjs variables if they're declared in the file scope.rename("module"); scope.rename("exports"); scope.rename("require"); let hasExports = false; let hasImports = false; const body: Array<Object> = path.get("body"); const imports = Object.create(null); const exports = Object.create(null); const nonHoistedExportNames = Object.create(null); const topNodes = []; const remaps = Object.create(null); const requires = Object.create(null); function addRequire(source, blockHoist) { const cached = requires[source]; if (cached) return cached; const ref = path.scope.generateUidIdentifier( basename(source, extname(source)), ); const varDecl = t.variableDeclaration("var", [ t.variableDeclarator( ref, buildRequire(t.stringLiteral(source)).expression, ), ]); // Copy location from the original import statement for sourcemap // generation. if (imports[source]) { varDecl.loc = imports[source].loc; } if (typeof blockHoist === "number" && blockHoist > 0) { varDecl._blockHoist = blockHoist; } topNodes.push(varDecl); return (requires[source] = ref); } function addTo(obj, key, arr) { const existing = obj[key] || []; obj[key] = existing.concat(arr); } for (const path of body) { if (path.isExportDeclaration()) { hasExports = true; const specifiers = [].concat( path.get("declaration"), path.get("specifiers"), ); for (const specifier of specifiers) { const ids = specifier.getBindingIdentifiers(); if (ids.__esModule) { throw specifier.buildCodeFrameError( 'Illegal export "__esModule"', ); } } } if (path.isImportDeclaration()) { hasImports = true; const key = path.node.source.value; const importsEntry = imports[key] || { specifiers: [], maxBlockHoist: 0, loc: path.node.loc, }; importsEntry.specifiers.push(...path.node.specifiers); if (typeof path.node._blockHoist === "number") { importsEntry.maxBlockHoist = Math.max( path.node._blockHoist, importsEntry.maxBlockHoist, ); } imports[key] = importsEntry; path.remove(); } else if (path.isExportDefaultDeclaration()) { const declaration = path.get("declaration"); if (declaration.isFunctionDeclaration()) { const id = declaration.node.id; const defNode = t.identifier("default"); if (id) { addTo(exports, id.name, defNode); topNodes.push(buildExportsAssignment(defNode, id)); path.replaceWith(declaration.node); } else { topNodes.push( buildExportsAssignment( defNode, t.toExpression(declaration.node), ), ); path.remove(); } } else if (declaration.isClassDeclaration()) { const id = declaration.node.id; const defNode = t.identifier("default"); if (id) { addTo(exports, id.name, defNode); path.replaceWithMultiple([ declaration.node, buildExportsAssignment(defNode, id), ]); } else { path.replaceWith( buildExportsAssignment( defNode, t.toExpression(declaration.node), ), ); // Manualy re-queue `export default class {}` expressions so that the ES3 transform // has an opportunity to convert them. Ideally this would happen automatically from the // replaceWith above. See #4140 for more info. path.parentPath.requeue(path.get("expression.left")); } } else { path.replaceWith( buildExportsAssignment( t.identifier("default"), declaration.node, ), ); // Manualy re-queue `export default foo;` expressions so that the ES3 transform // has an opportunity to convert them. Ideally this would happen automatically from the // replaceWith above. See #4140 for more info. path.parentPath.requeue(path.get("expression.left")); } } else if (path.isExportNamedDeclaration()) { const declaration = path.get("declaration"); if (declaration.node) { if (declaration.isFunctionDeclaration()) { const id = declaration.node.id; addTo(exports, id.name, id); topNodes.push(buildExportsAssignment(id, id)); path.replaceWith(declaration.node); } else if (declaration.isClassDeclaration()) { const id = declaration.node.id; addTo(exports, id.name, id); path.replaceWithMultiple([ declaration.node, buildExportsAssignment(id, id), ]); nonHoistedExportNames[id.name] = true; } else if (declaration.isVariableDeclaration()) { const ids = declaration.getBindingIdentifierPaths(); const exportsToInsert = []; for (const name in ids) { const id = ids[name]; const { parentPath, node } = id; addTo(exports, name, node); nonHoistedExportNames[name] = true; if (parentPath.isVariableDeclarator()) { const init = parentPath.get("init"); const assignment = buildExportsAssignment( node, init.node || path.scope.buildUndefinedNode(), ); init.replaceWith(assignment.expression); } else { exportsToInsert.push(buildExportsAssignment(node, node)); } } path.insertAfter(exportsToInsert); path.replaceWith(declaration.node); } continue; } const specifiers = path.get("specifiers"); const nodes = []; const source = path.node.source; if (source) { const ref = addRequire(source.value, path.node._blockHoist); for (const specifier of specifiers) { if (specifier.isExportNamespaceSpecifier()) { // todo } else if (specifier.isExportDefaultSpecifier()) { // todo } else if (specifier.isExportSpecifier()) { if (!noInterop && specifier.node.local.name === "default") { topNodes.push( buildExportsFrom( t.stringLiteral(specifier.node.exported.name), t.memberExpression( t.callExpression( this.addHelper("interopRequireDefault"), [ref], ), specifier.node.local, ), ), ); } else { topNodes.push( buildExportsFrom( t.stringLiteral(specifier.node.exported.name), t.memberExpression(ref, specifier.node.local), ), ); } nonHoistedExportNames[specifier.node.exported.name] = true; } } } else { for (const specifier of specifiers) { if (specifier.isExportSpecifier()) { addTo( exports, specifier.node.local.name, specifier.node.exported, ); nonHoistedExportNames[specifier.node.exported.name] = true; nodes.push( buildExportsAssignment( specifier.node.exported, specifier.node.local, ), ); } } } path.replaceWithMultiple(nodes); } else if (path.isExportAllDeclaration()) { const exportNode = buildExportAll({ OBJECT: addRequire( path.node.source.value, path.node._blockHoist, ), }); exportNode.loc = path.node.loc; topNodes.push(exportNode); path.remove(); } } for (const source in imports) { const { specifiers, maxBlockHoist } = imports[source]; if (specifiers.length) { const uid = addRequire(source, maxBlockHoist); let wildcard; for (let i = 0; i < specifiers.length; i++) { const specifier = specifiers[i]; if (t.isImportNamespaceSpecifier(specifier)) { if (strict || noInterop) { remaps[specifier.local.name] = uid; } else { const varDecl = t.variableDeclaration("var", [ t.variableDeclarator( specifier.local, t.callExpression( this.addHelper("interopRequireWildcard"), [uid], ), ), ]); if (maxBlockHoist > 0) { varDecl._blockHoist = maxBlockHoist; } topNodes.push(varDecl); } wildcard = specifier.local; } else if (t.isImportDefaultSpecifier(specifier)) { specifiers[i] = t.importSpecifier( specifier.local, t.identifier("default"), ); } } for (const specifier of specifiers) { if (t.isImportSpecifier(specifier)) { let target = uid; if (specifier.imported.name === "default") { if (wildcard) { target = wildcard; } else if (!noInterop) { target = wildcard = path.scope.generateUidIdentifier( uid.name, ); const varDecl = t.variableDeclaration("var", [ t.variableDeclarator( target, t.callExpression( this.addHelper("interopRequireDefault"), [uid], ), ), ]); if (maxBlockHoist > 0) { varDecl._blockHoist = maxBlockHoist; } topNodes.push(varDecl); } } remaps[specifier.local.name] = t.memberExpression( target, t.cloneWithoutLoc(specifier.imported), ); } } } else { // bare import const requireNode = buildRequire(t.stringLiteral(source)); requireNode.loc = imports[source].loc; topNodes.push(requireNode); } } if (hasImports && Object.keys(nonHoistedExportNames).length) { // avoid creating too long of export assignment to prevent stack overflow const maxHoistedExportsNodeAssignmentLength = 100; const nonHoistedExportNamesArr = Object.keys(nonHoistedExportNames); for ( let currentExportsNodeAssignmentLength = 0; currentExportsNodeAssignmentLength < nonHoistedExportNamesArr.length; currentExportsNodeAssignmentLength += maxHoistedExportsNodeAssignmentLength ) { const nonHoistedExportNamesChunk = nonHoistedExportNamesArr.slice( currentExportsNodeAssignmentLength, currentExportsNodeAssignmentLength + maxHoistedExportsNodeAssignmentLength, ); let hoistedExportsNode = scope.buildUndefinedNode(); nonHoistedExportNamesChunk.forEach(function(name) { hoistedExportsNode = buildExportsAssignment( t.identifier(name), hoistedExportsNode, ).expression; }); const node = t.expressionStatement(hoistedExportsNode); node._blockHoist = 3; topNodes.unshift(node); } } // add __esModule declaration if this file has any exports if (hasExports && !strict) { let buildTemplate = buildExportsModuleDeclaration; if (this.opts.loose) { buildTemplate = buildLooseExportsModuleDeclaration; } const declar = buildTemplate(); declar._blockHoist = 3; topNodes.unshift(declar); } path.unshiftContainer("body", topNodes); path.traverse(reassignmentVisitor, { remaps, scope, exports, requeueInParent: newPath => path.requeue(newPath), }); }, }, }, }; }
packages/babel-plugin-transform-es2015-modules-commonjs/src/index.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00884620938450098, 0.0008208765066228807, 0.00016435948782600462, 0.00019697067909874022, 0.0016043976647779346 ]
{ "id": 4, "code_window": [ " if (\n", " this.parentPath.isExpressionStatement() ||\n", " this.parentPath.isLabeledStatement()\n", " ) {\n", " // `replaceWithMultiple` requeues if there's a replacement for this.node,\n", " // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement\n", " // for an ancestor node can be enqueued. Fix #5628 and #5023.\n", " return this.parentPath._insertAfter(nodes, true);\n", " } else if (\n", " this.isNodeType(\"Expression\") ||\n", " (this.parentPath.isForStatement() && this.key === \"init\")\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return this.parentPath.insertAfter(nodes);\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 118 }
export {foo, bar};
packages/babel-plugin-transform-es2015-modules-systemjs/test/fixtures/systemjs/export-named-2/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.0001615228393347934, 0.0001615228393347934, 0.0001615228393347934, 0.0001615228393347934, 0 ]
{ "id": 5, "code_window": [ " (!this.isExpressionStatement() || this.node.expression != null)\n", " ) {\n", " nodes.unshift(this.node);\n", " }\n", " this._replaceWith(t.blockStatement(nodes));\n", " if (shouldRequeue) {\n", " this.requeue();\n", " }\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n", " \"We were previously a Statement but we can't fit in here?\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 144 }
// This file contains methods that modify the path/node in some ways. import { path as pathCache } from "../cache"; import PathHoister from "./lib/hoister"; import NodePath from "./index"; import * as t from "babel-types"; /** * Insert the provided nodes before the current one. */ export function insertBefore(nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); if ( this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() ) { return this.parentPath.insertBefore(nodes); } else if ( (this.isNodeType("Expression") && this.listKey !== "params") || (this.parentPath.isForStatement() && this.key === "init") ) { if (this.node) nodes.push(this.node); this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertBefore(nodes); } else if (this.isStatementOrBlock()) { if (this.node) nodes.push(this.node); this._replaceWith(t.blockStatement(nodes)); } else { throw new Error( "We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?", ); } return [this]; } export function _containerInsert(from, nodes) { this.updateSiblingKeys(from, nodes.length); const paths = []; for (let i = 0; i < nodes.length; i++) { const to = from + i; const node = nodes[i]; this.container.splice(to, 0, node); if (this.context) { const path = this.context.create( this.parent, this.container, to, this.listKey, ); // While this path may have a context, there is currently no guarantee that the context // will be the active context, because `popContext` may leave a final context in place. // We should remove this `if` and always push once #4145 has been resolved. if (this.context.queue) path.pushContext(this.context); paths.push(path); } else { paths.push( NodePath.get({ parentPath: this.parentPath, parent: this.parent, container: this.container, listKey: this.listKey, key: to, }), ); } } const contexts = this._getQueueContexts(); for (const path of paths) { path.setScope(); path.debug(() => "Inserted."); for (const context of contexts) { context.maybeQueue(path, true); } } return paths; } export function _containerInsertBefore(nodes) { return this._containerInsert(this.key, nodes); } export function _containerInsertAfter(nodes) { return this._containerInsert(this.key + 1, nodes); } /** * Insert the provided nodes after the current one. When inserting nodes after an * expression, ensure that the completion record is correct by pushing the current node. */ export function insertAfter(nodes) { return this._insertAfter(nodes); } export function _insertAfter(nodes, shouldRequeue = false) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); if ( this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() ) { // `replaceWithMultiple` requeues if there's a replacement for this.node, // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement // for an ancestor node can be enqueued. Fix #5628 and #5023. return this.parentPath._insertAfter(nodes, true); } else if ( this.isNodeType("Expression") || (this.parentPath.isForStatement() && this.key === "init") ) { if (this.node) { const temp = this.scope.generateDeclaredUidIdentifier(); nodes.unshift( t.expressionStatement(t.assignmentExpression("=", temp, this.node)), ); nodes.push(t.expressionStatement(temp)); } this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertAfter(nodes); } else if (this.isStatementOrBlock()) { // Unshift current node if it's not an empty expression if ( this.node && (!this.isExpressionStatement() || this.node.expression != null) ) { nodes.unshift(this.node); } this._replaceWith(t.blockStatement(nodes)); if (shouldRequeue) { this.requeue(); } } else { throw new Error( "We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?", ); } return [this]; } /** * Update all sibling node paths after `fromIndex` by `incrementBy`. */ export function updateSiblingKeys(fromIndex, incrementBy) { if (!this.parent) return; const paths = pathCache.get(this.parent); for (let i = 0; i < paths.length; i++) { const path = paths[i]; if (path.key >= fromIndex) { path.key += incrementBy; } } } export function _verifyNodeList(nodes) { if (!nodes) { return []; } if (nodes.constructor !== Array) { nodes = [nodes]; } for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; let msg; if (!node) { msg = "has falsy node"; } else if (typeof node !== "object") { msg = "contains a non-object node"; } else if (!node.type) { msg = "without a type"; } else if (node instanceof NodePath) { msg = "has a NodePath when it expected a raw object"; } if (msg) { const type = Array.isArray(node) ? "array" : typeof node; throw new Error( `Node list ${msg} with the index of ${i} and type of ${type}`, ); } } return nodes; } export function unshiftContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); // get the first path and insert our nodes before it, if it doesn't exist then it // doesn't matter, our nodes will be inserted anyway const path = NodePath.get({ parentPath: this, parent: this.node, container: this.node[listKey], listKey, key: 0, }); return path.insertBefore(nodes); } export function pushContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); // get an invisible path that represents the last node + 1 and replace it with our // nodes, effectively inlining it const container = this.node[listKey]; const path = NodePath.get({ parentPath: this, parent: this.node, container: container, listKey, key: container.length, }); return path.replaceWithMultiple(nodes); } /** * Hoist the current node to the highest scope possible and return a UID * referencing it. */ export function hoist(scope = this.scope) { const hoister = new PathHoister(this, scope); return hoister.run(); }
packages/babel-traverse/src/path/modification.js
1
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.9976255297660828, 0.0770072415471077, 0.00016462312487419695, 0.0004760417796205729, 0.2606859505176544 ]
{ "id": 5, "code_window": [ " (!this.isExpressionStatement() || this.node.expression != null)\n", " ) {\n", " nodes.unshift(this.node);\n", " }\n", " this._replaceWith(t.blockStatement(nodes));\n", " if (shouldRequeue) {\n", " this.requeue();\n", " }\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n", " \"We were previously a Statement but we can't fit in here?\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 144 }
define(["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = 42; });
packages/babel-plugin-transform-es2015-modules-amd/test/fixtures/amd/export-default/expected.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017442354874219745, 0.00017442354874219745, 0.00017442354874219745, 0.00017442354874219745, 0 ]
{ "id": 5, "code_window": [ " (!this.isExpressionStatement() || this.node.expression != null)\n", " ) {\n", " nodes.unshift(this.node);\n", " }\n", " this._replaceWith(t.blockStatement(nodes));\n", " if (shouldRequeue) {\n", " this.requeue();\n", " }\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n", " \"We were previously a Statement but we can't fit in here?\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 144 }
# Blank .gitignore to ensure this directory exists. !.gitignore
packages/babel-core/test/fixtures/config/ignore-negate-folder/folder/.gitignore
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017346521781291813, 0.00017346521781291813, 0.00017346521781291813, 0.00017346521781291813, 0 ]
{ "id": 5, "code_window": [ " (!this.isExpressionStatement() || this.node.expression != null)\n", " ) {\n", " nodes.unshift(this.node);\n", " }\n", " this._replaceWith(t.blockStatement(nodes));\n", " if (shouldRequeue) {\n", " this.requeue();\n", " }\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n", " \"We were previously a Statement but we can't fit in here?\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 144 }
{ "plugins": ["jsx" ] }
packages/babel-generator/test/fixtures/types/XJSSpreadAttribute/options.json
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017329907859675586, 0.00017329907859675586, 0.00017329907859675586, 0.00017329907859675586, 0 ]
{ "id": 0, "code_window": [ " matcherName: options.matcherName,\n", " message: message(),\n", " stack: stack(),\n", " passed: options.passed\n", " };\n", "\n", " if(!result.passed) {\n", " result.expected = options.expected;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " passed: options.passed,\n", " // CUSTOM JEST CHANGE: we pass error message to the result.\n", " error: options.error\n" ], "file_path": "packages/jest-jasmine2/vendor/jasmine-2.5.2.js", "type": "replace", "edit_start_line_idx": 1000 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ /* eslint-disable max-len */ 'use strict'; import type { MatchersObject, } from 'types/Matchers'; const { toMatchSnapshot, } = require('jest-snapshot'); const diff = require('jest-diff'); const {escapeStrForRegex} = require('jest-util'); const {getPath} = require('./utils'); const { EXPECTED_COLOR, RECEIVED_COLOR, ensureNoExpected, ensureNumbers, getType, matcherHint, printReceived, printExpected, printWithType, } = require('jest-matcher-utils'); type ContainIterable = ( Array<any> | Set<any> | NodeList<any> | DOMTokenList | HTMLCollection<any> ); const IteratorSymbol = Symbol.iterator; const equals = global.jasmine.matchersUtil.equals; const hasIterator = object => !!(object != null && object[IteratorSymbol]); const iterableEquality = (a, b) => { if ( typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b) ) { return undefined; } if (a.constructor !== b.constructor) { return false; } const bIterator = b[IteratorSymbol](); for (const aValue of a) { const nextB = bIterator.next(); if ( nextB.done || !global.jasmine.matchersUtil.equals( aValue, nextB.value, [iterableEquality], ) ) { return false; } } if (!bIterator.next().done) { return false; } return true; }; const matchers: MatchersObject = { toBe(received: any, expected: number) { const pass = received === expected; const message = pass ? () => matcherHint('.not.toBe') + '\n\n' + `Expected value to not be (using ===):\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return matcherHint('.toBe') + '\n\n' + `Expected value to be (using ===):\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` + (diffString ? `\n\nDifference:\n\n${diffString}` : ''); }; return {message, pass}; }, toBeCloseTo( actual: number, expected: number, precision?: number = 2, ) { ensureNumbers(actual, expected, '.toBeCloseTo'); const pass = Math.abs(expected - actual) < (Math.pow(10, -precision) / 2); const message = pass ? () => matcherHint('.not.toBeCloseTo', 'received', 'expected, precision') + '\n\n' + `Expected value not to be close to (with ${printExpected(precision)}-digit precision):\n` + ` ${printExpected(expected)}\n` + `Received: \n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeCloseTo', 'received', 'expected, precision') + '\n\n' + `Expected value to be close to (with ${printExpected(precision)}-digit precision):\n` + ` ${printExpected(expected)}\n` + `Received: \n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeDefined(actual: any, expected: void) { ensureNoExpected(expected, '.toBeDefined'); const pass = actual !== void 0; const message = pass ? () => matcherHint('.not.toBeDefined', 'received', '') + '\n\n' + `Expected value not to be defined, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeDefined', 'received', '') + '\n\n' + `Expected value to be defined, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeFalsy(actual: any, expected: void) { ensureNoExpected(expected, '.toBeFalsy'); const pass = !actual; const message = pass ? () => matcherHint('.not.toBeFalsy', 'received', '') + '\n\n' + `Expected value not to be falsy, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeFalsy', 'received', '') + '\n\n' + `Expected value to be falsy, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeGreaterThan(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeGreaterThan'); const pass = actual > expected; const message = pass ? () => matcherHint('.not.toBeGreaterThan') + '\n\n' + `Expected value not to be greater than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeGreaterThan') + '\n\n' + `Expected value to be greater than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeGreaterThanOrEqual(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeGreaterThanOrEqual'); const pass = actual >= expected; const message = pass ? () => matcherHint('.not.toBeGreaterThanOrEqual') + '\n\n' + `Expected value not to be greater than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeGreaterThanOrEqual') + '\n\n' + `Expected value to be greater than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeInstanceOf(received: any, constructor: Function) { const constType = getType(constructor); if (constType !== 'function') { throw new Error( matcherHint('[.not].toBeInstanceOf', 'value', 'constructor') + `\n\n` + `Expected constructor to be a function. Instead got:\n` + ` ${printExpected(constType)}`, ); } const pass = received instanceof constructor; const message = pass ? () => matcherHint('.not.toBeInstanceOf', 'value', 'constructor') + '\n\n' + `Expected value not to be an instance of:\n` + ` ${printExpected(constructor.name || constructor)}\n` + `Received:\n` + ` ${printReceived(received)}\n` : () => matcherHint('.toBeInstanceOf', 'value', 'constructor') + '\n\n' + `Expected value to be an instance of:\n` + ` ${printExpected(constructor.name || constructor)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `Constructor:\n` + ` ${printReceived(received.constructor && received.constructor.name)}`; return {message, pass}; }, toBeLessThan(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeLessThan'); const pass = actual < expected; const message = pass ? () => matcherHint('.not.toBeLessThan') + '\n\n' + `Expected value not to be less than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeLessThan') + '\n\n' + `Expected value to be less than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeLessThanOrEqual(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeLessThanOrEqual'); const pass = actual <= expected; const message = pass ? () => matcherHint('.not.toBeLessThanOrEqual') + '\n\n' + `Expected value not to be less than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeLessThanOrEqual') + '\n\n' + `Expected value to be less than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeNaN(actual: any, expected: void) { ensureNoExpected(expected, '.toBeNaN'); const pass = Number.isNaN(actual); const message = pass ? () => matcherHint('.not.toBeNaN', 'received', '') + '\n\n' + `Expected value not to be NaN, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeNaN', 'received', '') + '\n\n' + `Expected value to be NaN, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeNull(actual: any, expected: void) { ensureNoExpected(expected, '.toBeNull'); const pass = actual === null; const message = pass ? () => matcherHint('.not.toBeNull', 'received', '') + '\n\n' + `Expected value not to be null, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeNull', 'received', '') + '\n\n' + `Expected value to be null, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeTruthy(actual: any, expected: void) { ensureNoExpected(expected, '.toBeTruthy'); const pass = !!actual; const message = pass ? () => matcherHint('.not.toBeTruthy', 'received', '') + '\n\n' + `Expected value not to be truthy, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeTruthy', 'received', '') + '\n\n' + `Expected value to be truthy, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeUndefined(actual: any, expected: void) { ensureNoExpected(expected, '.toBeUndefined'); const pass = actual === void 0; const message = pass ? () => matcherHint('.not.toBeUndefined', 'received', '') + '\n\n' + `Expected value not to be undefined, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeUndefined', 'received', '') + '\n\n' + `Expected value to be undefined, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toContain(collection: ContainIterable | string, value: any) { const collectionType = getType(collection); let converted = null; if (Array.isArray(collection) || typeof collection === 'string') { // strings have `indexOf` so we don't need to convert // arrays have `indexOf` and we don't want to make a copy converted = collection; } else { try { converted = Array.from(collection); } catch (e) { throw new Error( matcherHint('[.not].toContainEqual', 'collection', 'value') + '\n\n' + `Expected ${RECEIVED_COLOR('collection')} to be an array-like structure.\n` + printWithType('Received', collection, printReceived), ); } } // At this point, we're either a string or an Array, // which was converted from an array-like structure. const pass = converted.indexOf(value) != -1; const message = pass ? () => matcherHint('.not.toContain', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `Not to contain value:\n` + ` ${printExpected(value)}\n` : () => matcherHint('.toContain', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `To contain value:\n` + ` ${printExpected(value)}`; return {message, pass}; }, toContainEqual(collection: ContainIterable, value: any) { const collectionType = getType(collection); let converted = null; if (Array.isArray(collection)) { converted = collection; } else { try { converted = Array.from(collection); } catch (e) { throw new Error( matcherHint('[.not].toContainEqual', 'collection', 'value') + '\n\n' + `Expected ${RECEIVED_COLOR('collection')} to be an array-like structure.\n` + printWithType('Received', collection, printReceived), ); } } const pass = converted.findIndex(item => equals(item, value, [iterableEquality])) !== -1; const message = pass ? () => matcherHint('.not.toContainEqual', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `Not to contain a value equal to:\n` + ` ${printExpected(value)}\n` : () => matcherHint('.toContainEqual', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `To contain a value equal to:\n` + ` ${printExpected(value)}`; return {message, pass}; }, toEqual(received: any, expected: any) { const pass = equals(received, expected, [iterableEquality]); const message = pass ? () => matcherHint('.not.toEqual') + '\n\n' + `Expected value to not equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return matcherHint('.toEqual') + '\n\n' + `Expected value to equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` + (diffString ? `\n\nDifference:\n\n${diffString}` : ''); }; return {message, pass}; }, toHaveLength(received: any, length: number) { if ( typeof received !== 'string' && (!received || typeof received.length !== 'number') ) { throw new Error( matcherHint('[.not].toHaveLength', 'received', 'length') + '\n\n' + `Expected value to have a 'length' property that is a number. ` + `Received:\n` + ` ${printReceived(received)}\n` + ( received ? `received.length:\n ${printReceived(received.length)}` : '' ), ); } const pass = received.length === length; const message = pass ? () => matcherHint('.not.toHaveLength', 'received', 'length') + '\n\n' + `Expected value to not have length:\n` + ` ${printExpected(length)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `received.length:\n` + ` ${printReceived(received.length)}` : () => matcherHint('.toHaveLength', 'received', 'length') + '\n\n' + `Expected value to have length:\n` + ` ${printExpected(length)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `received.length:\n` + ` ${printReceived(received.length)}`; return {message, pass}; }, toHaveProperty(object: Object, propPath: string, value?: any) { const valuePassed = arguments.length === 3; if (!object && typeof object !== 'string' && typeof object !== 'number') { throw new Error( matcherHint('[.not].toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected ${RECEIVED_COLOR('object')} to be an object. Received:\n` + ` ${getType(object)}: ${printReceived(object)}`, ); } if (getType(propPath) !== 'string') { throw new Error( matcherHint('[.not].toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected ${EXPECTED_COLOR('path')} to be a string. Received:\n` + ` ${getType(propPath)}: ${printReceived(propPath)}`, ); } const result = getPath(object, propPath); const {lastTraversedObject, hasEndProp} = result; let diffString; if (valuePassed && result.hasOwnProperty('value')) { diffString = diff(value, result.value, { expand: this.expand, }); } const pass = valuePassed ? equals(result.value, value, [iterableEquality]) : hasEndProp; if (result.hasOwnProperty('value')) { // we don't diff numbers. So instead we'll show the object that contains the resulting value. // And to get that object we need to go up a level. result.traversedPath.pop(); } const traversedPath = result.traversedPath.join('.'); const message = pass ? matcherHint('.not.toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected the object:\n` + ` ${printReceived(object)}\n` + `Not to have a nested property:\n` + ` ${printExpected(propPath)}\n` + (valuePassed ? `With a value of:\n ${printExpected(value)}\n` : '') : matcherHint('.toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected the object:\n` + ` ${printReceived(object)}\n` + `To have a nested property:\n` + ` ${printExpected(propPath)}\n` + (valuePassed ? `With a value of:\n ${printExpected(value)}\n` : '') + (traversedPath ? `Received:\n ${RECEIVED_COLOR('object')}.${traversedPath}: ${printReceived(lastTraversedObject)}` : '') + (diffString ? `\nDifference:\n\n${diffString}` : ''); if (pass === undefined) { throw new Error('pass must be initialized'); } return {message, pass}; }, toMatch(received: string, expected: string | RegExp) { if (typeof received !== 'string') { throw new Error( matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' + `${RECEIVED_COLOR('string')} value must be a string.\n` + printWithType('Received', received, printReceived), ); } if (!(expected instanceof RegExp) && !(typeof expected === 'string')) { throw new Error( matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' + `${EXPECTED_COLOR('expected')} value must be a string or a regular expression.\n` + printWithType('Expected', expected, printExpected), ); } const pass = new RegExp( typeof expected === 'string' ? escapeStrForRegex(expected) : expected, ).test(received); const message = pass ? () => matcherHint('.not.toMatch') + `\n\nExpected value not to match:\n` + ` ${printExpected(expected)}` + `\nReceived:\n` + ` ${printReceived(received)}` : () => matcherHint('.toMatch') + `\n\nExpected value to match:\n` + ` ${printExpected(expected)}` + `\nReceived:\n` + ` ${printReceived(received)}`; return {message, pass}; }, toMatchObject(receivedObject: Object, expectedObject: Object) { if (typeof receivedObject !== 'object' || receivedObject === null) { throw new Error( matcherHint('[.not].toMatchObject', 'object', 'expected') + '\n\n' + `${RECEIVED_COLOR('received')} value must be an object.\n` + printWithType('Received', receivedObject, printReceived), ); } if (typeof expectedObject !== 'object' || expectedObject === null) { throw new Error( matcherHint('[.not].toMatchObject', 'object', 'expected') + '\n\n' + `${EXPECTED_COLOR('expected')} value must be an object.\n` + printWithType('Expected', expectedObject, printExpected), ); } const compare = (expected: any, received: any): boolean => { if (typeof received !== typeof expected) { return false; } if (typeof expected !== 'object' || expected === null) { return expected === received; } if (Array.isArray(expected)) { if (!Array.isArray(received)) { return false; } if (expected.length !== received.length) { return false; } return expected.every(exp => { return received.some(act => { return compare(exp, act); }); }); } if (expected instanceof Date && received instanceof Date) { return expected.getTime() === received.getTime(); } return Object.keys(expected).every(key => { if (!received.hasOwnProperty(key)) { return false; } const exp = expected[key]; const act = received[key]; if (typeof exp === 'object' && exp !== null && act !== null) { return compare(exp, act); } return act === exp; }); }; // Strip properties form received object that are not present in the expected // object. We need it to print the diff without adding a lot of unrelated noise. const findMatchObject = (expected: Object, received: Object) => { if (Array.isArray(received)) { if (!Array.isArray(expected)) { return received; } if (expected.length !== received.length) { return received; } const matchArray = []; for (let i = 0; i < expected.length; i++) { matchArray.push(findMatchObject(expected[i], received[i])); } return matchArray; } else if (received instanceof Date) { return received; } else if (typeof received === 'object' && received !== null && typeof expected === 'object' && expected !== null) { const matchedObject = {}; let match = false; Object.keys(expected).forEach(key => { if (received.hasOwnProperty(key)) { match = true; const exp = expected[key]; const act = received[key]; if (typeof exp === 'object' && exp !== null) { matchedObject[key] = findMatchObject(exp, act); } else { matchedObject[key] = act; } } }); if (match) { return matchedObject; } else { return received; } } else { return received; } }; const pass = compare(expectedObject, receivedObject); const message = pass ? () => matcherHint('.not.toMatchObject') + `\n\nExpected value not to match object:\n` + ` ${printExpected(expectedObject)}` + `\nReceived:\n` + ` ${printReceived(receivedObject)}` : () => { const diffString = diff(expectedObject, findMatchObject(expectedObject, receivedObject), { expand: this.expand, }); return matcherHint('.toMatchObject') + `\n\nExpected value to match object:\n` + ` ${printExpected(expectedObject)}` + `\nReceived:\n` + ` ${printReceived(receivedObject)}` + (diffString ? `\nDifference:\n${diffString}` : ''); }; return {message, pass}; }, toMatchSnapshot, }; module.exports = matchers;
packages/jest-matchers/src/matchers.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.015213563106954098, 0.0011127821635454893, 0.0001637120876694098, 0.00017770298290997744, 0.0021107762586325407 ]
{ "id": 0, "code_window": [ " matcherName: options.matcherName,\n", " message: message(),\n", " stack: stack(),\n", " passed: options.passed\n", " };\n", "\n", " if(!result.passed) {\n", " result.expected = options.expected;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " passed: options.passed,\n", " // CUSTOM JEST CHANGE: we pass error message to the result.\n", " error: options.error\n" ], "file_path": "packages/jest-jasmine2/vendor/jasmine-2.5.2.js", "type": "replace", "edit_start_line_idx": 1000 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; exports.isNodeModule = true;
packages/jest-runtime/src/__tests__/test_root/subdir2/module_dir/my-module/core.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017680361634120345, 0.00017583163571543992, 0.0001748596696415916, 0.00017583163571543992, 9.719733498059213e-7 ]
{ "id": 0, "code_window": [ " matcherName: options.matcherName,\n", " message: message(),\n", " stack: stack(),\n", " passed: options.passed\n", " };\n", "\n", " if(!result.passed) {\n", " result.expected = options.expected;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " passed: options.passed,\n", " // CUSTOM JEST CHANGE: we pass error message to the result.\n", " error: options.error\n" ], "file_path": "packages/jest-jasmine2/vendor/jasmine-2.5.2.js", "type": "replace", "edit_start_line_idx": 1000 }
<resources> <string name="app_name">jestrn</string> </resources>
examples/react-native/android/app/src/main/res/values/strings.xml
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017653476970735937, 0.00017653476970735937, 0.00017653476970735937, 0.00017653476970735937, 0 ]
{ "id": 0, "code_window": [ " matcherName: options.matcherName,\n", " message: message(),\n", " stack: stack(),\n", " passed: options.passed\n", " };\n", "\n", " if(!result.passed) {\n", " result.expected = options.expected;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " passed: options.passed,\n", " // CUSTOM JEST CHANGE: we pass error message to the result.\n", " error: options.error\n" ], "file_path": "packages/jest-jasmine2/vendor/jasmine-2.5.2.js", "type": "replace", "edit_start_line_idx": 1000 }
{ "devDependencies": { "jest-cli": "*" }, "scripts": { "test": "jest" } }
examples/getting_started/package.json
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017536792438477278, 0.00017536792438477278, 0.00017536792438477278, 0.00017536792438477278, 0 ]
{ "id": 1, "code_window": [ "\n", "const utils = require('jest-matcher-utils');\n", "\n", "const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');\n", "\n", "class JestAssertionError extends Error {}\n", "\n", "if (!global[GLOBAL_STATE]) {\n", " Object.defineProperty(\n", " global,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "class JestAssertionError extends Error {\n", " matcherResult: any\n", "}\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 31 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ /* eslint-disable max-len */ 'use strict'; import type { MatchersObject, } from 'types/Matchers'; const { toMatchSnapshot, } = require('jest-snapshot'); const diff = require('jest-diff'); const {escapeStrForRegex} = require('jest-util'); const {getPath} = require('./utils'); const { EXPECTED_COLOR, RECEIVED_COLOR, ensureNoExpected, ensureNumbers, getType, matcherHint, printReceived, printExpected, printWithType, } = require('jest-matcher-utils'); type ContainIterable = ( Array<any> | Set<any> | NodeList<any> | DOMTokenList | HTMLCollection<any> ); const IteratorSymbol = Symbol.iterator; const equals = global.jasmine.matchersUtil.equals; const hasIterator = object => !!(object != null && object[IteratorSymbol]); const iterableEquality = (a, b) => { if ( typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b) ) { return undefined; } if (a.constructor !== b.constructor) { return false; } const bIterator = b[IteratorSymbol](); for (const aValue of a) { const nextB = bIterator.next(); if ( nextB.done || !global.jasmine.matchersUtil.equals( aValue, nextB.value, [iterableEquality], ) ) { return false; } } if (!bIterator.next().done) { return false; } return true; }; const matchers: MatchersObject = { toBe(received: any, expected: number) { const pass = received === expected; const message = pass ? () => matcherHint('.not.toBe') + '\n\n' + `Expected value to not be (using ===):\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return matcherHint('.toBe') + '\n\n' + `Expected value to be (using ===):\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` + (diffString ? `\n\nDifference:\n\n${diffString}` : ''); }; return {message, pass}; }, toBeCloseTo( actual: number, expected: number, precision?: number = 2, ) { ensureNumbers(actual, expected, '.toBeCloseTo'); const pass = Math.abs(expected - actual) < (Math.pow(10, -precision) / 2); const message = pass ? () => matcherHint('.not.toBeCloseTo', 'received', 'expected, precision') + '\n\n' + `Expected value not to be close to (with ${printExpected(precision)}-digit precision):\n` + ` ${printExpected(expected)}\n` + `Received: \n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeCloseTo', 'received', 'expected, precision') + '\n\n' + `Expected value to be close to (with ${printExpected(precision)}-digit precision):\n` + ` ${printExpected(expected)}\n` + `Received: \n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeDefined(actual: any, expected: void) { ensureNoExpected(expected, '.toBeDefined'); const pass = actual !== void 0; const message = pass ? () => matcherHint('.not.toBeDefined', 'received', '') + '\n\n' + `Expected value not to be defined, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeDefined', 'received', '') + '\n\n' + `Expected value to be defined, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeFalsy(actual: any, expected: void) { ensureNoExpected(expected, '.toBeFalsy'); const pass = !actual; const message = pass ? () => matcherHint('.not.toBeFalsy', 'received', '') + '\n\n' + `Expected value not to be falsy, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeFalsy', 'received', '') + '\n\n' + `Expected value to be falsy, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeGreaterThan(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeGreaterThan'); const pass = actual > expected; const message = pass ? () => matcherHint('.not.toBeGreaterThan') + '\n\n' + `Expected value not to be greater than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeGreaterThan') + '\n\n' + `Expected value to be greater than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeGreaterThanOrEqual(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeGreaterThanOrEqual'); const pass = actual >= expected; const message = pass ? () => matcherHint('.not.toBeGreaterThanOrEqual') + '\n\n' + `Expected value not to be greater than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeGreaterThanOrEqual') + '\n\n' + `Expected value to be greater than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeInstanceOf(received: any, constructor: Function) { const constType = getType(constructor); if (constType !== 'function') { throw new Error( matcherHint('[.not].toBeInstanceOf', 'value', 'constructor') + `\n\n` + `Expected constructor to be a function. Instead got:\n` + ` ${printExpected(constType)}`, ); } const pass = received instanceof constructor; const message = pass ? () => matcherHint('.not.toBeInstanceOf', 'value', 'constructor') + '\n\n' + `Expected value not to be an instance of:\n` + ` ${printExpected(constructor.name || constructor)}\n` + `Received:\n` + ` ${printReceived(received)}\n` : () => matcherHint('.toBeInstanceOf', 'value', 'constructor') + '\n\n' + `Expected value to be an instance of:\n` + ` ${printExpected(constructor.name || constructor)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `Constructor:\n` + ` ${printReceived(received.constructor && received.constructor.name)}`; return {message, pass}; }, toBeLessThan(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeLessThan'); const pass = actual < expected; const message = pass ? () => matcherHint('.not.toBeLessThan') + '\n\n' + `Expected value not to be less than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeLessThan') + '\n\n' + `Expected value to be less than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeLessThanOrEqual(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeLessThanOrEqual'); const pass = actual <= expected; const message = pass ? () => matcherHint('.not.toBeLessThanOrEqual') + '\n\n' + `Expected value not to be less than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeLessThanOrEqual') + '\n\n' + `Expected value to be less than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeNaN(actual: any, expected: void) { ensureNoExpected(expected, '.toBeNaN'); const pass = Number.isNaN(actual); const message = pass ? () => matcherHint('.not.toBeNaN', 'received', '') + '\n\n' + `Expected value not to be NaN, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeNaN', 'received', '') + '\n\n' + `Expected value to be NaN, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeNull(actual: any, expected: void) { ensureNoExpected(expected, '.toBeNull'); const pass = actual === null; const message = pass ? () => matcherHint('.not.toBeNull', 'received', '') + '\n\n' + `Expected value not to be null, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeNull', 'received', '') + '\n\n' + `Expected value to be null, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeTruthy(actual: any, expected: void) { ensureNoExpected(expected, '.toBeTruthy'); const pass = !!actual; const message = pass ? () => matcherHint('.not.toBeTruthy', 'received', '') + '\n\n' + `Expected value not to be truthy, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeTruthy', 'received', '') + '\n\n' + `Expected value to be truthy, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeUndefined(actual: any, expected: void) { ensureNoExpected(expected, '.toBeUndefined'); const pass = actual === void 0; const message = pass ? () => matcherHint('.not.toBeUndefined', 'received', '') + '\n\n' + `Expected value not to be undefined, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeUndefined', 'received', '') + '\n\n' + `Expected value to be undefined, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toContain(collection: ContainIterable | string, value: any) { const collectionType = getType(collection); let converted = null; if (Array.isArray(collection) || typeof collection === 'string') { // strings have `indexOf` so we don't need to convert // arrays have `indexOf` and we don't want to make a copy converted = collection; } else { try { converted = Array.from(collection); } catch (e) { throw new Error( matcherHint('[.not].toContainEqual', 'collection', 'value') + '\n\n' + `Expected ${RECEIVED_COLOR('collection')} to be an array-like structure.\n` + printWithType('Received', collection, printReceived), ); } } // At this point, we're either a string or an Array, // which was converted from an array-like structure. const pass = converted.indexOf(value) != -1; const message = pass ? () => matcherHint('.not.toContain', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `Not to contain value:\n` + ` ${printExpected(value)}\n` : () => matcherHint('.toContain', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `To contain value:\n` + ` ${printExpected(value)}`; return {message, pass}; }, toContainEqual(collection: ContainIterable, value: any) { const collectionType = getType(collection); let converted = null; if (Array.isArray(collection)) { converted = collection; } else { try { converted = Array.from(collection); } catch (e) { throw new Error( matcherHint('[.not].toContainEqual', 'collection', 'value') + '\n\n' + `Expected ${RECEIVED_COLOR('collection')} to be an array-like structure.\n` + printWithType('Received', collection, printReceived), ); } } const pass = converted.findIndex(item => equals(item, value, [iterableEquality])) !== -1; const message = pass ? () => matcherHint('.not.toContainEqual', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `Not to contain a value equal to:\n` + ` ${printExpected(value)}\n` : () => matcherHint('.toContainEqual', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `To contain a value equal to:\n` + ` ${printExpected(value)}`; return {message, pass}; }, toEqual(received: any, expected: any) { const pass = equals(received, expected, [iterableEquality]); const message = pass ? () => matcherHint('.not.toEqual') + '\n\n' + `Expected value to not equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return matcherHint('.toEqual') + '\n\n' + `Expected value to equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` + (diffString ? `\n\nDifference:\n\n${diffString}` : ''); }; return {message, pass}; }, toHaveLength(received: any, length: number) { if ( typeof received !== 'string' && (!received || typeof received.length !== 'number') ) { throw new Error( matcherHint('[.not].toHaveLength', 'received', 'length') + '\n\n' + `Expected value to have a 'length' property that is a number. ` + `Received:\n` + ` ${printReceived(received)}\n` + ( received ? `received.length:\n ${printReceived(received.length)}` : '' ), ); } const pass = received.length === length; const message = pass ? () => matcherHint('.not.toHaveLength', 'received', 'length') + '\n\n' + `Expected value to not have length:\n` + ` ${printExpected(length)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `received.length:\n` + ` ${printReceived(received.length)}` : () => matcherHint('.toHaveLength', 'received', 'length') + '\n\n' + `Expected value to have length:\n` + ` ${printExpected(length)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `received.length:\n` + ` ${printReceived(received.length)}`; return {message, pass}; }, toHaveProperty(object: Object, propPath: string, value?: any) { const valuePassed = arguments.length === 3; if (!object && typeof object !== 'string' && typeof object !== 'number') { throw new Error( matcherHint('[.not].toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected ${RECEIVED_COLOR('object')} to be an object. Received:\n` + ` ${getType(object)}: ${printReceived(object)}`, ); } if (getType(propPath) !== 'string') { throw new Error( matcherHint('[.not].toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected ${EXPECTED_COLOR('path')} to be a string. Received:\n` + ` ${getType(propPath)}: ${printReceived(propPath)}`, ); } const result = getPath(object, propPath); const {lastTraversedObject, hasEndProp} = result; let diffString; if (valuePassed && result.hasOwnProperty('value')) { diffString = diff(value, result.value, { expand: this.expand, }); } const pass = valuePassed ? equals(result.value, value, [iterableEquality]) : hasEndProp; if (result.hasOwnProperty('value')) { // we don't diff numbers. So instead we'll show the object that contains the resulting value. // And to get that object we need to go up a level. result.traversedPath.pop(); } const traversedPath = result.traversedPath.join('.'); const message = pass ? matcherHint('.not.toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected the object:\n` + ` ${printReceived(object)}\n` + `Not to have a nested property:\n` + ` ${printExpected(propPath)}\n` + (valuePassed ? `With a value of:\n ${printExpected(value)}\n` : '') : matcherHint('.toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected the object:\n` + ` ${printReceived(object)}\n` + `To have a nested property:\n` + ` ${printExpected(propPath)}\n` + (valuePassed ? `With a value of:\n ${printExpected(value)}\n` : '') + (traversedPath ? `Received:\n ${RECEIVED_COLOR('object')}.${traversedPath}: ${printReceived(lastTraversedObject)}` : '') + (diffString ? `\nDifference:\n\n${diffString}` : ''); if (pass === undefined) { throw new Error('pass must be initialized'); } return {message, pass}; }, toMatch(received: string, expected: string | RegExp) { if (typeof received !== 'string') { throw new Error( matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' + `${RECEIVED_COLOR('string')} value must be a string.\n` + printWithType('Received', received, printReceived), ); } if (!(expected instanceof RegExp) && !(typeof expected === 'string')) { throw new Error( matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' + `${EXPECTED_COLOR('expected')} value must be a string or a regular expression.\n` + printWithType('Expected', expected, printExpected), ); } const pass = new RegExp( typeof expected === 'string' ? escapeStrForRegex(expected) : expected, ).test(received); const message = pass ? () => matcherHint('.not.toMatch') + `\n\nExpected value not to match:\n` + ` ${printExpected(expected)}` + `\nReceived:\n` + ` ${printReceived(received)}` : () => matcherHint('.toMatch') + `\n\nExpected value to match:\n` + ` ${printExpected(expected)}` + `\nReceived:\n` + ` ${printReceived(received)}`; return {message, pass}; }, toMatchObject(receivedObject: Object, expectedObject: Object) { if (typeof receivedObject !== 'object' || receivedObject === null) { throw new Error( matcherHint('[.not].toMatchObject', 'object', 'expected') + '\n\n' + `${RECEIVED_COLOR('received')} value must be an object.\n` + printWithType('Received', receivedObject, printReceived), ); } if (typeof expectedObject !== 'object' || expectedObject === null) { throw new Error( matcherHint('[.not].toMatchObject', 'object', 'expected') + '\n\n' + `${EXPECTED_COLOR('expected')} value must be an object.\n` + printWithType('Expected', expectedObject, printExpected), ); } const compare = (expected: any, received: any): boolean => { if (typeof received !== typeof expected) { return false; } if (typeof expected !== 'object' || expected === null) { return expected === received; } if (Array.isArray(expected)) { if (!Array.isArray(received)) { return false; } if (expected.length !== received.length) { return false; } return expected.every(exp => { return received.some(act => { return compare(exp, act); }); }); } if (expected instanceof Date && received instanceof Date) { return expected.getTime() === received.getTime(); } return Object.keys(expected).every(key => { if (!received.hasOwnProperty(key)) { return false; } const exp = expected[key]; const act = received[key]; if (typeof exp === 'object' && exp !== null && act !== null) { return compare(exp, act); } return act === exp; }); }; // Strip properties form received object that are not present in the expected // object. We need it to print the diff without adding a lot of unrelated noise. const findMatchObject = (expected: Object, received: Object) => { if (Array.isArray(received)) { if (!Array.isArray(expected)) { return received; } if (expected.length !== received.length) { return received; } const matchArray = []; for (let i = 0; i < expected.length; i++) { matchArray.push(findMatchObject(expected[i], received[i])); } return matchArray; } else if (received instanceof Date) { return received; } else if (typeof received === 'object' && received !== null && typeof expected === 'object' && expected !== null) { const matchedObject = {}; let match = false; Object.keys(expected).forEach(key => { if (received.hasOwnProperty(key)) { match = true; const exp = expected[key]; const act = received[key]; if (typeof exp === 'object' && exp !== null) { matchedObject[key] = findMatchObject(exp, act); } else { matchedObject[key] = act; } } }); if (match) { return matchedObject; } else { return received; } } else { return received; } }; const pass = compare(expectedObject, receivedObject); const message = pass ? () => matcherHint('.not.toMatchObject') + `\n\nExpected value not to match object:\n` + ` ${printExpected(expectedObject)}` + `\nReceived:\n` + ` ${printReceived(receivedObject)}` : () => { const diffString = diff(expectedObject, findMatchObject(expectedObject, receivedObject), { expand: this.expand, }); return matcherHint('.toMatchObject') + `\n\nExpected value to match object:\n` + ` ${printExpected(expectedObject)}` + `\nReceived:\n` + ` ${printReceived(receivedObject)}` + (diffString ? `\nDifference:\n${diffString}` : ''); }; return {message, pass}; }, toMatchSnapshot, }; module.exports = matchers;
packages/jest-matchers/src/matchers.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.02230984717607498, 0.001203987398184836, 0.00016510447312612087, 0.00017323473002761602, 0.0037962375208735466 ]
{ "id": 1, "code_window": [ "\n", "const utils = require('jest-matcher-utils');\n", "\n", "const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');\n", "\n", "class JestAssertionError extends Error {}\n", "\n", "if (!global[GLOBAL_STATE]) {\n", " Object.defineProperty(\n", " global,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "class JestAssertionError extends Error {\n", " matcherResult: any\n", "}\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 31 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; describe('stack trace', () => { it('fails', () => { expect(1).toBe(3); }); });
integration_tests/stack_trace/__tests__/stack-trace-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017526828742120415, 0.00017446423589717597, 0.00017366018437314779, 0.00017446423589717597, 8.04051524028182e-7 ]
{ "id": 1, "code_window": [ "\n", "const utils = require('jest-matcher-utils');\n", "\n", "const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');\n", "\n", "class JestAssertionError extends Error {}\n", "\n", "if (!global[GLOBAL_STATE]) {\n", " Object.defineProperty(\n", " global,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "class JestAssertionError extends Error {\n", " matcherResult: any\n", "}\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 31 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const commentEndRe = /\*\/$/; const commentStartRe = /^\/\*\*/; const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; const lineCommentRe = /\/\/([^\r\n]*)/g; const ltrimRe = /^\s*/; const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g; const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; const stringStartRe = /(\r?\n|^) *\*/g; const wsRe = /[\t ]+/g; function extract(contents: string): string { const match = contents.match(docblockRe); return match ? match[0].replace(ltrimRe, '') || '' : ''; } function parse(docblock: string): { [key: string]: string } { docblock = docblock .replace(commentStartRe, '') .replace(commentEndRe, '') .replace(wsRe, ' ') .replace(lineCommentRe, '') .replace(stringStartRe, '$1'); // Normalize multi-line directives let prev = ''; while (prev !== docblock) { prev = docblock; docblock = docblock.replace(multilineRe, '\n$1 $2\n'); } docblock = docblock.trim(); const result = Object.create(null); let match; while ((match = propertyRe.exec(docblock))) { result[match[1]] = match[2]; } return result; } exports.extract = extract; exports.parse = parse;
packages/jest-haste-map/src/lib/docblock.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017535220831632614, 0.00017346565437037498, 0.0001704787864582613, 0.00017411945736967027, 0.000001905965063997428 ]
{ "id": 1, "code_window": [ "\n", "const utils = require('jest-matcher-utils');\n", "\n", "const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');\n", "\n", "class JestAssertionError extends Error {}\n", "\n", "if (!global[GLOBAL_STATE]) {\n", " Object.defineProperty(\n", " global,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "class JestAssertionError extends Error {\n", " matcherResult: any\n", "}\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 31 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type {Config, Path} from 'types/Config'; import type {TransformOptions} from 'types/Transform'; const babel = require('babel-core'); const crypto = require('crypto'); const fs = require('fs'); const jestPreset = require('babel-preset-jest'); const path = require('path'); const BABELRC_FILENAME = '.babelrc'; const cache = Object.create(null); const getBabelRC = (filename, {useCache}) => { const paths = []; let directory = filename; while (directory !== (directory = path.dirname(directory))) { if (useCache && cache[directory]) { break; } paths.push(directory); const configFilePath = path.join(directory, BABELRC_FILENAME); if (fs.existsSync(configFilePath)) { cache[directory] = fs.readFileSync(configFilePath, 'utf8'); break; } } paths.forEach(directoryPath => { cache[directoryPath] = cache[directory]; }); return cache[directory] || ''; }; const createTransformer = (options: any) => { options = Object.assign({}, options, { auxiliaryCommentBefore: ' istanbul ignore next ', presets: ((options && options.presets) || []).concat([jestPreset]), retainLines: true, }); delete options.cacheDirectory; return { canInstrument: true, getCacheKey( fileData: string, filename: Path, configString: string, {instrument, watch}: TransformOptions, ): string { return crypto.createHash('md5') .update(fileData) .update(configString) // Don't use the in-memory cache in watch mode because the .babelrc // file may be modified. .update(getBabelRC(filename, {useCache: !watch})) .update(instrument ? 'instrument' : '') .digest('hex'); }, process( src: string, filename: Path, config: Config, transformOptions: TransformOptions, ): string { let plugins = options.plugins || []; if (transformOptions && transformOptions.instrument) { // Copied from jest-runtime transform.js plugins = plugins.concat([ [ require('babel-plugin-istanbul').default, { // files outside `cwd` will not be instrumented cwd: config.rootDir, exclude: [], }, ], ]); } if (babel.util.canCompile(filename)) { return babel.transform( src, Object.assign({}, options, {filename, plugins}), ).code; } return src; }, }; }; module.exports = createTransformer(); (module.exports: any).createTransformer = createTransformer;
packages/babel-jest/src/index.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00019503801013343036, 0.0001738880091579631, 0.00016648347082082182, 0.00017273273260798305, 0.000007215829100459814 ]
{ "id": 2, "code_window": [ " Object.defineProperty(\n", " global,\n", " GLOBAL_STATE,\n", " {value: {\n", " matchers: Object.create(null), \n", " state: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " matchers: Object.create(null),\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 38 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ /* eslint-disable max-len */ 'use strict'; import type { MatchersObject, } from 'types/Matchers'; const { toMatchSnapshot, } = require('jest-snapshot'); const diff = require('jest-diff'); const {escapeStrForRegex} = require('jest-util'); const {getPath} = require('./utils'); const { EXPECTED_COLOR, RECEIVED_COLOR, ensureNoExpected, ensureNumbers, getType, matcherHint, printReceived, printExpected, printWithType, } = require('jest-matcher-utils'); type ContainIterable = ( Array<any> | Set<any> | NodeList<any> | DOMTokenList | HTMLCollection<any> ); const IteratorSymbol = Symbol.iterator; const equals = global.jasmine.matchersUtil.equals; const hasIterator = object => !!(object != null && object[IteratorSymbol]); const iterableEquality = (a, b) => { if ( typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b) ) { return undefined; } if (a.constructor !== b.constructor) { return false; } const bIterator = b[IteratorSymbol](); for (const aValue of a) { const nextB = bIterator.next(); if ( nextB.done || !global.jasmine.matchersUtil.equals( aValue, nextB.value, [iterableEquality], ) ) { return false; } } if (!bIterator.next().done) { return false; } return true; }; const matchers: MatchersObject = { toBe(received: any, expected: number) { const pass = received === expected; const message = pass ? () => matcherHint('.not.toBe') + '\n\n' + `Expected value to not be (using ===):\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return matcherHint('.toBe') + '\n\n' + `Expected value to be (using ===):\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` + (diffString ? `\n\nDifference:\n\n${diffString}` : ''); }; return {message, pass}; }, toBeCloseTo( actual: number, expected: number, precision?: number = 2, ) { ensureNumbers(actual, expected, '.toBeCloseTo'); const pass = Math.abs(expected - actual) < (Math.pow(10, -precision) / 2); const message = pass ? () => matcherHint('.not.toBeCloseTo', 'received', 'expected, precision') + '\n\n' + `Expected value not to be close to (with ${printExpected(precision)}-digit precision):\n` + ` ${printExpected(expected)}\n` + `Received: \n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeCloseTo', 'received', 'expected, precision') + '\n\n' + `Expected value to be close to (with ${printExpected(precision)}-digit precision):\n` + ` ${printExpected(expected)}\n` + `Received: \n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeDefined(actual: any, expected: void) { ensureNoExpected(expected, '.toBeDefined'); const pass = actual !== void 0; const message = pass ? () => matcherHint('.not.toBeDefined', 'received', '') + '\n\n' + `Expected value not to be defined, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeDefined', 'received', '') + '\n\n' + `Expected value to be defined, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeFalsy(actual: any, expected: void) { ensureNoExpected(expected, '.toBeFalsy'); const pass = !actual; const message = pass ? () => matcherHint('.not.toBeFalsy', 'received', '') + '\n\n' + `Expected value not to be falsy, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeFalsy', 'received', '') + '\n\n' + `Expected value to be falsy, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeGreaterThan(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeGreaterThan'); const pass = actual > expected; const message = pass ? () => matcherHint('.not.toBeGreaterThan') + '\n\n' + `Expected value not to be greater than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeGreaterThan') + '\n\n' + `Expected value to be greater than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeGreaterThanOrEqual(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeGreaterThanOrEqual'); const pass = actual >= expected; const message = pass ? () => matcherHint('.not.toBeGreaterThanOrEqual') + '\n\n' + `Expected value not to be greater than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeGreaterThanOrEqual') + '\n\n' + `Expected value to be greater than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeInstanceOf(received: any, constructor: Function) { const constType = getType(constructor); if (constType !== 'function') { throw new Error( matcherHint('[.not].toBeInstanceOf', 'value', 'constructor') + `\n\n` + `Expected constructor to be a function. Instead got:\n` + ` ${printExpected(constType)}`, ); } const pass = received instanceof constructor; const message = pass ? () => matcherHint('.not.toBeInstanceOf', 'value', 'constructor') + '\n\n' + `Expected value not to be an instance of:\n` + ` ${printExpected(constructor.name || constructor)}\n` + `Received:\n` + ` ${printReceived(received)}\n` : () => matcherHint('.toBeInstanceOf', 'value', 'constructor') + '\n\n' + `Expected value to be an instance of:\n` + ` ${printExpected(constructor.name || constructor)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `Constructor:\n` + ` ${printReceived(received.constructor && received.constructor.name)}`; return {message, pass}; }, toBeLessThan(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeLessThan'); const pass = actual < expected; const message = pass ? () => matcherHint('.not.toBeLessThan') + '\n\n' + `Expected value not to be less than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeLessThan') + '\n\n' + `Expected value to be less than:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeLessThanOrEqual(actual: number, expected: number) { ensureNumbers(actual, expected, '.toBeLessThanOrEqual'); const pass = actual <= expected; const message = pass ? () => matcherHint('.not.toBeLessThanOrEqual') + '\n\n' + `Expected value not to be less than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeLessThanOrEqual') + '\n\n' + `Expected value to be less than or equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeNaN(actual: any, expected: void) { ensureNoExpected(expected, '.toBeNaN'); const pass = Number.isNaN(actual); const message = pass ? () => matcherHint('.not.toBeNaN', 'received', '') + '\n\n' + `Expected value not to be NaN, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeNaN', 'received', '') + '\n\n' + `Expected value to be NaN, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeNull(actual: any, expected: void) { ensureNoExpected(expected, '.toBeNull'); const pass = actual === null; const message = pass ? () => matcherHint('.not.toBeNull', 'received', '') + '\n\n' + `Expected value not to be null, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeNull', 'received', '') + '\n\n' + `Expected value to be null, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeTruthy(actual: any, expected: void) { ensureNoExpected(expected, '.toBeTruthy'); const pass = !!actual; const message = pass ? () => matcherHint('.not.toBeTruthy', 'received', '') + '\n\n' + `Expected value not to be truthy, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeTruthy', 'received', '') + '\n\n' + `Expected value to be truthy, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toBeUndefined(actual: any, expected: void) { ensureNoExpected(expected, '.toBeUndefined'); const pass = actual === void 0; const message = pass ? () => matcherHint('.not.toBeUndefined', 'received', '') + '\n\n' + `Expected value not to be undefined, instead received\n` + ` ${printReceived(actual)}` : () => matcherHint('.toBeUndefined', 'received', '') + '\n\n' + `Expected value to be undefined, instead received\n` + ` ${printReceived(actual)}`; return {message, pass}; }, toContain(collection: ContainIterable | string, value: any) { const collectionType = getType(collection); let converted = null; if (Array.isArray(collection) || typeof collection === 'string') { // strings have `indexOf` so we don't need to convert // arrays have `indexOf` and we don't want to make a copy converted = collection; } else { try { converted = Array.from(collection); } catch (e) { throw new Error( matcherHint('[.not].toContainEqual', 'collection', 'value') + '\n\n' + `Expected ${RECEIVED_COLOR('collection')} to be an array-like structure.\n` + printWithType('Received', collection, printReceived), ); } } // At this point, we're either a string or an Array, // which was converted from an array-like structure. const pass = converted.indexOf(value) != -1; const message = pass ? () => matcherHint('.not.toContain', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `Not to contain value:\n` + ` ${printExpected(value)}\n` : () => matcherHint('.toContain', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `To contain value:\n` + ` ${printExpected(value)}`; return {message, pass}; }, toContainEqual(collection: ContainIterable, value: any) { const collectionType = getType(collection); let converted = null; if (Array.isArray(collection)) { converted = collection; } else { try { converted = Array.from(collection); } catch (e) { throw new Error( matcherHint('[.not].toContainEqual', 'collection', 'value') + '\n\n' + `Expected ${RECEIVED_COLOR('collection')} to be an array-like structure.\n` + printWithType('Received', collection, printReceived), ); } } const pass = converted.findIndex(item => equals(item, value, [iterableEquality])) !== -1; const message = pass ? () => matcherHint('.not.toContainEqual', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `Not to contain a value equal to:\n` + ` ${printExpected(value)}\n` : () => matcherHint('.toContainEqual', collectionType, 'value') + '\n\n' + `Expected ${collectionType}:\n` + ` ${printReceived(collection)}\n` + `To contain a value equal to:\n` + ` ${printExpected(value)}`; return {message, pass}; }, toEqual(received: any, expected: any) { const pass = equals(received, expected, [iterableEquality]); const message = pass ? () => matcherHint('.not.toEqual') + '\n\n' + `Expected value to not equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return matcherHint('.toEqual') + '\n\n' + `Expected value to equal:\n` + ` ${printExpected(expected)}\n` + `Received:\n` + ` ${printReceived(received)}` + (diffString ? `\n\nDifference:\n\n${diffString}` : ''); }; return {message, pass}; }, toHaveLength(received: any, length: number) { if ( typeof received !== 'string' && (!received || typeof received.length !== 'number') ) { throw new Error( matcherHint('[.not].toHaveLength', 'received', 'length') + '\n\n' + `Expected value to have a 'length' property that is a number. ` + `Received:\n` + ` ${printReceived(received)}\n` + ( received ? `received.length:\n ${printReceived(received.length)}` : '' ), ); } const pass = received.length === length; const message = pass ? () => matcherHint('.not.toHaveLength', 'received', 'length') + '\n\n' + `Expected value to not have length:\n` + ` ${printExpected(length)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `received.length:\n` + ` ${printReceived(received.length)}` : () => matcherHint('.toHaveLength', 'received', 'length') + '\n\n' + `Expected value to have length:\n` + ` ${printExpected(length)}\n` + `Received:\n` + ` ${printReceived(received)}\n` + `received.length:\n` + ` ${printReceived(received.length)}`; return {message, pass}; }, toHaveProperty(object: Object, propPath: string, value?: any) { const valuePassed = arguments.length === 3; if (!object && typeof object !== 'string' && typeof object !== 'number') { throw new Error( matcherHint('[.not].toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected ${RECEIVED_COLOR('object')} to be an object. Received:\n` + ` ${getType(object)}: ${printReceived(object)}`, ); } if (getType(propPath) !== 'string') { throw new Error( matcherHint('[.not].toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected ${EXPECTED_COLOR('path')} to be a string. Received:\n` + ` ${getType(propPath)}: ${printReceived(propPath)}`, ); } const result = getPath(object, propPath); const {lastTraversedObject, hasEndProp} = result; let diffString; if (valuePassed && result.hasOwnProperty('value')) { diffString = diff(value, result.value, { expand: this.expand, }); } const pass = valuePassed ? equals(result.value, value, [iterableEquality]) : hasEndProp; if (result.hasOwnProperty('value')) { // we don't diff numbers. So instead we'll show the object that contains the resulting value. // And to get that object we need to go up a level. result.traversedPath.pop(); } const traversedPath = result.traversedPath.join('.'); const message = pass ? matcherHint('.not.toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected the object:\n` + ` ${printReceived(object)}\n` + `Not to have a nested property:\n` + ` ${printExpected(propPath)}\n` + (valuePassed ? `With a value of:\n ${printExpected(value)}\n` : '') : matcherHint('.toHaveProperty', 'object', 'path', {secondArgument: (valuePassed ? 'value' : null)}) + '\n\n' + `Expected the object:\n` + ` ${printReceived(object)}\n` + `To have a nested property:\n` + ` ${printExpected(propPath)}\n` + (valuePassed ? `With a value of:\n ${printExpected(value)}\n` : '') + (traversedPath ? `Received:\n ${RECEIVED_COLOR('object')}.${traversedPath}: ${printReceived(lastTraversedObject)}` : '') + (diffString ? `\nDifference:\n\n${diffString}` : ''); if (pass === undefined) { throw new Error('pass must be initialized'); } return {message, pass}; }, toMatch(received: string, expected: string | RegExp) { if (typeof received !== 'string') { throw new Error( matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' + `${RECEIVED_COLOR('string')} value must be a string.\n` + printWithType('Received', received, printReceived), ); } if (!(expected instanceof RegExp) && !(typeof expected === 'string')) { throw new Error( matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' + `${EXPECTED_COLOR('expected')} value must be a string or a regular expression.\n` + printWithType('Expected', expected, printExpected), ); } const pass = new RegExp( typeof expected === 'string' ? escapeStrForRegex(expected) : expected, ).test(received); const message = pass ? () => matcherHint('.not.toMatch') + `\n\nExpected value not to match:\n` + ` ${printExpected(expected)}` + `\nReceived:\n` + ` ${printReceived(received)}` : () => matcherHint('.toMatch') + `\n\nExpected value to match:\n` + ` ${printExpected(expected)}` + `\nReceived:\n` + ` ${printReceived(received)}`; return {message, pass}; }, toMatchObject(receivedObject: Object, expectedObject: Object) { if (typeof receivedObject !== 'object' || receivedObject === null) { throw new Error( matcherHint('[.not].toMatchObject', 'object', 'expected') + '\n\n' + `${RECEIVED_COLOR('received')} value must be an object.\n` + printWithType('Received', receivedObject, printReceived), ); } if (typeof expectedObject !== 'object' || expectedObject === null) { throw new Error( matcherHint('[.not].toMatchObject', 'object', 'expected') + '\n\n' + `${EXPECTED_COLOR('expected')} value must be an object.\n` + printWithType('Expected', expectedObject, printExpected), ); } const compare = (expected: any, received: any): boolean => { if (typeof received !== typeof expected) { return false; } if (typeof expected !== 'object' || expected === null) { return expected === received; } if (Array.isArray(expected)) { if (!Array.isArray(received)) { return false; } if (expected.length !== received.length) { return false; } return expected.every(exp => { return received.some(act => { return compare(exp, act); }); }); } if (expected instanceof Date && received instanceof Date) { return expected.getTime() === received.getTime(); } return Object.keys(expected).every(key => { if (!received.hasOwnProperty(key)) { return false; } const exp = expected[key]; const act = received[key]; if (typeof exp === 'object' && exp !== null && act !== null) { return compare(exp, act); } return act === exp; }); }; // Strip properties form received object that are not present in the expected // object. We need it to print the diff without adding a lot of unrelated noise. const findMatchObject = (expected: Object, received: Object) => { if (Array.isArray(received)) { if (!Array.isArray(expected)) { return received; } if (expected.length !== received.length) { return received; } const matchArray = []; for (let i = 0; i < expected.length; i++) { matchArray.push(findMatchObject(expected[i], received[i])); } return matchArray; } else if (received instanceof Date) { return received; } else if (typeof received === 'object' && received !== null && typeof expected === 'object' && expected !== null) { const matchedObject = {}; let match = false; Object.keys(expected).forEach(key => { if (received.hasOwnProperty(key)) { match = true; const exp = expected[key]; const act = received[key]; if (typeof exp === 'object' && exp !== null) { matchedObject[key] = findMatchObject(exp, act); } else { matchedObject[key] = act; } } }); if (match) { return matchedObject; } else { return received; } } else { return received; } }; const pass = compare(expectedObject, receivedObject); const message = pass ? () => matcherHint('.not.toMatchObject') + `\n\nExpected value not to match object:\n` + ` ${printExpected(expectedObject)}` + `\nReceived:\n` + ` ${printReceived(receivedObject)}` : () => { const diffString = diff(expectedObject, findMatchObject(expectedObject, receivedObject), { expand: this.expand, }); return matcherHint('.toMatchObject') + `\n\nExpected value to match object:\n` + ` ${printExpected(expectedObject)}` + `\nReceived:\n` + ` ${printReceived(receivedObject)}` + (diffString ? `\nDifference:\n${diffString}` : ''); }; return {message, pass}; }, toMatchSnapshot, }; module.exports = matchers;
packages/jest-matchers/src/matchers.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.9858973026275635, 0.014754213392734528, 0.00016389686788897961, 0.00017182785086333752, 0.11864591389894485 ]
{ "id": 2, "code_window": [ " Object.defineProperty(\n", " global,\n", " GLOBAL_STATE,\n", " {value: {\n", " matchers: Object.create(null), \n", " state: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " matchers: Object.create(null),\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 38 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const runCommands = require('./_runCommands'); const getPackages = require('./_getPackages'); const fs = require('graceful-fs'); const path = require('path'); const chalk = require('chalk'); const mkdirp = require('mkdirp'); const rimraf = require('rimraf'); const EXAMPLES_DIR = path.resolve(__dirname, '../examples'); const JEST_CLI_PATH = path.resolve(__dirname, '../packages/jest-cli'); const JEST_BIN_PATH = path.resolve(JEST_CLI_PATH, 'bin/jest.js'); const LINKED_MODULES = ['jest-react-native']; const NODE_VERSION = Number(process.version.match(/^v(\d+\.\d+)/)[1]); const SKIP_ON_OLD_NODE = ['react-native']; const VERSION = require('../lerna').version; const packages = getPackages(); const examples = fs.readdirSync(EXAMPLES_DIR) .map(file => path.resolve(EXAMPLES_DIR, file)) .filter(f => fs.lstatSync(path.resolve(f)).isDirectory()); function runExampleTests(exampleDirectory) { console.log(chalk.bold(chalk.cyan('Testing example: ') + exampleDirectory)); const exampleName = path.basename(exampleDirectory); if (NODE_VERSION < 6 && SKIP_ON_OLD_NODE.indexOf(exampleName) !== -1) { console.log(`Skipping ${exampleName} on node ${process.version}.`); return; } runCommands('npm update', exampleDirectory); packages.forEach(pkg => { const name = path.basename(pkg); const directory = path.resolve(exampleDirectory, 'node_modules', name); if (fs.existsSync(directory)) { rimraf.sync(directory); if (LINKED_MODULES.indexOf(name) !== -1) { runCommands(`ln -s ${pkg} ./node_modules/`, exampleDirectory); } else { mkdirp.sync(directory); // Using `npm link jest-*` can create problems with module resolution, // so instead of this we'll create a proxy module. fs.writeFileSync( path.resolve(directory, 'index.js'), `module.exports = require('${pkg}');\n`, 'utf8' ); fs.writeFileSync( path.resolve(directory, 'package.json'), `{"name": "${name}", "version": "${VERSION}"}\n`, 'utf8' ); } } }); // overwrite the jest link and point it to the local jest-cli mkdirp.sync(path.resolve(exampleDirectory, './node_modules/.bin')); runCommands( `ln -sf ${JEST_BIN_PATH} ./node_modules/.bin/jest`, exampleDirectory ); runCommands('npm test', exampleDirectory); } examples.forEach(runExampleTests);
scripts/test_examples.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00018239930795971304, 0.00017363057122565806, 0.0001676273241173476, 0.00017288011440541595, 0.000004443815214472124 ]
{ "id": 2, "code_window": [ " Object.defineProperty(\n", " global,\n", " GLOBAL_STATE,\n", " {value: {\n", " matchers: Object.create(null), \n", " state: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " matchers: Object.create(null),\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 38 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; function setFromArgv(config, argv) { if (argv.coverage) { config.collectCoverage = true; } if (argv.verbose) { config.verbose = argv.verbose; } if (argv.notify) { config.notify = argv.notify; } if (argv.bail) { config.bail = argv.bail; } if (argv.cache !== null) { config.cache = argv.cache; } if (argv.watchman !== null) { config.watchman = argv.watchman; } if (argv.useStderr) { config.useStderr = argv.useStderr; } if (argv.json) { config.useStderr = true; } if (argv.logHeapUsage) { config.logHeapUsage = argv.logHeapUsage; } if (argv.replname) { config.replname = argv.replname; } if (argv.silent) { config.silent = true; } if (argv.setupTestFrameworkScriptFile) { config.setupTestFrameworkScriptFile = argv.setupTestFrameworkScriptFile; } if (argv.testNamePattern) { config.testNamePattern = argv.testNamePattern; } if (argv.updateSnapshot) { config.updateSnapshot = argv.updateSnapshot; } if (argv.watch || argv.watchAll) { config.watch = true; } if (argv.expand) { config.expand = argv.expand; } config.noStackTrace = argv.noStackTrace; return config; } module.exports = setFromArgv;
packages/jest-config/src/setFromArgv.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.0001759754668455571, 0.0001741826708894223, 0.00016804292681626976, 0.0001747613277984783, 0.0000022956517113925656 ]
{ "id": 2, "code_window": [ " Object.defineProperty(\n", " global,\n", " GLOBAL_STATE,\n", " {value: {\n", " matchers: Object.create(null), \n", " state: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " matchers: Object.create(null),\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 38 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const path = require('path'); module.exports = { process(src, filename, config, options) { return ` module.exports = '${path.basename(filename)}'; `; }, };
integration_tests/transform/multiple-transformers/filePreprocessor.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.0001744541514199227, 0.00017405608377885073, 0.00017365801613777876, 0.00017405608377885073, 3.9806764107197523e-7 ]
{ "id": 3, "code_window": [ " state: {\n", " assertionsExpected: null, \n", " assertionsMade: 0, \n", " suppressedErrors: [],\n", " },\n", " }},\n", " );\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " assertionsExpected: null,\n", " assertionsMade: 0,\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 40 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type { Expect, ExpectationObject, ExpectationResult, MatcherContext, MatcherState, MatchersObject, RawMatcherFn, ThrowingMatcherFn, } from 'types/Matchers'; const matchers = require('./matchers'); const spyMatchers = require('./spyMatchers'); const toThrowMatchers = require('./toThrowMatchers'); const utils = require('jest-matcher-utils'); const GLOBAL_STATE = Symbol.for('$$jest-matchers-object'); class JestAssertionError extends Error {} if (!global[GLOBAL_STATE]) { Object.defineProperty( global, GLOBAL_STATE, {value: { matchers: Object.create(null), state: { assertionsExpected: null, assertionsMade: 0, suppressedErrors: [], }, }}, ); } const expect: Expect = (actual: any): ExpectationObject => { const allMatchers = global[GLOBAL_STATE].matchers; const expectation = {not: {}}; Object.keys(allMatchers).forEach(name => { expectation[name] = makeThrowingMatcher(allMatchers[name], false, actual); expectation.not[name] = makeThrowingMatcher(allMatchers[name], true, actual); }); return expectation; }; const getMessage = message => { // for performance reasons some of the messages are evaluated // lazily if (typeof message === 'function') { message = message(); } if (!message) { message = utils.RECEIVED_COLOR( 'No message was specified for this matcher.', ); } return message; }; const makeThrowingMatcher = ( matcher: RawMatcherFn, isNot: boolean, actual: any, ): ThrowingMatcherFn => { return function throwingMatcher(...args) { let throws = true; const matcherContext: MatcherContext = Object.assign( // When throws is disabled, the matcher will not throw errors during test // execution but instead add them to the global matcher state. If a // matcher throws, test execution is normally stopped immediately. The // snapshot matcher uses it because we want to log all snapshot // failures in a test. {dontThrow: () => throws = false}, global[GLOBAL_STATE].state, { isNot, utils, }, ); let result: ExpectationResult; try { result = matcher.apply( matcherContext, [actual].concat(args), ); } catch (error) { // Remove this and deeper functions from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); throw error; } _validateResult(result); global[GLOBAL_STATE].state.assertionsMade++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); const error = new JestAssertionError(message); // Remove this function from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); if (throws) { throw error; } else { global[GLOBAL_STATE].state.suppressedErrors.push(error); } } }; }; expect.extend = (matchersObj: MatchersObject): void => { Object.assign(global[GLOBAL_STATE].matchers, matchersObj); }; const _validateResult = result => { if ( typeof result !== 'object' || typeof result.pass !== 'boolean' || ( result.message && ( typeof result.message !== 'string' && typeof result.message !== 'function' ) ) ) { throw new Error( 'Unexpected return from a matcher function.\n' + 'Matcher functions should ' + 'return an object in the following format:\n' + ' {message?: string | function, pass: boolean}\n' + `'${utils.stringify(result)}' was returned`, ); } }; const setState = (state: MatcherState) => { Object.assign(global[GLOBAL_STATE].state, state); }; const getState = () => global[GLOBAL_STATE].state; // add default jest matchers expect.extend(matchers); expect.extend(spyMatchers); expect.extend(toThrowMatchers); expect.assertions = (expected: number) => ( global[GLOBAL_STATE].state.assertionsExpected = expected ); module.exports = { expect, getState, setState, };
packages/jest-matchers/src/index.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.0034655537456274033, 0.000594383804127574, 0.000164490396855399, 0.0001712990051601082, 0.0009194695157930255 ]
{ "id": 3, "code_window": [ " state: {\n", " assertionsExpected: null, \n", " assertionsMade: 0, \n", " suppressedErrors: [],\n", " },\n", " }},\n", " );\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " assertionsExpected: null,\n", " assertionsMade: 0,\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 40 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+jsinfra */ 'use strict'; test('globals are properly defined', () => { expect(global.Object).toBe(Object); });
integration_tests/__tests__/global-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017146833124570549, 0.00016918356413953006, 0.0001668987824814394, 0.00016918356413953006, 0.000002284774382133037 ]
{ "id": 3, "code_window": [ " state: {\n", " assertionsExpected: null, \n", " assertionsMade: 0, \n", " suppressedErrors: [],\n", " },\n", " }},\n", " );\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " assertionsExpected: null,\n", " assertionsMade: 0,\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 40 }
{ "rules": { "babel/func-params-comma-dangle": 0 } }
integration_tests/.eslintrc
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00016755606338847429, 0.00016755606338847429, 0.00016755606338847429, 0.00016755606338847429, 0 ]
{ "id": 3, "code_window": [ " state: {\n", " assertionsExpected: null, \n", " assertionsMade: 0, \n", " suppressedErrors: [],\n", " },\n", " }},\n", " );\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " assertionsExpected: null,\n", " assertionsMade: 0,\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "replace", "edit_start_line_idx": 40 }
/** * Sample React Native Snapshot Test */ 'use strict'; import 'react-native'; import React from 'react'; import Intro from '../Intro'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Intro /> ).toJSON(); expect(tree).toMatchSnapshot(); }); // These serve as integration tests for the jest-react-native preset. it('renders the ActivityIndicator component', () => { const ActivityIndicator = require('ActivityIndicator'); const tree = renderer.create( <ActivityIndicator animating={true} size="small" /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('renders the Image component', done => { const Image = require('Image'); Image.getSize('path.jpg', (width, height) => { const tree = renderer.create( <Image style={{width, height}} /> ).toJSON(); expect(tree).toMatchSnapshot(); done(); }); }); it('renders the TextInput component', () => { const TextInput = require('TextInput'); const tree = renderer.create( <TextInput autoCorrect={false} value="apple banana kiwi" /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('renders the ListView component', () => { const ListView = require('ListView'); const Text = require('Text'); const dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2, }).cloneWithRows([ 'apple', 'banana', 'kiwi', ]); const tree = renderer.create( <ListView dataSource={dataSource} renderRow={(rowData) => <Text>{rowData}</Text>} /> ).toJSON(); expect(tree).toMatchSnapshot(); });
examples/react-native/__tests__/Intro-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017268283409066498, 0.0001717762934276834, 0.0001704971509752795, 0.00017188511264976114, 7.373565154011885e-7 ]
{ "id": 4, "code_window": [ " if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR\n", " const message = getMessage(result.message);\n", " const error = new JestAssertionError(message);\n", " // Remove this function from the stack trace frame.\n", " Error.captureStackTrace(error, throwingMatcher);\n", "\n", " if (throws) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " error.matcherResult = result;\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "add", "edit_start_line_idx": 116 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type { Expect, ExpectationObject, ExpectationResult, MatcherContext, MatcherState, MatchersObject, RawMatcherFn, ThrowingMatcherFn, } from 'types/Matchers'; const matchers = require('./matchers'); const spyMatchers = require('./spyMatchers'); const toThrowMatchers = require('./toThrowMatchers'); const utils = require('jest-matcher-utils'); const GLOBAL_STATE = Symbol.for('$$jest-matchers-object'); class JestAssertionError extends Error {} if (!global[GLOBAL_STATE]) { Object.defineProperty( global, GLOBAL_STATE, {value: { matchers: Object.create(null), state: { assertionsExpected: null, assertionsMade: 0, suppressedErrors: [], }, }}, ); } const expect: Expect = (actual: any): ExpectationObject => { const allMatchers = global[GLOBAL_STATE].matchers; const expectation = {not: {}}; Object.keys(allMatchers).forEach(name => { expectation[name] = makeThrowingMatcher(allMatchers[name], false, actual); expectation.not[name] = makeThrowingMatcher(allMatchers[name], true, actual); }); return expectation; }; const getMessage = message => { // for performance reasons some of the messages are evaluated // lazily if (typeof message === 'function') { message = message(); } if (!message) { message = utils.RECEIVED_COLOR( 'No message was specified for this matcher.', ); } return message; }; const makeThrowingMatcher = ( matcher: RawMatcherFn, isNot: boolean, actual: any, ): ThrowingMatcherFn => { return function throwingMatcher(...args) { let throws = true; const matcherContext: MatcherContext = Object.assign( // When throws is disabled, the matcher will not throw errors during test // execution but instead add them to the global matcher state. If a // matcher throws, test execution is normally stopped immediately. The // snapshot matcher uses it because we want to log all snapshot // failures in a test. {dontThrow: () => throws = false}, global[GLOBAL_STATE].state, { isNot, utils, }, ); let result: ExpectationResult; try { result = matcher.apply( matcherContext, [actual].concat(args), ); } catch (error) { // Remove this and deeper functions from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); throw error; } _validateResult(result); global[GLOBAL_STATE].state.assertionsMade++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); const error = new JestAssertionError(message); // Remove this function from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); if (throws) { throw error; } else { global[GLOBAL_STATE].state.suppressedErrors.push(error); } } }; }; expect.extend = (matchersObj: MatchersObject): void => { Object.assign(global[GLOBAL_STATE].matchers, matchersObj); }; const _validateResult = result => { if ( typeof result !== 'object' || typeof result.pass !== 'boolean' || ( result.message && ( typeof result.message !== 'string' && typeof result.message !== 'function' ) ) ) { throw new Error( 'Unexpected return from a matcher function.\n' + 'Matcher functions should ' + 'return an object in the following format:\n' + ' {message?: string | function, pass: boolean}\n' + `'${utils.stringify(result)}' was returned`, ); } }; const setState = (state: MatcherState) => { Object.assign(global[GLOBAL_STATE].state, state); }; const getState = () => global[GLOBAL_STATE].state; // add default jest matchers expect.extend(matchers); expect.extend(spyMatchers); expect.extend(toThrowMatchers); expect.assertions = (expected: number) => ( global[GLOBAL_STATE].state.assertionsExpected = expected ); module.exports = { expect, getState, setState, };
packages/jest-matchers/src/index.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.9986281394958496, 0.11347246170043945, 0.00016287223843391985, 0.0010269080521538854, 0.3098846673965454 ]
{ "id": 4, "code_window": [ " if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR\n", " const message = getMessage(result.message);\n", " const error = new JestAssertionError(message);\n", " // Remove this function from the stack trace frame.\n", " Error.captureStackTrace(error, throwingMatcher);\n", "\n", " if (throws) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " error.matcherResult = result;\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "add", "edit_start_line_idx": 116 }
--- id: configuration title: Configuration layout: docs category: Reference permalink: docs/configuration.html next: troubleshooting --- #### The Jest configuration options Jest's configuration can be defined in the `package.json` file of your project or through the `--config <path/to/json>` option. If you'd like to use your `package.json` to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings: ```js { "name": "my-project", "jest": { "verbose": true } } ``` When using the --config option, the JSON file must not contain a "jest" key: ```js { "bail": true, "verbose": true } ``` #### [Configuration Options](#configuration) These options let you control Jest's behavior in your `package.json` file. The Jest philosophy is to work great by default, but sometimes you just need more configuration power. - [`automock` [boolean]](#automock-boolean) - [`browser` [boolean]](#browser-boolean) - [`bail` [boolean]](#bail-boolean) - [`cacheDirectory` [string]](#cachedirectory-string) - [`collectCoverage` [boolean]](#collectcoverage-boolean) - [`collectCoverageFrom` [array]](#collectcoveragefrom-array) - [`coverageDirectory` [string]](#coveragedirectory-string) - [`coveragePathIgnorePatterns` [array<string>]](#coveragepathignorepatterns-array-string) - [`coverageReporters` [array<string>]](#coveragereporters-array-string) - [`coverageThreshold` [object]](#coveragethreshold-object) - [`globals` [object]](#globals-object) - [`mocksPattern` [string]](#mockspattern-string) - [`moduleDirectories` [array<string>]](#moduledirectories-array-string) - [`moduleFileExtensions` [array<string>]](#modulefileextensions-array-string) - [`moduleNameMapper` [object<string, string>]](#modulenamemapper-object-string-string) - [`modulePathIgnorePatterns` [array<string>]](#modulepathignorepatterns-array-string) - [`modulePaths` [array<string>]](#modulepaths-array-string) - [`notify` [boolean]](#notify-boolean) - [`preset` [string]](#preset-string) - [`resetMocks` [boolean]](#resetmocks-boolean) - [`resetModules` [boolean]](#resetmodules-boolean) - [`rootDir` [string]](#rootdir-string) - [`setupFiles` [array]](#setupfiles-array) - [`setupTestFrameworkScriptFile` [string]](#setuptestframeworkscriptfile-string) - [`snapshotSerializers` [array<string>]](#snapshotserializers-array-string) - [`testEnvironment` [string]](#testenvironment-string) - [`testPathDirs` [array<string>]](#testpathdirs-array-string) - [`testPathIgnorePatterns` [array<string>]](#testpathignorepatterns-array-string) - [`testRegex` [string]](#testregex-string) - [`testResultsProcessor` [string]](#testresultsprocessor-string) - [`testRunner` [string]](#testrunner-string) - [`testURL` [string]](#testurl-string) - [`timers` [string]](#timers-string) - [`transform` [object<string, string>]](#transform-object-string-string) - [`transformIgnorePatterns` [array<string>]](#transformignorepatterns-array-string) - [`unmockedModulePathPatterns` [array<string>]](#unmockedmodulepathpatterns-array-string) - [`verbose` [boolean]](#verbose-boolean) ----- ## Jest options ### `automock` [boolean] (default: false) This option is disabled by default. If you are introducing Jest to a large organization with an existing codebase but few tests, enabling this option can be helpful to introduce unit tests gradually. Modules can be explicitly auto-mocked using `jest.mock(moduleName)`. ### `browser` [boolean] (default: false) Respect Browserify's [`"browser"` field](https://github.com/substack/browserify-handbook#browser-field) in `package.json` when resolving modules. Some modules export different versions based on whether they are operating in Node or a browser. ### `bail` [boolean] (default: false) By default, Jest runs all tests and produces all errors into the console upon completion. The bail config option can be used here to have Jest stop running tests after the first failure. ### `cacheDirectory` [string] (default: '/tmp/<path>') The directory where Jest should store its cached dependency information. Jest attempts to scan your dependency tree once (up-front) and cache it in order to ease some of the filesystem raking that needs to happen while running tests. This config option lets you customize where Jest stores that cache data on disk. ### `collectCoverage` [boolean] (default: `false`) Indicates whether the coverage information should be collected while executing the test. Because this retrofits all executed files with coverage collection statements, it may significantly slow down your tests. ### `collectCoverageFrom` [array] (default: `undefined`) An array of [glob patterns](https://github.com/sindresorhus/multimatch) indicating a set of files for which coverage information should be collected. If a file matches the specified glob pattern, coverage information will be collected for it even if no tests exist for this file and it's never required in the test suite. Example: ```js collectCoverageFrom: ['**/*.{js,jsx}', '!**/node_modules/**', '!**/vendor/**'] ``` This will collect coverage information for all the files inside the project's `rootDir`, except the ones that match `**/node_modules/**` or `**/vendor/**`. *Note: This option requires `collectCoverage` to be set to true or Jest to be invoked with `--coverage`.* ### `coverageDirectory` [string] (default: `undefined`) The directory where Jest should output its coverage files. ### `coveragePathIgnorePatterns` [array<string>] (default: `['/node_modules/']`) An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped. These pattern strings match against the full path. Use the `<rootDir>` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `['<rootDir>/build/', '<rootDir>/node_modules/']`. ### `coverageReporters` [array<string>] (default: `['json', 'lcov', 'text']`) A list of reporter names that Jest uses when writing coverage reports. Any [istanbul reporter](https://github.com/gotwarlost/istanbul/tree/master/lib/report) can be used. *Note: Setting this option overwrites the default values. Add `'text'` or `'text-summary'` to see a coverage summary in the console output.* ### `coverageThreshold` [object] (default: `undefined`) This will be used to configure minimum threshold enforcement for coverage results. If the thresholds are not met, jest will return failure. Thresholds, when specified as a positive number are taken to be the minimum percentage required. When a threshold is specified as a negative number it represents the maximum number of uncovered entities allowed. For example, statements: 90 implies minimum statement coverage is 90%. statements: -10 implies that no more than 10 uncovered statements are allowed. ```js { ... "jest": { "coverageThreshold": { "global": { "branches": 50, "functions": 50, "lines": 50, "statements": 50 } } } } ``` ### `globals` [object] (default: `{}`) A set of global variables that need to be available in all test environments. For example, the following would create a global `__DEV__` variable set to `true` in all test environments: ```js { ... "jest": { "globals": { "__DEV__": true } } } ``` Note that, if you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will *not* be persisted across test runs for other test files. ### `mocksPattern` [string] (default: `(?:[\\/]|^)__mocks__[\\/]`) A pattern that is matched against file paths to determine which folder contains manual mocks. ### `moduleFileExtensions` [array<string>] (default: `['js', 'json', 'jsx', 'node']`) An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for. If you are using TypeScript this should be `['js', 'jsx', 'json', 'ts', 'tsx']` ### `moduleDirectories` [array<string>] (default: `['node_modules']`) An array of directory names to be searched recursively up from the requiring module's location. Setting this option will _override_ the default, if you wish to still search `node_modules` for packages include it along with any other options: `['node_modules', 'bower_components']` ### `moduleNameMapper` [object<string, string>] (default: `null`) A map from regular expressions to module names that allow to stub out resources, like images or styles with a single module. Modules that are mapped to an alias are unmocked by default, regardless of whether automocking is enabled or not. Use `<rootDir>` string token to refer to [`rootDir`](#rootdir-string) value if you want to use file paths. Additionally, you can substitute captured regex groups using numbered backreferences. Example: ```js "moduleNameMapper": { "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub", "^[./a-zA-Z0-9$_-]+\.png$": "<rootDir>/RelativeImageStub.js", "module_name_(.*)": "<rootDir>/substituted_module_$1.js" } ``` *Note: If you provide module name without boundaries `^$` it may cause hard to spot errors. E.g. `relay` will replace all modules which contain `relay` as a substring in its name: `relay`, `react-relay` and `graphql-relay` will all be pointed to your stub.* ### `modulePathIgnorePatterns` [array<string>] (default: `[]`) An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be `require()`-able in the test environment. These pattern strings match against the full path. Use the `<rootDir>` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `['<rootDir>/build/']`. ### `modulePaths` [array<string>] (default: `[]`) An alternative API to setting the `NODE_PATH` env variable, `modulePaths` is an array of absolute paths to additional locations to search when resolving modules. Use the `<rootDir>` string token to include the path to your project's root directory. Example: `["<rootDir>/app/"]`. ### `notify` [boolean] (default: `false`) Activates notifications for test results. ### `preset` [string] (default: `undefined`) A preset that is used as a base for Jest's configuration. A preset should point to an npm module that exports a `jest-preset.json` module on its top level. ### `resetMocks` [boolean] (default: false) Automatically reset mock state between every test. Equivalent to calling `jest.resetAllMocks()` between each test. ### `resetModules` [boolean] (default: `false`) If enabled, the module registry for every test file will be reset before running each individual test. This is useful to isolate modules for every test so that local module state doesn't conflict between tests. This can be done programmatically using [`jest.resetModules()`](#jest-resetmodules). ### `rootDir` [string] (default: The root of the directory containing the `package.json` *or* the [`pwd`](http://en.wikipedia.org/wiki/Pwd) if no `package.json` is found) The root directory that Jest should scan for tests and modules within. If you put your Jest config inside your `package.json` and want the root directory to be the root of your repo, the value for this config param will default to the directory of the `package.json`. Oftentimes, you'll want to set this to `'src'` or `'lib'`, corresponding to where in your repository the code is stored. *Note that using `'<rootDir>'` as a string token in any other path-based config settings to refer back to this value. So, for example, if you want your [`setupFiles`](#setupfiles-array) config entry to point at the `env-setup.js` file at the root of your project, you could set its value to `['<rootDir>/env-setup.js']`.* ### `setupFiles` [array] (default: `[]`) The paths to modules that run some code to configure or set up the testing environment before each test. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself. It's worth noting that this code will execute *before* [`setupTestFrameworkScriptFile`](#setuptestframeworkscriptfile-string). ### `setupTestFrameworkScriptFile` [string] (default: `undefined`) The path to a module that runs some code to configure or set up the testing framework before each test. Since [`setupFiles`](#setupfiles-array) executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment. For example, Jest ships with several plug-ins to `jasmine` that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in this module. ### `snapshotSerializers` [array<string>] (default: `[]`) A list of paths to snapshot serializer modules Jest should use for snapshot testing. Jest has default serializers for built-in javascript types and for react elements. See [snapshot test tutorial](/jest/docs/tutorial-react-native.html#snapshot-test) for more information. Example serializer module: ```js // my-serializer-module module.exports = { test: function(val) { return val && val.hasOwnProperty('foo'); }, print: function(val, serialize, indent) { return 'Pretty foo: ' + serialize(val.foo); } }; ``` `serialize` is a function that serializes a value using existing plugins. To use `my-serializer-module` as a serializer, configuration would be as follows: ```js { ... "jest": { "snapshotSerializers": ["<rootDir>/node_modules/my-serializer-module"] } } ``` Finally tests would look as follows: ```js test(() => { const bar = { foo: {x: 1, y: 2} }; expect(foo).toMatchSnapshot(); }); ``` Rendered snapshot: ``` Pretty foo: Object { "x": 1, "y": 2, } ``` ### `testEnvironment` [string] (default: `'jsdom'`) The test environment that will be used for testing. The default environment in Jest is a browser-like environment through [jsdom](https://github.com/tmpvar/jsdom). If you are building a node service, you can use the `node` option to use a node-like environment instead. ### `testPathDirs` [array<string>] (default: `['<rootDir>']`) A list of paths to directories that Jest should use to search for tests in. There are times where you only want Jest to search in a single sub-directory (such as cases where you have a `src/` directory in your repo), but not the rest of the repo. ### `testPathIgnorePatterns` [array<string>] (default: `['/node_modules/']`) An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped. These pattern strings match against the full path. Use the `<rootDir>` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `['<rootDir>/build/', '<rootDir>/node_modules/']`. ### `testRegex` [string] (default: `(/__tests__/.*|\\.(test|spec))\\.jsx?$`) The pattern Jest uses to detect test files. By default it looks for `.js` and `.jsx` files inside of `__tests__` folders, as well as any files with a suffix of `.test` or `.spec` (e.g. `Component.test.js` or `Component.spec.js`). ### `testResultsProcessor` [string] (default: `undefined`) This option allows the use of a custom results processor. This processor must be a node module that exports a function expecting an object with the following structure as the first argument: ``` { "success": bool, "startTime": epoch, "numTotalTestSuites": number, "numPassedTestSuites": number, "numFailedTestSuites": number, "numRuntimeErrorTestSuites": number, "numTotalTests": number, "numPassedTests": number, "numFailedTests": number, "numPendingTests": number, "testResults": [{ "numFailingTests": number, "numPassingTests": number, "numPendingTests": number, "testResults": [{ "title": string (message in it block), "status": "failed" | "pending" | "passed", "ancestorTitles": [string (message in describe blocks)], "failureMessages": [string], "numPassingAsserts": number }, ... ], "perfStats": { "start": epoch, "end": epoch }, "testFilePath": absolute path to test file, "coverage": {} }, ... ] } ``` ### `testRunner` [string] (default: `jasmine2`) This option allows use of a custom test runner. The default is jasmine2. A custom test runner can be provided by specifying a path to a test runner implementation. ### `testURL` [string] (default: `about:blank`) This option sets the URL for the jsdom environment. It is reflected in properties such as `location.href`. ### `timers` [string] (default: `real`) Setting this value to `fake` allows the use of fake timers for functions such as `setTimeout`. Fake timers are useful when a piece of code sets a long timeout that we don't want to wait for in a test. ### `transform` [object<string, string>] (default: `undefined`) A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that isn't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](/jest/examples/typescript/package.json#L16) example or the [webpack tutorial](/jest/docs/tutorial-webpack.html). Examples of such compilers include [babel](https://babeljs.io/), [typescript](http://www.typescriptlang.org/), and [async-to-gen](http://github.com/leebyron/async-to-gen#jest). *Note: a transformer is only ran once per file unless the file has changed. During development of a transformer it can be useful to run Jest with `--no-cache` or to frequently [delete Jest's cache](/jest/docs/troubleshooting.html#caching-issues).* *Note: if you are using the `babel-jest` transformer and want to use an additional code preprocessor, keep in mind that when "transform" is overwritten in any way the `babel-jest` is not loaded automatically anymore. If you want to use it to compile JavaScript code it has to be explicitly defined. See [babel-jest plugin](https://github.com/facebook/jest/tree/master/packages/babel-jest#setup)* ### `transformIgnorePatterns` [array<string>] (default: `['/node_modules/']`) An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed. These pattern strings match against the full path. Use the `<rootDir>` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `['<rootDir>/bower_components/', '<rootDir>/node_modules/']`. ### `unmockedModulePathPatterns` [array<string>] (default: `[]`) An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader. This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like underscore/lo-dash, etc). It's generally a best practice to keep this list as small as possible and always use explicit `jest.mock()`/`jest.unmock()` calls in individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test will run in. It is possible to override this setting in individual tests by explicitly calling `jest.mock()` at the top of the test file. ### `verbose` [boolean] (default: `false`) Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution.
docs/Configuration.md
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017826331895776093, 0.0001683604932622984, 0.00015960115706548095, 0.0001695300015853718, 0.00000481563347420888 ]
{ "id": 4, "code_window": [ " if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR\n", " const message = getMessage(result.message);\n", " const error = new JestAssertionError(message);\n", " // Remove this function from the stack trace frame.\n", " Error.captureStackTrace(error, throwingMatcher);\n", "\n", " if (throws) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " error.matcherResult = result;\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "add", "edit_start_line_idx": 116 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type {Path} from 'types/Config'; import type {HasteFS} from 'types/HasteMap'; const fs = require('fs'); module.exports = ( filePath: Path, hasteFS: ?HasteFS, ): boolean => (hasteFS && hasteFS.exists(filePath)) || fs.existsSync(filePath);
packages/jest-file-exists/src/index.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.0001791992544895038, 0.00017643127648625523, 0.000171155363204889, 0.00017893921176437289, 0.000003732144250534475 ]
{ "id": 4, "code_window": [ " if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR\n", " const message = getMessage(result.message);\n", " const error = new JestAssertionError(message);\n", " // Remove this function from the stack trace frame.\n", " Error.captureStackTrace(error, throwingMatcher);\n", "\n", " if (throws) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " error.matcherResult = result;\n" ], "file_path": "packages/jest-matchers/src/index.js", "type": "add", "edit_start_line_idx": 116 }
{ "name": "my-module", "main": "./core.js" }
packages/jest-runtime/src/__tests__/test_root/module_dir/my-module/package.json
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017717489390634, 0.00017717489390634, 0.00017717489390634, 0.00017717489390634, 0 ]
{ "id": 5, "code_window": [ " `Received:\\n` +\n", " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toBeCloseTo(\n", " actual: number,\n", " expected: number,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toBe', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 105 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type { Expect, ExpectationObject, ExpectationResult, MatcherContext, MatcherState, MatchersObject, RawMatcherFn, ThrowingMatcherFn, } from 'types/Matchers'; const matchers = require('./matchers'); const spyMatchers = require('./spyMatchers'); const toThrowMatchers = require('./toThrowMatchers'); const utils = require('jest-matcher-utils'); const GLOBAL_STATE = Symbol.for('$$jest-matchers-object'); class JestAssertionError extends Error {} if (!global[GLOBAL_STATE]) { Object.defineProperty( global, GLOBAL_STATE, {value: { matchers: Object.create(null), state: { assertionsExpected: null, assertionsMade: 0, suppressedErrors: [], }, }}, ); } const expect: Expect = (actual: any): ExpectationObject => { const allMatchers = global[GLOBAL_STATE].matchers; const expectation = {not: {}}; Object.keys(allMatchers).forEach(name => { expectation[name] = makeThrowingMatcher(allMatchers[name], false, actual); expectation.not[name] = makeThrowingMatcher(allMatchers[name], true, actual); }); return expectation; }; const getMessage = message => { // for performance reasons some of the messages are evaluated // lazily if (typeof message === 'function') { message = message(); } if (!message) { message = utils.RECEIVED_COLOR( 'No message was specified for this matcher.', ); } return message; }; const makeThrowingMatcher = ( matcher: RawMatcherFn, isNot: boolean, actual: any, ): ThrowingMatcherFn => { return function throwingMatcher(...args) { let throws = true; const matcherContext: MatcherContext = Object.assign( // When throws is disabled, the matcher will not throw errors during test // execution but instead add them to the global matcher state. If a // matcher throws, test execution is normally stopped immediately. The // snapshot matcher uses it because we want to log all snapshot // failures in a test. {dontThrow: () => throws = false}, global[GLOBAL_STATE].state, { isNot, utils, }, ); let result: ExpectationResult; try { result = matcher.apply( matcherContext, [actual].concat(args), ); } catch (error) { // Remove this and deeper functions from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); throw error; } _validateResult(result); global[GLOBAL_STATE].state.assertionsMade++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); const error = new JestAssertionError(message); // Remove this function from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); if (throws) { throw error; } else { global[GLOBAL_STATE].state.suppressedErrors.push(error); } } }; }; expect.extend = (matchersObj: MatchersObject): void => { Object.assign(global[GLOBAL_STATE].matchers, matchersObj); }; const _validateResult = result => { if ( typeof result !== 'object' || typeof result.pass !== 'boolean' || ( result.message && ( typeof result.message !== 'string' && typeof result.message !== 'function' ) ) ) { throw new Error( 'Unexpected return from a matcher function.\n' + 'Matcher functions should ' + 'return an object in the following format:\n' + ' {message?: string | function, pass: boolean}\n' + `'${utils.stringify(result)}' was returned`, ); } }; const setState = (state: MatcherState) => { Object.assign(global[GLOBAL_STATE].state, state); }; const getState = () => global[GLOBAL_STATE].state; // add default jest matchers expect.extend(matchers); expect.extend(spyMatchers); expect.extend(toThrowMatchers); expect.assertions = (expected: number) => ( global[GLOBAL_STATE].state.assertionsExpected = expected ); module.exports = { expect, getState, setState, };
packages/jest-matchers/src/index.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.007011490408331156, 0.0009888776112347841, 0.00016559354844503105, 0.0001734347315505147, 0.0017290051328018308 ]
{ "id": 5, "code_window": [ " `Received:\\n` +\n", " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toBeCloseTo(\n", " actual: number,\n", " expected: number,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toBe', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 105 }
module.exports.isBrowser = false;
packages/jest-runtime/src/__tests__/test_root/node_modules/jest-resolve-test/node.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00016782563761807978, 0.00016782563761807978, 0.00016782563761807978, 0.00016782563761807978, 0 ]
{ "id": 5, "code_window": [ " `Received:\\n` +\n", " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toBeCloseTo(\n", " actual: number,\n", " expected: number,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toBe', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 105 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+jsinfra */ 'use strict'; const runJest = require('../runJest'); const skipOnWindows = require('skipOnWindows'); skipOnWindows.suite(); test('does not crash when expect involving a DOM node fails', () => { const result = runJest('compare-dom-nodes'); expect(result.stderr).toContain('FAIL __tests__/failed-assertion.js'); });
integration_tests/__tests__/compare-dom-nodes-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017587582988198847, 0.00017201640002895147, 0.0001690694480203092, 0.0001711039658403024, 0.000002852616489690263 ]
{ "id": 5, "code_window": [ " `Received:\\n` +\n", " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toBeCloseTo(\n", " actual: number,\n", " expected: number,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toBe', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 105 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; describe('promise fit', () => { it('fails but will be skipped', () => { expect(true).toBe(false); }); fit('will run', () => { return Promise.resolve(); }); fit('will run and fail', () => { return Promise.reject(); }); });
integration_tests/jasmine_async/__tests__/promise_fit-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017641815065871924, 0.00017285071953665465, 0.0001662902213865891, 0.00017584380111657083, 0.000004644898126571206 ]
{ "id": 6, "code_window": [ " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toHaveLength(received: any, length: number) {\n", " if (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toEqual', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 398 }
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type { Expect, ExpectationObject, ExpectationResult, MatcherContext, MatcherState, MatchersObject, RawMatcherFn, ThrowingMatcherFn, } from 'types/Matchers'; const matchers = require('./matchers'); const spyMatchers = require('./spyMatchers'); const toThrowMatchers = require('./toThrowMatchers'); const utils = require('jest-matcher-utils'); const GLOBAL_STATE = Symbol.for('$$jest-matchers-object'); class JestAssertionError extends Error {} if (!global[GLOBAL_STATE]) { Object.defineProperty( global, GLOBAL_STATE, {value: { matchers: Object.create(null), state: { assertionsExpected: null, assertionsMade: 0, suppressedErrors: [], }, }}, ); } const expect: Expect = (actual: any): ExpectationObject => { const allMatchers = global[GLOBAL_STATE].matchers; const expectation = {not: {}}; Object.keys(allMatchers).forEach(name => { expectation[name] = makeThrowingMatcher(allMatchers[name], false, actual); expectation.not[name] = makeThrowingMatcher(allMatchers[name], true, actual); }); return expectation; }; const getMessage = message => { // for performance reasons some of the messages are evaluated // lazily if (typeof message === 'function') { message = message(); } if (!message) { message = utils.RECEIVED_COLOR( 'No message was specified for this matcher.', ); } return message; }; const makeThrowingMatcher = ( matcher: RawMatcherFn, isNot: boolean, actual: any, ): ThrowingMatcherFn => { return function throwingMatcher(...args) { let throws = true; const matcherContext: MatcherContext = Object.assign( // When throws is disabled, the matcher will not throw errors during test // execution but instead add them to the global matcher state. If a // matcher throws, test execution is normally stopped immediately. The // snapshot matcher uses it because we want to log all snapshot // failures in a test. {dontThrow: () => throws = false}, global[GLOBAL_STATE].state, { isNot, utils, }, ); let result: ExpectationResult; try { result = matcher.apply( matcherContext, [actual].concat(args), ); } catch (error) { // Remove this and deeper functions from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); throw error; } _validateResult(result); global[GLOBAL_STATE].state.assertionsMade++; if ((result.pass && isNot) || (!result.pass && !isNot)) { // XOR const message = getMessage(result.message); const error = new JestAssertionError(message); // Remove this function from the stack trace frame. Error.captureStackTrace(error, throwingMatcher); if (throws) { throw error; } else { global[GLOBAL_STATE].state.suppressedErrors.push(error); } } }; }; expect.extend = (matchersObj: MatchersObject): void => { Object.assign(global[GLOBAL_STATE].matchers, matchersObj); }; const _validateResult = result => { if ( typeof result !== 'object' || typeof result.pass !== 'boolean' || ( result.message && ( typeof result.message !== 'string' && typeof result.message !== 'function' ) ) ) { throw new Error( 'Unexpected return from a matcher function.\n' + 'Matcher functions should ' + 'return an object in the following format:\n' + ' {message?: string | function, pass: boolean}\n' + `'${utils.stringify(result)}' was returned`, ); } }; const setState = (state: MatcherState) => { Object.assign(global[GLOBAL_STATE].state, state); }; const getState = () => global[GLOBAL_STATE].state; // add default jest matchers expect.extend(matchers); expect.extend(spyMatchers); expect.extend(toThrowMatchers); expect.assertions = (expected: number) => ( global[GLOBAL_STATE].state.assertionsExpected = expected ); module.exports = { expect, getState, setState, };
packages/jest-matchers/src/index.js
1
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.009284363128244877, 0.001075430540367961, 0.00016489397967234254, 0.0001719814317766577, 0.0021488661877810955 ]
{ "id": 6, "code_window": [ " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toHaveLength(received: any, length: number) {\n", " if (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toEqual', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 398 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; describe('promise it', () => { beforeEach(() => { this.someContextValue = 'value'; }); // passing tests it('passes a sync test', () => { expect(1).toBe(1); }); it('waits for promise to be resolved', () => { return Promise.resolve(); }); it('works with done', done => { done(); }); it('is bound to context object', () => { return new Promise(resolve => { if (this.someContextValue !== 'value') { throw new Error( 'expected this.someContextValue to be set: ' + this.someContextValue ); } resolve(); }); }); // failing tests it('fails if promise is rejected', () => { return Promise.reject(new Error('rejected promise returned')); }); it('works with done.fail', done => { done.fail(new Error('done.fail was called')); }); it('fails a sync test', () => { expect('sync').toBe('failed'); }); it('succeeds if the test finishes in time', () => { return new Promise(resolve => setTimeout(resolve, 10)); }, 250); // failing tests it('fails if a custom timeout is exceeded', () => { return new Promise(resolve => setTimeout(resolve, 100)); }, 10); });
integration_tests/jasmine_async/__tests__/promise_it-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017663865583017468, 0.00017393170855939388, 0.00016929543926380575, 0.00017372095317114145, 0.000002310506033609272 ]
{ "id": 6, "code_window": [ " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toHaveLength(received: any, length: number) {\n", " if (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toEqual', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 398 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; module.exports.process = () => `throw new Error('preprocessor must not run.');`;
packages/jest-runtime/src/__tests__/test_root/test-preprocessor.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017663865583017468, 0.0001740774605423212, 0.00017151626525446773, 0.0001740774605423212, 0.0000025611952878534794 ]
{ "id": 6, "code_window": [ " ` ${printReceived(received)}` +\n", " (diffString ? `\\n\\nDifference:\\n\\n${diffString}` : '');\n", " };\n", "\n", " return {message, pass};\n", " },\n", "\n", " toHaveLength(received: any, length: number) {\n", " if (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return {actual: received, expected, message, name: 'toEqual', pass};\n" ], "file_path": "packages/jest-matchers/src/matchers.js", "type": "replace", "edit_start_line_idx": 398 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+jsinfra */ 'use strict'; const skipOnWindows = require('skipOnWindows'); const spawnSync = require('child_process').spawnSync; const path = require('path'); const JEST_RUNTIME = path.resolve(__dirname, '../../bin/jest-runtime.js'); const run = args => spawnSync(JEST_RUNTIME, args, { cwd: process.cwd(), encoding: 'utf8', env: process.env, }); describe('Runtime', () => { skipOnWindows.suite(); describe('cli', () => { it('fails with no path', () => { const expectedOutput = 'Please provide a path to a script. (See --help for details)\n'; expect(run([]).stdout).toBe(expectedOutput); }); it('displays script output', () => { const scriptPath = path.resolve(__dirname, './test_root/logging.js'); expect(run([scriptPath, '--no-cache']).stdout).toMatch('Hello, world!\n'); }); it('always disables automocking', () => { const scriptPath = path.resolve(__dirname, './test_root/logging.js'); const output = run([ scriptPath, '--no-cache', '--config=' + JSON.stringify({ automock: true, }), ]); expect(output.stdout).toMatch('Hello, world!\n'); }); it('throws script errors', () => { const scriptPath = path.resolve(__dirname, './test_root/throwing.js'); expect( run([scriptPath, '--no-cache']).stderr, ).toMatch('Error: throwing\n'); }); }); });
packages/jest-runtime/src/__tests__/Runtime-cli-test.js
0
https://github.com/jestjs/jest/commit/db0f3b4902ddb360020be8f737db1fae7a8508c4
[ 0.00017630818183533847, 0.00017286976799368858, 0.00017100120021495968, 0.00017236272105947137, 0.0000018266862298332853 ]
{ "id": 0, "code_window": [ "import { lstatSync } from 'node:fs'\n", "import type { Nuxt, NuxtModule } from '@nuxt/schema'\n", "import { dirname, isAbsolute, normalize, resolve } from 'pathe'\n", "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { dirname, isAbsolute } from 'pathe'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 2 }
import { lstatSync } from 'node:fs' import type { Nuxt, NuxtModule } from '@nuxt/schema' import { dirname, isAbsolute, normalize, resolve } from 'pathe' import { isNuxt2 } from '../compatibility' import { useNuxt } from '../context' import { requireModule } from '../internal/cjs' import { importModule } from '../internal/esm' import { resolveAlias } from '../resolve' /** Installs a module on a Nuxt instance. */ export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) { const nuxt = useNuxt() const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions) // Call module const res = ( isNuxt2() // @ts-expect-error Nuxt 2 `moduleContainer` is not typed ? await nuxtModule.call(nuxt.moduleContainer, inlineOptions, nuxt) : await nuxtModule(inlineOptions, nuxt) ) ?? {} if (res === false /* setup aborted */) { return } if (typeof moduleToInstall === 'string') { nuxt.options.build.transpile.push(normalizeModuleTranspilePath(moduleToInstall)) } nuxt.options._installedModules = nuxt.options._installedModules || [] nuxt.options._installedModules.push({ meta: await nuxtModule.getMeta?.(), timings: res.timings, entryPath: typeof moduleToInstall === 'string' ? resolveAlias(moduleToInstall) : undefined }) } // --- Internal --- export const normalizeModuleTranspilePath = (p: string) => { try { // we need to target directories instead of module file paths themselves // /home/user/project/node_modules/module/index.js -> /home/user/project/node_modules/module p = isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p } catch (e) { // maybe the path is absolute but does not exist, allow this to bubble up } return p.split('node_modules/').pop() as string } async function normalizeModule (nuxtModule: string | NuxtModule, inlineOptions?: any) { const nuxt = useNuxt() // Import if input is string if (typeof nuxtModule === 'string') { let src = resolveAlias(nuxtModule) if (src.match(/^\.{1,2}\//)) { src = resolve(nuxt.options.rootDir, src) } src = normalize(src) try { // Prefer ESM resolution if possible nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir }) } catch (error: unknown) { console.error(`Error while requiring module \`${nuxtModule}\`: ${error}`) throw error } } // Throw error if input is not a function if (typeof nuxtModule !== 'function') { throw new TypeError('Nuxt module should be a function: ' + nuxtModule) } return { nuxtModule, inlineOptions } as { nuxtModule: NuxtModule<any>, inlineOptions: undefined | Record<string, any> } }
packages/kit/src/module/install.ts
1
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.9898651242256165, 0.1269710212945938, 0.0004178045492153615, 0.00363440765067935, 0.3261573016643524 ]
{ "id": 0, "code_window": [ "import { lstatSync } from 'node:fs'\n", "import type { Nuxt, NuxtModule } from '@nuxt/schema'\n", "import { dirname, isAbsolute, normalize, resolve } from 'pathe'\n", "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { dirname, isAbsolute } from 'pathe'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 2 }
export * from '@nuxt/schema'
packages/nuxt/schema.js
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00024031271459534764, 0.00024031271459534764, 0.00024031271459534764, 0.00024031271459534764, 0 ]
{ "id": 0, "code_window": [ "import { lstatSync } from 'node:fs'\n", "import type { Nuxt, NuxtModule } from '@nuxt/schema'\n", "import { dirname, isAbsolute, normalize, resolve } from 'pathe'\n", "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { dirname, isAbsolute } from 'pathe'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 2 }
--- description: "Nuxt uses Vue and adds features such as component auto-imports and file-based routing." --- # Vue.js Development Nuxt uses Vue as a frontend framework and adds features such as component auto-imports and file-based routing. Nuxt 3 integrates Vue 3, the new major release of Vue that enables new patterns for Nuxt users. > While an in-depth knowledge of Vue is not required to use Nuxt, we recommend that you read the documentation and go through some of the examples on [vuejs.org](https://vuejs.org/). > Nuxt has always used Vue as a frontend framework. We chose to build Nuxt on top of Vue for these reasons: - The reactivity model of Vue, where a change in data automatically triggers a change in the interface. - The component-based templating, while keeping HTML as the common language of the web, enables intuitive patterns to keep your interface consistent, yet powerful. - From small projects to large web applications, Vue keeps performing well at scale to ensure that your application keeps delivering value to your users. ## Vue with Nuxt ### Single File Components [Vue’s single-file components](https://v3.vuejs.org/guide/single-file-component.html) (SFC, or `*.vue` files) encapsulate the markup (`<template>`), logic (`<script>`) and styling (`<style>`) of a Vue component. Nuxt provides a zero-config experience for SFCs with [Hot Module Replacement](https://webpack.js.org/concepts/hot-module-replacement/) that offers a seamless developer experience. ### Components Auto-imports Every Vue component created in the [`components/` directory](/docs/guide/directory-structure/components) of a Nuxt project will be available in your project without having to import it. If a component is not used anywhere, your production’s code will not include it. ### Vue Router Most applications need multiple pages and a way to navigate between them. This is called **routing**. Nuxt uses a [`pages/` directory](/docs/guide/directory-structure/pages) and naming conventions to directly create routes mapped to your files using the official [Vue Router library](https://router.vuejs.org/). ### Example :button-link[Open on StackBlitz]{href="https://stackblitz.com/edit/github-9hzuns?file=app.vue" blank .mr-2} :button-link[Open on CodeSandbox]{href="https://codesandbox.io/s/nuxt-3-components-auto-import-2xq9z?file=/app.vue" blank} The `app.vue` file is the entry point, which represents the page displayed in the browser window. Inside the `<template>` of the component, we use the `<Welcome>` component created in the `components/` directory without having to import it. Try to replace the `<template>`’s content with a custom welcome message. The browser window on the right will automatically render the changes without reloading. ::alert{type="info"} 💡 If you're familiar with Vue, you might be looking for the `main.js` file that creates a Vue app instance. Nuxt automatically handles this behind the scenes. :: **If you were a previous user of Nuxt 2 or Vue 2, keep reading to get a feel of the differences between Vue 2 and Vue 3, and how Nuxt integrates those evolutions.** **Otherwise, go to the next chapter to discover another key feature of Nuxt: [Rendering modes](/docs/guide/concepts/rendering)**. ## Differences with Nuxt 2 / Vue 2 Nuxt 3 is based on Vue 3. The new major Vue version introduces several changes that Nuxt takes advantage of: - Better performance - Composition API - TypeScript support ### Faster Rendering The Vue Virtual DOM (VDOM) has been rewritten from the ground up and allows for better rendering performance. On top of that, when working with compiled Single-File Components, the Vue compiler can further optimize them at build time by separating static and dynamic markup. This results in faster first rendering (component creation) and updates, and less memory usage. In Nuxt 3, it enables faster server-side rendering as well. ### Smaller Bundle With Vue 3 and Nuxt 3, a focus has been put on bundle size reduction. With version 3, most of Vue’s functionality, including template directives and built-in components, is tree-shakable. Your production bundle will not include them if you don’t use them. This way, a minimal Vue 3 application can be reduced to 12 kb gzipped. ### Composition API The only way to provide data and logic to components in Vue 2 was through the Options API, which allows you to return data and methods to a template with pre-defined properties like `data` and `methods`: ```vue <script> export default { data() { return { count: 0 } }, methods: { increment(){ this.count++ } } } </script> ``` The [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) introduced in Vue 3 is not a replacement of the Options API, but it enables better logic reuse throughout an application, and is a more natural way to group code by concern in complex components. Used with the `setup` keyword in the `<script>` definition, here is the above component rewritten with Composition API and Nuxt 3’s auto-imported Reactivity APIs: ```vue <script setup> const count = ref(0); const increment = () => count.value++; </script> ``` The goal of Nuxt 3 is to provide a great developer experience around the Composition API. - Use auto-imported [Reactivity functions](https://vuejs.org/api/reactivity-core.html) from Vue and Nuxt 3 [built-in composables](/docs/api/composables/use-async-data). - Write your own auto-imported reusable functions in the `composables/` directory. ### TypeScript Support Both Vue 3 and Nuxt 3 are written in TypeScript. A fully typed codebase prevents mistakes and documents APIs usage. This doesn’t mean that you have to write your application in TypeScript to take advantage of it. With Nuxt 3, you can opt-in by renaming your file from `.js` to `.ts` , or add `<script lang="ts">` in a component. ::alert{type="info"} 🔎 [Read the details about TypeScript in Nuxt 3](/docs/guide/concepts/typescript) ::
docs/2.guide/1.concepts/2.vuejs-development.md
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.0007581569370813668, 0.0002870346943382174, 0.00016047540702857077, 0.0001859671901911497, 0.00019934015290345997 ]
{ "id": 0, "code_window": [ "import { lstatSync } from 'node:fs'\n", "import type { Nuxt, NuxtModule } from '@nuxt/schema'\n", "import { dirname, isAbsolute, normalize, resolve } from 'pathe'\n", "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { dirname, isAbsolute } from 'pathe'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 2 }
import type { TestHooks } from '../types' export default async function setupVitest (hooks: TestHooks) { const vitest = await import('vitest') hooks.ctx.mockFn = vitest.vi.fn vitest.beforeAll(hooks.setup, hooks.ctx.options.setupTimeout) vitest.beforeEach(hooks.beforeEach) vitest.afterEach(hooks.afterEach) vitest.afterAll(hooks.afterAll) }
packages/test-utils/src/setup/vitest.ts
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00016762892482802272, 0.0001674469094723463, 0.0001672648941166699, 0.0001674469094723463, 1.8201535567641258e-7 ]
{ "id": 1, "code_window": [ "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n", "import { resolveAlias } from '../resolve'\n", "\n", "/** Installs a module on a Nuxt instance. */\n", "export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { resolveAlias, resolvePath } from '../resolve'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 7 }
import { addBuildPlugin, addComponent } from 'nuxt/kit' import type { NuxtPage } from 'nuxt/schema' import { createUnplugin } from 'unplugin' import { withoutLeadingSlash } from 'ufo' // (defined in nuxt/src/core/nitro.ts) declare module 'nitropack' { interface NitroRouteConfig { ssr?: boolean } } export default defineNuxtConfig({ typescript: { strict: true, tsConfig: { compilerOptions: { moduleResolution: process.env.MODULE_RESOLUTION } } }, app: { pageTransition: true, layoutTransition: true, head: { charset: 'utf-8', link: [undefined], meta: [ { name: 'viewport', content: 'width=1024, initial-scale=1' }, { charset: 'utf-8' }, { name: 'description', content: 'Nuxt Fixture' } ] } }, buildDir: process.env.NITRO_BUILD_DIR, builder: process.env.TEST_BUILDER as 'webpack' | 'vite' ?? 'vite', build: { transpile: [ (ctx) => { if (typeof ctx.isDev !== 'boolean') { throw new TypeError('context not passed') } return false } ] }, theme: './extends/bar', css: ['~/assets/global.css'], extends: [ './extends/node_modules/foo' ], nitro: { routeRules: { '/route-rules/spa': { ssr: false }, '/no-scripts': { experimentalNoScripts: true } }, output: { dir: process.env.NITRO_OUTPUT_DIR }, prerender: { routes: [ '/random/a', '/random/b', '/random/c' ] } }, optimization: { keyedComposables: [ { name: 'useKeyedComposable', argumentLength: 1 } ] }, runtimeConfig: { baseURL: '', baseAPIToken: '', privateConfig: 'secret_key', public: { ids: [1, 2, 3], needsFallback: undefined, testConfig: 123 } }, modules: [ './modules/test/index', [ '~/modules/example', { typeTest (val) { // @ts-expect-error module type defines val as boolean const b: string = val return !!b } } ], function (_, nuxt) { if (typeof nuxt.options.builder === 'string' && nuxt.options.builder.includes('webpack')) { return } nuxt.options.css.push('virtual.css') nuxt.options.build.transpile.push('virtual.css') const plugin = createUnplugin(() => ({ name: 'virtual', resolveId (id) { if (id === 'virtual.css') { return 'virtual.css' } }, load (id) { if (id === 'virtual.css') { return ':root { --virtual: red }' } } })) addBuildPlugin(plugin) }, function (_options, nuxt) { const routesToDuplicate = ['/async-parent', '/fixed-keyed-child-parent', '/keyed-child-parent', '/with-layout', '/with-layout2'] const stripLayout = (page: NuxtPage): NuxtPage => ({ ...page, children: page.children?.map(child => stripLayout(child)), name: 'internal-' + page.name, path: withoutLeadingSlash(page.path), meta: { ...page.meta || {}, layout: undefined, _layout: page.meta?.layout } }) nuxt.hook('pages:extend', (pages) => { const newPages = [] for (const page of pages) { if (routesToDuplicate.includes(page.path)) { newPages.push(stripLayout(page)) } } const internalParent = pages.find(page => page.path === '/internal-layout') internalParent!.children = newPages }) }, function (_, nuxt) { nuxt.options.optimization.treeShake.composables.server[nuxt.options.rootDir] = ['useClientOnlyComposable', 'setTitleToPink'] nuxt.options.optimization.treeShake.composables.client[nuxt.options.rootDir] = ['useServerOnlyComposable'] }, // To test falsy module values undefined ], vite: { logLevel: 'silent' }, telemetry: false, // for testing telemetry types - it is auto-disabled in tests hooks: { 'schema:extend' (schemas) { schemas.push({ appConfig: { someThing: { value: { $default: 'default', $schema: { tsType: 'string | false' } } } } }) }, 'prepare:types' ({ tsConfig }) { tsConfig.include = tsConfig.include!.filter(i => i !== '../../../../**/*') }, 'modules:done' () { addComponent({ name: 'CustomComponent', export: 'namedExport', filePath: '~/other-components-folder/named-export' }) }, 'vite:extendConfig' (config) { config.plugins!.push({ name: 'nuxt:server', configureServer (server) { server.middlewares.use((req, res, next) => { if (req.url === '/vite-plugin-without-path') { res.end('vite-plugin without path') return } next() }) server.middlewares.use((req, res, next) => { if (req.url === '/__nuxt-test') { res.end('vite-plugin with __nuxt prefix') return } next() }) } }) } }, vue: { compilerOptions: { isCustomElement: (tag) => { return tag === 'custom-component' } } }, experimental: { typedPages: true, polyfillVueUseHead: true, renderJsonPayloads: process.env.TEST_PAYLOAD !== 'js', respectNoSSRHeader: true, clientFallback: true, restoreState: true, inlineSSRStyles: id => !!id && !id.includes('assets.vue'), componentIslands: true, reactivityTransform: true, treeshakeClientOnly: true, payloadExtraction: true }, appConfig: { fromNuxtConfig: true, nested: { val: 1 } } })
test/fixtures/basic/nuxt.config.ts
1
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00031056225998327136, 0.00017707032384350896, 0.00016428598610218614, 0.00016887360834516585, 0.000030015398806426674 ]
{ "id": 1, "code_window": [ "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n", "import { resolveAlias } from '../resolve'\n", "\n", "/** Installs a module on a Nuxt instance. */\n", "export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { resolveAlias, resolvePath } from '../resolve'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 7 }
export default defineNuxtConfig({ modules: [ '@nuxt/ui' ] })
examples/app/error-handling/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00023679820878896862, 0.00023679820878896862, 0.00023679820878896862, 0.00023679820878896862, 0 ]
{ "id": 1, "code_window": [ "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n", "import { resolveAlias } from '../resolve'\n", "\n", "/** Installs a module on a Nuxt instance. */\n", "export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { resolveAlias, resolvePath } from '../resolve'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 7 }
--- title: "defineNuxtRouteMiddleware" --- # `defineNuxtRouteMiddleware` Create named route middleware using `defineNuxtRouteMiddleware` helper function. Route middleware are stored in the `middleware/` directory of your Nuxt application (unless [set otherwise](/docs/api/configuration/nuxt-config#middleware)). ## Type ```ts defineNuxtRouteMiddleware(middleware: RouteMiddleware) => RouteMiddleware interface RouteMiddleware { (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard> } ``` ## Parameters ### `middleware` - **Type**: `RouteMiddleware` A function that takes two Vue Router's route location objects as parameters: the next route `to` as the first, and the current route `from` as the second. Learn more about available properties of `RouteLocationNormalized` in the **[Vue Router docs](https://router.vuejs.org/api/interfaces/RouteLocationNormalized.html)**. ## Examples ### Showing Error Page You can use route middleware to throw errors and show helpful error messages: ```ts [middleware/error.ts] export default defineNuxtRouteMiddleware((to) => { if (to.params.id === '1') { throw createError({ statusCode: 404, statusMessage: 'Page Not Found' }) } }) ``` The above route middleware will redirect a user to the custom error page defined in the `~/error.vue` file, and expose the error message and code passed from the middleware. ### Redirection Use `useState` in combination with `navigateTo` helper function inside the route middleware to redirect users to different routes based on their authentication status: ```ts [middleware/auth.ts] export default defineNuxtRouteMiddleware((to, from) => { const auth = useState('auth') if (!auth.value.isAuthenticated) { return navigateTo('/login') } if (to.path !== '/dashboard') { return navigateTo('/dashboard') } }) ``` Both [navigateTo](/docs/api/utils/navigate-to) and [abortNavigation](/docs/api/utils/abort-navigation) are globally available helper functions that you can use inside `defineNuxtRouteMiddleware`.
docs/3.api/3.utils/define-nuxt-route-middleware.md
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00021709995053242892, 0.00017953364294953644, 0.00016244772996287793, 0.00017132893844973296, 0.000018198450561612844 ]
{ "id": 1, "code_window": [ "import { isNuxt2 } from '../compatibility'\n", "import { useNuxt } from '../context'\n", "import { requireModule } from '../internal/cjs'\n", "import { importModule } from '../internal/esm'\n", "import { resolveAlias } from '../resolve'\n", "\n", "/** Installs a module on a Nuxt instance. */\n", "export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { resolveAlias, resolvePath } from '../resolve'\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 7 }
export default defineNuxtConfig({ modules: [ '@nuxt/ui' ] })
examples/app/plugins/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00023679820878896862, 0.00023679820878896862, 0.00023679820878896862, 0.00023679820878896862, 0 ]
{ "id": 2, "code_window": [ "\n", " // Import if input is string\n", " if (typeof nuxtModule === 'string') {\n", " let src = resolveAlias(nuxtModule)\n", " if (src.match(/^\\.{1,2}\\//)) {\n", " src = resolve(nuxt.options.rootDir, src)\n", " }\n", " src = normalize(src)\n", " try {\n", " // Prefer ESM resolution if possible\n", " nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir })\n", " } catch (error: unknown) {\n", " console.error(`Error while requiring module \\`${nuxtModule}\\`: ${error}`)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const src = await resolvePath(nuxtModule)\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 55 }
import { lstatSync } from 'node:fs' import type { Nuxt, NuxtModule } from '@nuxt/schema' import { dirname, isAbsolute, normalize, resolve } from 'pathe' import { isNuxt2 } from '../compatibility' import { useNuxt } from '../context' import { requireModule } from '../internal/cjs' import { importModule } from '../internal/esm' import { resolveAlias } from '../resolve' /** Installs a module on a Nuxt instance. */ export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) { const nuxt = useNuxt() const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions) // Call module const res = ( isNuxt2() // @ts-expect-error Nuxt 2 `moduleContainer` is not typed ? await nuxtModule.call(nuxt.moduleContainer, inlineOptions, nuxt) : await nuxtModule(inlineOptions, nuxt) ) ?? {} if (res === false /* setup aborted */) { return } if (typeof moduleToInstall === 'string') { nuxt.options.build.transpile.push(normalizeModuleTranspilePath(moduleToInstall)) } nuxt.options._installedModules = nuxt.options._installedModules || [] nuxt.options._installedModules.push({ meta: await nuxtModule.getMeta?.(), timings: res.timings, entryPath: typeof moduleToInstall === 'string' ? resolveAlias(moduleToInstall) : undefined }) } // --- Internal --- export const normalizeModuleTranspilePath = (p: string) => { try { // we need to target directories instead of module file paths themselves // /home/user/project/node_modules/module/index.js -> /home/user/project/node_modules/module p = isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p } catch (e) { // maybe the path is absolute but does not exist, allow this to bubble up } return p.split('node_modules/').pop() as string } async function normalizeModule (nuxtModule: string | NuxtModule, inlineOptions?: any) { const nuxt = useNuxt() // Import if input is string if (typeof nuxtModule === 'string') { let src = resolveAlias(nuxtModule) if (src.match(/^\.{1,2}\//)) { src = resolve(nuxt.options.rootDir, src) } src = normalize(src) try { // Prefer ESM resolution if possible nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir }) } catch (error: unknown) { console.error(`Error while requiring module \`${nuxtModule}\`: ${error}`) throw error } } // Throw error if input is not a function if (typeof nuxtModule !== 'function') { throw new TypeError('Nuxt module should be a function: ' + nuxtModule) } return { nuxtModule, inlineOptions } as { nuxtModule: NuxtModule<any>, inlineOptions: undefined | Record<string, any> } }
packages/kit/src/module/install.ts
1
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.9975792765617371, 0.2524300515651703, 0.00017557172395754606, 0.0037941662594676018, 0.4296777546405792 ]
{ "id": 2, "code_window": [ "\n", " // Import if input is string\n", " if (typeof nuxtModule === 'string') {\n", " let src = resolveAlias(nuxtModule)\n", " if (src.match(/^\\.{1,2}\\//)) {\n", " src = resolve(nuxt.options.rootDir, src)\n", " }\n", " src = normalize(src)\n", " try {\n", " // Prefer ESM resolution if possible\n", " nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir })\n", " } catch (error: unknown) {\n", " console.error(`Error while requiring module \\`${nuxtModule}\\`: ${error}`)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const src = await resolvePath(nuxtModule)\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 55 }
import { resolve } from 'node:path' import { defineConfig } from 'vite' import { configDefaults } from 'vitest/config' import { isWindows } from 'std-env' export default defineConfig({ resolve: { alias: { '#app': resolve('./packages/nuxt/dist/app/index'), '@nuxt/test-utils/experimental': resolve('./packages/test-utils/src/experimental.ts'), '@nuxt/test-utils': resolve('./packages/test-utils/src/index.ts') } }, test: { globalSetup: 'test/setup.ts', testTimeout: isWindows ? 60000 : 10000, deps: { inline: ['@vitejs/plugin-vue'] }, // Excluded plugin because it should throw an error when accidentally loaded via Nuxt exclude: [...configDefaults.exclude, '**/this-should-not-load.spec.js'], maxThreads: process.env.TEST_ENV === 'dev' ? 1 : undefined, minThreads: process.env.TEST_ENV === 'dev' ? 1 : undefined } })
vitest.config.ts
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.0001652131468290463, 0.00016402873734477907, 0.00016274774679914117, 0.0001641253475099802, 0.0000010088105000249925 ]
{ "id": 2, "code_window": [ "\n", " // Import if input is string\n", " if (typeof nuxtModule === 'string') {\n", " let src = resolveAlias(nuxtModule)\n", " if (src.match(/^\\.{1,2}\\//)) {\n", " src = resolve(nuxt.options.rootDir, src)\n", " }\n", " src = normalize(src)\n", " try {\n", " // Prefer ESM resolution if possible\n", " nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir })\n", " } catch (error: unknown) {\n", " console.error(`Error while requiring module \\`${nuxtModule}\\`: ${error}`)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const src = await resolvePath(nuxtModule)\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 55 }
import { defineComponent, getCurrentInstance, onErrorCaptured, ref } from 'vue' import { ssrRenderAttrs, ssrRenderSlot, ssrRenderVNode } from 'vue/server-renderer' import { useState } from '../composables/state' import { createBuffer } from './utils' const NuxtClientFallbackServer = defineComponent({ name: 'NuxtClientFallback', inheritAttrs: false, props: { uid: { type: String }, fallbackTag: { type: String, default: () => 'div' }, fallback: { type: String, default: () => '' }, placeholder: { type: String }, placeholderTag: { type: String }, keepFallback: { type: Boolean, default: () => false } }, emits: ['ssr-error'], setup (props, ctx) { const vm = getCurrentInstance() const ssrFailed = ref(false) onErrorCaptured(() => { useState(`${props.uid}`, () => true) ssrFailed.value = true ctx.emit('ssr-error') return false }) try { const defaultSlot = ctx.slots.default?.() const ssrVNodes = createBuffer() for (let i = 0; i < (defaultSlot?.length || 0); i++) { ssrRenderVNode(ssrVNodes.push, defaultSlot![i], vm!) } return { ssrFailed, ssrVNodes } } catch { // catch in dev useState(`${props.uid}`, () => true) ctx.emit('ssr-error') return { ssrFailed: true, ssrVNodes: [] } } }, ssrRender (ctx: any, push: any, parent: any) { if (ctx.ssrFailed) { const { fallback, placeholder } = ctx.$slots if (fallback || placeholder) { ssrRenderSlot(ctx.$slots, fallback ? 'fallback' : 'placeholder', {}, null, push, parent) } else { const content = ctx.placeholder || ctx.fallback const tag = ctx.placeholderTag || ctx.fallbackTag push(`<${tag}${ssrRenderAttrs(ctx.$attrs)}>${content}</${tag}>`) } } else { // push Fragment markup push('<!--[-->') push(ctx.ssrVNodes.getBuffer()) push('<!--]-->') } } }) export default NuxtClientFallbackServer
packages/nuxt/src/app/components/client-fallback.server.ts
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.0002029047318501398, 0.0001737033308017999, 0.00016540655633434653, 0.0001698487758403644, 0.000011429367077653296 ]
{ "id": 2, "code_window": [ "\n", " // Import if input is string\n", " if (typeof nuxtModule === 'string') {\n", " let src = resolveAlias(nuxtModule)\n", " if (src.match(/^\\.{1,2}\\//)) {\n", " src = resolve(nuxt.options.rootDir, src)\n", " }\n", " src = normalize(src)\n", " try {\n", " // Prefer ESM resolution if possible\n", " nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir })\n", " } catch (error: unknown) {\n", " console.error(`Error while requiring module \\`${nuxtModule}\\`: ${error}`)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const src = await resolvePath(nuxtModule)\n" ], "file_path": "packages/kit/src/module/install.ts", "type": "replace", "edit_start_line_idx": 55 }
--- description: You can use this function to create an error object with additional metadata. --- # `createError` You can use this function to create an error object with additional metadata. It is usable in both the Vue and Nitro portions of your app, and is meant to be thrown. **Parameters:** * err: { cause, data, message, name, stack, statusCode, statusMessage, fatal } ## Throwing Errors in Your Vue App If you throw an error created with `createError`: * on server-side, it will trigger a full-screen error page which you can clear with `clearError`. * on client-side, it will throw a non-fatal error for you to handle. If you need to trigger a full-screen error page, then you can do this by setting `fatal: true`. ### Example ```vue [pages/movies/[slug].vue] <script setup> const route = useRoute() const { data } = await useFetch(`/api/movies/${route.params.slug}`) if (!data.value) { throw createError({ statusCode: 404, statusMessage: 'Page Not Found' }) } </script> ``` ## Throwing Errors in API Routes Use `createError` to trigger error handling in server API routes. ### Example ```js export default eventHandler(() => { throw createError({ statusCode: 404, statusMessage: 'Page Not Found' }) } ``` ::ReadMore{link="/docs/getting-started/error-handling"} ::
docs/3.api/3.utils/create-error.md
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00021989278320688754, 0.00017604813911020756, 0.00016219251847360283, 0.00016683514695614576, 0.000022073243599152192 ]
{ "id": 3, "code_window": [ " testConfig: 123\n", " }\n", " },\n", " modules: [\n", " './modules/test/index',\n", " [\n", " '~/modules/example',\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " './modules/test',\n" ], "file_path": "test/fixtures/basic/nuxt.config.ts", "type": "replace", "edit_start_line_idx": 82 }
import { addBuildPlugin, addComponent } from 'nuxt/kit' import type { NuxtPage } from 'nuxt/schema' import { createUnplugin } from 'unplugin' import { withoutLeadingSlash } from 'ufo' // (defined in nuxt/src/core/nitro.ts) declare module 'nitropack' { interface NitroRouteConfig { ssr?: boolean } } export default defineNuxtConfig({ typescript: { strict: true, tsConfig: { compilerOptions: { moduleResolution: process.env.MODULE_RESOLUTION } } }, app: { pageTransition: true, layoutTransition: true, head: { charset: 'utf-8', link: [undefined], meta: [ { name: 'viewport', content: 'width=1024, initial-scale=1' }, { charset: 'utf-8' }, { name: 'description', content: 'Nuxt Fixture' } ] } }, buildDir: process.env.NITRO_BUILD_DIR, builder: process.env.TEST_BUILDER as 'webpack' | 'vite' ?? 'vite', build: { transpile: [ (ctx) => { if (typeof ctx.isDev !== 'boolean') { throw new TypeError('context not passed') } return false } ] }, theme: './extends/bar', css: ['~/assets/global.css'], extends: [ './extends/node_modules/foo' ], nitro: { routeRules: { '/route-rules/spa': { ssr: false }, '/no-scripts': { experimentalNoScripts: true } }, output: { dir: process.env.NITRO_OUTPUT_DIR }, prerender: { routes: [ '/random/a', '/random/b', '/random/c' ] } }, optimization: { keyedComposables: [ { name: 'useKeyedComposable', argumentLength: 1 } ] }, runtimeConfig: { baseURL: '', baseAPIToken: '', privateConfig: 'secret_key', public: { ids: [1, 2, 3], needsFallback: undefined, testConfig: 123 } }, modules: [ './modules/test/index', [ '~/modules/example', { typeTest (val) { // @ts-expect-error module type defines val as boolean const b: string = val return !!b } } ], function (_, nuxt) { if (typeof nuxt.options.builder === 'string' && nuxt.options.builder.includes('webpack')) { return } nuxt.options.css.push('virtual.css') nuxt.options.build.transpile.push('virtual.css') const plugin = createUnplugin(() => ({ name: 'virtual', resolveId (id) { if (id === 'virtual.css') { return 'virtual.css' } }, load (id) { if (id === 'virtual.css') { return ':root { --virtual: red }' } } })) addBuildPlugin(plugin) }, function (_options, nuxt) { const routesToDuplicate = ['/async-parent', '/fixed-keyed-child-parent', '/keyed-child-parent', '/with-layout', '/with-layout2'] const stripLayout = (page: NuxtPage): NuxtPage => ({ ...page, children: page.children?.map(child => stripLayout(child)), name: 'internal-' + page.name, path: withoutLeadingSlash(page.path), meta: { ...page.meta || {}, layout: undefined, _layout: page.meta?.layout } }) nuxt.hook('pages:extend', (pages) => { const newPages = [] for (const page of pages) { if (routesToDuplicate.includes(page.path)) { newPages.push(stripLayout(page)) } } const internalParent = pages.find(page => page.path === '/internal-layout') internalParent!.children = newPages }) }, function (_, nuxt) { nuxt.options.optimization.treeShake.composables.server[nuxt.options.rootDir] = ['useClientOnlyComposable', 'setTitleToPink'] nuxt.options.optimization.treeShake.composables.client[nuxt.options.rootDir] = ['useServerOnlyComposable'] }, // To test falsy module values undefined ], vite: { logLevel: 'silent' }, telemetry: false, // for testing telemetry types - it is auto-disabled in tests hooks: { 'schema:extend' (schemas) { schemas.push({ appConfig: { someThing: { value: { $default: 'default', $schema: { tsType: 'string | false' } } } } }) }, 'prepare:types' ({ tsConfig }) { tsConfig.include = tsConfig.include!.filter(i => i !== '../../../../**/*') }, 'modules:done' () { addComponent({ name: 'CustomComponent', export: 'namedExport', filePath: '~/other-components-folder/named-export' }) }, 'vite:extendConfig' (config) { config.plugins!.push({ name: 'nuxt:server', configureServer (server) { server.middlewares.use((req, res, next) => { if (req.url === '/vite-plugin-without-path') { res.end('vite-plugin without path') return } next() }) server.middlewares.use((req, res, next) => { if (req.url === '/__nuxt-test') { res.end('vite-plugin with __nuxt prefix') return } next() }) } }) } }, vue: { compilerOptions: { isCustomElement: (tag) => { return tag === 'custom-component' } } }, experimental: { typedPages: true, polyfillVueUseHead: true, renderJsonPayloads: process.env.TEST_PAYLOAD !== 'js', respectNoSSRHeader: true, clientFallback: true, restoreState: true, inlineSSRStyles: id => !!id && !id.includes('assets.vue'), componentIslands: true, reactivityTransform: true, treeshakeClientOnly: true, payloadExtraction: true }, appConfig: { fromNuxtConfig: true, nested: { val: 1 } } })
test/fixtures/basic/nuxt.config.ts
1
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.028506940230727196, 0.0014760110061615705, 0.0001632704515941441, 0.00016797365969978273, 0.0058991434052586555 ]
{ "id": 3, "code_window": [ " testConfig: 123\n", " }\n", " },\n", " modules: [\n", " './modules/test/index',\n", " [\n", " '~/modules/example',\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " './modules/test',\n" ], "file_path": "test/fixtures/basic/nuxt.config.ts", "type": "replace", "edit_start_line_idx": 82 }
<template> <div> Hello from extended page ! </div> </template> <script setup> definePageMeta({ middleware: 'foo' }) </script>
examples/advanced/config-extends/base/pages/foo.vue
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00019728262850549072, 0.0001832549023674801, 0.00016922717622946948, 0.0001832549023674801, 0.000014027726138010621 ]
{ "id": 3, "code_window": [ " testConfig: 123\n", " }\n", " },\n", " modules: [\n", " './modules/test/index',\n", " [\n", " '~/modules/example',\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " './modules/test',\n" ], "file_path": "test/fixtures/basic/nuxt.config.ts", "type": "replace", "edit_start_line_idx": 82 }
# Auto Imports Nuxt 3 adopts a minimal friction approach, meaning wherever possible components and composables are auto-imported. ::alert{type=info} In the rest of the migration documentation, you will notice that key Nuxt and Vue utilities do not have explicit imports. This is not a typo; Nuxt will automatically import them for you, and you should get full type hinting if you have followed [the instructions](/docs/migration/configuration#typescript) to use Nuxt's TypeScript support. :: [Read more about auto imports](/docs/guide/concepts/auto-imports) ## Migration 1. If you have been using `@nuxt/components` in Nuxt 2, you can remove `components: true` in your `nuxt.config`. If you had a more complex setup, then note that the component options have changed somewhat. See the [components documentation](/docs/guide/directory-structure/components) for more information. ::alert{type=info} You can look at `.nuxt/types/components.d.ts` and `.nuxt/types/imports.d.ts` to see how Nuxt has resolved your components and composable auto-imports. ::
docs/7.migration/3.auto-imports.md
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.00016780116129666567, 0.00016705726739019156, 0.00016631337348371744, 0.00016705726739019156, 7.438939064741135e-7 ]
{ "id": 3, "code_window": [ " testConfig: 123\n", " }\n", " },\n", " modules: [\n", " './modules/test/index',\n", " [\n", " '~/modules/example',\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " './modules/test',\n" ], "file_path": "test/fixtures/basic/nuxt.config.ts", "type": "replace", "edit_start_line_idx": 82 }
--- navigation.icon: uil:window-section --- # Views Nuxt provides several component layers to implement the user interface of your application. ## `app.vue` ![The `app.vue` file is the entry point of your application](/assets/docs/getting-started/views/app.svg) By default, Nuxt will treat this file as the **entrypoint** and render its content for every route of the application. ```vue [app.vue] <template> <div> <h1>Welcome to the homepage</h1> </div> </template> ``` ::alert If you are familiar with Vue, you might wonder where `main.js` is (the file that normally creates a Vue app). Nuxt does this behind the scene. :: ## Components ![Components are reusable pieces of UI](/assets/docs/getting-started/views/components.svg) Most components are reusable pieces of the user interface, like buttons and menus. In Nuxt, you can create these components in the `components/` directory, and they will be automatically available across your application without having to explicitly import them. ::code-group ```vue [app.vue] <template> <div> <h1>Welcome to the homepage</h1> <AppAlert> This is an auto-imported component. </AppAlert> </div> </template> ``` ```vue [components/AppAlert.vue] <template> <span> <slot /> </span> </template> ``` :: ## Pages ![Pages are views tied to a specific route](/assets/docs/getting-started/views/pages.svg) Pages represent views for each specific route pattern. Every file in the `pages/` directory represents a different route displaying its content. To use pages, create `pages/index.vue` file and add `<NuxtPage />` component to the `app.vue` (or remove `app.vue` for default entry). You can now create more pages and their corresponding routes by adding new files in the `pages/` directory. ::code-group ```vue [pages/index.vue] <template> <div> <h1>Welcome to the homepage</h1> <AppAlert> This is an auto-imported component </AppAlert> </div> </template> ``` ```vue [pages/about.vue] <template> <section> <p>This page will be displayed at the /about route.</p> </section> </template> ``` :: ::alert You will learn more about pages in the [Routing section](/docs/getting-started/routing) :: ## Layouts ![Layouts are wrapper around pages](/assets/docs/getting-started/views/layouts.svg) Layouts are wrappers around pages that contain a common User Interface for several pages, such as a header and footer display. Layouts are Vue files using `<slot />` components to display the **page** content. The `layouts/default.vue` file will be used by default. Custom layouts can be set as part of your page metadata. ::alert If you only have a single layout in your application, we recommend using app.vue with the [`<NuxtPage />` component](/docs/api/components/nuxt-page) instead. :: ::code-group ```vue [layouts/default.vue] <template> <div> <AppHeader /> <slot /> <AppFooter /> </div> </template> ``` ```vue [pages/index.vue] <template> <div> <h1>Welcome to the homepage</h1> <AppAlert> This is an auto-imported component </AppAlert> </div> </template> ``` ```vue [pages/about.vue] <template> <section> <p>This page will be displayed at the /about route.</p> </section> </template> ``` :: If you want to create more layouts and learn how to use them in your pages, find more information in the [Layouts section](/docs/guide/directory-structure/layouts).
docs/1.getting-started/3.views.md
0
https://github.com/nuxt/nuxt/commit/980728275a7bfab0fef40d6d8ba045ebc1c0b1a6
[ 0.0001728350471239537, 0.00016787451750133187, 0.00016269824118353426, 0.00016827895888127387, 0.0000029848922622477403 ]
{ "id": 0, "code_window": [ "// Type definitions for requestretry 1.12\n", "// Project: https://github.com/FGRibreau/node-request-retry\n", "// Definitions by: Eric Byers <https://github.com/EricByers>\n", "// \t\t\t\t Andrew Throener <https://github.com/trainerbill>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "// Definitions by: \tEric Byers <https://github.com/EricByers>\n", "// \t\t\t\t \t\t\t\tAndrew Throener <https://github.com/trainerbill>\n", "// \t\t\t\t\t\t\t\t\tAniket Patel <https://github.com/baaka-ani>\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 2 }
import request = require('requestretry'); import http = require('http'); // HTTPOrNetworkError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.HTTPOrNetworkError }, (err, response, body) => { // Body. }); // HttpError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.HttpError }, (err, response, body) => { // Body. }); // NetworkError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.NetworkError }, (err, response, body) => { // Body. }); // Custom strategy. const CustomRetryStrategy = (err: Error, response: http.IncomingMessage, body: any): boolean => { // Return a boolean return true; }; request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: CustomRetryStrategy }, (err, response, body) => { // Body. }); // No options required request({ url: 'https://api.example.com/v1/a/b', json: true }, (err, response, body) => { // Body. }); // Define options const options: request.RequestRetryOptions = { maxAttempts: 2, promiseFactory: (resolver: any) => { return new Promise(resolver); }, retryDelay: 4, retryStrategy: (err: Error, response: http.IncomingMessage, body: any) => { return true; }, };
types/requestretry/requestretry-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.0006701675010845065, 0.0002902755222748965, 0.00016472802963107824, 0.00018257557530887425, 0.00016156320634763688 ]
{ "id": 0, "code_window": [ "// Type definitions for requestretry 1.12\n", "// Project: https://github.com/FGRibreau/node-request-retry\n", "// Definitions by: Eric Byers <https://github.com/EricByers>\n", "// \t\t\t\t Andrew Throener <https://github.com/trainerbill>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "// Definitions by: \tEric Byers <https://github.com/EricByers>\n", "// \t\t\t\t \t\t\t\tAndrew Throener <https://github.com/trainerbill>\n", "// \t\t\t\t\t\t\t\t\tAniket Patel <https://github.com/baaka-ani>\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 2 }
{ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, "array-type": false, "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, "comment-format": false, "dt-header": false, "npm-naming": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, "no-duplicate-variable": false, "no-empty-interface": false, "no-for-in-array": false, "no-inferrable-types": false, "no-internal-module": false, "no-irregular-whitespace": false, "no-mergeable-namespace": false, "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, "no-reference-import": false, "no-relative-import-in-test": false, "no-self-import": false, "no-single-declare-module": false, "no-string-throw": false, "no-unnecessary-callback-wrapper": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-useless-files": false, "no-var-keyword": false, "no-var-requires": false, "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, "only-arrow-functions": false, "prefer-conditional-expression": false, "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, "prefer-template": false, "radix": false, "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, "trim-file": false, "triple-equals": false, "typedef-whitespace": false, "unified-signatures": false, "void-return": false, "whitespace": false } }
types/gulp-sass/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.00017674682021606714, 0.00017443823162466288, 0.00017243126058019698, 0.0001744295295793563, 0.0000011659312804113142 ]
{ "id": 0, "code_window": [ "// Type definitions for requestretry 1.12\n", "// Project: https://github.com/FGRibreau/node-request-retry\n", "// Definitions by: Eric Byers <https://github.com/EricByers>\n", "// \t\t\t\t Andrew Throener <https://github.com/trainerbill>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "// Definitions by: \tEric Byers <https://github.com/EricByers>\n", "// \t\t\t\t \t\t\t\tAndrew Throener <https://github.com/trainerbill>\n", "// \t\t\t\t\t\t\t\t\tAniket Patel <https://github.com/baaka-ani>\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 2 }
import Crawler = require('simplecrawler'); const crawler = new Crawler('https://github.com/'); crawler.initialURL; // $ExpectType string crawler.host; // $ExpectType string crawler.interval; // $ExpectType number crawler.maxConcurrency; // $ExpectType number crawler.timeout; // $ExpectType number crawler.listenerTTL; // $ExpectType number crawler.userAgent; // $ExpectType string crawler.queue; // $ExpectType FetchQueue crawler.respectRobotsTxt; // $ExpectType boolean crawler.allowInitialDomainChange; // $ExpectType boolean crawler.decompressResponses; // $ExpectType boolean crawler.decodeResponses; // $ExpectType boolean crawler.filterByDomain; // $ExpectType boolean crawler.scanSubdomains; // $ExpectType boolean crawler.ignoreWWWDomain; // $ExpectType boolean crawler.stripWWWDomain; // $ExpectType boolean crawler.cache; // $ExpectType Cache | undefined crawler.useProxy; // $ExpectType boolean crawler.proxyHostname; // $ExpectType string crawler.proxyPort; // $ExpectType number crawler.proxyUser; // $ExpectType string | undefined crawler.proxyPass; // $ExpectType string | undefined crawler.needsAuth; // $ExpectType boolean crawler.authUser; // $ExpectType string | undefined crawler.authPass; // $ExpectType string | undefined crawler.acceptCookies; // $ExpectType boolean crawler.cookies; // $ExpectType CookieJar crawler.customHeaders; // $ExpectType object crawler.domainWhitelist; // $ExpectType string[] crawler.allowedProtocols; // $ExpectType RegExp[] crawler.maxResourceSize; // $ExpectType number crawler.supportedMimeTypes; // $ExpectType (string | RegExp)[] crawler.downloadUnsupported; // $ExpectType boolean crawler.urlEncoding; // $ExpectType string crawler.stripQuerystring; // $ExpectType boolean crawler.sortQueryParameters; // $ExpectType boolean crawler.discoverRegex; // $ExpectType (RegExp | (() => void))[] crawler.parseHTMLComments; // $ExpectType boolean crawler.parseScriptTags; // $ExpectType boolean crawler.maxDepth; // $ExpectType number crawler.ignoreInvalidSSL; // $ExpectType boolean crawler.httpAgent; // $ExpectType Agent crawler.httpsAgent; // $ExpectType Agent crawler.start(); crawler.on('fetchcomplete', (queueItem, responseBody, response) => { queueItem; // $ExpectType QueueItem responseBody; // $ExpectType string | Buffer response; // $ExpectType IncomingMessage });
types/simplecrawler/simplecrawler-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.00020411048899404705, 0.00017689832020550966, 0.00016510148998349905, 0.00017409052816219628, 0.000012652013538172469 ]
{ "id": 0, "code_window": [ "// Type definitions for requestretry 1.12\n", "// Project: https://github.com/FGRibreau/node-request-retry\n", "// Definitions by: Eric Byers <https://github.com/EricByers>\n", "// \t\t\t\t Andrew Throener <https://github.com/trainerbill>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.3\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "// Definitions by: \tEric Byers <https://github.com/EricByers>\n", "// \t\t\t\t \t\t\t\tAndrew Throener <https://github.com/trainerbill>\n", "// \t\t\t\t\t\t\t\t\tAniket Patel <https://github.com/baaka-ani>\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 2 }
import { RefractorSyntax } from '../core'; declare const lang: RefractorSyntax; export = lang;
types/refractor/lang/objectivec.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.00017502698756288737, 0.00017502698756288737, 0.00017502698756288737, 0.00017502698756288737, 0 ]
{ "id": 1, "code_window": [ "import request = require('request');\n", "import http = require('http');\n", "\n", "declare namespace requestretry {\n", "\ttype RetryStrategy = (err: Error, response: http.IncomingMessage, body: any) => boolean;\n", "\tinterface RetryRequestAPI extends request.RequestAPI<request.Request, RequestRetryOptions, request.RequiredUriUrl> {\n", "\t\tRetryStrategies: {\n", "\t\t\t'HttpError': RetryStrategy;\n", "\t\t\t'HTTPOrNetworkError': RetryStrategy;\n", "\t\t\t'NetworkError': RetryStrategy;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinterface RequestPromise extends request.Request {\n", "\t\tthen: Promise<any>[\"then\"];\n", "\t\tcatch: Promise<any>[\"catch\"];\n", "\t\tpromise(): Promise<any>;\n", "\t}\n", "\tinterface RetryRequestAPI extends request.RequestAPI<RequestPromise, RequestRetryOptions, request.RequiredUriUrl> {\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 14 }
import request = require('requestretry'); import http = require('http'); // HTTPOrNetworkError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.HTTPOrNetworkError }, (err, response, body) => { // Body. }); // HttpError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.HttpError }, (err, response, body) => { // Body. }); // NetworkError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.NetworkError }, (err, response, body) => { // Body. }); // Custom strategy. const CustomRetryStrategy = (err: Error, response: http.IncomingMessage, body: any): boolean => { // Return a boolean return true; }; request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: CustomRetryStrategy }, (err, response, body) => { // Body. }); // No options required request({ url: 'https://api.example.com/v1/a/b', json: true }, (err, response, body) => { // Body. }); // Define options const options: request.RequestRetryOptions = { maxAttempts: 2, promiseFactory: (resolver: any) => { return new Promise(resolver); }, retryDelay: 4, retryStrategy: (err: Error, response: http.IncomingMessage, body: any) => { return true; }, };
types/requestretry/requestretry-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.9939601421356201, 0.2281995415687561, 0.00044248829362913966, 0.016786938533186913, 0.39556649327278137 ]
{ "id": 1, "code_window": [ "import request = require('request');\n", "import http = require('http');\n", "\n", "declare namespace requestretry {\n", "\ttype RetryStrategy = (err: Error, response: http.IncomingMessage, body: any) => boolean;\n", "\tinterface RetryRequestAPI extends request.RequestAPI<request.Request, RequestRetryOptions, request.RequiredUriUrl> {\n", "\t\tRetryStrategies: {\n", "\t\t\t'HttpError': RetryStrategy;\n", "\t\t\t'HTTPOrNetworkError': RetryStrategy;\n", "\t\t\t'NetworkError': RetryStrategy;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinterface RequestPromise extends request.Request {\n", "\t\tthen: Promise<any>[\"then\"];\n", "\t\tcatch: Promise<any>[\"catch\"];\n", "\t\tpromise(): Promise<any>;\n", "\t}\n", "\tinterface RetryRequestAPI extends request.RequestAPI<RequestPromise, RequestRetryOptions, request.RequiredUriUrl> {\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 14 }
import { Action, createStore, applyMiddleware } from "redux"; import { reducer, createMiddleware, createLoader } from "redux-storage"; import reduxStorageImmutableMerger from "redux-storage-merger-immutablejs"; import filter from "redux-storage-decorator-filter"; import createEngine from "redux-storage-engine-localstorage"; import createReactNativeAsyncStorageEngine from "redux-storage-engine-reactnativeasyncstorage"; interface TestState { a: number; b: string; c: string; } function rootReducer(state: TestState, action: Action): TestState { return state; } const enhancedReducer = reducer(rootReducer, reduxStorageImmutableMerger); const storageEngine = filter(createEngine("test"), ['a', 'b'], ['c']); const initialStateLoader = createLoader(storageEngine); const storageMiddleware = createMiddleware(storageEngine, [], []); const store = applyMiddleware(storageMiddleware)(createStore)(enhancedReducer); initialStateLoader(store).then(() => { // render app }) // Test for React Native Async Storage engine const storageEngineReactNative = createReactNativeAsyncStorageEngine("test"); const storageMiddlewareReactNative = createMiddleware(storageEngine); const storeReactNative = applyMiddleware(storageMiddlewareReactNative)(createStore)(enhancedReducer); initialStateLoader(storeReactNative).then(() => { // render app })
types/redux-storage/redux-storage-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.00017304181528743356, 0.00017247020150534809, 0.00017202022718265653, 0.00017240940360352397, 3.667962573672412e-7 ]
{ "id": 1, "code_window": [ "import request = require('request');\n", "import http = require('http');\n", "\n", "declare namespace requestretry {\n", "\ttype RetryStrategy = (err: Error, response: http.IncomingMessage, body: any) => boolean;\n", "\tinterface RetryRequestAPI extends request.RequestAPI<request.Request, RequestRetryOptions, request.RequiredUriUrl> {\n", "\t\tRetryStrategies: {\n", "\t\t\t'HttpError': RetryStrategy;\n", "\t\t\t'HTTPOrNetworkError': RetryStrategy;\n", "\t\t\t'NetworkError': RetryStrategy;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinterface RequestPromise extends request.Request {\n", "\t\tthen: Promise<any>[\"then\"];\n", "\t\tcatch: Promise<any>[\"catch\"];\n", "\t\tpromise(): Promise<any>;\n", "\t}\n", "\tinterface RetryRequestAPI extends request.RequestAPI<RequestPromise, RequestRetryOptions, request.RequiredUriUrl> {\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 14 }
// Type definitions for gulp-shell // Project: https://github.com/sun-zheng-an/gulp-shell // Definitions by: Qubo <https://github.com/tkqubo> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> declare namespace shell { interface Shell { (commands: string | string[], options?: Option): NodeJS.ReadWriteStream; task(commands: string | string[], options?: Option): (done: Function) => NodeJS.ReadWriteStream; } interface Option { /** * You can add a custom error message for when the command fails. This can be a template which can be * interpolated with the current command, some file info (e.g. file.path) and some error info * (e.g. error.code). * @default 'Command `<%= command %>` failed with exit code <%= error.code %>' */ errorMessage?: string; /** * By default, it will emit an error event when the command finishes unsuccessfully. * @default false */ ignoreErrors?: boolean; /** * By default, it will print the command output. * @default false */ quiet?: boolean; /** * Sets the current working directory for the command. * @default process.cwd() */ cwd?: string; /** * The data that can be accessed in template. */ templateData?: any; /** * You won't need to set this option unless you encounter a "stdout maxBuffer exceeded" error. * @default 16MB(16 * 1024 * 1024) */ maxBuffer?: number; /** * The maximum amount of time in milliseconds the process is allowed to run. * @default */ timeout?: number; /** * By default, all the commands will be executed in an environment with all the variables in process.env * and PATH prepended by ./node_modules/.bin (allowing you to run executables in your Node's dependencies). * You can override any environment variables with this option. * For example, setting it to {PATH: process.env.PATH} will reset the PATH * if the default one brings your some troubles. */ env?: any; } } declare var shell: shell.Shell; export = shell;
types/gulp-shell/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.0001756241254042834, 0.00016899325419217348, 0.00016530942230019718, 0.00016902785864658654, 0.0000033527119285281515 ]
{ "id": 1, "code_window": [ "import request = require('request');\n", "import http = require('http');\n", "\n", "declare namespace requestretry {\n", "\ttype RetryStrategy = (err: Error, response: http.IncomingMessage, body: any) => boolean;\n", "\tinterface RetryRequestAPI extends request.RequestAPI<request.Request, RequestRetryOptions, request.RequiredUriUrl> {\n", "\t\tRetryStrategies: {\n", "\t\t\t'HttpError': RetryStrategy;\n", "\t\t\t'HTTPOrNetworkError': RetryStrategy;\n", "\t\t\t'NetworkError': RetryStrategy;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tinterface RequestPromise extends request.Request {\n", "\t\tthen: Promise<any>[\"then\"];\n", "\t\tcatch: Promise<any>[\"catch\"];\n", "\t\tpromise(): Promise<any>;\n", "\t}\n", "\tinterface RetryRequestAPI extends request.RequestAPI<RequestPromise, RequestRetryOptions, request.RequiredUriUrl> {\n" ], "file_path": "types/requestretry/index.d.ts", "type": "replace", "edit_start_line_idx": 14 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "yeoman-environment-tests.ts" ] }
types/yeoman-environment/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.00017170017235912383, 0.00017061678227037191, 0.00016853267152328044, 0.0001716175174806267, 0.0000014740785445610527 ]
{ "id": 2, "code_window": [ "import request = require('requestretry');\n", "import http = require('http');\n", "\n", "// HTTPOrNetworkError strategy.\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Promisified request function\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n", "\tjson: true,\n", "\t// The below parameters are specific to request-retry\n", "\t// (default) try 5 times\n", "\tmaxAttempts: 5,\n", "\t// (default) wait for 5s before trying again\n", "\tretryDelay: 5000,\n", "\t// (default) retry on 5xx or network errors\n", "\tretryStrategy: request.RetryStrategies.HTTPOrNetworkError\n", "}).then(res => {\n", "\t// Body\n", "});\n", "\n" ], "file_path": "types/requestretry/requestretry-tests.ts", "type": "add", "edit_start_line_idx": 3 }
import request = require('requestretry'); import http = require('http'); // HTTPOrNetworkError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.HTTPOrNetworkError }, (err, response, body) => { // Body. }); // HttpError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.HttpError }, (err, response, body) => { // Body. }); // NetworkError strategy. request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: request.RetryStrategies.NetworkError }, (err, response, body) => { // Body. }); // Custom strategy. const CustomRetryStrategy = (err: Error, response: http.IncomingMessage, body: any): boolean => { // Return a boolean return true; }; request({ url: 'https://api.example.com/v1/a/b', json: true, // The below parameters are specific to request-retry // (default) try 5 times maxAttempts: 5, // (default) wait for 5s before trying again retryDelay: 5000, // (default) retry on 5xx or network errors retryStrategy: CustomRetryStrategy }, (err, response, body) => { // Body. }); // No options required request({ url: 'https://api.example.com/v1/a/b', json: true }, (err, response, body) => { // Body. }); // Define options const options: request.RequestRetryOptions = { maxAttempts: 2, promiseFactory: (resolver: any) => { return new Promise(resolver); }, retryDelay: 4, retryStrategy: (err: Error, response: http.IncomingMessage, body: any) => { return true; }, };
types/requestretry/requestretry-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.9982213377952576, 0.3457266390323639, 0.005078521091490984, 0.040901392698287964, 0.4570446312427521 ]
{ "id": 2, "code_window": [ "import request = require('requestretry');\n", "import http = require('http');\n", "\n", "// HTTPOrNetworkError strategy.\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Promisified request function\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n", "\tjson: true,\n", "\t// The below parameters are specific to request-retry\n", "\t// (default) try 5 times\n", "\tmaxAttempts: 5,\n", "\t// (default) wait for 5s before trying again\n", "\tretryDelay: 5000,\n", "\t// (default) retry on 5xx or network errors\n", "\tretryStrategy: request.RetryStrategies.HTTPOrNetworkError\n", "}).then(res => {\n", "\t// Body\n", "});\n", "\n" ], "file_path": "types/requestretry/requestretry-tests.ts", "type": "add", "edit_start_line_idx": 3 }
// Type definitions for ssh2-sftp-client 2.5 // Project: https://github.com/jyu213/ssh2-sftp-client // Definitions by: igrayson <https://github.com/igrayson> // Ascari Andrea <https://github.com/ascariandrea> // Kartik Malik <https://github.com/kartik2406> // Michael Pertl <https://github.com/viamuli> // Orblazer <https://github.com/orblazer> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as ssh2 from 'ssh2'; import * as ssh2Stream from 'ssh2-streams'; export = sftp; declare class sftp { connect(options: ssh2.ConnectConfig): Promise<ssh2.SFTPWrapper>; list(remoteFilePath: string): Promise<sftp.FileInfo[]>; exists(remotePath: string): Promise<boolean>; stat(remotePath: string): Promise<sftp.FileStats>; get(path: string, dst?: string | NodeJS.ReadableStream, options?: boolean): Promise<string | NodeJS.ReadableStream | Buffer>; fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise<string>; put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise<string>; fastPut(localPath: string, remoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise<string>; mkdir(remoteFilePath: string, recursive?: boolean): Promise<string>; rmdir(remoteFilePath: string, recursive?: boolean): Promise<string>; delete(remoteFilePath: string): Promise<string>; rename(remoteSourcePath: string, remoteDestPath: string): Promise<string>; chmod(remotePath: string, mode: number | string): Promise<string>; append(input: Buffer | NodeJS.ReadableStream, remotePath: string, options?: ssh2Stream.TransferOptions): Promise<string>; end(): Promise<void>; on(event: string, callback: (...args: any[]) => void): void; } declare namespace sftp { interface FileInfo { type: string; name: string; size: number; modifyTime: number; accessTime: number; rights: { user: string; group: string; other: string; }; owner: number; group: number; } interface FileStats { mode: number; permissions?: any; owner: number; group: number; size: number; accessTime: number; modifyTime: number; } }
types/ssh2-sftp-client/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.0001727488706819713, 0.00017054170893970877, 0.00016797965508885682, 0.00017068340093828738, 0.0000015622192677255953 ]
{ "id": 2, "code_window": [ "import request = require('requestretry');\n", "import http = require('http');\n", "\n", "// HTTPOrNetworkError strategy.\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Promisified request function\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n", "\tjson: true,\n", "\t// The below parameters are specific to request-retry\n", "\t// (default) try 5 times\n", "\tmaxAttempts: 5,\n", "\t// (default) wait for 5s before trying again\n", "\tretryDelay: 5000,\n", "\t// (default) retry on 5xx or network errors\n", "\tretryStrategy: request.RetryStrategies.HTTPOrNetworkError\n", "}).then(res => {\n", "\t// Body\n", "});\n", "\n" ], "file_path": "types/requestretry/requestretry-tests.ts", "type": "add", "edit_start_line_idx": 3 }
// Type definitions for passport-remember-me-extended 0.0 // Project: https://github.com/dereklakin/passport-remember-me // Definitions by: AylaJK <https://github.com/AylaJK> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import passport = require('passport'); import express = require('express'); export interface StrategyOption { key?: string; cookie?: express.CookieOptions; } export interface StrategyOptionWithRequest extends StrategyOption { passReqToCallback: true; } export type VerifyFunction = (token: any, done: (err: any, user?: any, info?: any) => void) => void; export type VerifyFunctionWithRequest = (req: express.Request, token: any, done: (err: any, user?: any, info?: any) => void) => void; export type IssueFunction = (user: any, done: (err: any, token?: any) => void) => void; export type IssueFunctionWithRequest = (req: express.Request, user: any, done: (err: any, token?: any) => void) => void; export class Strategy extends passport.Strategy { constructor(verify: VerifyFunction, issue: IssueFunction); constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest, issue: IssueFunctionWithRequest); constructor(options: StrategyOption, verify: VerifyFunction, issue: IssueFunction); authenticate(req: express.Request, options?: passport.AuthenticateOptions): void; }
types/passport-remember-me-extended/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.00042381868115626276, 0.0002410158485872671, 0.0001662320428295061, 0.00018700631335377693, 0.0001068211131496355 ]
{ "id": 2, "code_window": [ "import request = require('requestretry');\n", "import http = require('http');\n", "\n", "// HTTPOrNetworkError strategy.\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// Promisified request function\n", "request({\n", "\turl: 'https://api.example.com/v1/a/b',\n", "\tjson: true,\n", "\t// The below parameters are specific to request-retry\n", "\t// (default) try 5 times\n", "\tmaxAttempts: 5,\n", "\t// (default) wait for 5s before trying again\n", "\tretryDelay: 5000,\n", "\t// (default) retry on 5xx or network errors\n", "\tretryStrategy: request.RetryStrategies.HTTPOrNetworkError\n", "}).then(res => {\n", "\t// Body\n", "});\n", "\n" ], "file_path": "types/requestretry/requestretry-tests.ts", "type": "add", "edit_start_line_idx": 3 }
{ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, "array-type": false, "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, "comment-format": false, "dt-header": false, "npm-naming": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, "no-duplicate-variable": false, "no-empty-interface": false, "no-for-in-array": false, "no-inferrable-types": false, "no-internal-module": false, "no-irregular-whitespace": false, "no-mergeable-namespace": false, "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, "no-reference-import": false, "no-relative-import-in-test": false, "no-self-import": false, "no-single-declare-module": false, "no-string-throw": false, "no-unnecessary-callback-wrapper": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-useless-files": false, "no-var-keyword": false, "no-var-requires": false, "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, "only-arrow-functions": false, "prefer-conditional-expression": false, "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, "prefer-template": false, "radix": false, "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, "trim-file": false, "triple-equals": false, "typedef-whitespace": false, "unified-signatures": false, "void-return": false, "whitespace": false } }
types/event-loop-lag/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/27d37c0d0eafa95e49fc8beca44cde0ab46a3b74
[ 0.0001717211416689679, 0.00016930491256061941, 0.0001674519298831001, 0.00016914878506213427, 0.0000014921428146408289 ]
{ "id": 0, "code_window": [ "\n", " if (contextOptions.isMobile && browserType.name() === 'firefox')\n", " contextOptions.isMobile = undefined;\n", "\n", " // Proxy\n", "\n", " if (options.proxyServer) {\n", " launchOptions.proxy = {\n", " server: options.proxyServer\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 242 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './inspectorTest'; import * as url from 'url'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test('should contain open page', async ({ openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); const sources = await recorder.waitForOutput('<javascript>', `page.goto`); expect(sources.get('<javascript>').text).toContain(` // Open new page const page = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page = await context.NewPageAsync();`); }); test('should contain second page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); const sources = await recorder.waitForOutput('<javascript>', 'page1'); expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page1 = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page1 = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync();`); }); test('should contain close page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); await recorder.page.close(); const sources = await recorder.waitForOutput('<javascript>', 'page.close();'); expect(sources.get('<javascript>').text).toContain(` await page.close();`); expect(sources.get('<java>').text).toContain(` page.close();`); expect(sources.get('<python>').text).toContain(` page.close()`); expect(sources.get('<async python>').text).toContain(` await page.close()`); expect(sources.get('<csharp>').text).toContain(` await page.CloseAsync();`); }); test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(''); await page.context().newPage(); const errors: any[] = []; recorder.page.on('pageerror', e => errors.push(e)); await recorder.page.evaluate(() => document.querySelector('body').remove()); const selector = await recorder.hoverOverElement('html'); expect(selector).toBe('html'); await recorder.page.close(); await recorder.waitForOutput('<javascript>', 'page.close();'); expect(errors.length).toBe(0); }); test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file"> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`); }); test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`); }); test('should clear files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.setInputFiles('input[type=file]', []); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Clear selected files await page.setInputFiles('input[type=\"file\"]', []);`); expect(sources.get('<java>').text).toContain(` // Clear selected files page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`); expect(sources.get('<python>').text).toContain(` # Clear selected files page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<async python>').text).toContain(` # Clear selected files await page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<csharp>').text).toContain(` // Clear selected files await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`); }); test('should download files', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/download', (req, res) => { const pathName = url.parse(req.url!).path; if (pathName === '/download') { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment; filename=file.txt'); res.end(`Hello world`); } else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); } }); await recorder.setContentAndWait(` <a href="${server.PREFIX}/download" download>Download</a> `, server.PREFIX); await recorder.hoverOverElement('text=Download'); await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]); const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent'); expect(sources.get('<javascript>').text).toContain(` // Click text=Download const [download] = await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]);`); expect(sources.get('<java>').text).toContain(` // Click text=Download Download download = page.waitForDownload(() -> { page.click("text=Download"); });`); expect(sources.get('<python>').text).toContain(` # Click text=Download with page.expect_download() as download_info: page.click(\"text=Download\") download = download_info.value`); expect(sources.get('<async python>').text).toContain(` # Click text=Download async with page.expect_download() as download_info: await page.click(\"text=Download\") download = await download_info.value`); expect(sources.get('<csharp>').text).toContain(` // Click text=Download var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () => { await page.ClickAsync(\"text=Download\"); });`); }); test('should handle dialogs', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button onclick="alert()">click me</button> `); await recorder.hoverOverElement('button'); page.once('dialog', async dialog => { await dialog.dismiss(); }); await page.click('text=click me'); const sources = await recorder.waitForOutput('<javascript>', 'once'); expect(sources.get('<javascript>').text).toContain(` // Click text=click me page.once('dialog', dialog => { console.log(\`Dialog message: \${dialog.message()}\`); dialog.dismiss().catch(() => {}); }); await page.click('text=click me');`); expect(sources.get('<java>').text).toContain(` // Click text=click me page.onceDialog(dialog -> { System.out.println(String.format("Dialog message: %s", dialog.message())); dialog.dismiss(); }); page.click("text=click me");`); expect(sources.get('<python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) page.click(\"text=click me\")`); expect(sources.get('<async python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) await page.click(\"text=click me\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=click me void page_Dialog1_EventHandler(object sender, IDialog dialog) { Console.WriteLine($\"Dialog message: {dialog.Message}\"); dialog.DismissAsync(); page.Dialog -= page_Dialog1_EventHandler; } page.Dialog += page_Dialog1_EventHandler; await page.ClickAsync(\"text=click me\");`); }); test('should handle history.postData', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> let seqNum = 0; function pushState() { history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum)); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) { await page.evaluate('pushState()'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`); } }); test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => { test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] }); const sources = await recorder.waitForOutput('<javascript>', 'page1'); if (browserName === 'chromium') { expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage(); await page1.goto('about:blank?foo');`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page() await page1.goto("about:blank?foo")`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync(); await page1.GotoAsync("about:blank?foo");`); } else if (browserName === 'firefox') { expect(sources.get('<javascript>').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link', { modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}'] }) ]);`); } }); test('should not clash pages', async ({ page, openRecorder, browserName }) => { test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue'); const recorder = await openRecorder(); const [popup1] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup1, '<input id=name>'); const [popup2] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup2, '<input id=name>'); await popup1.type('input', 'TextA'); await recorder.waitForOutput('<javascript>', 'TextA'); await popup2.type('input', 'TextB'); await recorder.waitForOutput('<javascript>', 'TextB'); const sources = recorder.sources(); expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`); expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`); expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`); expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`); expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`); expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`); expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`); expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`); expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`); expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`); }); test('click should emit events in order', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button id=button> <script> button.addEventListener('mousedown', e => console.log(e.type)); button.addEventListener('mouseup', e => console.log(e.type)); button.addEventListener('click', e => console.log(e.type)); </script> `); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message.text()); }); await Promise.all([ page.click('button'), recorder.waitForOutput('<javascript>', 'page.click') ]); expect(messages).toEqual(['mousedown', 'mouseup', 'click']); }); test('should update hover model on action', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.hovered).toBe('input[name="updated"]'); }); test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && headless); test.fixme(browserName === 'firefox' && headless); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.active).toBe('input[name="updated"]'); }); test('should check input with chaning id', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`); await Promise.all([ recorder.waitForActionPerformed(), page.click('input[id=checkbox]') ]); }); test('should prefer frame name', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <iframe src='./frames/frame.html' name='one'></iframe> <iframe src='./frames/frame.html' name='two'></iframe> <iframe src='./frames/frame.html'></iframe> `, server.EMPTY_PAGE, 4); const frameOne = page.frame({ name: 'one' }); const frameTwo = page.frame({ name: 'two' }); const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name()); let [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'one'), frameOne.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'one' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("one").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'two'), frameTwo.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'two' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("two").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'url: \''), otherFrame.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ url: 'http://localhost:${server.PORT}/frames/frame.html' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`); }); test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/page2.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('Hello world'); }); await recorder.setContentAndWait(` <script> function pushState() { history.pushState({}, 'title', '${server.PREFIX}'); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) await page.evaluate('pushState()'); await page.goto(server.PREFIX + '/page2.html'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`); }); test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> async function onClick() { await new Promise(f => setTimeout(f, 100)); await window.letTheMouseMove(); window.location = ${JSON.stringify(server.EMPTY_PAGE)}; } </script> <button onclick="onClick()">Click me</button> `); await page.exposeBinding('letTheMouseMove', async () => { await page.mouse.move(200, 200); }); const [, sources] = await Promise.all([ // This will click, finish the click, then mouse move, then navigate. page.click('button'), recorder.waitForOutput('<javascript>', 'waitForNavigation'), ]); expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`); }); });
tests/inspector/cli-codegen-2.spec.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0009747610311023891, 0.00018738543440122157, 0.00016397393483202904, 0.0001762464817147702, 0.00010013747669290751 ]
{ "id": 0, "code_window": [ "\n", " if (contextOptions.isMobile && browserType.name() === 'firefox')\n", " contextOptions.isMobile = undefined;\n", "\n", " // Proxy\n", "\n", " if (options.proxyServer) {\n", " launchOptions.proxy = {\n", " server: options.proxyServer\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 242 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export function applyTheme() { if ((document as any).playwrightThemeInitialized) return; (document as any).playwrightThemeInitialized = true; document!.defaultView!.addEventListener('focus', (event: any) => { if (event.target.document.nodeType === Node.DOCUMENT_NODE) document.body.classList.remove('inactive'); }, false); document!.defaultView!.addEventListener('blur', event => { document.body.classList.add('inactive'); }, false); }
src/web/theme.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017897351062856615, 0.00017674628179520369, 0.00017472483159508556, 0.00017654048861004412, 0.0000017406090364602278 ]
{ "id": 0, "code_window": [ "\n", " if (contextOptions.isMobile && browserType.name() === 'firefox')\n", " contextOptions.isMobile = undefined;\n", "\n", " // Proxy\n", "\n", " if (options.proxyServer) {\n", " launchOptions.proxy = {\n", " server: options.proxyServer\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 242 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; it('should work with css selector', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('css=section', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with id selector', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('id=testAttribute', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with data-test selector', async ({page, server}) => { await page.setContent('<section data-test=foo id="testAttribute">43543</section>'); const idAttribute = await page.$eval('data-test=foo', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with data-testid selector', async ({page, server}) => { await page.setContent('<section data-testid=foo id="testAttribute">43543</section>'); const idAttribute = await page.$eval('data-testid=foo', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with data-test-id selector', async ({page, server}) => { await page.setContent('<section data-test-id=foo id="testAttribute">43543</section>'); const idAttribute = await page.$eval('data-test-id=foo', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with text selector', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('text="43543"', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with xpath selector', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('xpath=/html/body/section', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should work with text selector', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('text=43543', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should auto-detect css selector', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('section', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should auto-detect css selector with attributes', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('section[id="testAttribute"]', e => e.id); expect(idAttribute).toBe('testAttribute'); }); it('should auto-detect nested selectors', async ({page, server}) => { await page.setContent('<div foo=bar><section>43543<span>Hello<div id=target></div></span></section></div>'); const idAttribute = await page.$eval('div[foo=bar] > section >> "Hello" >> div', e => e.id); expect(idAttribute).toBe('target'); }); it('should accept arguments', async ({page, server}) => { await page.setContent('<section>hello</section>'); const text = await page.$eval('section', (e, suffix) => e.textContent + suffix, ' world!'); expect(text).toBe('hello world!'); }); it('should accept ElementHandles as arguments', async ({page, server}) => { await page.setContent('<section>hello</section><div> world</div>'); const divHandle = await page.$('div'); const text = await page.$eval('section', (e, div) => e.textContent + div.textContent, divHandle); expect(text).toBe('hello world'); }); it('should throw error if no element is found', async ({page, server}) => { let error = null; await page.$eval('section', e => e.id).catch(e => error = e); expect(error.message).toContain('failed to find element matching selector "section"'); }); it('should support >> syntax', async ({page, server}) => { await page.setContent('<section><div>hello</div></section>'); const text = await page.$eval('css=section >> css=div', (e, suffix) => e.textContent + suffix, ' world!'); expect(text).toBe('hello world!'); }); it('should support >> syntax with different engines', async ({page, server}) => { await page.setContent('<section><div><span>hello</span></div></section>'); const text = await page.$eval('xpath=/html/body/section >> css=div >> text="hello"', (e, suffix) => e.textContent + suffix, ' world!'); expect(text).toBe('hello world!'); }); it('should support spaces with >> syntax', async ({page, server}) => { await page.goto(server.PREFIX + '/deep-shadow.html'); const text = await page.$eval(' css = div >>css=div>>css = span ', e => e.textContent); expect(text).toBe('Hello from root2'); }); it('should not stop at first failure with >> syntax', async ({page, server}) => { await page.setContent('<div><span>Next</span><button>Previous</button><button>Next</button></div>'); const html = await page.$eval('button >> "Next"', e => e.outerHTML); expect(html).toBe('<button>Next</button>'); }); it('should support * capture', async ({page, server}) => { await page.setContent('<section><div><span>a</span></div></section><section><div><span>b</span></div></section>'); expect(await page.$eval('*css=div >> "b"', e => e.outerHTML)).toBe('<div><span>b</span></div>'); expect(await page.$eval('section >> *css=div >> "b"', e => e.outerHTML)).toBe('<div><span>b</span></div>'); expect(await page.$eval('css=div >> *text="b"', e => e.outerHTML)).toBe('<span>b</span>'); expect(await page.$('*')).toBeTruthy(); }); it('should throw on multiple * captures', async ({page, server}) => { const error = await page.$eval('*css=div >> *css=span', e => e.outerHTML).catch(e => e); expect(error.message).toContain('Only one of the selectors can capture using * modifier'); }); it('should throw on malformed * capture', async ({page, server}) => { const error = await page.$eval('*=div', e => e.outerHTML).catch(e => e); expect(error.message).toContain('Unknown engine "" while parsing selector *=div'); }); it('should work with spaces in css attributes', async ({page, server}) => { await page.setContent('<div><input placeholder="Select date"></div>'); expect(await page.waitForSelector(`[placeholder="Select date"]`)).toBeTruthy(); expect(await page.waitForSelector(`[placeholder='Select date']`)).toBeTruthy(); expect(await page.waitForSelector(`input[placeholder="Select date"]`)).toBeTruthy(); expect(await page.waitForSelector(`input[placeholder='Select date']`)).toBeTruthy(); expect(await page.$(`[placeholder="Select date"]`)).toBeTruthy(); expect(await page.$(`[placeholder='Select date']`)).toBeTruthy(); expect(await page.$(`input[placeholder="Select date"]`)).toBeTruthy(); expect(await page.$(`input[placeholder='Select date']`)).toBeTruthy(); expect(await page.$eval(`[placeholder="Select date"]`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`[placeholder='Select date']`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`input[placeholder="Select date"]`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`input[placeholder='Select date']`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`css=[placeholder="Select date"]`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`css=[placeholder='Select date']`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`css=input[placeholder="Select date"]`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`css=input[placeholder='Select date']`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`div >> [placeholder="Select date"]`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); expect(await page.$eval(`div >> [placeholder='Select date']`, e => e.outerHTML)).toBe('<input placeholder="Select date">'); }); it('should work with quotes in css attributes', async ({page, server}) => { await page.setContent('<div><input placeholder="Select&quot;date"></div>'); expect(await page.$(`[placeholder="Select\\"date"]`)).toBeTruthy(); expect(await page.$(`[placeholder='Select"date']`)).toBeTruthy(); await page.setContent('<div><input placeholder="Select &quot; date"></div>'); expect(await page.$(`[placeholder="Select \\" date"]`)).toBeTruthy(); expect(await page.$(`[placeholder='Select " date']`)).toBeTruthy(); await page.setContent('<div><input placeholder="Select&apos;date"></div>'); expect(await page.$(`[placeholder="Select'date"]`)).toBeTruthy(); expect(await page.$(`[placeholder='Select\\'date']`)).toBeTruthy(); await page.setContent('<div><input placeholder="Select &apos; date"></div>'); expect(await page.$(`[placeholder="Select ' date"]`)).toBeTruthy(); expect(await page.$(`[placeholder='Select \\' date']`)).toBeTruthy(); }); it('should work with spaces in css attributes when missing', async ({page, server}) => { const inputPromise = page.waitForSelector(`[placeholder="Select date"]`); expect(await page.$(`[placeholder="Select date"]`)).toBe(null); await page.setContent('<div><input placeholder="Select date"></div>'); await inputPromise; }); it('should work with quotes in css attributes when missing', async ({page, server}) => { const inputPromise = page.waitForSelector(`[placeholder="Select\\"date"]`); expect(await page.$(`[placeholder="Select\\"date"]`)).toBe(null); await page.setContent('<div><input placeholder="Select&quot;date"></div>'); await inputPromise; }); it('should return complex values', async ({page, server}) => { await page.setContent('<section id="testAttribute">43543</section>'); const idAttribute = await page.$eval('css=section', e => [{ id: e.id }]); expect(idAttribute).toEqual([{ id: 'testAttribute' }]); });
tests/page/eval-on-selector.spec.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017699808813631535, 0.000172088184626773, 0.00016468734247609973, 0.00017208419740200043, 0.0000034282825254194904 ]
{ "id": 0, "code_window": [ "\n", " if (contextOptions.isMobile && browserType.name() === 'firefox')\n", " contextOptions.isMobile = undefined;\n", "\n", " // Proxy\n", "\n", " if (options.proxyServer) {\n", " launchOptions.proxy = {\n", " server: options.proxyServer\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 242 }
// Copyright (C) 2010-2017 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include? "../../../../Internal/Configurations/HaveInternalSDK.xcconfig" #include "SDKVariant.xcconfig" USE_INTERNAL_SDK = $(USE_INTERNAL_SDK_$(CONFIGURATION)); USE_INTERNAL_SDK_Production = YES; USE_INTERNAL_SDK_Debug = $(HAVE_INTERNAL_SDK); USE_INTERNAL_SDK_Release = $(HAVE_INTERNAL_SDK); GCC_PREPROCESSOR_DEFINITIONS = DISABLE_LEGACY_WEBKIT_DEPRECATIONS $(inherited); CLANG_CXX_LANGUAGE_STANDARD = gnu++1z; CLANG_CXX_LIBRARY = libc++; CLANG_ENABLE_OBJC_WEAK = YES; DEBUG_INFORMATION_FORMAT = dwarf-with-dsym; PREBINDING = NO GCC_C_LANGUAGE_STANDARD = gnu99 GCC_ENABLE_CPP_EXCEPTIONS = NO; GCC_PRECOMPILE_PREFIX_HEADER = YES ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_TREAT_WARNINGS_AS_ERRORS = YES CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_UNREACHABLE_CODE = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES GCC_WARN_UNUSED_VARIABLE = YES CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; WARNING_CFLAGS = -Wall -W -Wno-unused-parameter GCC_NO_COMMON_BLOCKS = YES; SUPPORTED_PLATFORMS = iphoneos iphonesimulator macosx tvos tvsimulator watchos watchsimulator; TARGET_MAC_OS_X_VERSION_MAJOR = $(TARGET_MAC_OS_X_VERSION_MAJOR$(MACOSX_DEPLOYMENT_TARGET:suffix:identifier)); TARGET_MAC_OS_X_VERSION_MAJOR_13 = 101300; TARGET_MAC_OS_X_VERSION_MAJOR_14 = 101400; TARGET_MAC_OS_X_VERSION_MAJOR_15 = 101500; TARGET_MAC_OS_X_VERSION_MAJOR_16 = 101600; SDKROOT = macosx.internal; OTHER_CFLAGS = $(ASAN_OTHER_CFLAGS); OTHER_CPLUSPLUSFLAGS = $(ASAN_OTHER_CPLUSPLUSFLAGS); OTHER_LDFLAGS = $(ASAN_OTHER_LDFLAGS); CODE_SIGN_IDENTITY = -;
browser_patches/webkit/embedder/Playwright/Configurations/Base.xcconfig
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0004687834298238158, 0.00026620610151439905, 0.0001713037781883031, 0.00021655435557477176, 0.00011112589709227905 ]
{ "id": 1, "code_window": [ " context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));\n", " }\n", "\n", " // Omit options that we add automatically for presentation purpose.\n", " delete launchOptions.headless;\n", " delete contextOptions.deviceScaleFactor;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " delete launchOptions.executablePath;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 337 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './inspectorTest'; import * as url from 'url'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test('should contain open page', async ({ openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); const sources = await recorder.waitForOutput('<javascript>', `page.goto`); expect(sources.get('<javascript>').text).toContain(` // Open new page const page = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page = await context.NewPageAsync();`); }); test('should contain second page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); const sources = await recorder.waitForOutput('<javascript>', 'page1'); expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page1 = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page1 = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync();`); }); test('should contain close page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); await recorder.page.close(); const sources = await recorder.waitForOutput('<javascript>', 'page.close();'); expect(sources.get('<javascript>').text).toContain(` await page.close();`); expect(sources.get('<java>').text).toContain(` page.close();`); expect(sources.get('<python>').text).toContain(` page.close()`); expect(sources.get('<async python>').text).toContain(` await page.close()`); expect(sources.get('<csharp>').text).toContain(` await page.CloseAsync();`); }); test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(''); await page.context().newPage(); const errors: any[] = []; recorder.page.on('pageerror', e => errors.push(e)); await recorder.page.evaluate(() => document.querySelector('body').remove()); const selector = await recorder.hoverOverElement('html'); expect(selector).toBe('html'); await recorder.page.close(); await recorder.waitForOutput('<javascript>', 'page.close();'); expect(errors.length).toBe(0); }); test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file"> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`); }); test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`); }); test('should clear files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.setInputFiles('input[type=file]', []); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Clear selected files await page.setInputFiles('input[type=\"file\"]', []);`); expect(sources.get('<java>').text).toContain(` // Clear selected files page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`); expect(sources.get('<python>').text).toContain(` # Clear selected files page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<async python>').text).toContain(` # Clear selected files await page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<csharp>').text).toContain(` // Clear selected files await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`); }); test('should download files', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/download', (req, res) => { const pathName = url.parse(req.url!).path; if (pathName === '/download') { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment; filename=file.txt'); res.end(`Hello world`); } else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); } }); await recorder.setContentAndWait(` <a href="${server.PREFIX}/download" download>Download</a> `, server.PREFIX); await recorder.hoverOverElement('text=Download'); await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]); const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent'); expect(sources.get('<javascript>').text).toContain(` // Click text=Download const [download] = await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]);`); expect(sources.get('<java>').text).toContain(` // Click text=Download Download download = page.waitForDownload(() -> { page.click("text=Download"); });`); expect(sources.get('<python>').text).toContain(` # Click text=Download with page.expect_download() as download_info: page.click(\"text=Download\") download = download_info.value`); expect(sources.get('<async python>').text).toContain(` # Click text=Download async with page.expect_download() as download_info: await page.click(\"text=Download\") download = await download_info.value`); expect(sources.get('<csharp>').text).toContain(` // Click text=Download var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () => { await page.ClickAsync(\"text=Download\"); });`); }); test('should handle dialogs', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button onclick="alert()">click me</button> `); await recorder.hoverOverElement('button'); page.once('dialog', async dialog => { await dialog.dismiss(); }); await page.click('text=click me'); const sources = await recorder.waitForOutput('<javascript>', 'once'); expect(sources.get('<javascript>').text).toContain(` // Click text=click me page.once('dialog', dialog => { console.log(\`Dialog message: \${dialog.message()}\`); dialog.dismiss().catch(() => {}); }); await page.click('text=click me');`); expect(sources.get('<java>').text).toContain(` // Click text=click me page.onceDialog(dialog -> { System.out.println(String.format("Dialog message: %s", dialog.message())); dialog.dismiss(); }); page.click("text=click me");`); expect(sources.get('<python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) page.click(\"text=click me\")`); expect(sources.get('<async python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) await page.click(\"text=click me\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=click me void page_Dialog1_EventHandler(object sender, IDialog dialog) { Console.WriteLine($\"Dialog message: {dialog.Message}\"); dialog.DismissAsync(); page.Dialog -= page_Dialog1_EventHandler; } page.Dialog += page_Dialog1_EventHandler; await page.ClickAsync(\"text=click me\");`); }); test('should handle history.postData', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> let seqNum = 0; function pushState() { history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum)); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) { await page.evaluate('pushState()'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`); } }); test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => { test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] }); const sources = await recorder.waitForOutput('<javascript>', 'page1'); if (browserName === 'chromium') { expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage(); await page1.goto('about:blank?foo');`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page() await page1.goto("about:blank?foo")`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync(); await page1.GotoAsync("about:blank?foo");`); } else if (browserName === 'firefox') { expect(sources.get('<javascript>').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link', { modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}'] }) ]);`); } }); test('should not clash pages', async ({ page, openRecorder, browserName }) => { test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue'); const recorder = await openRecorder(); const [popup1] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup1, '<input id=name>'); const [popup2] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup2, '<input id=name>'); await popup1.type('input', 'TextA'); await recorder.waitForOutput('<javascript>', 'TextA'); await popup2.type('input', 'TextB'); await recorder.waitForOutput('<javascript>', 'TextB'); const sources = recorder.sources(); expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`); expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`); expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`); expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`); expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`); expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`); expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`); expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`); expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`); expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`); }); test('click should emit events in order', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button id=button> <script> button.addEventListener('mousedown', e => console.log(e.type)); button.addEventListener('mouseup', e => console.log(e.type)); button.addEventListener('click', e => console.log(e.type)); </script> `); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message.text()); }); await Promise.all([ page.click('button'), recorder.waitForOutput('<javascript>', 'page.click') ]); expect(messages).toEqual(['mousedown', 'mouseup', 'click']); }); test('should update hover model on action', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.hovered).toBe('input[name="updated"]'); }); test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && headless); test.fixme(browserName === 'firefox' && headless); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.active).toBe('input[name="updated"]'); }); test('should check input with chaning id', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`); await Promise.all([ recorder.waitForActionPerformed(), page.click('input[id=checkbox]') ]); }); test('should prefer frame name', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <iframe src='./frames/frame.html' name='one'></iframe> <iframe src='./frames/frame.html' name='two'></iframe> <iframe src='./frames/frame.html'></iframe> `, server.EMPTY_PAGE, 4); const frameOne = page.frame({ name: 'one' }); const frameTwo = page.frame({ name: 'two' }); const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name()); let [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'one'), frameOne.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'one' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("one").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'two'), frameTwo.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'two' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("two").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'url: \''), otherFrame.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ url: 'http://localhost:${server.PORT}/frames/frame.html' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`); }); test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/page2.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('Hello world'); }); await recorder.setContentAndWait(` <script> function pushState() { history.pushState({}, 'title', '${server.PREFIX}'); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) await page.evaluate('pushState()'); await page.goto(server.PREFIX + '/page2.html'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`); }); test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> async function onClick() { await new Promise(f => setTimeout(f, 100)); await window.letTheMouseMove(); window.location = ${JSON.stringify(server.EMPTY_PAGE)}; } </script> <button onclick="onClick()">Click me</button> `); await page.exposeBinding('letTheMouseMove', async () => { await page.mouse.move(200, 200); }); const [, sources] = await Promise.all([ // This will click, finish the click, then mouse move, then navigate. page.click('button'), recorder.waitForOutput('<javascript>', 'waitForNavigation'), ]); expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`); }); });
tests/inspector/cli-codegen-2.spec.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.000182997333467938, 0.000173547028680332, 0.00016485340893268585, 0.00017374116578139365, 0.000003423899897825322 ]
{ "id": 1, "code_window": [ " context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));\n", " }\n", "\n", " // Omit options that we add automatically for presentation purpose.\n", " delete launchOptions.headless;\n", " delete contextOptions.deviceScaleFactor;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " delete launchOptions.executablePath;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 337 }
/* Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ .tabbed-pane { display: flex; flex: auto; overflow: hidden; } .tab-content { display: flex; flex: auto; overflow: hidden; } .tab-strip { color: var(--toolbar-color); display: flex; box-shadow: var(--box-shadow); background-color: var(--toolbar-bg-color); height: 32px; align-items: center; padding-right: 10px; flex: none; width: 100%; z-index: 2; } .tab-strip:focus { outline: none; } .tab-element { padding: 2px 6px 0 6px; margin-right: 4px; cursor: pointer; display: flex; flex: none; align-items: center; justify-content: center; user-select: none; border-bottom: 3px solid transparent; width: 80px; outline: none; height: 100%; } .tab-label { max-width: 250px; white-space: pre; overflow: hidden; text-overflow: ellipsis; display: inline-block; } .tab-element.selected { border-bottom-color: #666; } .tab-element:hover { color: #333; }
src/web/traceViewer/ui/tabbedPane.css
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.000176854882738553, 0.00017419259529560804, 0.0001701390719972551, 0.0001742476160870865, 0.000002122729028997128 ]
{ "id": 1, "code_window": [ " context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));\n", " }\n", "\n", " // Omit options that we add automatically for presentation purpose.\n", " delete launchOptions.headless;\n", " delete contextOptions.deviceScaleFactor;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " delete launchOptions.executablePath;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 337 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as input from '../input'; import * as types from '../types'; import { CRSession } from './crConnection'; import { macEditingCommands } from '../macEditingCommands'; import { isString } from '../../utils/utils'; function toModifiersMask(modifiers: Set<types.KeyboardModifier>): number { let mask = 0; if (modifiers.has('Alt')) mask |= 1; if (modifiers.has('Control')) mask |= 2; if (modifiers.has('Meta')) mask |= 4; if (modifiers.has('Shift')) mask |= 8; return mask; } export class RawKeyboardImpl implements input.RawKeyboard { constructor( private _client: CRSession, private _isMac: boolean, ) { } _commandsForCode(code: string, modifiers: Set<types.KeyboardModifier>) { if (!this._isMac) return []; const parts = []; for (const modifier of (['Shift', 'Control', 'Alt', 'Meta']) as types.KeyboardModifier[]) { if (modifiers.has(modifier)) parts.push(modifier); } parts.push(code); const shortcut = parts.join('+'); let commands = macEditingCommands[shortcut] || []; if (isString(commands)) commands = [commands]; // Commands that insert text are not supported commands = commands.filter(x => !x.startsWith('insert')); // remove the trailing : to match the Chromium command names. return commands.map(c => c.substring(0, c.length - 1)); } async keydown(modifiers: Set<types.KeyboardModifier>, code: string, keyCode: number, keyCodeWithoutLocation: number, key: string, location: number, autoRepeat: boolean, text: string | undefined): Promise<void> { const commands = this._commandsForCode(code, modifiers); await this._client.send('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', modifiers: toModifiersMask(modifiers), windowsVirtualKeyCode: keyCodeWithoutLocation, code, commands, key, text, unmodifiedText: text, autoRepeat, location, isKeypad: location === input.keypadLocation }); } async keyup(modifiers: Set<types.KeyboardModifier>, code: string, keyCode: number, keyCodeWithoutLocation: number, key: string, location: number): Promise<void> { await this._client.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: toModifiersMask(modifiers), key, windowsVirtualKeyCode: keyCodeWithoutLocation, code, location }); } async sendText(text: string): Promise<void> { await this._client.send('Input.insertText', { text }); } } export class RawMouseImpl implements input.RawMouse { private _client: CRSession; constructor(client: CRSession) { this._client = client; } async move(x: number, y: number, button: types.MouseButton | 'none', buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>): Promise<void> { await this._client.send('Input.dispatchMouseEvent', { type: 'mouseMoved', button, x, y, modifiers: toModifiersMask(modifiers) }); } async down(x: number, y: number, button: types.MouseButton, buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, clickCount: number): Promise<void> { await this._client.send('Input.dispatchMouseEvent', { type: 'mousePressed', button, x, y, modifiers: toModifiersMask(modifiers), clickCount }); } async up(x: number, y: number, button: types.MouseButton, buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, clickCount: number): Promise<void> { await this._client.send('Input.dispatchMouseEvent', { type: 'mouseReleased', button, x, y, modifiers: toModifiersMask(modifiers), clickCount }); } } export class RawTouchscreenImpl implements input.RawTouchscreen { private _client: CRSession; constructor(client: CRSession) { this._client = client; } async tap(x: number, y: number, modifiers: Set<types.KeyboardModifier>) { await Promise.all([ this._client.send('Input.dispatchTouchEvent', { type: 'touchStart', modifiers: toModifiersMask(modifiers), touchPoints: [{ x, y }] }), this._client.send('Input.dispatchTouchEvent', { type: 'touchEnd', modifiers: toModifiersMask(modifiers), touchPoints: [] }), ]); } }
src/server/chromium/crInput.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017713182023726404, 0.00017324982036370784, 0.00016842519107740372, 0.00017349534027744085, 0.0000022624451503361342 ]
{ "id": 1, "code_window": [ " context.setDefaultNavigationTimeout(parseInt(options.timeout, 10));\n", " }\n", "\n", " // Omit options that we add automatically for presentation purpose.\n", " delete launchOptions.headless;\n", " delete contextOptions.deviceScaleFactor;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " delete launchOptions.executablePath;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 337 }
// Copyright (C) 2019 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. WK_EMPTY_ = YES; WK_NOT_ = YES; WK_NOT_YES = NO; WK_ALTERNATE_FRAMEWORKS_DIR = $(WK_ALTERNATE_FRAMEWORKS_DIR_$(SDK_VARIANT)); WK_ALTERNATE_FRAMEWORKS_DIR_iosmac = /System/iOSSupport; WK_USE_ALTERNATE_FRAMEWORKS_DIR = $(WK_NOT_$(WK_EMPTY_$(WK_ALTERNATE_FRAMEWORKS_DIR))); WK_ALTERNATE_PLATFORM_NAME = $(WK_ALTERNATE_PLATFORM_NAME_$(SDK_VARIANT)); WK_ALTERNATE_PLATFORM_NAME_iosmac = maccatalyst; WK_USE_ALTERNATE_PLATFORM_NAME = $(WK_NOT_$(WK_EMPTY_$(WK_ALTERNATE_PLATFORM_NAME))); WK_ALTERNATE_WEBKIT_SDK_PATH = $(WK_ALTERNATE_WEBKIT_SDK_PATH_$(WK_USE_ALTERNATE_FRAMEWORKS_DIR)); WK_ALTERNATE_WEBKIT_SDK_PATH_YES = $(WK_ALTERNATE_FRAMEWORKS_DIR)/; WK_PLATFORM_NAME = $(WK_PLATFORM_NAME_ALTERNATE_$(WK_USE_ALTERNATE_PLATFORM_NAME)); WK_PLATFORM_NAME_ALTERNATE_YES = $(WK_ALTERNATE_PLATFORM_NAME); WK_PLATFORM_NAME_ALTERNATE_NO = $(PLATFORM_NAME); EFFECTIVE_PLATFORM_NAME = $(EFFECTIVE_PLATFORM_NAME_ALTERNATE_$(WK_USE_ALTERNATE_PLATFORM_NAME)); EFFECTIVE_PLATFORM_NAME_ALTERNATE_YES = -$(WK_ALTERNATE_PLATFORM_NAME); EFFECTIVE_PLATFORM_NAME_ALTERNATE_NO = $(EFFECTIVE_PLATFORM_NAME);
browser_patches/deprecated-webkit-mac-10.14/embedder/Playwright/Configurations/SDKVariant.xcconfig
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0002134411915903911, 0.00019136218179482967, 0.00017086006118915975, 0.000193924322957173, 0.00001654178231547121 ]
{ "id": 2, "code_window": [ " delete contextOptions.deviceScaleFactor;\n", " return { browser, browserName: browserType.name(), context, contextOptions, launchOptions };\n", "}\n", "\n", "async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> {\n", " const page = await context.newPage();\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " delete contextOptions.acceptDownloads;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 338 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './inspectorTest'; import * as url from 'url'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test('should contain open page', async ({ openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); const sources = await recorder.waitForOutput('<javascript>', `page.goto`); expect(sources.get('<javascript>').text).toContain(` // Open new page const page = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page = await context.NewPageAsync();`); }); test('should contain second page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); const sources = await recorder.waitForOutput('<javascript>', 'page1'); expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page1 = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page1 = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync();`); }); test('should contain close page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); await recorder.page.close(); const sources = await recorder.waitForOutput('<javascript>', 'page.close();'); expect(sources.get('<javascript>').text).toContain(` await page.close();`); expect(sources.get('<java>').text).toContain(` page.close();`); expect(sources.get('<python>').text).toContain(` page.close()`); expect(sources.get('<async python>').text).toContain(` await page.close()`); expect(sources.get('<csharp>').text).toContain(` await page.CloseAsync();`); }); test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(''); await page.context().newPage(); const errors: any[] = []; recorder.page.on('pageerror', e => errors.push(e)); await recorder.page.evaluate(() => document.querySelector('body').remove()); const selector = await recorder.hoverOverElement('html'); expect(selector).toBe('html'); await recorder.page.close(); await recorder.waitForOutput('<javascript>', 'page.close();'); expect(errors.length).toBe(0); }); test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file"> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`); }); test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`); }); test('should clear files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.setInputFiles('input[type=file]', []); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Clear selected files await page.setInputFiles('input[type=\"file\"]', []);`); expect(sources.get('<java>').text).toContain(` // Clear selected files page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`); expect(sources.get('<python>').text).toContain(` # Clear selected files page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<async python>').text).toContain(` # Clear selected files await page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<csharp>').text).toContain(` // Clear selected files await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`); }); test('should download files', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/download', (req, res) => { const pathName = url.parse(req.url!).path; if (pathName === '/download') { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment; filename=file.txt'); res.end(`Hello world`); } else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); } }); await recorder.setContentAndWait(` <a href="${server.PREFIX}/download" download>Download</a> `, server.PREFIX); await recorder.hoverOverElement('text=Download'); await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]); const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent'); expect(sources.get('<javascript>').text).toContain(` // Click text=Download const [download] = await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]);`); expect(sources.get('<java>').text).toContain(` // Click text=Download Download download = page.waitForDownload(() -> { page.click("text=Download"); });`); expect(sources.get('<python>').text).toContain(` # Click text=Download with page.expect_download() as download_info: page.click(\"text=Download\") download = download_info.value`); expect(sources.get('<async python>').text).toContain(` # Click text=Download async with page.expect_download() as download_info: await page.click(\"text=Download\") download = await download_info.value`); expect(sources.get('<csharp>').text).toContain(` // Click text=Download var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () => { await page.ClickAsync(\"text=Download\"); });`); }); test('should handle dialogs', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button onclick="alert()">click me</button> `); await recorder.hoverOverElement('button'); page.once('dialog', async dialog => { await dialog.dismiss(); }); await page.click('text=click me'); const sources = await recorder.waitForOutput('<javascript>', 'once'); expect(sources.get('<javascript>').text).toContain(` // Click text=click me page.once('dialog', dialog => { console.log(\`Dialog message: \${dialog.message()}\`); dialog.dismiss().catch(() => {}); }); await page.click('text=click me');`); expect(sources.get('<java>').text).toContain(` // Click text=click me page.onceDialog(dialog -> { System.out.println(String.format("Dialog message: %s", dialog.message())); dialog.dismiss(); }); page.click("text=click me");`); expect(sources.get('<python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) page.click(\"text=click me\")`); expect(sources.get('<async python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) await page.click(\"text=click me\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=click me void page_Dialog1_EventHandler(object sender, IDialog dialog) { Console.WriteLine($\"Dialog message: {dialog.Message}\"); dialog.DismissAsync(); page.Dialog -= page_Dialog1_EventHandler; } page.Dialog += page_Dialog1_EventHandler; await page.ClickAsync(\"text=click me\");`); }); test('should handle history.postData', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> let seqNum = 0; function pushState() { history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum)); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) { await page.evaluate('pushState()'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`); } }); test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => { test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] }); const sources = await recorder.waitForOutput('<javascript>', 'page1'); if (browserName === 'chromium') { expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage(); await page1.goto('about:blank?foo');`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page() await page1.goto("about:blank?foo")`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync(); await page1.GotoAsync("about:blank?foo");`); } else if (browserName === 'firefox') { expect(sources.get('<javascript>').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link', { modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}'] }) ]);`); } }); test('should not clash pages', async ({ page, openRecorder, browserName }) => { test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue'); const recorder = await openRecorder(); const [popup1] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup1, '<input id=name>'); const [popup2] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup2, '<input id=name>'); await popup1.type('input', 'TextA'); await recorder.waitForOutput('<javascript>', 'TextA'); await popup2.type('input', 'TextB'); await recorder.waitForOutput('<javascript>', 'TextB'); const sources = recorder.sources(); expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`); expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`); expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`); expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`); expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`); expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`); expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`); expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`); expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`); expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`); }); test('click should emit events in order', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button id=button> <script> button.addEventListener('mousedown', e => console.log(e.type)); button.addEventListener('mouseup', e => console.log(e.type)); button.addEventListener('click', e => console.log(e.type)); </script> `); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message.text()); }); await Promise.all([ page.click('button'), recorder.waitForOutput('<javascript>', 'page.click') ]); expect(messages).toEqual(['mousedown', 'mouseup', 'click']); }); test('should update hover model on action', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.hovered).toBe('input[name="updated"]'); }); test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && headless); test.fixme(browserName === 'firefox' && headless); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.active).toBe('input[name="updated"]'); }); test('should check input with chaning id', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`); await Promise.all([ recorder.waitForActionPerformed(), page.click('input[id=checkbox]') ]); }); test('should prefer frame name', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <iframe src='./frames/frame.html' name='one'></iframe> <iframe src='./frames/frame.html' name='two'></iframe> <iframe src='./frames/frame.html'></iframe> `, server.EMPTY_PAGE, 4); const frameOne = page.frame({ name: 'one' }); const frameTwo = page.frame({ name: 'two' }); const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name()); let [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'one'), frameOne.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'one' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("one").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'two'), frameTwo.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'two' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("two").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'url: \''), otherFrame.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ url: 'http://localhost:${server.PORT}/frames/frame.html' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`); }); test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/page2.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('Hello world'); }); await recorder.setContentAndWait(` <script> function pushState() { history.pushState({}, 'title', '${server.PREFIX}'); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) await page.evaluate('pushState()'); await page.goto(server.PREFIX + '/page2.html'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`); }); test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> async function onClick() { await new Promise(f => setTimeout(f, 100)); await window.letTheMouseMove(); window.location = ${JSON.stringify(server.EMPTY_PAGE)}; } </script> <button onclick="onClick()">Click me</button> `); await page.exposeBinding('letTheMouseMove', async () => { await page.mouse.move(200, 200); }); const [, sources] = await Promise.all([ // This will click, finish the click, then mouse move, then navigate. page.click('button'), recorder.waitForOutput('<javascript>', 'waitForNavigation'), ]); expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`); }); });
tests/inspector/cli-codegen-2.spec.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.9933532476425171, 0.2920999825000763, 0.0001685784664005041, 0.0010520853102207184, 0.4278565049171448 ]
{ "id": 2, "code_window": [ " delete contextOptions.deviceScaleFactor;\n", " return { browser, browserName: browserType.name(), context, contextOptions, launchOptions };\n", "}\n", "\n", "async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> {\n", " const page = await context.newPage();\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " delete contextOptions.acceptDownloads;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 338 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export type FatalDOMError = 'error:notelement' | 'error:nothtmlelement' | 'error:notfillableelement' | 'error:notfillableinputtype' | 'error:notfillablenumberinput' | 'error:notvaliddate' | 'error:notinput' | 'error:notselect' | 'error:notcheckbox'; export type RetargetableDOMError = 'error:notconnected';
src/server/common/domErrors.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017700552416499704, 0.00017553225916344672, 0.00017477499204687774, 0.0001748163194861263, 0.000001041878590513079 ]
{ "id": 2, "code_window": [ " delete contextOptions.deviceScaleFactor;\n", " return { browser, browserName: browserType.name(), context, contextOptions, launchOptions };\n", "}\n", "\n", "async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> {\n", " const page = await context.newPage();\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " delete contextOptions.acceptDownloads;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 338 }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; const {EventEmitter} = ChromeUtils.import('resource://gre/modules/EventEmitter.jsm'); const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js'); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const {NetUtil} = ChromeUtils.import('resource://gre/modules/NetUtil.jsm'); const Cc = Components.classes; const Ci = Components.interfaces; const Cu = Components.utils; const Cr = Components.results; const Cm = Components.manager; const CC = Components.Constructor; const helper = new Helper(); const UINT32_MAX = Math.pow(2, 32)-1; const BinaryInputStream = CC('@mozilla.org/binaryinputstream;1', 'nsIBinaryInputStream', 'setInputStream'); const BinaryOutputStream = CC('@mozilla.org/binaryoutputstream;1', 'nsIBinaryOutputStream', 'setOutputStream'); const StorageStream = CC('@mozilla.org/storagestream;1', 'nsIStorageStream', 'init'); // Cap response storage with 100Mb per tracked tab. const MAX_RESPONSE_STORAGE_SIZE = 100 * 1024 * 1024; /** * This is a nsIChannelEventSink implementation that monitors channel redirects. */ const SINK_CLASS_DESCRIPTION = "Juggler NetworkMonitor Channel Event Sink"; const SINK_CLASS_ID = Components.ID("{c2b4c83e-607a-405a-beab-0ef5dbfb7617}"); const SINK_CONTRACT_ID = "@mozilla.org/network/monitor/channeleventsink;1"; const SINK_CATEGORY_NAME = "net-channel-event-sinks"; const pageNetworkSymbol = Symbol('PageNetwork'); class PageNetwork { static _forPageTarget(target) { let result = target[pageNetworkSymbol]; if (!result) { result = new PageNetwork(target); target[pageNetworkSymbol] = result; } return result; } constructor(target) { EventEmitter.decorate(this); this._target = target; this._extraHTTPHeaders = null; this._responseStorage = new ResponseStorage(MAX_RESPONSE_STORAGE_SIZE, MAX_RESPONSE_STORAGE_SIZE / 10); this._requestInterceptionEnabled = false; // This is requestId => NetworkRequest map, only contains requests that are // awaiting interception action (abort, resume, fulfill) over the protocol. this._interceptedRequests = new Map(); } setExtraHTTPHeaders(headers) { this._extraHTTPHeaders = headers; } enableRequestInterception() { this._requestInterceptionEnabled = true; } disableRequestInterception() { this._requestInterceptionEnabled = false; for (const intercepted of this._interceptedRequests.values()) intercepted.resume(); this._interceptedRequests.clear(); } resumeInterceptedRequest(requestId, url, method, headers, postData) { this._takeIntercepted(requestId).resume(url, method, headers, postData); } fulfillInterceptedRequest(requestId, status, statusText, headers, base64body) { this._takeIntercepted(requestId).fulfill(status, statusText, headers, base64body); } abortInterceptedRequest(requestId, errorCode) { this._takeIntercepted(requestId).abort(errorCode); } getResponseBody(requestId) { if (!this._responseStorage) throw new Error('Responses are not tracked for the given browser'); return this._responseStorage.getBase64EncodedResponse(requestId); } _takeIntercepted(requestId) { const intercepted = this._interceptedRequests.get(requestId); if (!intercepted) throw new Error(`Cannot find request "${requestId}"`); this._interceptedRequests.delete(requestId); return intercepted; } } class NetworkRequest { constructor(networkObserver, httpChannel, redirectedFrom) { this._networkObserver = networkObserver; this.httpChannel = httpChannel; this._networkObserver._channelToRequest.set(this.httpChannel, this); const loadInfo = this.httpChannel.loadInfo; let browsingContext = loadInfo?.frameBrowsingContext || loadInfo?.browsingContext; // TODO: Unfortunately, requests from web workers don't have frameBrowsingContext or // browsingContext. // // We fail to attribute them to the original frames on the browser side, but we // can use load context top frame to attribute them to the top frame at least. if (!browsingContext) { const loadContext = helper.getLoadContext(this.httpChannel); browsingContext = loadContext?.topFrameElement?.browsingContext; } this._frameId = helper.browsingContextToFrameId(browsingContext); this.requestId = httpChannel.channelId + ''; this.navigationId = httpChannel.isMainDocumentChannel ? this.requestId : undefined; const internalCauseType = this.httpChannel.loadInfo ? this.httpChannel.loadInfo.internalContentPolicyType : Ci.nsIContentPolicy.TYPE_OTHER; this._redirectedIndex = 0; const ignoredRedirect = redirectedFrom && !redirectedFrom._sentOnResponse; if (ignoredRedirect) { // We just ignore redirect that did not hit the network before being redirected. // This happens, for example, for automatic http->https redirects. this.navigationId = redirectedFrom.navigationId; } else if (redirectedFrom) { this.redirectedFromId = redirectedFrom.requestId; this._redirectedIndex = redirectedFrom._redirectedIndex + 1; this.requestId = this.requestId + '-redirect' + this._redirectedIndex; this.navigationId = redirectedFrom.navigationId; // Finish previous request now. Since we inherit the listener, we could in theory // use onStopRequest, but that will only happen after the last redirect has finished. redirectedFrom._sendOnRequestFinished(); } this._maybeInactivePageNetwork = this._findPageNetwork(); this._expectingInterception = false; this._expectingResumedRequest = undefined; // { method, headers, postData } this._sentOnResponse = false; const pageNetwork = this._activePageNetwork(); if (pageNetwork) { appendExtraHTTPHeaders(httpChannel, pageNetwork._target.browserContext().extraHTTPHeaders); appendExtraHTTPHeaders(httpChannel, pageNetwork._extraHTTPHeaders); } this._responseBodyChunks = []; httpChannel.QueryInterface(Ci.nsITraceableChannel); this._originalListener = httpChannel.setNewListener(this); if (redirectedFrom) { // Listener is inherited for regular redirects, so we'd like to avoid // calling into previous NetworkRequest. this._originalListener = redirectedFrom._originalListener; } this._previousCallbacks = httpChannel.notificationCallbacks; httpChannel.notificationCallbacks = this; this.QueryInterface = ChromeUtils.generateQI([ Ci.nsIAuthPrompt2, Ci.nsIAuthPromptProvider, Ci.nsIInterfaceRequestor, Ci.nsINetworkInterceptController, Ci.nsIStreamListener, ]); if (this.redirectedFromId) { // Redirects are not interceptable. this._sendOnRequest(false); } } // Public interception API. resume(url, method, headers, postData) { this._expectingResumedRequest = { method, headers, postData }; const newUri = url ? Services.io.newURI(url) : null; this._interceptedChannel.resetInterceptionWithURI(newUri); this._interceptedChannel = undefined; } // Public interception API. abort(errorCode) { const error = errorMap[errorCode] || Cr.NS_ERROR_FAILURE; this._interceptedChannel.cancelInterception(error); this._interceptedChannel = undefined; } // Public interception API. fulfill(status, statusText, headers, base64body) { this._interceptedChannel.synthesizeStatus(status, statusText); for (const header of headers) { this._interceptedChannel.synthesizeHeader(header.name, header.value); if (header.name.toLowerCase() === 'set-cookie') { Services.cookies.QueryInterface(Ci.nsICookieService); Services.cookies.setCookieStringFromHttp(this.httpChannel.URI, header.value, this.httpChannel); } } const synthesized = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream); const body = base64body ? atob(base64body) : ''; synthesized.data = body; this._interceptedChannel.startSynthesizedResponse(synthesized, null, null, '', false); this._interceptedChannel.finishSynthesizedResponse(); this._interceptedChannel = undefined; } // Instrumentation called by NetworkObserver. _onInternalRedirect(newChannel) { // Intercepted requests produce "internal redirects" - this is both for our own // interception and service workers. // An internal redirect has the same channelId, inherits notificationCallbacks and // listener, and should be used instead of an old channel. this._networkObserver._channelToRequest.delete(this.httpChannel); this.httpChannel = newChannel; this._networkObserver._channelToRequest.set(this.httpChannel, this); } // Instrumentation called by NetworkObserver. _onInternalRedirectReady() { // Resumed request is first internally redirected to a new request, // and then the new request is ready to be updated. if (!this._expectingResumedRequest) return; const { method, headers, postData } = this._expectingResumedRequest; this._expectingResumedRequest = undefined; if (headers) { for (const header of requestHeaders(this.httpChannel)) this.httpChannel.setRequestHeader(header.name, '', false /* merge */); for (const header of headers) this.httpChannel.setRequestHeader(header.name, header.value, false /* merge */); } if (method) this.httpChannel.requestMethod = method; if (postData && this.httpChannel instanceof Ci.nsIUploadChannel2) { const synthesized = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream); const body = atob(postData); synthesized.setData(body, body.length); const overriddenHeader = (lowerCaseName, defaultValue) => { if (headers) { for (const header of headers) { if (header.name.toLowerCase() === lowerCaseName) { return header.value; } } } return defaultValue; } // Clear content-length, so that upload stream resets it. this.httpChannel.setRequestHeader('content-length', overriddenHeader('content-length', ''), false /* merge */); this.httpChannel.explicitSetUploadStream(synthesized, overriddenHeader('content-type', 'application/octet-stream'), -1, this.httpChannel.requestMethod, false); } } // Instrumentation called by NetworkObserver. _onResponse(fromCache) { this._sendOnResponse(fromCache); } // nsIInterfaceRequestor getInterface(iid) { if (iid.equals(Ci.nsIAuthPrompt2) || iid.equals(Ci.nsIAuthPromptProvider) || iid.equals(Ci.nsINetworkInterceptController)) return this; if (iid.equals(Ci.nsIAuthPrompt)) // Block nsIAuthPrompt - we want nsIAuthPrompt2 to be used instead. throw Cr.NS_ERROR_NO_INTERFACE; if (this._previousCallbacks) return this._previousCallbacks.getInterface(iid); throw Cr.NS_ERROR_NO_INTERFACE; } // nsIAuthPromptProvider getAuthPrompt(aPromptReason, iid) { return this; } // nsIAuthPrompt2 asyncPromptAuth(aChannel, aCallback, aContext, level, authInfo) { let canceled = false; Promise.resolve().then(() => { if (canceled) return; const hasAuth = this.promptAuth(aChannel, level, authInfo); if (hasAuth) aCallback.onAuthAvailable(aContext, authInfo); else aCallback.onAuthCancelled(aContext, true); }); return { QueryInterface: ChromeUtils.generateQI([Ci.nsICancelable]), cancel: () => { aCallback.onAuthCancelled(aContext, false); canceled = true; } }; } // nsIAuthPrompt2 promptAuth(aChannel, level, authInfo) { if (authInfo.flags & Ci.nsIAuthInformation.PREVIOUS_FAILED) return false; const pageNetwork = this._activePageNetwork(); if (!pageNetwork) return false; let credentials = null; if (authInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) { const proxy = this._networkObserver._targetRegistry.getProxyInfo(aChannel); credentials = proxy ? {username: proxy.username, password: proxy.password} : null; } else { credentials = pageNetwork._target.browserContext().httpCredentials; } if (!credentials) return false; authInfo.username = credentials.username; authInfo.password = credentials.password; // This will produce a new request with respective auth header set. // It will have the same id as ours. We expect it to arrive as new request and // will treat it as our own redirect. this._networkObserver._expectRedirect(this.httpChannel.channelId + '', this); return true; } // nsINetworkInterceptController shouldPrepareForIntercept(aURI, channel) { const interceptController = this._fallThroughInterceptController(); if (interceptController && interceptController.shouldPrepareForIntercept(aURI, channel)) { // We assume that interceptController is a service worker if there is one, // and yield interception to it. We are not going to intercept ourselves, // so we send onRequest now. this._sendOnRequest(false); return true; } if (channel !== this.httpChannel) { // Not our channel? Just in case this happens, don't do anything. return false; } // We do not want to intercept any redirects, because we are not able // to intercept subresource redirects, and it's unreliable for main requests. // We do not sendOnRequest here, because redirects do that in constructor. if (this.redirectedFromId) return false; const shouldIntercept = this._shouldIntercept(); if (!shouldIntercept) { // We are not intercepting - ready to issue onRequest. this._sendOnRequest(false); return false; } this._expectingInterception = true; return true; } // nsINetworkInterceptController channelIntercepted(intercepted) { if (!this._expectingInterception) { // We are not intercepting, fall-through. const interceptController = this._fallThroughInterceptController(); if (interceptController) interceptController.channelIntercepted(intercepted); return; } this._expectingInterception = false; this._interceptedChannel = intercepted.QueryInterface(Ci.nsIInterceptedChannel); const pageNetwork = this._activePageNetwork(); if (!pageNetwork) { // Just in case we disabled instrumentation while intercepting, resume and forget. this.resume(); return; } const browserContext = pageNetwork._target.browserContext(); if (browserContext.settings.onlineOverride === 'offline') { // Implement offline. this.abort(Cr.NS_ERROR_OFFLINE); return; } // Ok, so now we have intercepted the request, let's issue onRequest. // If interception has been disabled while we were intercepting, resume and forget. const interceptionEnabled = this._shouldIntercept(); this._sendOnRequest(!!interceptionEnabled); if (interceptionEnabled) pageNetwork._interceptedRequests.set(this.requestId, this); else this.resume(); } // nsIStreamListener onDataAvailable(aRequest, aInputStream, aOffset, aCount) { // For requests with internal redirect (e.g. intercepted by Service Worker), // we do not get onResponse normally, but we do get nsIStreamListener notifications. this._sendOnResponse(false); const iStream = new BinaryInputStream(aInputStream); const sStream = new StorageStream(8192, aCount, null); const oStream = new BinaryOutputStream(sStream.getOutputStream(0)); // Copy received data as they come. const data = iStream.readBytes(aCount); this._responseBodyChunks.push(data); oStream.writeBytes(data, aCount); try { this._originalListener.onDataAvailable(aRequest, sStream.newInputStream(0), aOffset, aCount); } catch (e) { // Be ready to original listener exceptions. } } // nsIStreamListener onStartRequest(aRequest) { try { this._originalListener.onStartRequest(aRequest); } catch (e) { // Be ready to original listener exceptions. } } // nsIStreamListener onStopRequest(aRequest, aStatusCode) { try { this._originalListener.onStopRequest(aRequest, aStatusCode); } catch (e) { // Be ready to original listener exceptions. } if (aStatusCode === 0) { // For requests with internal redirect (e.g. intercepted by Service Worker), // we do not get onResponse normally, but we do get nsIRequestObserver notifications. this._sendOnResponse(false); const body = this._responseBodyChunks.join(''); const pageNetwork = this._activePageNetwork(); if (pageNetwork) pageNetwork._responseStorage.addResponseBody(this, body); this._sendOnRequestFinished(); } else { this._sendOnRequestFailed(aStatusCode); } delete this._responseBodyChunks; } _shouldIntercept() { const pageNetwork = this._activePageNetwork(); if (!pageNetwork) return false; if (pageNetwork._requestInterceptionEnabled) return true; const browserContext = pageNetwork._target.browserContext(); if (browserContext.requestInterceptionEnabled) return true; if (browserContext.settings.onlineOverride === 'offline') return true; return false; } _fallThroughInterceptController() { if (!this._previousCallbacks || !(this._previousCallbacks instanceof Ci.nsINetworkInterceptController)) return undefined; return this._previousCallbacks.getInterface(Ci.nsINetworkInterceptController); } _activePageNetwork() { if (!this._maybeInactivePageNetwork) return undefined; return this._maybeInactivePageNetwork; } _findPageNetwork() { let loadContext = helper.getLoadContext(this.httpChannel); if (!loadContext) return; const target = this._networkObserver._targetRegistry.targetForBrowser(loadContext.topFrameElement); if (!target) return; return PageNetwork._forPageTarget(target); } _sendOnRequest(isIntercepted) { // Note: we call _sendOnRequest either after we intercepted the request, // or at the first moment we know that we are not going to intercept. const pageNetwork = this._activePageNetwork(); if (!pageNetwork) return; const loadInfo = this.httpChannel.loadInfo; const causeType = loadInfo?.externalContentPolicyType || Ci.nsIContentPolicy.TYPE_OTHER; const internalCauseType = loadInfo?.internalContentPolicyType || Ci.nsIContentPolicy.TYPE_OTHER; pageNetwork.emit(PageNetwork.Events.Request, { url: this.httpChannel.URI.spec, frameId: this._frameId, isIntercepted, requestId: this.requestId, redirectedFrom: this.redirectedFromId, postData: readRequestPostData(this.httpChannel), headers: requestHeaders(this.httpChannel), method: this.httpChannel.requestMethod, navigationId: this.navigationId, cause: causeTypeToString(causeType), internalCause: causeTypeToString(internalCauseType), }, this._frameId); } _sendOnResponse(fromCache) { if (this._sentOnResponse) { // We can come here twice because of internal redirects, e.g. service workers. return; } this._sentOnResponse = true; const pageNetwork = this._activePageNetwork(); if (!pageNetwork) return; this.httpChannel.QueryInterface(Ci.nsIHttpChannelInternal); this.httpChannel.QueryInterface(Ci.nsITimedChannel); const timing = { startTime: this.httpChannel.channelCreationTime, domainLookupStart: this.httpChannel.domainLookupStartTime, domainLookupEnd: this.httpChannel.domainLookupEndTime, connectStart: this.httpChannel.connectStartTime, secureConnectionStart: this.httpChannel.secureConnectionStartTime, connectEnd: this.httpChannel.connectEndTime, requestStart: this.httpChannel.requestStartTime, responseStart: this.httpChannel.responseStartTime, }; const headers = []; let status = 0; let statusText = ''; try { status = this.httpChannel.responseStatus; statusText = this.httpChannel.responseStatusText; this.httpChannel.visitResponseHeaders({ visitHeader: (name, value) => headers.push({name, value}), }); } catch (e) { // Response headers, status and/or statusText are not available // when redirect did not actually hit the network. } let remoteIPAddress = undefined; let remotePort = undefined; try { remoteIPAddress = this.httpChannel.remoteAddress; remotePort = this.httpChannel.remotePort; } catch (e) { // remoteAddress is not defined for cached requests. } pageNetwork.emit(PageNetwork.Events.Response, { requestId: this.requestId, securityDetails: getSecurityDetails(this.httpChannel), fromCache, headers, remoteIPAddress, remotePort, status, statusText, timing, }, this._frameId); } _sendOnRequestFailed(error) { const pageNetwork = this._activePageNetwork(); if (pageNetwork) { pageNetwork.emit(PageNetwork.Events.RequestFailed, { requestId: this.requestId, errorCode: helper.getNetworkErrorStatusText(error), }, this._frameId); } this._networkObserver._channelToRequest.delete(this.httpChannel); } _sendOnRequestFinished() { const pageNetwork = this._activePageNetwork(); if (pageNetwork) { pageNetwork.emit(PageNetwork.Events.RequestFinished, { requestId: this.requestId, responseEndTime: this.httpChannel.responseEndTime, }, this._frameId); } this._networkObserver._channelToRequest.delete(this.httpChannel); } } class NetworkObserver { static instance() { return NetworkObserver._instance || null; } constructor(targetRegistry) { EventEmitter.decorate(this); NetworkObserver._instance = this; this._targetRegistry = targetRegistry; this._channelToRequest = new Map(); // http channel -> network request this._expectedRedirect = new Map(); // expected redirect channel id (string) -> network request const protocolProxyService = Cc['@mozilla.org/network/protocol-proxy-service;1'].getService(); this._channelProxyFilter = { QueryInterface: ChromeUtils.generateQI([Ci.nsIProtocolProxyChannelFilter]), applyFilter: (channel, defaultProxyInfo, proxyFilter) => { const proxy = this._targetRegistry.getProxyInfo(channel); if (!proxy) { proxyFilter.onProxyFilterResult(defaultProxyInfo); return; } proxyFilter.onProxyFilterResult(protocolProxyService.newProxyInfo( proxy.type, proxy.host, proxy.port, '', /* aProxyAuthorizationHeader */ '', /* aConnectionIsolationKey */ 0, /* aFlags */ UINT32_MAX, /* aFailoverTimeout */ null, /* failover proxy */ )); }, }; protocolProxyService.registerChannelFilter(this._channelProxyFilter, 0 /* position */); this._channelSink = { QueryInterface: ChromeUtils.generateQI([Ci.nsIChannelEventSink]), asyncOnChannelRedirect: (oldChannel, newChannel, flags, callback) => { this._onRedirect(oldChannel, newChannel, flags); callback.onRedirectVerifyCallback(Cr.NS_OK); }, }; this._channelSinkFactory = { QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]), createInstance: (aOuter, aIID) => this._channelSink.QueryInterface(aIID), }; // Register self as ChannelEventSink to track redirects. const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory(SINK_CLASS_ID, SINK_CLASS_DESCRIPTION, SINK_CONTRACT_ID, this._channelSinkFactory); Services.catMan.addCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID, SINK_CONTRACT_ID, false, true); this._eventListeners = [ helper.addObserver(this._onRequest.bind(this), 'http-on-modify-request'), helper.addObserver(this._onResponse.bind(this, false /* fromCache */), 'http-on-examine-response'), helper.addObserver(this._onResponse.bind(this, true /* fromCache */), 'http-on-examine-cached-response'), helper.addObserver(this._onResponse.bind(this, true /* fromCache */), 'http-on-examine-merged-response'), ]; } _expectRedirect(channelId, previous) { this._expectedRedirect.set(channelId, previous); } _onRedirect(oldChannel, newChannel, flags) { if (!(oldChannel instanceof Ci.nsIHttpChannel) || !(newChannel instanceof Ci.nsIHttpChannel)) return; const oldHttpChannel = oldChannel.QueryInterface(Ci.nsIHttpChannel); const newHttpChannel = newChannel.QueryInterface(Ci.nsIHttpChannel); if (!(flags & Ci.nsIChannelEventSink.REDIRECT_INTERNAL)) { const previous = this._channelToRequest.get(oldHttpChannel); if (previous) this._expectRedirect(newHttpChannel.channelId + '', previous); } else { const request = this._channelToRequest.get(oldHttpChannel); if (request) request._onInternalRedirect(newHttpChannel); } } pageNetworkForTarget(target) { return PageNetwork._forPageTarget(target); } _onRequest(channel, topic) { if (!(channel instanceof Ci.nsIHttpChannel)) return; const httpChannel = channel.QueryInterface(Ci.nsIHttpChannel); const channelId = httpChannel.channelId + ''; const redirectedFrom = this._expectedRedirect.get(channelId); if (redirectedFrom) { this._expectedRedirect.delete(channelId); new NetworkRequest(this, httpChannel, redirectedFrom); } else { const redirectedRequest = this._channelToRequest.get(httpChannel); if (redirectedRequest) redirectedRequest._onInternalRedirectReady(); else new NetworkRequest(this, httpChannel); } } _onResponse(fromCache, httpChannel, topic) { const request = this._channelToRequest.get(httpChannel); if (request) request._onResponse(fromCache); } dispose() { this._activityDistributor.removeObserver(this); const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(SINK_CLASS_ID, this._channelSinkFactory); Services.catMan.deleteCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID, false); helper.removeListeners(this._eventListeners); } } const protocolVersionNames = { [Ci.nsITransportSecurityInfo.TLS_VERSION_1]: 'TLS 1', [Ci.nsITransportSecurityInfo.TLS_VERSION_1_1]: 'TLS 1.1', [Ci.nsITransportSecurityInfo.TLS_VERSION_1_2]: 'TLS 1.2', [Ci.nsITransportSecurityInfo.TLS_VERSION_1_3]: 'TLS 1.3', }; function getSecurityDetails(httpChannel) { const securityInfo = httpChannel.securityInfo; if (!securityInfo) return null; securityInfo.QueryInterface(Ci.nsITransportSecurityInfo); if (!securityInfo.serverCert) return null; return { protocol: protocolVersionNames[securityInfo.protocolVersion] || '<unknown>', subjectName: securityInfo.serverCert.commonName, issuer: securityInfo.serverCert.issuerCommonName, // Convert to seconds. validFrom: securityInfo.serverCert.validity.notBefore / 1000 / 1000, validTo: securityInfo.serverCert.validity.notAfter / 1000 / 1000, }; } function readRequestPostData(httpChannel) { if (!(httpChannel instanceof Ci.nsIUploadChannel)) return undefined; let iStream = httpChannel.uploadStream; if (!iStream) return undefined; const isSeekableStream = iStream instanceof Ci.nsISeekableStream; // For some reason, we cannot rewind back big streams, // so instead we should clone them. const isCloneable = iStream instanceof Ci.nsICloneableInputStream; if (isCloneable) iStream = iStream.clone(); let prevOffset; if (isSeekableStream) { prevOffset = iStream.tell(); iStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0); } // Read data from the stream. let result = undefined; try { const buffer = NetUtil.readInputStream(iStream, iStream.available()); const bytes = new Uint8Array(buffer); let binary = ''; for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]); result = btoa(binary); } catch (err) { result = ''; } // Seek locks the file, so seek to the beginning only if necko hasn't // read it yet, since necko doesn't seek to 0 before reading (at lest // not till 459384 is fixed). if (isSeekableStream && prevOffset == 0 && !isCloneable) iStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0); return result; } function requestHeaders(httpChannel) { const headers = []; httpChannel.visitRequestHeaders({ visitHeader: (name, value) => headers.push({name, value}), }); return headers; } function causeTypeToString(causeType) { for (let key in Ci.nsIContentPolicy) { if (Ci.nsIContentPolicy[key] === causeType) return key; } return 'TYPE_OTHER'; } function appendExtraHTTPHeaders(httpChannel, headers) { if (!headers) return; for (const header of headers) httpChannel.setRequestHeader(header.name, header.value, false /* merge */); } class ResponseStorage { constructor(maxTotalSize, maxResponseSize) { this._totalSize = 0; this._maxResponseSize = maxResponseSize; this._maxTotalSize = maxTotalSize; this._responses = new Map(); } addResponseBody(request, body) { if (body.length > this._maxResponseSize) { this._responses.set(request.requestId, { evicted: true, body: '', }); return; } let encodings = []; if ((request.httpChannel instanceof Ci.nsIEncodedChannel) && request.httpChannel.contentEncodings && !request.httpChannel.applyConversion) { const encodingHeader = request.httpChannel.getResponseHeader("Content-Encoding"); encodings = encodingHeader.split(/\s*\t*,\s*\t*/); } this._responses.set(request.requestId, {body, encodings}); this._totalSize += body.length; if (this._totalSize > this._maxTotalSize) { for (let [requestId, response] of this._responses) { this._totalSize -= response.body.length; response.body = ''; response.evicted = true; if (this._totalSize < this._maxTotalSize) break; } } } getBase64EncodedResponse(requestId) { const response = this._responses.get(requestId); if (!response) throw new Error(`Request "${requestId}" is not found`); if (response.evicted) return {base64body: '', evicted: true}; let result = response.body; if (response.encodings && response.encodings.length) { for (const encoding of response.encodings) result = convertString(result, encoding, 'uncompressed'); } return {base64body: btoa(result)}; } } function convertString(s, source, dest) { const is = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( Ci.nsIStringInputStream ); is.setData(s, s.length); const listener = Cc["@mozilla.org/network/stream-loader;1"].createInstance( Ci.nsIStreamLoader ); let result = []; listener.init({ onStreamComplete: function onStreamComplete( loader, context, status, length, data ) { const array = Array.from(data); const kChunk = 100000; for (let i = 0; i < length; i += kChunk) { const len = Math.min(kChunk, length - i); const chunk = String.fromCharCode.apply(this, array.slice(i, i + len)); result.push(chunk); } }, }); const converter = Cc["@mozilla.org/streamConverters;1"].getService( Ci.nsIStreamConverterService ).asyncConvertData( source, dest, listener, null ); converter.onStartRequest(null, null); converter.onDataAvailable(null, is, 0, s.length); converter.onStopRequest(null, null, null); return result.join(''); } const errorMap = { 'aborted': Cr.NS_ERROR_ABORT, 'accessdenied': Cr.NS_ERROR_PORT_ACCESS_NOT_ALLOWED, 'addressunreachable': Cr.NS_ERROR_UNKNOWN_HOST, 'blockedbyclient': Cr.NS_ERROR_FAILURE, 'blockedbyresponse': Cr.NS_ERROR_FAILURE, 'connectionaborted': Cr.NS_ERROR_NET_INTERRUPT, 'connectionclosed': Cr.NS_ERROR_FAILURE, 'connectionfailed': Cr.NS_ERROR_FAILURE, 'connectionrefused': Cr.NS_ERROR_CONNECTION_REFUSED, 'connectionreset': Cr.NS_ERROR_NET_RESET, 'internetdisconnected': Cr.NS_ERROR_OFFLINE, 'namenotresolved': Cr.NS_ERROR_UNKNOWN_HOST, 'timedout': Cr.NS_ERROR_NET_TIMEOUT, 'failed': Cr.NS_ERROR_FAILURE, }; PageNetwork.Events = { Request: Symbol('PageNetwork.Events.Request'), Response: Symbol('PageNetwork.Events.Response'), RequestFinished: Symbol('PageNetwork.Events.RequestFinished'), RequestFailed: Symbol('PageNetwork.Events.RequestFailed'), }; var EXPORTED_SYMBOLS = ['NetworkObserver', 'PageNetwork']; this.NetworkObserver = NetworkObserver; this.PageNetwork = PageNetwork;
browser_patches/firefox-stable/juggler/NetworkObserver.js
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0007189424941316247, 0.00019001253531314433, 0.0001639063993934542, 0.0001730424992274493, 0.00008852581231622025 ]
{ "id": 2, "code_window": [ " delete contextOptions.deviceScaleFactor;\n", " return { browser, browserName: browserType.name(), context, contextOptions, launchOptions };\n", "}\n", "\n", "async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> {\n", " const page = await context.newPage();\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " delete contextOptions.acceptDownloads;\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 338 }
#!/bin/bash # Copyright (c) Microsoft Corporation. # # Licensed under the Apache License, Version 2.0 (the 'License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e set +x if [[ ($1 == '--help') || ($1 == '-h') ]]; then echo "usage: $(basename $0) <report.json>" echo echo "Upload report to the flakiness dashboard." echo echo "NOTE: the following env variables are required:" echo " FLAKINESS_CONNECTION_STRING connection for the azure blob storage to upload report" exit 0 fi if [[ ("${GITHUB_REPOSITORY}" != "microsoft/playwright") && ("${GITHUB_REPOSITORY}" != "microsoft/playwright-internal") ]]; then echo "NOTE: skipping dashboard uploading from fork" exit 0 fi if [[ "${GITHUB_REF}" != "refs/heads/master" && "${GITHUB_REF}" != 'refs/heads/release-'* ]]; then echo "NOTE: skipping dashboard uploading from Playwright branches" exit 0 fi if [[ -z "${FLAKINESS_CONNECTION_STRING}" ]]; then echo "ERROR: \$FLAKINESS_CONNECTION_STRING environment variable is missing." echo " 'Azure Account Name' and 'Azure Account Key' secrets are required" echo " to upload flakiness results to Azure blob storage." exit 1 fi if [[ $# == 0 ]]; then echo "ERROR: missing report name!" echo "try './$(basename $0) --help' for more information" exit 1 fi export BUILD_URL="https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" export COMMIT_SHA=$(git rev-parse HEAD) export COMMIT_TITLE=$(git show -s --format=%s HEAD) export COMMIT_AUTHOR_NAME=$(git show -s --format=%an HEAD) export COMMIT_AUTHOR_EMAIL=$(git show -s --format=%ae HEAD) export COMMIT_TIMESTAMP=$(git show -s --format=%ct HEAD) export HOST_OS_NAME="$(uname)" export HOST_ARCH="$(uname -m)" export HOST_OS_VERSION="" if [[ "$HOST_OS_NAME" == "Darwin" ]]; then HOST_OS_VERSION=$(sw_vers -productVersion | grep -o '^\d\+.\d\+') elif [[ "$HOST_OS_NAME" == "Linux" ]]; then HOST_OS_NAME="$(bash -c 'source /etc/os-release && echo $NAME')" HOST_OS_VERSION="$(bash -c 'source /etc/os-release && echo $VERSION_ID')" fi EMBED_METADATA_SCRIPT=$(cat <<EOF const json = require('./' + process.argv[1]); json.metadata = { runURL: process.env.BUILD_URL, osName: process.env.HOST_OS_NAME, arch: process.env.HOST_ARCH, osVersion: process.env.HOST_OS_VERSION, commitSHA: process.env.COMMIT_SHA, commitTimestamp: process.env.COMMIT_TIMESTAMP, commitTitle: process.env.COMMIT_TITLE, commitAuthorName: process.env.COMMIT_AUTHOR_NAME, commitAuthorEmail: process.env.COMMIT_AUTHOR_EMAIL, }; console.log(JSON.stringify(json)); EOF ) REPORT_NAME=$(node -e "console.log(require('crypto').randomBytes(20).toString('hex'))") node -e "${EMBED_METADATA_SCRIPT}" "$1" > "${REPORT_NAME}" gzip "${REPORT_NAME}" az storage blob upload --connection-string "${FLAKINESS_CONNECTION_STRING}" -c uploads -f "${REPORT_NAME}.gz" -n "${REPORT_NAME}.gz" rm -rf "${REPORT_NAME}.gz"
utils/upload_flakiness_dashboard.sh
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017762889910954982, 0.00017379217024426907, 0.0001699038257356733, 0.00017370819114148617, 0.0000030745475214644102 ]
{ "id": 3, "code_window": [ " constructor(browserName: string, generateHeaders: boolean, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, deviceName: string | undefined, saveStorage: string | undefined) {\n", " super();\n", "\n", " launchOptions = { headless: false, ...launchOptions };\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " // Make a copy of options to modify them later.\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 42 }
#!/usr/bin/env node /** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-console */ import extract from 'extract-zip'; import fs from 'fs'; import os from 'os'; import path from 'path'; import rimraf from 'rimraf'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer, installBrowsers } from './driver'; import { TraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { installDeps } from '../install/installDeps'; import { allBrowserNames } from '../utils/registry'; program .version('Version ' + require('../../package.json').version) .name('npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to use, one of javascript, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]') .description('run command in debug mode: disable timeout, open inspector') .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); program .command('install [browserType...]') .description('ensure browsers necessary for this version of Playwright are installed') .action(async function(browserTypes) { try { const allBrowsers = new Set(allBrowserNames); for (const browserType of browserTypes) { if (!allBrowsers.has(browserType)) { console.log(`Invalid browser name: '${browserType}'. Expecting one of: ${allBrowserNames.map(name => `'${name}'`).join(', ')}`); process.exit(1); } } if (browserTypes.length && browserTypes.includes('chromium')) browserTypes = browserTypes.concat('ffmpeg'); await installBrowsers(browserTypes.length ? browserTypes : undefined); } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }); program .command('install-deps [browserType...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(browserType) { try { await installDeps(browserType); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete contextOptions.deviceScaleFactor; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'javascript'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); } export async function showTraceViewer(tracePath: string, browserName: string) { let stat; try { stat = fs.statSync(tracePath); } catch (e) { console.log(`No such file or directory: ${tracePath}`); return; } if (stat.isDirectory()) { const traceViewer = new TraceViewer(tracePath, browserName); await traceViewer.show(); return; } const zipFile = tracePath; const dir = fs.mkdtempSync(path.join(os.tmpdir(), `playwright-trace`)); process.on('exit', () => rimraf.sync(dir)); try { await extract(zipFile, { dir: dir }); } catch (e) { console.log(`Invalid trace file: ${zipFile}`); return; } const traceViewer = new TraceViewer(dir, browserName); await traceViewer.show(); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.9987096786499023, 0.1066560298204422, 0.00016557966591790318, 0.00017395052418578416, 0.29790419340133667 ]
{ "id": 3, "code_window": [ " constructor(browserName: string, generateHeaders: boolean, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, deviceName: string | undefined, saveStorage: string | undefined) {\n", " super();\n", "\n", " launchOptions = { headless: false, ...launchOptions };\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " // Make a copy of options to modify them later.\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 42 }
{ "comment": "Do not edit this file, use utils/roll_browser.js", "browsers": [ { "name": "chromium", "revision": "884693", "installByDefault": true }, { "name": "firefox", "revision": "1265", "installByDefault": true }, { "name": "firefox-stable", "revision": "1255", "installByDefault": false }, { "name": "webkit", "revision": "1482", "installByDefault": true, "revisionOverrides": { "mac10.14": "1444" } }, { "name": "webkit-technology-preview", "revision": "1443", "installByDefault": false }, { "name": "ffmpeg", "revision": "1005", "installByDefault": true } ] }
browsers.json
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001735509285936132, 0.00017304420180153102, 0.0001724777976050973, 0.00017307403322774917, 3.895428051237104e-7 ]
{ "id": 3, "code_window": [ " constructor(browserName: string, generateHeaders: boolean, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, deviceName: string | undefined, saveStorage: string | undefined) {\n", " super();\n", "\n", " launchOptions = { headless: false, ...launchOptions };\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " // Make a copy of options to modify them later.\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 42 }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); const {ComponentUtils} = ChromeUtils.import("resource://gre/modules/ComponentUtils.jsm"); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const {Dispatcher} = ChromeUtils.import("chrome://juggler/content/protocol/Dispatcher.js"); const {BrowserHandler} = ChromeUtils.import("chrome://juggler/content/protocol/BrowserHandler.js"); const {NetworkObserver} = ChromeUtils.import("chrome://juggler/content/NetworkObserver.js"); const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js"); const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js'); const helper = new Helper(); const Cc = Components.classes; const Ci = Components.interfaces; const FRAME_SCRIPT = "chrome://juggler/content/content/main.js"; // Command Line Handler function CommandLineHandler() { }; CommandLineHandler.prototype = { classDescription: "Sample command-line handler", classID: Components.ID('{f7a74a33-e2ab-422d-b022-4fb213dd2639}'), contractID: "@mozilla.org/remote/juggler;1", _xpcom_categories: [{ category: "command-line-handler", entry: "m-juggler" }], /* nsICommandLineHandler */ handle: async function(cmdLine) { const jugglerFlag = cmdLine.handleFlagWithParam("juggler", false); const jugglerPipeFlag = cmdLine.handleFlag("juggler-pipe", false); if (!jugglerPipeFlag && (!jugglerFlag || isNaN(jugglerFlag))) return; const silent = cmdLine.preventDefault; if (silent) Services.startup.enterLastWindowClosingSurvivalArea(); const targetRegistry = new TargetRegistry(); new NetworkObserver(targetRegistry); const loadFrameScript = () => { Services.mm.loadFrameScript(FRAME_SCRIPT, true /* aAllowDelayedLoad */); if (Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo).isHeadless) { const styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService); const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); const uri = ioService.newURI('chrome://juggler/content/content/hidden-scrollbars.css', null, null); styleSheetService.loadAndRegisterSheet(uri, styleSheetService.AGENT_SHEET); } }; // Force create hidden window here, otherwise its creation later closes the web socket! Services.appShell.hiddenDOMWindow; if (jugglerFlag) { const port = parseInt(jugglerFlag, 10); const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); const WebSocketServer = require('devtools/server/socket/websocket-server'); this._server = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket); this._server.initSpecialConnection(port, Ci.nsIServerSocket.KeepWhenOffline | Ci.nsIServerSocket.LoopbackOnly, 4); const token = helper.generateId(); this._server.asyncListen({ onSocketAccepted: async(socket, transport) => { const input = transport.openInputStream(0, 0, 0); const output = transport.openOutputStream(0, 0, 0); const webSocket = await WebSocketServer.accept(transport, input, output, "/" + token); const dispatcher = new Dispatcher(webSocket); const browserHandler = new BrowserHandler(dispatcher.rootSession(), dispatcher, targetRegistry, () => { if (silent) Services.startup.exitLastWindowClosingSurvivalArea(); }); dispatcher.rootSession().setHandler(browserHandler); } }); loadFrameScript(); dump(`Juggler listening on ws://127.0.0.1:${this._server.port}/${token}\n`); } else if (jugglerPipeFlag) { let browserHandler; let pipeStopped = false; const pipe = Cc['@mozilla.org/juggler/remotedebuggingpipe;1'].getService(Ci.nsIRemoteDebuggingPipe); const connection = { QueryInterface: ChromeUtils.generateQI([Ci.nsIRemoteDebuggingPipeClient]), receiveMessage(message) { if (this.onmessage) this.onmessage({ data: message }); }, disconnected() { if (browserHandler) browserHandler['Browser.close'](); }, send(message) { if (pipeStopped) { // We are missing the response to Browser.close, // but everything works fine. Once we actually need it, // we have to stop the pipe after the response is sent. return; } pipe.sendMessage(message); }, }; pipe.init(connection); const dispatcher = new Dispatcher(connection); browserHandler = new BrowserHandler(dispatcher.rootSession(), dispatcher, targetRegistry, () => { if (silent) Services.startup.exitLastWindowClosingSurvivalArea(); connection.onclose(); pipe.stop(); pipeStopped = true; }); dispatcher.rootSession().setHandler(browserHandler); loadFrameScript(); dump(`\nJuggler listening to the pipe\n`); } }, QueryInterface: ChromeUtils.generateQI([ Ci.nsICommandLineHandler ]), // CHANGEME: change the help info as appropriate, but // follow the guidelines in nsICommandLineHandler.idl // specifically, flag descriptions should start at // character 24, and lines should be wrapped at // 72 characters with embedded newlines, // and finally, the string should end with a newline helpInfo : " --juggler Enable Juggler automation\n" }; var NSGetFactory = ComponentUtils.generateNSGetFactory([CommandLineHandler]);
browser_patches/firefox-stable/juggler/components/juggler.js
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00018492521485313773, 0.00017108848260249943, 0.00016661608242429793, 0.0001697967672953382, 0.000004497335339692654 ]
{ "id": 3, "code_window": [ " constructor(browserName: string, generateHeaders: boolean, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, deviceName: string | undefined, saveStorage: string | undefined) {\n", " super();\n", "\n", " launchOptions = { headless: false, ...launchOptions };\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ " // Make a copy of options to modify them later.\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 42 }
{ "name": "playwright-core", "version": "1.0.0", "description": "A high-level API to automate web browsers", "repository": "github:Microsoft/playwright", "license": "Apache-2.0" }
.github/dummy-package-files-for-dependents-analytics/playwright-core/package.json
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001707221381366253, 0.0001707221381366253, 0.0001707221381366253, 0.0001707221381366253, 0 ]
{ "id": 4, "code_window": [ " launchOptions = { headless: false, ...launchOptions };\n", " delete launchOptions.executablePath;\n", " this._enabled = generateHeaders;\n", " this._options = { browserName, generateHeaders, launchOptions, contextOptions, deviceName, saveStorage };\n", " this.restart();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " contextOptions = { ...contextOptions };\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "replace", "edit_start_line_idx": 43 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './inspectorTest'; import * as url from 'url'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test('should contain open page', async ({ openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); const sources = await recorder.waitForOutput('<javascript>', `page.goto`); expect(sources.get('<javascript>').text).toContain(` // Open new page const page = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page = await context.NewPageAsync();`); }); test('should contain second page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); const sources = await recorder.waitForOutput('<javascript>', 'page1'); expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page1 = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page1 = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync();`); }); test('should contain close page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); await recorder.page.close(); const sources = await recorder.waitForOutput('<javascript>', 'page.close();'); expect(sources.get('<javascript>').text).toContain(` await page.close();`); expect(sources.get('<java>').text).toContain(` page.close();`); expect(sources.get('<python>').text).toContain(` page.close()`); expect(sources.get('<async python>').text).toContain(` await page.close()`); expect(sources.get('<csharp>').text).toContain(` await page.CloseAsync();`); }); test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(''); await page.context().newPage(); const errors: any[] = []; recorder.page.on('pageerror', e => errors.push(e)); await recorder.page.evaluate(() => document.querySelector('body').remove()); const selector = await recorder.hoverOverElement('html'); expect(selector).toBe('html'); await recorder.page.close(); await recorder.waitForOutput('<javascript>', 'page.close();'); expect(errors.length).toBe(0); }); test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file"> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`); }); test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`); }); test('should clear files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.setInputFiles('input[type=file]', []); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Clear selected files await page.setInputFiles('input[type=\"file\"]', []);`); expect(sources.get('<java>').text).toContain(` // Clear selected files page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`); expect(sources.get('<python>').text).toContain(` # Clear selected files page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<async python>').text).toContain(` # Clear selected files await page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<csharp>').text).toContain(` // Clear selected files await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`); }); test('should download files', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/download', (req, res) => { const pathName = url.parse(req.url!).path; if (pathName === '/download') { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment; filename=file.txt'); res.end(`Hello world`); } else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); } }); await recorder.setContentAndWait(` <a href="${server.PREFIX}/download" download>Download</a> `, server.PREFIX); await recorder.hoverOverElement('text=Download'); await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]); const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent'); expect(sources.get('<javascript>').text).toContain(` // Click text=Download const [download] = await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]);`); expect(sources.get('<java>').text).toContain(` // Click text=Download Download download = page.waitForDownload(() -> { page.click("text=Download"); });`); expect(sources.get('<python>').text).toContain(` # Click text=Download with page.expect_download() as download_info: page.click(\"text=Download\") download = download_info.value`); expect(sources.get('<async python>').text).toContain(` # Click text=Download async with page.expect_download() as download_info: await page.click(\"text=Download\") download = await download_info.value`); expect(sources.get('<csharp>').text).toContain(` // Click text=Download var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () => { await page.ClickAsync(\"text=Download\"); });`); }); test('should handle dialogs', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button onclick="alert()">click me</button> `); await recorder.hoverOverElement('button'); page.once('dialog', async dialog => { await dialog.dismiss(); }); await page.click('text=click me'); const sources = await recorder.waitForOutput('<javascript>', 'once'); expect(sources.get('<javascript>').text).toContain(` // Click text=click me page.once('dialog', dialog => { console.log(\`Dialog message: \${dialog.message()}\`); dialog.dismiss().catch(() => {}); }); await page.click('text=click me');`); expect(sources.get('<java>').text).toContain(` // Click text=click me page.onceDialog(dialog -> { System.out.println(String.format("Dialog message: %s", dialog.message())); dialog.dismiss(); }); page.click("text=click me");`); expect(sources.get('<python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) page.click(\"text=click me\")`); expect(sources.get('<async python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) await page.click(\"text=click me\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=click me void page_Dialog1_EventHandler(object sender, IDialog dialog) { Console.WriteLine($\"Dialog message: {dialog.Message}\"); dialog.DismissAsync(); page.Dialog -= page_Dialog1_EventHandler; } page.Dialog += page_Dialog1_EventHandler; await page.ClickAsync(\"text=click me\");`); }); test('should handle history.postData', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> let seqNum = 0; function pushState() { history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum)); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) { await page.evaluate('pushState()'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`); } }); test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => { test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] }); const sources = await recorder.waitForOutput('<javascript>', 'page1'); if (browserName === 'chromium') { expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage(); await page1.goto('about:blank?foo');`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page() await page1.goto("about:blank?foo")`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync(); await page1.GotoAsync("about:blank?foo");`); } else if (browserName === 'firefox') { expect(sources.get('<javascript>').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link', { modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}'] }) ]);`); } }); test('should not clash pages', async ({ page, openRecorder, browserName }) => { test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue'); const recorder = await openRecorder(); const [popup1] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup1, '<input id=name>'); const [popup2] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup2, '<input id=name>'); await popup1.type('input', 'TextA'); await recorder.waitForOutput('<javascript>', 'TextA'); await popup2.type('input', 'TextB'); await recorder.waitForOutput('<javascript>', 'TextB'); const sources = recorder.sources(); expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`); expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`); expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`); expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`); expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`); expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`); expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`); expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`); expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`); expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`); }); test('click should emit events in order', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button id=button> <script> button.addEventListener('mousedown', e => console.log(e.type)); button.addEventListener('mouseup', e => console.log(e.type)); button.addEventListener('click', e => console.log(e.type)); </script> `); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message.text()); }); await Promise.all([ page.click('button'), recorder.waitForOutput('<javascript>', 'page.click') ]); expect(messages).toEqual(['mousedown', 'mouseup', 'click']); }); test('should update hover model on action', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.hovered).toBe('input[name="updated"]'); }); test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && headless); test.fixme(browserName === 'firefox' && headless); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.active).toBe('input[name="updated"]'); }); test('should check input with chaning id', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`); await Promise.all([ recorder.waitForActionPerformed(), page.click('input[id=checkbox]') ]); }); test('should prefer frame name', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <iframe src='./frames/frame.html' name='one'></iframe> <iframe src='./frames/frame.html' name='two'></iframe> <iframe src='./frames/frame.html'></iframe> `, server.EMPTY_PAGE, 4); const frameOne = page.frame({ name: 'one' }); const frameTwo = page.frame({ name: 'two' }); const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name()); let [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'one'), frameOne.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'one' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("one").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'two'), frameTwo.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'two' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("two").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'url: \''), otherFrame.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ url: 'http://localhost:${server.PORT}/frames/frame.html' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`); }); test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/page2.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('Hello world'); }); await recorder.setContentAndWait(` <script> function pushState() { history.pushState({}, 'title', '${server.PREFIX}'); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) await page.evaluate('pushState()'); await page.goto(server.PREFIX + '/page2.html'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`); }); test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> async function onClick() { await new Promise(f => setTimeout(f, 100)); await window.letTheMouseMove(); window.location = ${JSON.stringify(server.EMPTY_PAGE)}; } </script> <button onclick="onClick()">Click me</button> `); await page.exposeBinding('letTheMouseMove', async () => { await page.mouse.move(200, 200); }); const [, sources] = await Promise.all([ // This will click, finish the click, then mouse move, then navigate. page.click('button'), recorder.waitForOutput('<javascript>', 'waitForNavigation'), ]); expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`); }); });
tests/inspector/cli-codegen-2.spec.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0006867271731607616, 0.00019368329958524555, 0.00016312371008098125, 0.00017580928397364914, 0.00008970374619821087 ]
{ "id": 4, "code_window": [ " launchOptions = { headless: false, ...launchOptions };\n", " delete launchOptions.executablePath;\n", " this._enabled = generateHeaders;\n", " this._options = { browserName, generateHeaders, launchOptions, contextOptions, deviceName, saveStorage };\n", " this.restart();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " contextOptions = { ...contextOptions };\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "replace", "edit_start_line_idx": 43 }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/build/classes" /> </component> <component name="ProjectType"> <option name="id" value="Android" /> </component> </project>
src/server/android/driver/.idea/misc.xml
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001738041319185868, 0.0001738041319185868, 0.0001738041319185868, 0.0001738041319185868, 0 ]
{ "id": 4, "code_window": [ " launchOptions = { headless: false, ...launchOptions };\n", " delete launchOptions.executablePath;\n", " this._enabled = generateHeaders;\n", " this._options = { browserName, generateHeaders, launchOptions, contextOptions, deviceName, saveStorage };\n", " this.restart();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " contextOptions = { ...contextOptions };\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "replace", "edit_start_line_idx": 43 }
1;/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import '../third_party/vscode/codicon.css'; import { Workbench } from './ui/workbench'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { applyTheme } from '../theme'; import '../common.css'; (async () => { applyTheme(); const debugNames = await fetch('/contexts').then(response => response.json()); ReactDOM.render(<Workbench debugNames={debugNames} />, document.querySelector('#root')); })();
src/web/traceViewer/index.tsx
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001776842982508242, 0.00017555880185682327, 0.00017434838810004294, 0.00017464371921960264, 0.0000015077812349773012 ]
{ "id": 4, "code_window": [ " launchOptions = { headless: false, ...launchOptions };\n", " delete launchOptions.executablePath;\n", " this._enabled = generateHeaders;\n", " this._options = { browserName, generateHeaders, launchOptions, contextOptions, deviceName, saveStorage };\n", " this.restart();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " contextOptions = { ...contextOptions };\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "replace", "edit_start_line_idx": 43 }
set PATH=%WEBKIT_BUILD_PATH% set WEBKIT_LIBRARIES=%CD%\WebKitLibraries\win set WEBKIT_OUTPUTDIR=%CD%\WebKitBuild perl %CD%\Tools\Scripts\build-webkit --wincairo --release --no-ninja --touch-events --orientation-events --dark-mode-css --generate-project-only --cmakeargs="-DLIBVPX_PACKAGE_PATH=C:\vcpkg\packages\libvpx_x64-windows" %DEVENV% %CD%\WebKitBuild\Release\WebKit.sln /build "Release|x64"
browser_patches/deprecated-webkit-mac-10.14/buildwin.bat
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001619736576685682, 0.0001619736576685682, 0.0001619736576685682, 0.0001619736576685682, 0 ]
{ "id": 5, "code_window": [ "\n", " signal(pageAlias: string, frame: Frame, signal: Signal) {\n", " if (!this._enabled)\n", " return;\n", " // Signal either arrives while action is being performed or shortly after.\n", " if (this._currentAction) {\n", " this._currentAction.action.signals.push(signal);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " // We'll need to pass acceptDownloads for any generated downloads code to work.\n", " if (signal.name === 'download')\n", " this._options.contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 129 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './inspectorTest'; import * as url from 'url'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test('should contain open page', async ({ openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); const sources = await recorder.waitForOutput('<javascript>', `page.goto`); expect(sources.get('<javascript>').text).toContain(` // Open new page const page = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page = await context.NewPageAsync();`); }); test('should contain second page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); const sources = await recorder.waitForOutput('<javascript>', 'page1'); expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page1 = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page1 = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync();`); }); test('should contain close page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); await recorder.page.close(); const sources = await recorder.waitForOutput('<javascript>', 'page.close();'); expect(sources.get('<javascript>').text).toContain(` await page.close();`); expect(sources.get('<java>').text).toContain(` page.close();`); expect(sources.get('<python>').text).toContain(` page.close()`); expect(sources.get('<async python>').text).toContain(` await page.close()`); expect(sources.get('<csharp>').text).toContain(` await page.CloseAsync();`); }); test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(''); await page.context().newPage(); const errors: any[] = []; recorder.page.on('pageerror', e => errors.push(e)); await recorder.page.evaluate(() => document.querySelector('body').remove()); const selector = await recorder.hoverOverElement('html'); expect(selector).toBe('html'); await recorder.page.close(); await recorder.waitForOutput('<javascript>', 'page.close();'); expect(errors.length).toBe(0); }); test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file"> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`); }); test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`); }); test('should clear files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.setInputFiles('input[type=file]', []); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Clear selected files await page.setInputFiles('input[type=\"file\"]', []);`); expect(sources.get('<java>').text).toContain(` // Clear selected files page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`); expect(sources.get('<python>').text).toContain(` # Clear selected files page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<async python>').text).toContain(` # Clear selected files await page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<csharp>').text).toContain(` // Clear selected files await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`); }); test('should download files', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/download', (req, res) => { const pathName = url.parse(req.url!).path; if (pathName === '/download') { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment; filename=file.txt'); res.end(`Hello world`); } else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); } }); await recorder.setContentAndWait(` <a href="${server.PREFIX}/download" download>Download</a> `, server.PREFIX); await recorder.hoverOverElement('text=Download'); await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]); const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent'); expect(sources.get('<javascript>').text).toContain(` // Click text=Download const [download] = await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]);`); expect(sources.get('<java>').text).toContain(` // Click text=Download Download download = page.waitForDownload(() -> { page.click("text=Download"); });`); expect(sources.get('<python>').text).toContain(` # Click text=Download with page.expect_download() as download_info: page.click(\"text=Download\") download = download_info.value`); expect(sources.get('<async python>').text).toContain(` # Click text=Download async with page.expect_download() as download_info: await page.click(\"text=Download\") download = await download_info.value`); expect(sources.get('<csharp>').text).toContain(` // Click text=Download var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () => { await page.ClickAsync(\"text=Download\"); });`); }); test('should handle dialogs', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button onclick="alert()">click me</button> `); await recorder.hoverOverElement('button'); page.once('dialog', async dialog => { await dialog.dismiss(); }); await page.click('text=click me'); const sources = await recorder.waitForOutput('<javascript>', 'once'); expect(sources.get('<javascript>').text).toContain(` // Click text=click me page.once('dialog', dialog => { console.log(\`Dialog message: \${dialog.message()}\`); dialog.dismiss().catch(() => {}); }); await page.click('text=click me');`); expect(sources.get('<java>').text).toContain(` // Click text=click me page.onceDialog(dialog -> { System.out.println(String.format("Dialog message: %s", dialog.message())); dialog.dismiss(); }); page.click("text=click me");`); expect(sources.get('<python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) page.click(\"text=click me\")`); expect(sources.get('<async python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) await page.click(\"text=click me\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=click me void page_Dialog1_EventHandler(object sender, IDialog dialog) { Console.WriteLine($\"Dialog message: {dialog.Message}\"); dialog.DismissAsync(); page.Dialog -= page_Dialog1_EventHandler; } page.Dialog += page_Dialog1_EventHandler; await page.ClickAsync(\"text=click me\");`); }); test('should handle history.postData', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> let seqNum = 0; function pushState() { history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum)); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) { await page.evaluate('pushState()'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`); } }); test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => { test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] }); const sources = await recorder.waitForOutput('<javascript>', 'page1'); if (browserName === 'chromium') { expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage(); await page1.goto('about:blank?foo');`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page() await page1.goto("about:blank?foo")`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync(); await page1.GotoAsync("about:blank?foo");`); } else if (browserName === 'firefox') { expect(sources.get('<javascript>').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link', { modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}'] }) ]);`); } }); test('should not clash pages', async ({ page, openRecorder, browserName }) => { test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue'); const recorder = await openRecorder(); const [popup1] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup1, '<input id=name>'); const [popup2] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup2, '<input id=name>'); await popup1.type('input', 'TextA'); await recorder.waitForOutput('<javascript>', 'TextA'); await popup2.type('input', 'TextB'); await recorder.waitForOutput('<javascript>', 'TextB'); const sources = recorder.sources(); expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`); expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`); expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`); expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`); expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`); expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`); expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`); expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`); expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`); expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`); }); test('click should emit events in order', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button id=button> <script> button.addEventListener('mousedown', e => console.log(e.type)); button.addEventListener('mouseup', e => console.log(e.type)); button.addEventListener('click', e => console.log(e.type)); </script> `); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message.text()); }); await Promise.all([ page.click('button'), recorder.waitForOutput('<javascript>', 'page.click') ]); expect(messages).toEqual(['mousedown', 'mouseup', 'click']); }); test('should update hover model on action', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.hovered).toBe('input[name="updated"]'); }); test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && headless); test.fixme(browserName === 'firefox' && headless); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.active).toBe('input[name="updated"]'); }); test('should check input with chaning id', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`); await Promise.all([ recorder.waitForActionPerformed(), page.click('input[id=checkbox]') ]); }); test('should prefer frame name', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <iframe src='./frames/frame.html' name='one'></iframe> <iframe src='./frames/frame.html' name='two'></iframe> <iframe src='./frames/frame.html'></iframe> `, server.EMPTY_PAGE, 4); const frameOne = page.frame({ name: 'one' }); const frameTwo = page.frame({ name: 'two' }); const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name()); let [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'one'), frameOne.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'one' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("one").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'two'), frameTwo.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'two' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("two").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'url: \''), otherFrame.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ url: 'http://localhost:${server.PORT}/frames/frame.html' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`); }); test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/page2.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('Hello world'); }); await recorder.setContentAndWait(` <script> function pushState() { history.pushState({}, 'title', '${server.PREFIX}'); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) await page.evaluate('pushState()'); await page.goto(server.PREFIX + '/page2.html'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`); }); test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> async function onClick() { await new Promise(f => setTimeout(f, 100)); await window.letTheMouseMove(); window.location = ${JSON.stringify(server.EMPTY_PAGE)}; } </script> <button onclick="onClick()">Click me</button> `); await page.exposeBinding('letTheMouseMove', async () => { await page.mouse.move(200, 200); }); const [, sources] = await Promise.all([ // This will click, finish the click, then mouse move, then navigate. page.click('button'), recorder.waitForOutput('<javascript>', 'waitForNavigation'), ]); expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`); }); });
tests/inspector/cli-codegen-2.spec.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0010178302181884646, 0.00018477662524674088, 0.00016386951028835028, 0.00017101132834795862, 0.00010617898806231096 ]
{ "id": 5, "code_window": [ "\n", " signal(pageAlias: string, frame: Frame, signal: Signal) {\n", " if (!this._enabled)\n", " return;\n", " // Signal either arrives while action is being performed or shortly after.\n", " if (this._currentAction) {\n", " this._currentAction.action.signals.push(signal);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " // We'll need to pass acceptDownloads for any generated downloads code to work.\n", " if (signal.name === 'download')\n", " this._options.contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 129 }
# Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile
src/server/android/driver/app/proguard-rules.pro
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017221618327312171, 0.00016856880392879248, 0.00016425340436398983, 0.00016923686780501157, 0.0000032849332001205767 ]
{ "id": 5, "code_window": [ "\n", " signal(pageAlias: string, frame: Frame, signal: Signal) {\n", " if (!this._enabled)\n", " return;\n", " // Signal either arrives while action is being performed or shortly after.\n", " if (this._currentAction) {\n", " this._currentAction.action.signals.push(signal);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " // We'll need to pass acceptDownloads for any generated downloads code to work.\n", " if (signal.name === 'download')\n", " this._options.contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 129 }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export type Size = { width: number, height: number }; export type Point = { x: number, y: number }; export type Rect = Size & Point; export type Quad = [ Point, Point, Point, Point ]; export type URLMatch = string | RegExp | ((url: URL) => boolean); export type TimeoutOptions = { timeout?: number }; export type StackFrame = { file: string, line?: number, column?: number, function?: string, };
src/common/types.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.001277443952858448, 0.0005432880716398358, 0.0001751924428390339, 0.00017722779011819512, 0.0005191272939555347 ]
{ "id": 5, "code_window": [ "\n", " signal(pageAlias: string, frame: Frame, signal: Signal) {\n", " if (!this._enabled)\n", " return;\n", " // Signal either arrives while action is being performed or shortly after.\n", " if (this._currentAction) {\n", " this._currentAction.action.signals.push(signal);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " // We'll need to pass acceptDownloads for any generated downloads code to work.\n", " if (signal.name === 'download')\n", " this._options.contextOptions.acceptDownloads = true;\n", "\n" ], "file_path": "src/server/supplements/recorder/codeGenerator.ts", "type": "add", "edit_start_line_idx": 129 }
<style> body { margin: 0 } </style> <canvas id="webgl" width="640" height="480"></canvas> <script type="text/javascript"> function shaderProgram(gl, vs, fs) { var prog = gl.createProgram(); var addshader = function(type, source) { var s = gl.createShader((type == 'vertex') ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); gl.shaderSource(s, source); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { throw "Could not compile "+type+ " shader:\n\n"+gl.getShaderInfoLog(s); } gl.attachShader(prog, s); }; addshader('vertex', vs); addshader('fragment', fs); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { throw "Could not link the shader program!"; } return prog; } function attributeSetFloats(gl, prog, attr_name, rsize, arr) { gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arr), gl.STATIC_DRAW); var attr = gl.getAttribLocation(prog, attr_name); gl.enableVertexAttribArray(attr); gl.vertexAttribPointer(attr, rsize, gl.FLOAT, false, 0, 0); } var gl = document.getElementById("webgl") .getContext("experimental-webgl"); gl.clearColor(0.8, 0.8, 0.8, 1); gl.clear(gl.COLOR_BUFFER_BIT); var prog = shaderProgram(gl, "attribute vec3 pos;"+ "void main() {"+ " gl_Position = vec4(pos, 2.0);"+ "}", "void main() {"+ " gl_FragColor = vec4(0.5, 0.5, 1.0, 1.0);"+ "}" ); gl.useProgram(prog); attributeSetFloats(gl, prog, "pos", 3, [ -1, 0, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0 ]); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); </script>
tests/assets/screenshots/webgl.html
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017674446280580014, 0.00017360471247229725, 0.00017212965758517385, 0.0001733919489197433, 0.0000013711290876017301 ]
{ "id": 6, "code_window": [ " ]);\n", " const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent');\n", "\n", " expect(sources.get('<javascript>').text).toContain(`\n", " // Click text=Download\n", " const [download] = await Promise.all([\n", " page.waitForEvent('download'),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<javascript>').text).toContain(`\n", " const context = await browser.newContext({\n", " acceptDownloads: true\n", " });`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 252 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './inspectorTest'; import * as url from 'url'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test('should contain open page', async ({ openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); const sources = await recorder.waitForOutput('<javascript>', `page.goto`); expect(sources.get('<javascript>').text).toContain(` // Open new page const page = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page = await context.NewPageAsync();`); }); test('should contain second page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); const sources = await recorder.waitForOutput('<javascript>', 'page1'); expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage();`); expect(sources.get('<java>').text).toContain(` // Open new page Page page1 = context.newPage();`); expect(sources.get('<python>').text).toContain(` # Open new page page1 = context.new_page()`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page()`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync();`); }); test('should contain close page', async ({ openRecorder, page }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(``); await page.context().newPage(); await recorder.page.close(); const sources = await recorder.waitForOutput('<javascript>', 'page.close();'); expect(sources.get('<javascript>').text).toContain(` await page.close();`); expect(sources.get('<java>').text).toContain(` page.close();`); expect(sources.get('<python>').text).toContain(` page.close()`); expect(sources.get('<async python>').text).toContain(` await page.close()`); expect(sources.get('<csharp>').text).toContain(` await page.CloseAsync();`); }); test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(''); await page.context().newPage(); const errors: any[] = []; recorder.page.on('pageerror', e => errors.push(e)); await recorder.page.evaluate(() => document.querySelector('body').remove()); const selector = await recorder.hoverOverElement('html'); expect(selector).toBe('html'); await recorder.page.close(); await recorder.waitForOutput('<javascript>', 'page.close();'); expect(errors.length).toBe(0); }); test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file"> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`); }); test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`); expect(sources.get('<java>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`); expect(sources.get('<python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<async python>').text).toContain(` # Upload file-to-upload.txt, file-to-upload-2.txt await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`); expect(sources.get('<csharp>').text).toContain(` // Upload file-to-upload.txt, file-to-upload-2.txt await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`); }); test('should clear files', async ({ page, openRecorder, browserName, asset }) => { test.fixme(browserName === 'firefox', 'Hangs'); const recorder = await openRecorder(); await recorder.setContentAndWait(` <form> <input type="file" multiple> </form> `); await page.focus('input[type=file]'); await page.setInputFiles('input[type=file]', asset('file-to-upload.txt')); await page.setInputFiles('input[type=file]', []); await page.click('input[type=file]'); const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles'); expect(sources.get('<javascript>').text).toContain(` // Clear selected files await page.setInputFiles('input[type=\"file\"]', []);`); expect(sources.get('<java>').text).toContain(` // Clear selected files page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`); expect(sources.get('<python>').text).toContain(` # Clear selected files page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<async python>').text).toContain(` # Clear selected files await page.set_input_files(\"input[type=\\\"file\\\"]\", []`); expect(sources.get('<csharp>').text).toContain(` // Clear selected files await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`); }); test('should download files', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/download', (req, res) => { const pathName = url.parse(req.url!).path; if (pathName === '/download') { res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Disposition', 'attachment; filename=file.txt'); res.end(`Hello world`); } else { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); } }); await recorder.setContentAndWait(` <a href="${server.PREFIX}/download" download>Download</a> `, server.PREFIX); await recorder.hoverOverElement('text=Download'); await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]); const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent'); expect(sources.get('<javascript>').text).toContain(` // Click text=Download const [download] = await Promise.all([ page.waitForEvent('download'), page.click('text=Download') ]);`); expect(sources.get('<java>').text).toContain(` // Click text=Download Download download = page.waitForDownload(() -> { page.click("text=Download"); });`); expect(sources.get('<python>').text).toContain(` # Click text=Download with page.expect_download() as download_info: page.click(\"text=Download\") download = download_info.value`); expect(sources.get('<async python>').text).toContain(` # Click text=Download async with page.expect_download() as download_info: await page.click(\"text=Download\") download = await download_info.value`); expect(sources.get('<csharp>').text).toContain(` // Click text=Download var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () => { await page.ClickAsync(\"text=Download\"); });`); }); test('should handle dialogs', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button onclick="alert()">click me</button> `); await recorder.hoverOverElement('button'); page.once('dialog', async dialog => { await dialog.dismiss(); }); await page.click('text=click me'); const sources = await recorder.waitForOutput('<javascript>', 'once'); expect(sources.get('<javascript>').text).toContain(` // Click text=click me page.once('dialog', dialog => { console.log(\`Dialog message: \${dialog.message()}\`); dialog.dismiss().catch(() => {}); }); await page.click('text=click me');`); expect(sources.get('<java>').text).toContain(` // Click text=click me page.onceDialog(dialog -> { System.out.println(String.format("Dialog message: %s", dialog.message())); dialog.dismiss(); }); page.click("text=click me");`); expect(sources.get('<python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) page.click(\"text=click me\")`); expect(sources.get('<async python>').text).toContain(` # Click text=click me page.once(\"dialog\", lambda dialog: dialog.dismiss()) await page.click(\"text=click me\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=click me void page_Dialog1_EventHandler(object sender, IDialog dialog) { Console.WriteLine($\"Dialog message: {dialog.Message}\"); dialog.DismissAsync(); page.Dialog -= page_Dialog1_EventHandler; } page.Dialog += page_Dialog1_EventHandler; await page.ClickAsync(\"text=click me\");`); }); test('should handle history.postData', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> let seqNum = 0; function pushState() { history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum)); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) { await page.evaluate('pushState()'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`); } }); test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => { test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] }); const sources = await recorder.waitForOutput('<javascript>', 'page1'); if (browserName === 'chromium') { expect(sources.get('<javascript>').text).toContain(` // Open new page const page1 = await context.newPage(); await page1.goto('about:blank?foo');`); expect(sources.get('<async python>').text).toContain(` # Open new page page1 = await context.new_page() await page1.goto("about:blank?foo")`); expect(sources.get('<csharp>').text).toContain(` // Open new page var page1 = await context.NewPageAsync(); await page1.GotoAsync("about:blank?foo");`); } else if (browserName === 'firefox') { expect(sources.get('<javascript>').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link', { modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}'] }) ]);`); } }); test('should not clash pages', async ({ page, openRecorder, browserName }) => { test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue'); const recorder = await openRecorder(); const [popup1] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup1, '<input id=name>'); const [popup2] = await Promise.all([ page.context().waitForEvent('page'), page.evaluate(`window.open('about:blank')`) ]); await recorder.setPageContentAndWait(popup2, '<input id=name>'); await popup1.type('input', 'TextA'); await recorder.waitForOutput('<javascript>', 'TextA'); await popup2.type('input', 'TextB'); await recorder.waitForOutput('<javascript>', 'TextB'); const sources = recorder.sources(); expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`); expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`); expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`); expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`); expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`); expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`); expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`); expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`); expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`); expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`); }); test('click should emit events in order', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <button id=button> <script> button.addEventListener('mousedown', e => console.log(e.type)); button.addEventListener('mouseup', e => console.log(e.type)); button.addEventListener('click', e => console.log(e.type)); </script> `); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message.text()); }); await Promise.all([ page.click('button'), recorder.waitForOutput('<javascript>', 'page.click') ]); expect(messages).toEqual(['mousedown', 'mouseup', 'click']); }); test('should update hover model on action', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.hovered).toBe('input[name="updated"]'); }); test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && headless); test.fixme(browserName === 'firefox' && headless); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`); const [ models ] = await Promise.all([ recorder.waitForActionPerformed(), page.click('input') ]); expect(models.active).toBe('input[name="updated"]'); }); test('should check input with chaning id', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`); await Promise.all([ recorder.waitForActionPerformed(), page.click('input[id=checkbox]') ]); }); test('should prefer frame name', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <iframe src='./frames/frame.html' name='one'></iframe> <iframe src='./frames/frame.html' name='two'></iframe> <iframe src='./frames/frame.html'></iframe> `, server.EMPTY_PAGE, 4); const frameOne = page.frame({ name: 'one' }); const frameTwo = page.frame({ name: 'two' }); const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name()); let [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'one'), frameOne.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'one' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("one").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'two'), frameTwo.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ name: 'two' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frame("two").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`); [sources] = await Promise.all([ recorder.waitForOutput('<javascript>', 'url: \''), otherFrame.click('div'), ]); expect(sources.get('<javascript>').text).toContain(` // Click text=Hi, I'm frame await page.frame({ url: 'http://localhost:${server.PORT}/frames/frame.html' }).click('text=Hi, I\\'m frame');`); expect(sources.get('<java>').text).toContain(` // Click text=Hi, I'm frame page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`); expect(sources.get('<python>').text).toContain(` # Click text=Hi, I'm frame page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<async python>').text).toContain(` # Click text=Hi, I'm frame await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`); expect(sources.get('<csharp>').text).toContain(` // Click text=Hi, I'm frame await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`); }); test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/page2.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end('Hello world'); }); await recorder.setContentAndWait(` <script> function pushState() { history.pushState({}, 'title', '${server.PREFIX}'); } </script>`, server.PREFIX); for (let i = 1; i < 3; ++i) await page.evaluate('pushState()'); await page.goto(server.PREFIX + '/page2.html'); await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`); }); test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <script> async function onClick() { await new Promise(f => setTimeout(f, 100)); await window.letTheMouseMove(); window.location = ${JSON.stringify(server.EMPTY_PAGE)}; } </script> <button onclick="onClick()">Click me</button> `); await page.exposeBinding('letTheMouseMove', async () => { await page.mouse.move(200, 200); }); const [, sources] = await Promise.all([ // This will click, finish the click, then mouse move, then navigate. page.click('button'), recorder.waitForOutput('<javascript>', 'waitForNavigation'), ]); expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`); }); });
tests/inspector/cli-codegen-2.spec.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.9984090924263, 0.1410369724035263, 0.00017441222735214978, 0.017501970753073692, 0.2943888008594513 ]
{ "id": 6, "code_window": [ " ]);\n", " const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent');\n", "\n", " expect(sources.get('<javascript>').text).toContain(`\n", " // Click text=Download\n", " const [download] = await Promise.all([\n", " page.waitForEvent('download'),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<javascript>').text).toContain(`\n", " const context = await browser.newContext({\n", " acceptDownloads: true\n", " });`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 252 }
const { app } = require('electron'); app.on('window-all-closed', e => e.preventDefault());
packages/installation-tests/electron-app.js
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00016926122771110386, 0.00016926122771110386, 0.00016926122771110386, 0.00016926122771110386, 0 ]
{ "id": 6, "code_window": [ " ]);\n", " const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent');\n", "\n", " expect(sources.get('<javascript>').text).toContain(`\n", " // Click text=Download\n", " const [download] = await Promise.all([\n", " page.waitForEvent('download'),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<javascript>').text).toContain(`\n", " const context = await browser.newContext({\n", " acceptDownloads: true\n", " });`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 252 }
# class: WebSocketFrame * langs: csharp, java The [WebSocketFrame] class represents frames sent over [WebSocket] connections in the page. Frame payload is returned by either [`method: WebSocketFrame.text`] or [`method: WebSocketFrame.binary`] method depending on the its type. ## method: WebSocketFrame.binary - returns: <[null]|[Buffer]> Returns binary payload. ## method: WebSocketFrame.text - returns: <[null]|[string]> Returns text payload.
docs/src/api/class-websocketframe.md
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00016677359235472977, 0.00016573150060139596, 0.00016468939429614693, 0.00016573150060139596, 0.0000010420990292914212 ]
{ "id": 6, "code_window": [ " ]);\n", " const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent');\n", "\n", " expect(sources.get('<javascript>').text).toContain(`\n", " // Click text=Download\n", " const [download] = await Promise.all([\n", " page.waitForEvent('download'),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<javascript>').text).toContain(`\n", " const context = await browser.newContext({\n", " acceptDownloads: true\n", " });`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 252 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './pageTest'; test.describe('non-stalling evaluate', () => { test.skip(({mode}) => mode !== 'default'); test('should work', async ({page, server, toImpl}) => { await page.goto(server.EMPTY_PAGE); const result = await toImpl(page.mainFrame()).nonStallingRawEvaluateInExistingMainContext('2+2'); expect(result).toBe(4); }); test('should throw while pending navigation', async ({page, server, toImpl}) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => document.body.textContent = 'HELLO WORLD'); let error; await page.route('**/empty.html', async (route, request) => { error = await toImpl(page.mainFrame()).nonStallingRawEvaluateInExistingMainContext('2+2').catch(e => e); route.abort(); }); await page.goto(server.EMPTY_PAGE).catch(() => {}); expect(error.message).toContain('Frame is currently attempting a navigation'); }); test('should throw when no main execution context', async ({page, toImpl}) => { let errorPromise; page.on('frameattached', frame => { errorPromise = toImpl(frame).nonStallingRawEvaluateInExistingMainContext('2+2').catch(e => e); }); await page.setContent('<iframe></iframe>'); const error = await errorPromise; // Testing this as a race. const success = error.message === 'Frame does not yet have a main execution context' || 'Frame is currently attempting a navigation'; expect(success).toBeTruthy(); }); });
tests/page/page-evaluate-no-stall.spec.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00023344969667959958, 0.0001872861321317032, 0.0001669465418672189, 0.00017747626407071948, 0.000021932690287940204 ]
{ "id": 7, "code_window": [ " page.click('text=Download')\n", " ]);`);\n", "\n", " expect(sources.get('<java>').text).toContain(`\n", " // Click text=Download\n", " Download download = page.waitForDownload(() -> {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // TODO: fix generated options in java.\n", " expect(sources.get('<java>').text).toContain(`\n", " BrowserContext context = browser.newContext(new Browser.NewContextOptions());`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 259 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { EventEmitter } from 'events'; import type { BrowserContextOptions, LaunchOptions } from '../../../..'; import { Frame } from '../../frames'; import { LanguageGenerator, LanguageGeneratorOptions } from './language'; import { Action, Signal } from './recorderActions'; import { describeFrame } from './utils'; export type ActionInContext = { pageAlias: string; frameName?: string; frameUrl: string; isMainFrame: boolean; action: Action; committed?: boolean; } export class CodeGenerator extends EventEmitter { private _currentAction: ActionInContext | null = null; private _lastAction: ActionInContext | null = null; private _actions: ActionInContext[] = []; private _enabled: boolean; private _options: LanguageGeneratorOptions; constructor(browserName: string, generateHeaders: boolean, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, deviceName: string | undefined, saveStorage: string | undefined) { super(); launchOptions = { headless: false, ...launchOptions }; delete launchOptions.executablePath; this._enabled = generateHeaders; this._options = { browserName, generateHeaders, launchOptions, contextOptions, deviceName, saveStorage }; this.restart(); } restart() { this._currentAction = null; this._lastAction = null; this._actions = []; this.emit('change'); } setEnabled(enabled: boolean) { this._enabled = enabled; } addAction(action: ActionInContext) { if (!this._enabled) return; this.willPerformAction(action); this.didPerformAction(action); } willPerformAction(action: ActionInContext) { if (!this._enabled) return; this._currentAction = action; } performedActionFailed(action: ActionInContext) { if (!this._enabled) return; if (this._currentAction === action) this._currentAction = null; } didPerformAction(actionInContext: ActionInContext) { if (!this._enabled) return; const { action, pageAlias } = actionInContext; let eraseLastAction = false; if (this._lastAction && this._lastAction.pageAlias === pageAlias) { const { action: lastAction } = this._lastAction; // We augment last action based on the type. if (this._lastAction && action.name === 'fill' && lastAction.name === 'fill') { if (action.selector === lastAction.selector) eraseLastAction = true; } if (lastAction && action.name === 'click' && lastAction.name === 'click') { if (action.selector === lastAction.selector && action.clickCount > lastAction.clickCount) eraseLastAction = true; } if (lastAction && action.name === 'navigate' && lastAction.name === 'navigate') { if (action.url === lastAction.url) { // Already at a target URL. this._currentAction = null; return; } } // Check and uncheck erase click. if (lastAction && (action.name === 'check' || action.name === 'uncheck') && lastAction.name === 'click') { if (action.selector === lastAction.selector) eraseLastAction = true; } } this._lastAction = actionInContext; this._currentAction = null; if (eraseLastAction) this._actions.pop(); this._actions.push(actionInContext); this.emit('change'); } commitLastAction() { if (!this._enabled) return; const action = this._lastAction; if (action) action.committed = true; } signal(pageAlias: string, frame: Frame, signal: Signal) { if (!this._enabled) return; // Signal either arrives while action is being performed or shortly after. if (this._currentAction) { this._currentAction.action.signals.push(signal); return; } if (this._lastAction && !this._lastAction.committed) { const signals = this._lastAction.action.signals; if (signal.name === 'navigation' && signals.length && signals[signals.length - 1].name === 'download') return; if (signal.name === 'download' && signals.length && signals[signals.length - 1].name === 'navigation') signals.length = signals.length - 1; signal.isAsync = true; this._lastAction.action.signals.push(signal); this.emit('change'); return; } if (signal.name === 'navigation') { this.addAction({ pageAlias, ...describeFrame(frame), committed: true, action: { name: 'navigate', url: frame.url(), signals: [], }, }); } } generateText(languageGenerator: LanguageGenerator) { const text = []; if (this._options.generateHeaders) text.push(languageGenerator.generateHeader(this._options)); for (const action of this._actions) text.push(languageGenerator.generateAction(action)); if (this._options.generateHeaders) text.push(languageGenerator.generateFooter(this._options.saveStorage)); return text.join('\n'); } }
src/server/supplements/recorder/codeGenerator.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0002149865176761523, 0.00017571629723533988, 0.00016464589862152934, 0.0001753213000483811, 0.000010392556760052685 ]
{ "id": 7, "code_window": [ " page.click('text=Download')\n", " ]);`);\n", "\n", " expect(sources.get('<java>').text).toContain(`\n", " // Click text=Download\n", " Download download = page.waitForDownload(() -> {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // TODO: fix generated options in java.\n", " expect(sources.get('<java>').text).toContain(`\n", " BrowserContext context = browser.newContext(new Browser.NewContextOptions());`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 259 }
/** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const http = require('http'); const https = require('https'); const url = require('url'); const fs = require('fs'); const path = require('path'); const zlib = require('zlib'); const util = require('util'); const WebSocketServer = require('ws').Server; const fulfillSymbol = Symbol('fullfil callback'); const rejectSymbol = Symbol('reject callback'); const readFileAsync = util.promisify(fs.readFile.bind(fs)); const gzipAsync = util.promisify(zlib.gzip.bind(zlib)); class TestServer { /** * @param {string} dirPath * @param {number} port * @param {string=} loopback * @return {!Promise<TestServer>} */ static async create(dirPath, port, loopback) { const server = new TestServer(dirPath, port, loopback); await new Promise(x => server._server.once('listening', x)); return server; } /** * @param {string} dirPath * @param {number} port * @param {string=} loopback * @return {!Promise<TestServer>} */ static async createHTTPS(dirPath, port, loopback) { const server = new TestServer(dirPath, port, loopback, { key: fs.readFileSync(path.join(__dirname, 'key.pem')), cert: fs.readFileSync(path.join(__dirname, 'cert.pem')), passphrase: 'aaaa', }); await new Promise(x => server._server.once('listening', x)); return server; } /** * @param {string} dirPath * @param {number} port * @param {string=} loopback * @param {!Object=} sslOptions */ constructor(dirPath, port, loopback, sslOptions) { if (sslOptions) this._server = https.createServer(sslOptions, this._onRequest.bind(this)); else this._server = http.createServer(this._onRequest.bind(this)); this._server.on('connection', socket => this._onSocket(socket)); this._wsServer = new WebSocketServer({server: this._server, path: '/ws'}); this._wsServer.on('connection', this._onWebSocketConnection.bind(this)); this._server.listen(port); this._dirPath = dirPath; this.debugServer = require('debug')('pw:server'); this._startTime = new Date(); this._cachedPathPrefix = null; /** @type {!Set<!NodeJS.Socket>} */ this._sockets = new Set(); /** @type {!Map<string, function(!http.IncomingMessage,http.ServerResponse)>} */ this._routes = new Map(); /** @type {!Map<string, !{username:string, password:string}>} */ this._auths = new Map(); /** @type {!Map<string, string>} */ this._csp = new Map(); /** @type {!Set<string>} */ this._gzipRoutes = new Set(); /** @type {!Map<string, !Promise>} */ this._requestSubscribers = new Map(); const cross_origin = loopback || '127.0.0.1'; const same_origin = loopback || 'localhost'; const protocol = sslOptions ? 'https' : 'http'; this.PORT = port; this.PREFIX = `${protocol}://${same_origin}:${port}`; this.CROSS_PROCESS_PREFIX = `${protocol}://${cross_origin}:${port}`; this.EMPTY_PAGE = `${protocol}://${same_origin}:${port}/empty.html`; } _onSocket(socket) { this._sockets.add(socket); // ECONNRESET and HPE_INVALID_EOF_STATE are legit errors given // that tab closing aborts outgoing connections to the server. socket.on('error', error => { if (error.code !== 'ECONNRESET' && error.code !== 'HPE_INVALID_EOF_STATE') throw error; }); socket.once('close', () => this._sockets.delete(socket)); } /** * @param {string} pathPrefix */ enableHTTPCache(pathPrefix) { this._cachedPathPrefix = pathPrefix; } /** * @param {string} path * @param {string} username * @param {string} password */ setAuth(path, username, password) { this.debugServer(`set auth for ${path} to ${username}:${password}`); this._auths.set(path, {username, password}); } enableGzip(path) { this._gzipRoutes.add(path); } /** * @param {string} path * @param {string} csp */ setCSP(path, csp) { this._csp.set(path, csp); } async stop() { this.reset(); for (const socket of this._sockets) socket.destroy(); this._sockets.clear(); await new Promise(x => this._server.close(x)); } /** * @param {string} path * @param {function(!http.IncomingMessage,http.ServerResponse)} handler */ setRoute(path, handler) { this._routes.set(path, handler); } /** * @param {string} from * @param {string} to */ setRedirect(from, to) { this.setRoute(from, (req, res) => { res.writeHead(302, { location: to }); res.end(); }); } /** * @param {string} path * @return {!Promise<!http.IncomingMessage>} */ waitForRequest(path) { let promise = this._requestSubscribers.get(path); if (promise) return promise; let fulfill, reject; promise = new Promise((f, r) => { fulfill = f; reject = r; }); promise[fulfillSymbol] = fulfill; promise[rejectSymbol] = reject; this._requestSubscribers.set(path, promise); return promise; } reset() { this._routes.clear(); this._auths.clear(); this._csp.clear(); this._gzipRoutes.clear(); const error = new Error('Static Server has been reset'); for (const subscriber of this._requestSubscribers.values()) subscriber[rejectSymbol].call(null, error); this._requestSubscribers.clear(); } /** * @param {http.IncomingMessage} request * @param {http.ServerResponse} response */ _onRequest(request, response) { request.on('error', error => { if (error.code === 'ECONNRESET') response.end(); else throw error; }); request.postBody = new Promise(resolve => { let body = Buffer.from([]); request.on('data', chunk => body = Buffer.concat([body, chunk])); request.on('end', () => resolve(body)); }); const pathName = url.parse(request.url).path; this.debugServer(`request ${request.method} ${pathName}`); if (this._auths.has(pathName)) { const auth = this._auths.get(pathName); const credentials = Buffer.from((request.headers.authorization || '').split(' ')[1] || '', 'base64').toString(); this.debugServer(`request credentials ${credentials}`); this.debugServer(`actual credentials ${auth.username}:${auth.password}`); if (credentials !== `${auth.username}:${auth.password}`) { this.debugServer(`request write www-auth`); response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Secure Area"' }); response.end('HTTP Error 401 Unauthorized: Access is denied'); return; } } // Notify request subscriber. if (this._requestSubscribers.has(pathName)) { this._requestSubscribers.get(pathName)[fulfillSymbol].call(null, request); this._requestSubscribers.delete(pathName); } const handler = this._routes.get(pathName); if (handler) { handler.call(null, request, response); } else { this.serveFile(request, response); } } /** * @param {!http.IncomingMessage} request * @param {!http.ServerResponse} response * @param {string|undefined} filePath */ async serveFile(request, response, filePath) { let pathName = url.parse(request.url).path; if (!filePath) { if (pathName === '/') pathName = '/index.html'; filePath = path.join(this._dirPath, pathName.substring(1)); } if (this._cachedPathPrefix !== null && filePath.startsWith(this._cachedPathPrefix)) { if (request.headers['if-modified-since']) { response.statusCode = 304; // not modified response.end(); return; } response.setHeader('Cache-Control', 'public, max-age=31536000, no-cache'); response.setHeader('Last-Modified', this._startTime.toISOString()); } else { response.setHeader('Cache-Control', 'no-cache, no-store'); } if (this._csp.has(pathName)) response.setHeader('Content-Security-Policy', this._csp.get(pathName)); const {err, data} = await readFileAsync(filePath).then(data => ({data})).catch(err => ({err})); // The HTTP transaction might be already terminated after async hop here - do nothing in this case. if (response.writableEnded) return; if (err) { response.statusCode = 404; response.end(`File not found: ${filePath}`); return; } const extension = filePath.substring(filePath.lastIndexOf('.') + 1); const mimeType = extensionToMime[extension] || 'application/octet-stream'; const isTextEncoding = /^text\/|^application\/(javascript|json)/.test(mimeType); const contentType = isTextEncoding ? `${mimeType}; charset=utf-8` : mimeType; response.setHeader('Content-Type', contentType); if (this._gzipRoutes.has(pathName)) { response.setHeader('Content-Encoding', 'gzip'); const result = await gzipAsync(data); // The HTTP transaction might be already terminated after async hop here. if (!response.writableEnded) response.end(result); } else { response.end(data); } } waitForWebSocketConnectionRequest() { return new Promise(fullfil => { this._wsServer.once('connection', (ws, req) => fullfil(req)); }); } _onWebSocketConnection(ws) { ws.send('incoming'); } } const extensionToMime = { 'ai': 'application/postscript', 'apng': 'image/apng', 'appcache': 'text/cache-manifest', 'au': 'audio/basic', 'bmp': 'image/bmp', 'cer': 'application/pkix-cert', 'cgm': 'image/cgm', 'coffee': 'text/coffeescript', 'conf': 'text/plain', 'crl': 'application/pkix-crl', 'css': 'text/css', 'csv': 'text/csv', 'def': 'text/plain', 'doc': 'application/msword', 'dot': 'application/msword', 'drle': 'image/dicom-rle', 'dtd': 'application/xml-dtd', 'ear': 'application/java-archive', 'emf': 'image/emf', 'eps': 'application/postscript', 'exr': 'image/aces', 'fits': 'image/fits', 'g3': 'image/g3fax', 'gbr': 'application/rpki-ghostbusters', 'gif': 'image/gif', 'glb': 'model/gltf-binary', 'gltf': 'model/gltf+json', 'gz': 'application/gzip', 'h261': 'video/h261', 'h263': 'video/h263', 'h264': 'video/h264', 'heic': 'image/heic', 'heics': 'image/heic-sequence', 'heif': 'image/heif', 'heifs': 'image/heif-sequence', 'htm': 'text/html', 'html': 'text/html', 'ics': 'text/calendar', 'ief': 'image/ief', 'ifb': 'text/calendar', 'iges': 'model/iges', 'igs': 'model/iges', 'in': 'text/plain', 'ini': 'text/plain', 'jade': 'text/jade', 'jar': 'application/java-archive', 'jls': 'image/jls', 'jp2': 'image/jp2', 'jpe': 'image/jpeg', 'jpeg': 'image/jpeg', 'jpf': 'image/jpx', 'jpg': 'image/jpeg', 'jpg2': 'image/jp2', 'jpgm': 'video/jpm', 'jpgv': 'video/jpeg', 'jpm': 'image/jpm', 'jpx': 'image/jpx', 'js': 'application/javascript', 'json': 'application/json', 'json5': 'application/json5', 'jsx': 'text/jsx', 'jxr': 'image/jxr', 'kar': 'audio/midi', 'ktx': 'image/ktx', 'less': 'text/less', 'list': 'text/plain', 'litcoffee': 'text/coffeescript', 'log': 'text/plain', 'm1v': 'video/mpeg', 'm21': 'application/mp21', 'm2a': 'audio/mpeg', 'm2v': 'video/mpeg', 'm3a': 'audio/mpeg', 'm4a': 'audio/mp4', 'm4p': 'application/mp4', 'man': 'text/troff', 'manifest': 'text/cache-manifest', 'markdown': 'text/markdown', 'mathml': 'application/mathml+xml', 'md': 'text/markdown', 'mdx': 'text/mdx', 'me': 'text/troff', 'mesh': 'model/mesh', 'mft': 'application/rpki-manifest', 'mid': 'audio/midi', 'midi': 'audio/midi', 'mj2': 'video/mj2', 'mjp2': 'video/mj2', 'mjs': 'application/javascript', 'mml': 'text/mathml', 'mov': 'video/quicktime', 'mp2': 'audio/mpeg', 'mp21': 'application/mp21', 'mp2a': 'audio/mpeg', 'mp3': 'audio/mpeg', 'mp4': 'video/mp4', 'mp4a': 'audio/mp4', 'mp4s': 'application/mp4', 'mp4v': 'video/mp4', 'mpe': 'video/mpeg', 'mpeg': 'video/mpeg', 'mpg': 'video/mpeg', 'mpg4': 'video/mp4', 'mpga': 'audio/mpeg', 'mrc': 'application/marc', 'ms': 'text/troff', 'msh': 'model/mesh', 'n3': 'text/n3', 'oga': 'audio/ogg', 'ogg': 'audio/ogg', 'ogv': 'video/ogg', 'ogx': 'application/ogg', 'otf': 'font/otf', 'p10': 'application/pkcs10', 'p7c': 'application/pkcs7-mime', 'p7m': 'application/pkcs7-mime', 'p7s': 'application/pkcs7-signature', 'p8': 'application/pkcs8', 'pdf': 'application/pdf', 'pki': 'application/pkixcmp', 'pkipath': 'application/pkix-pkipath', 'png': 'image/png', 'ps': 'application/postscript', 'pskcxml': 'application/pskc+xml', 'qt': 'video/quicktime', 'rmi': 'audio/midi', 'rng': 'application/xml', 'roa': 'application/rpki-roa', 'roff': 'text/troff', 'rsd': 'application/rsd+xml', 'rss': 'application/rss+xml', 'rtf': 'application/rtf', 'rtx': 'text/richtext', 's3m': 'audio/s3m', 'sgi': 'image/sgi', 'sgm': 'text/sgml', 'sgml': 'text/sgml', 'shex': 'text/shex', 'shtml': 'text/html', 'sil': 'audio/silk', 'silo': 'model/mesh', 'slim': 'text/slim', 'slm': 'text/slim', 'snd': 'audio/basic', 'spx': 'audio/ogg', 'stl': 'model/stl', 'styl': 'text/stylus', 'stylus': 'text/stylus', 'svg': 'image/svg+xml', 'svgz': 'image/svg+xml', 't': 'text/troff', 't38': 'image/t38', 'text': 'text/plain', 'tfx': 'image/tiff-fx', 'tif': 'image/tiff', 'tiff': 'image/tiff', 'tr': 'text/troff', 'ts': 'video/mp2t', 'tsv': 'text/tab-separated-values', 'ttc': 'font/collection', 'ttf': 'font/ttf', 'ttl': 'text/turtle', 'txt': 'text/plain', 'uri': 'text/uri-list', 'uris': 'text/uri-list', 'urls': 'text/uri-list', 'vcard': 'text/vcard', 'vrml': 'model/vrml', 'vtt': 'text/vtt', 'war': 'application/java-archive', 'wasm': 'application/wasm', 'wav': 'audio/wav', 'weba': 'audio/webm', 'webm': 'video/webm', 'webmanifest': 'application/manifest+json', 'webp': 'image/webp', 'wmf': 'image/wmf', 'woff': 'font/woff', 'woff2': 'font/woff2', 'wrl': 'model/vrml', 'x3d': 'model/x3d+xml', 'x3db': 'model/x3d+fastinfoset', 'x3dbz': 'model/x3d+binary', 'x3dv': 'model/x3d-vrml', 'x3dvz': 'model/x3d+vrml', 'x3dz': 'model/x3d+xml', 'xaml': 'application/xaml+xml', 'xht': 'application/xhtml+xml', 'xhtml': 'application/xhtml+xml', 'xm': 'audio/xm', 'xml': 'text/xml', 'xsd': 'application/xml', 'xsl': 'application/xml', 'xslt': 'application/xslt+xml', 'yaml': 'text/yaml', 'yml': 'text/yaml', 'zip': 'application/zip' }; module.exports = {TestServer};
utils/testserver/index.js
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0016538618365302682, 0.00020919663074892014, 0.0001596183719811961, 0.0001741632877383381, 0.0002094624360324815 ]
{ "id": 7, "code_window": [ " page.click('text=Download')\n", " ]);`);\n", "\n", " expect(sources.get('<java>').text).toContain(`\n", " // Click text=Download\n", " Download download = page.waitForDownload(() -> {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // TODO: fix generated options in java.\n", " expect(sources.get('<java>').text).toContain(`\n", " BrowserContext context = browser.newContext(new Browser.NewContextOptions());`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 259 }
{ "version": "2.0", "extensions": { "queues": { "batchSize": 1, "newBatchThreshold": 0 } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[1.*, 2.0.0)" } }
utils/flakiness-dashboard/processing/host.json
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001732605742290616, 0.00017219092114828527, 0.00017112126806750894, 0.00017219092114828527, 0.0000010696530807763338 ]
{ "id": 7, "code_window": [ " page.click('text=Download')\n", " ]);`);\n", "\n", " expect(sources.get('<java>').text).toContain(`\n", " // Click text=Download\n", " Download download = page.waitForDownload(() -> {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // TODO: fix generated options in java.\n", " expect(sources.get('<java>').text).toContain(`\n", " BrowserContext context = browser.newContext(new Browser.NewContextOptions());`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 259 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test as it, expect } from './pageTest'; import type { Route } from '../../index'; it('should pick up ongoing navigation', async ({page, server}) => { let response = null; server.setRoute('/one-style.css', (req, res) => response = res); await Promise.all([ server.waitForRequest('/one-style.css'), page.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'}), ]); const waitPromise = page.waitForLoadState(); response.statusCode = 404; response.end('Not found'); await waitPromise; }); it('should respect timeout', async ({page, server}) => { server.setRoute('/one-style.css', (req, res) => void 0); await page.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'}); const error = await page.waitForLoadState('load', { timeout: 1 }).catch(e => e); expect(error.message).toContain('page.waitForLoadState: Timeout 1ms exceeded.'); }); it('should resolve immediately if loaded', async ({page, server}) => { await page.goto(server.PREFIX + '/one-style.html'); await page.waitForLoadState(); }); it('should throw for bad state', async ({page, server}) => { await page.goto(server.PREFIX + '/one-style.html'); // @ts-expect-error 'bad' is not a valid load state const error = await page.waitForLoadState('bad').catch(e => e); expect(error.message).toContain(`state: expected one of (load|domcontentloaded|networkidle)`); }); it('should resolve immediately if load state matches', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); server.setRoute('/one-style.css', (req, res) => void 0); await page.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'}); await page.waitForLoadState('domcontentloaded'); }); it('should work with pages that have loaded before being connected to', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window['_popup'] = window.open(document.location.href)), ]); // The url is about:blank in FF. // expect(popup.url()).toBe(server.EMPTY_PAGE); await popup.waitForLoadState(); expect(popup.url()).toBe(server.EMPTY_PAGE); }); it('should wait for load state of empty url popup', async ({page, browserName}) => { const [popup, readyState] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => { const popup = window.open(''); return popup.document.readyState; }), ]); await popup.waitForLoadState(); expect(readyState).toBe(browserName === 'firefox' ? 'uninitialized' : 'complete'); expect(await popup.evaluate(() => document.readyState)).toBe(browserName === 'firefox' ? 'uninitialized' : 'complete'); }); it('should wait for load state of about:blank popup ', async ({page}) => { const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window.open('about:blank') && 1), ]); await popup.waitForLoadState(); expect(await popup.evaluate(() => document.readyState)).toBe('complete'); }); it('should wait for load state of about:blank popup with noopener ', async ({page}) => { const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(() => window.open('about:blank', null, 'noopener') && 1), ]); await popup.waitForLoadState(); expect(await popup.evaluate(() => document.readyState)).toBe('complete'); }); it('should wait for load state of popup with network url ', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(url => window.open(url) && 1, server.EMPTY_PAGE), ]); await popup.waitForLoadState(); expect(await popup.evaluate(() => document.readyState)).toBe('complete'); }); it('should wait for load state of popup with network url and noopener ', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.evaluate(url => window.open(url, null, 'noopener') && 1, server.EMPTY_PAGE), ]); await popup.waitForLoadState(); expect(await popup.evaluate(() => document.readyState)).toBe('complete'); }); it('should work with clicking target=_blank', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); await page.setContent('<a target=_blank rel="opener" href="/one-style.html">yo</a>'); const [popup] = await Promise.all([ page.waitForEvent('popup'), page.click('a'), ]); await popup.waitForLoadState(); expect(await popup.evaluate(() => document.readyState)).toBe('complete'); }); it('should wait for load state of newPage', async ({page, server, isElectron}) => { it.fixme(isElectron, 'BrowserContext.newPage does not work in Electron'); const [newPage] = await Promise.all([ page.context().waitForEvent('page'), page.context().newPage(), ]); await newPage.waitForLoadState(); expect(await newPage.evaluate(() => document.readyState)).toBe('complete'); }); it('should resolve after popup load', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); // Stall the 'load' by delaying css. let cssResponse; server.setRoute('/one-style.css', (req, res) => cssResponse = res); const [popup] = await Promise.all([ page.waitForEvent('popup'), server.waitForRequest('/one-style.css'), page.evaluate(url => window['popup'] = window.open(url), server.PREFIX + '/one-style.html'), ]); let resolved = false; const loadSatePromise = popup.waitForLoadState().then(() => resolved = true); // Round trips! for (let i = 0; i < 5; i++) await page.evaluate('window'); expect(resolved).toBe(false); cssResponse.end(''); await loadSatePromise; expect(resolved).toBe(true); expect(popup.url()).toBe(server.PREFIX + '/one-style.html'); }); it('should work for frame', async ({page, server}) => { await page.goto(server.PREFIX + '/frames/one-frame.html'); const frame = page.frames()[1]; const requestPromise = new Promise<Route>(resolve => page.route(server.PREFIX + '/one-style.css',resolve)); await frame.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'}); const request = await requestPromise; let resolved = false; const loadPromise = frame.waitForLoadState().then(() => resolved = true); // give the promise a chance to resolve, even though it shouldn't await page.evaluate('1'); expect(resolved).toBe(false); request.continue(); await loadPromise; });
tests/page/page-wait-for-load-state.spec.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0003305441641714424, 0.00019661236729007214, 0.00016680301632732153, 0.00017574071534909308, 0.00004722301309811883 ]
{ "id": 8, "code_window": [ " Download download = page.waitForDownload(() -> {\n", " page.click(\"text=Download\");\n", " });`);\n", "\n", " expect(sources.get('<python>').text).toContain(`\n", " # Click text=Download\n", " with page.expect_download() as download_info:\n", " page.click(\\\"text=Download\\\")\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<python>').text).toContain(`\n", " context = browser.new_context(accept_downloads=True)`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 265 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { EventEmitter } from 'events'; import type { BrowserContextOptions, LaunchOptions } from '../../../..'; import { Frame } from '../../frames'; import { LanguageGenerator, LanguageGeneratorOptions } from './language'; import { Action, Signal } from './recorderActions'; import { describeFrame } from './utils'; export type ActionInContext = { pageAlias: string; frameName?: string; frameUrl: string; isMainFrame: boolean; action: Action; committed?: boolean; } export class CodeGenerator extends EventEmitter { private _currentAction: ActionInContext | null = null; private _lastAction: ActionInContext | null = null; private _actions: ActionInContext[] = []; private _enabled: boolean; private _options: LanguageGeneratorOptions; constructor(browserName: string, generateHeaders: boolean, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, deviceName: string | undefined, saveStorage: string | undefined) { super(); launchOptions = { headless: false, ...launchOptions }; delete launchOptions.executablePath; this._enabled = generateHeaders; this._options = { browserName, generateHeaders, launchOptions, contextOptions, deviceName, saveStorage }; this.restart(); } restart() { this._currentAction = null; this._lastAction = null; this._actions = []; this.emit('change'); } setEnabled(enabled: boolean) { this._enabled = enabled; } addAction(action: ActionInContext) { if (!this._enabled) return; this.willPerformAction(action); this.didPerformAction(action); } willPerformAction(action: ActionInContext) { if (!this._enabled) return; this._currentAction = action; } performedActionFailed(action: ActionInContext) { if (!this._enabled) return; if (this._currentAction === action) this._currentAction = null; } didPerformAction(actionInContext: ActionInContext) { if (!this._enabled) return; const { action, pageAlias } = actionInContext; let eraseLastAction = false; if (this._lastAction && this._lastAction.pageAlias === pageAlias) { const { action: lastAction } = this._lastAction; // We augment last action based on the type. if (this._lastAction && action.name === 'fill' && lastAction.name === 'fill') { if (action.selector === lastAction.selector) eraseLastAction = true; } if (lastAction && action.name === 'click' && lastAction.name === 'click') { if (action.selector === lastAction.selector && action.clickCount > lastAction.clickCount) eraseLastAction = true; } if (lastAction && action.name === 'navigate' && lastAction.name === 'navigate') { if (action.url === lastAction.url) { // Already at a target URL. this._currentAction = null; return; } } // Check and uncheck erase click. if (lastAction && (action.name === 'check' || action.name === 'uncheck') && lastAction.name === 'click') { if (action.selector === lastAction.selector) eraseLastAction = true; } } this._lastAction = actionInContext; this._currentAction = null; if (eraseLastAction) this._actions.pop(); this._actions.push(actionInContext); this.emit('change'); } commitLastAction() { if (!this._enabled) return; const action = this._lastAction; if (action) action.committed = true; } signal(pageAlias: string, frame: Frame, signal: Signal) { if (!this._enabled) return; // Signal either arrives while action is being performed or shortly after. if (this._currentAction) { this._currentAction.action.signals.push(signal); return; } if (this._lastAction && !this._lastAction.committed) { const signals = this._lastAction.action.signals; if (signal.name === 'navigation' && signals.length && signals[signals.length - 1].name === 'download') return; if (signal.name === 'download' && signals.length && signals[signals.length - 1].name === 'navigation') signals.length = signals.length - 1; signal.isAsync = true; this._lastAction.action.signals.push(signal); this.emit('change'); return; } if (signal.name === 'navigation') { this.addAction({ pageAlias, ...describeFrame(frame), committed: true, action: { name: 'navigate', url: frame.url(), signals: [], }, }); } } generateText(languageGenerator: LanguageGenerator) { const text = []; if (this._options.generateHeaders) text.push(languageGenerator.generateHeader(this._options)); for (const action of this._actions) text.push(languageGenerator.generateAction(action)); if (this._options.generateHeaders) text.push(languageGenerator.generateFooter(this._options.saveStorage)); return text.join('\n'); } }
src/server/supplements/recorder/codeGenerator.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017840869259089231, 0.0001743497996358201, 0.00016533132293261588, 0.00017574624507687986, 0.000003859479420498246 ]
{ "id": 8, "code_window": [ " Download download = page.waitForDownload(() -> {\n", " page.click(\"text=Download\");\n", " });`);\n", "\n", " expect(sources.get('<python>').text).toContain(`\n", " # Click text=Download\n", " with page.expect_download() as download_info:\n", " page.click(\\\"text=Download\\\")\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<python>').text).toContain(`\n", " context = browser.new_context(accept_downloads=True)`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 265 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { contextTest as it, expect } from './config/browserTest'; import { Server as WebSocketServer } from 'ws'; it('should work', async ({ page, server }) => { const value = await page.evaluate(port => { let cb; const result = new Promise(f => cb = f); const ws = new WebSocket('ws://localhost:' + port + '/ws'); ws.addEventListener('message', data => { ws.close(); cb(data.data); }); return result; }, server.PORT); expect(value).toBe('incoming'); }); it('should emit close events', async ({ page, server }) => { let socketClosed; const socketClosePromise = new Promise(f => socketClosed = f); const log = []; let webSocket; page.on('websocket', ws => { log.push(`open<${ws.url()}>`); webSocket = ws; ws.on('close', () => { log.push('close'); socketClosed(); }); }); await page.evaluate(port => { const ws = new WebSocket('ws://localhost:' + port + '/ws'); ws.addEventListener('open', () => ws.close()); }, server.PORT); await socketClosePromise; expect(log.join(':')).toBe(`open<ws://localhost:${server.PORT}/ws>:close`); expect(webSocket.isClosed()).toBeTruthy(); }); it('should emit frame events', async ({ page, server }) => { let socketClosed; const socketClosePromise = new Promise(f => socketClosed = f); const log = []; page.on('websocket', ws => { log.push('open'); ws.on('framesent', d => log.push('sent<' + d.payload + '>')); ws.on('framereceived', d => log.push('received<' + d.payload + '>')); ws.on('close', () => { log.push('close'); socketClosed(); }); }); await page.evaluate(port => { const ws = new WebSocket('ws://localhost:' + port + '/ws'); ws.addEventListener('open', () => ws.send('outgoing')); ws.addEventListener('message', () => { ws.close(); }); }, server.PORT); await socketClosePromise; expect(log[0]).toBe('open'); expect(log[3]).toBe('close'); log.sort(); expect(log.join(':')).toBe('close:open:received<incoming>:sent<outgoing>'); }); it('should pass self as argument to close event', async ({ page, server }) => { let socketClosed; const socketClosePromise = new Promise(f => socketClosed = f); let webSocket; page.on('websocket', ws => { webSocket = ws; ws.on('close', socketClosed); }); await page.evaluate(port => { const ws = new WebSocket('ws://localhost:' + port + '/ws'); ws.addEventListener('open', () => ws.close()); }, server.PORT); const eventArg = await socketClosePromise; expect(eventArg).toBe(webSocket); }); it('should emit binary frame events', async ({ page, server }) => { let doneCallback; const donePromise = new Promise(f => doneCallback = f); const sent = []; page.on('websocket', ws => { ws.on('close', doneCallback); ws.on('framesent', d => sent.push(d.payload)); }); await page.evaluate(port => { const ws = new WebSocket('ws://localhost:' + port + '/ws'); ws.addEventListener('open', () => { const binary = new Uint8Array(5); for (let i = 0; i < 5; ++i) binary[i] = i; ws.send('text'); ws.send(binary); ws.close(); }); }, server.PORT); await donePromise; expect(sent[0]).toBe('text'); for (let i = 0; i < 5; ++i) expect(sent[1][i]).toBe(i); }); it('should emit error', async ({page, server, browserName}) => { let callback; const result = new Promise(f => callback = f); page.on('websocket', ws => ws.on('socketerror', callback)); page.evaluate(port => { new WebSocket('ws://localhost:' + port + '/bogus-ws'); }, server.PORT); const message = await result; if (browserName === 'firefox') expect(message).toBe('CLOSE_ABNORMAL'); else expect(message).toContain(': 400'); }); it('should not have stray error events', async ({page, server}) => { let error; page.on('websocket', ws => ws.on('socketerror', e => error = e)); await Promise.all([ page.waitForEvent('websocket').then(async ws => { await ws.waitForEvent('framereceived'); return ws; }), page.evaluate(port => { (window as any).ws = new WebSocket('ws://localhost:' + port + '/ws'); }, server.PORT) ]); await page.evaluate('window.ws.close()'); expect(error).toBeFalsy(); }); it('should reject waitForEvent on socket close', async ({page, server}) => { const [ws] = await Promise.all([ page.waitForEvent('websocket').then(async ws => { await ws.waitForEvent('framereceived'); return ws; }), page.evaluate(port => { (window as any).ws = new WebSocket('ws://localhost:' + port + '/ws'); }, server.PORT) ]); const error = ws.waitForEvent('framesent').catch(e => e); await page.evaluate('window.ws.close()'); expect((await error).message).toContain('Socket closed'); }); it('should reject waitForEvent on page close', async ({page, server}) => { const [ws] = await Promise.all([ page.waitForEvent('websocket').then(async ws => { await ws.waitForEvent('framereceived'); return ws; }), page.evaluate(port => { (window as any).ws = new WebSocket('ws://localhost:' + port + '/ws'); }, server.PORT) ]); const error = ws.waitForEvent('framesent').catch(e => e); await page.close(); expect((await error).message).toContain('Page closed'); }); it('should turn off when offline', async ({page}) => { it.fixme(); const webSocketServer = new WebSocketServer(); const address = webSocketServer.address(); const [socket, wsHandle] = await Promise.all([ new Promise<import('ws')>(x => webSocketServer.once('connection', x)), page.evaluateHandle(async address => { const ws = new WebSocket(`ws://${address}/`); await new Promise(x => ws.onopen = x); return ws; }, typeof address === 'string' ? address : 'localhost:' + address.port), ]); const failurePromise = new Promise(x => socket.on('message', data => x(data))); const closePromise = wsHandle.evaluate(async ws => { if (ws.readyState !== WebSocket.CLOSED) await new Promise(x => ws.onclose = x); return 'successfully closed'; }); const result = Promise.race([ failurePromise, closePromise ]); await page.context().setOffline(true); await wsHandle.evaluate(ws => ws.send('if this arrives it failed')); expect(await result).toBe('successfully closed'); await new Promise(x => webSocketServer.close(x)); });
tests/web-socket.spec.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00020702977781184018, 0.00017445598496124148, 0.00016403335030190647, 0.0001734481775201857, 0.00000996293056232389 ]
{ "id": 8, "code_window": [ " Download download = page.waitForDownload(() -> {\n", " page.click(\"text=Download\");\n", " });`);\n", "\n", " expect(sources.get('<python>').text).toContain(`\n", " # Click text=Download\n", " with page.expect_download() as download_info:\n", " page.click(\\\"text=Download\\\")\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<python>').text).toContain(`\n", " context = browser.new_context(accept_downloads=True)`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 265 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as channels from '../protocol/channels'; import { BrowserType } from './browserType'; import { ChannelOwner } from './channelOwner'; import { Selectors, SelectorsOwner, sharedSelectors } from './selectors'; import { Electron } from './electron'; import { TimeoutError } from '../utils/errors'; import { Size } from './types'; import { Android } from './android'; type DeviceDescriptor = { userAgent: string, viewport: Size, deviceScaleFactor: number, isMobile: boolean, hasTouch: boolean, defaultBrowserType: 'chromium' | 'firefox' | 'webkit' }; type Devices = { [name: string]: DeviceDescriptor }; export class Playwright extends ChannelOwner<channels.PlaywrightChannel, channels.PlaywrightInitializer> { readonly _android: Android; readonly _electron: Electron; readonly chromium: BrowserType; readonly firefox: BrowserType; readonly webkit: BrowserType; readonly devices: Devices; readonly selectors: Selectors; readonly errors: { TimeoutError: typeof TimeoutError }; private _selectorsOwner: SelectorsOwner; constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PlaywrightInitializer) { super(parent, type, guid, initializer); this.chromium = BrowserType.from(initializer.chromium); this.firefox = BrowserType.from(initializer.firefox); this.webkit = BrowserType.from(initializer.webkit); this._android = Android.from(initializer.android); this._electron = Electron.from(initializer.electron); this.devices = {}; for (const { name, descriptor } of initializer.deviceDescriptors) this.devices[name] = descriptor; this.selectors = sharedSelectors; this.errors = { TimeoutError }; this._selectorsOwner = SelectorsOwner.from(initializer.selectors); this.selectors._addChannel(this._selectorsOwner); } _cleanup() { this.selectors._removeChannel(this._selectorsOwner); } }
src/client/playwright.ts
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017831125296652317, 0.00017582274449523538, 0.00017134592053480446, 0.00017654772091191262, 0.0000024416790438408498 ]
{ "id": 8, "code_window": [ " Download download = page.waitForDownload(() -> {\n", " page.click(\"text=Download\");\n", " });`);\n", "\n", " expect(sources.get('<python>').text).toContain(`\n", " # Click text=Download\n", " with page.expect_download() as download_info:\n", " page.click(\\\"text=Download\\\")\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<python>').text).toContain(`\n", " context = browser.new_context(accept_downloads=True)`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 265 }
MIT License Copyright (c) 2015 - present Microsoft Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
src/web/third_party/vscode/LICENSE.txt
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.00017596405814401805, 0.00017303931235801429, 0.00017074067727662623, 0.00017241317254956812, 0.0000021779128474008758 ]
{ "id": 9, "code_window": [ " with page.expect_download() as download_info:\n", " page.click(\\\"text=Download\\\")\n", " download = download_info.value`);\n", "\n", " expect(sources.get('<async python>').text).toContain(`\n", " # Click text=Download\n", " async with page.expect_download() as download_info:\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<async python>').text).toContain(`\n", " context = await browser.new_context(accept_downloads=True)`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 271 }
#!/usr/bin/env node /** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-console */ import extract from 'extract-zip'; import fs from 'fs'; import os from 'os'; import path from 'path'; import rimraf from 'rimraf'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer, installBrowsers } from './driver'; import { TraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { installDeps } from '../install/installDeps'; import { allBrowserNames } from '../utils/registry'; program .version('Version ' + require('../../package.json').version) .name('npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to use, one of javascript, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]') .description('run command in debug mode: disable timeout, open inspector') .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); program .command('install [browserType...]') .description('ensure browsers necessary for this version of Playwright are installed') .action(async function(browserTypes) { try { const allBrowsers = new Set(allBrowserNames); for (const browserType of browserTypes) { if (!allBrowsers.has(browserType)) { console.log(`Invalid browser name: '${browserType}'. Expecting one of: ${allBrowserNames.map(name => `'${name}'`).join(', ')}`); process.exit(1); } } if (browserTypes.length && browserTypes.includes('chromium')) browserTypes = browserTypes.concat('ffmpeg'); await installBrowsers(browserTypes.length ? browserTypes : undefined); } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }); program .command('install-deps [browserType...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(browserType) { try { await installDeps(browserType); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete contextOptions.deviceScaleFactor; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'javascript'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); } export async function showTraceViewer(tracePath: string, browserName: string) { let stat; try { stat = fs.statSync(tracePath); } catch (e) { console.log(`No such file or directory: ${tracePath}`); return; } if (stat.isDirectory()) { const traceViewer = new TraceViewer(tracePath, browserName); await traceViewer.show(); return; } const zipFile = tracePath; const dir = fs.mkdtempSync(path.join(os.tmpdir(), `playwright-trace`)); process.on('exit', () => rimraf.sync(dir)); try { await extract(zipFile, { dir: dir }); } catch (e) { console.log(`Invalid trace file: ${zipFile}`); return; } const traceViewer = new TraceViewer(dir, browserName); await traceViewer.show(); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.002201961586251855, 0.0002382788370596245, 0.00016482544015161693, 0.00017484383715782315, 0.0003006074402946979 ]
{ "id": 9, "code_window": [ " with page.expect_download() as download_info:\n", " page.click(\\\"text=Download\\\")\n", " download = download_info.value`);\n", "\n", " expect(sources.get('<async python>').text).toContain(`\n", " # Click text=Download\n", " async with page.expect_download() as download_info:\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " expect(sources.get('<async python>').text).toContain(`\n", " context = await browser.new_context(accept_downloads=True)`);\n" ], "file_path": "tests/inspector/cli-codegen-2.spec.ts", "type": "add", "edit_start_line_idx": 271 }
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"WebKitLinkedOnOrAfterEverything"]; return NSApplicationMain(argc, (const char **) argv); }
browser_patches/webkit/embedder/Playwright/mac/main.m
0
https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0
[ 0.0001714186364552006, 0.00017008358554448932, 0.00016818287258502096, 0.0001703664311207831, 0.0000012311169257372967 ]