How to use formatTrace method in Playwright Internal

Best JavaScript code snippet using playwright-internal

grammar.js

Source:grammar.js Github

copy

Full Screen

1// Generated automatically by nearley, version 2.16.02// http://github.com/Hardmath123/nearley3(function () {4function id(x) { return x[0]; }5/** About the grammar6 * math expressions involve the following operators:7 * +: numeric addition, concatenate strings, concatenate lists8 * -: unary numeric negation or numeric subtraction9 * *: numeric mult or list build e.g. '[0] * 4'10 * /: numeric (float and int (javascript / )) division11 * ^: numeric exponentiation12 *13 * math expressions reduce to the following single 'terms':14 * number, list, string, callable, varName15 *16 * math expressions are a strict subset of bool expressions17 *18 * bool expressions are a superset of math expressions 19 * (5 || 0 makes sense; True * False does not). bool20 * expressions involve the following operators:21 * ||: logical incluisve or22 * &&: logical and23 * !: logical not24 *25 * bool expressions reduce to the following single 'terms':26 * math expression terms + true, false, or parenthesized 27 * boolean expressions28 *29 * expressions (most generic) are simply the union of bool expressions30 * and dictionary terms. dictionary terms have no applicable31 * operators, so they get their own classification32 */33 const lexer = moo.compile({34 " ": " ",35 "\t": "\t",36 "\n": "\n",37 "-": "-",38 "+": "+",39 "*": "*",40 "//": "//",41 "/": "/",42 "^": "^",43 MOD: "%",44 DOT: ".",45 LESSEQ: "<=",46 GREATEQ: ">=",47 EQEQ: "==",48 NOTEQ: "!=",49 TRUE: "true",50 FALSE: "false",51 OR: "||",52 AND: "&&",53 NOT: "!",54 ">": ">",55 "<": "<",56 ",": ",",57 "(": "(",58 ")": ")",59 "=": "=",60 "{": "{",61 "}": "}",62 "[": "[",63 "]": "]",64 ":": ":",65 ";": ";",66 "$": "$",67 QUOTE: "\"",68 FOR: "for",69 WHILE: "while",70 IF: "if",71 ELSE: "else",72 ELIF: "elif",73 DEF: "define",74 RET: "return",75 NULL: "null",76 number: /-?(?:[0-9]|[0-9][0-9]+)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?\b/,77 varName: /[a-zA-Z][a-zA-Z0-9_]*/,78 character: /[^\n"]/, 79 });80// overloaded + for str-like objects81// including react <span> elements 82function combineStrings(...strings) {83 return makeSpan(strings);84}85/** Postprocessors build a tree of function/operator calls86 * where each node is an object with the following properties:87 *88 * isLiteral: this subtree is composed entirely of literal (string/number) nodes89 * opNodes: references to child nodes90 * command: command object that calculates the desired result by calling 91 * child node commands and combining these with the operator or function92 *93 * About Command object nodes and evaluation:94 * semantic checks for errors in expressions like ("cat" + 3)95 * occur when the function is evaluated (i.e. when node.command.execute() is called), 96 * not when the tree is built. 97 * This is because the types of some operands may not be known at compiile time 98 * (i.e. variable and function calls)99 */100/** cloneOperands101 * helper method to clone an array of operands102 */103function cloneOperands(operands) {104 return operands.map(x => {105 if (x == null) return null;106 if (x.isLiteral) return x;107 if (x.clone) return x.clone();108 if (x instanceof Array) return cloneOperands(x);109 return x;110 });111}112/** buildAddSub 113 * create addition or subtraction node114 *115 * pattern:116 * sum -> sum _ ("+"|"-") _ product 117 */118function buildAddSub(operands) {119 var operator = operands[2];120 if (operator == "+")121 return buildAdd(operands[0], operands[4]);122 return buildSub(operands[0], operands[4]);123}124/** buildAdd 125 * valid operator only for two string/number results126 */127function buildAdd(opNode1, opNode2) {128 return {129 isLiteral: opNode1.isLiteral && opNode2.isLiteral,130 opNodes: [opNode1, opNode2],131 command: new AddCommand(opNode1, opNode2),132 clone: function() {133 return buildAdd(opNode1.clone(), opNode2.clone());134 },135 toString: () => "buildAdd",136 text: opNode1.text + " + " + opNode2.text,137 formatTrace: (o1, o2) => combineStrings(o1," + ", o2),138 };139}140function buildSub(opNode1, opNode2) {141 return {142 isLiteral: opNode1.isLiteral && opNode2.isLiteral,143 opNodes: [opNode1, opNode2],144 command: new SubCommand(opNode1, opNode2),145 clone: function() {146 return buildSub(opNode1.clone(), opNode2.clone());147 },148 toString: () => "buildSub",149 text: opNode1.text + " - " + opNode2.text,150 formatTrace: (o1, o2) => combineStrings(o1, " - ", o2),151 };152}153/** buildMultDiv154 * create multiplication or division node155 *156 * pattern:157 * product -> product _ ("*"|"/") _ exp158 */159function buildMultDiv(operands) {160 var operator = operands[2];161 if (operator == "*")162 return buildMult(operands[0], operands[4]);163 else if (operator == "/")164 return buildDiv(operands[0], operands[4]);165 else if (operator == "//")166 return buildFloorDiv(operands[0], operands[4]);167 else 168 return buildMod(operands[0], operands[4]);169}170/** buildMult 171 * valid operator only for two string/number results172 */173function buildMult(opNode1, opNode2) {174 return {175 isLiteral: opNode1.isLiteral && opNode2.isLiteral,176 opNodes: [opNode1, opNode2],177 command: new MultCommand(opNode1, opNode2),178 clone: function() {179 return buildMult(opNode1.clone(), opNode2.clone());180 },181 toString: () => "buildMult",182 text: opNode1.text + " * " + opNode2.text,183 formatTrace: (o1, o2) => combineStrings(o1, " * ", o2),184 };185}186/** buildDiv 187 * valid operator only for two number results188 */189function buildDiv(opNode1, opNode2) {190 return {191 isLiteral: opNode1.isLiteral && opNode2.isLiteral,192 opNodes: [opNode1, opNode2],193 command: new DivCommand(opNode1, opNode2),194 clone: function() {195 return buildDiv(opNode1.clone(), opNode2.clone());196 },197 toString: () => "buildDiv",198 text: opNode1.text + " / " + opNode2.text,199 formatTrace: (o1, o2) => combineStrings(o1, " / ", o2),200 };201}202function buildFloorDiv(opNode1, opNode2) {203 return {204 isLiteral: opNode1.isLiteral && opNode2.isLiteral,205 opNodes: [opNode1, opNode2],206 command: new FloorDivCommand(opNode1, opNode2),207 clone: function() {208 return buildFloorDiv(opNode1.clone(), opNode2.clone());209 },210 toString: () => "buildFloorDiv",211 text: opNode1.text + " // " + opNode2.text,212 formatTrace: (o1, o2) => combineStrings(o1, " // ", o2),213 };214}215function buildMod(opNode1, opNode2) {216 return {217 isLiteral: opNode1.isLiteral && opNode2.isLiteral,218 opNodes: [opNode1, opNode2],219 command: new ModCommand(opNode1, opNode2),220 clone: function() {221 return buildMod(opNode1.clone(), opNode2.clone());222 },223 toString: () => "buildMod",224 text: opNode1.text + " % " + opNode2.text,225 formatTrace: (o1, o2) => combineStrings(o1, " % ", o2),226 }227}228/** buildExp229 * create exponentiation node (right associative)230 *231 * pattern:232 * exp -> unaryNeg _ "^" _ exp 233 */234function buildExp(operands) {235 var opNode1 = operands[0];236 var opNode2 = operands[4];237 return {238 isLiteral: opNode1.isLiteral && opNode2.isLiteral,239 opNodes: [opNode1, opNode2],240 command: new ExponentCommand(opNode1, opNode2),241 clone: function() {242 return buildExp(cloneOperands(operands));243 },244 toString: () => "buildExp",245 text: opNode1.text + " ^ " + opNode2.text,246 formatTrace: (o1, o2) => combineStrings(o1, " ^ ", o2),247 };248}249/** buildNegate250 * create unary negation node 251 *252 * pattern:253 * Negate -> "-" factor 254 */255function buildNegate(operands) {256 var opNode = operands[1];257 return {258 isLiteral: opNode.isLiteral,259 opNodes: [opNode],260 command: new NegateNumberCommand(opNode),261 clone: function() {262 return buildNegate(cloneOperands(operands));263 },264 toString: () => "buildNegate",265 text: "- " + opNode.text,266 formatTrace: (o1) => combineStrings(" - ", o1),267 };268}269/** buildFunctionCall 270 * build command node using 271 * factory method for function Command272 * objects273 *274 * isLiteral false by definition275 *276 * pattern:277 * function -> objExpr "(" _ args _ ")" 278 * | objExpr "(" ")" 279 * | "$" "(" _ args _ ")" 280 * 281 */282function buildFunctionCall(operands) {283 var functionNode = operands[0];284 var functionArgs = []; // default (no args function)285 // save function name for interpreter286 var functionName = operands[0].varName || operands[0].text || "";287 if (operands.length == 6) 288 functionArgs = operands[3];289 return {290 isLiteral: false,291 functionName: operands[0].text,292 opNodes: functionArgs,293 command: new FunctionCallCommand(functionName, functionNode, functionArgs),294 clone: function() {295 return buildFunctionCall(cloneOperands(operands));296 },297 toString: () => "buildFunctionCall",298 text: operands[0].text + "( " + functionArgs.map(x => x.text).join(", ") + " )",299 formatTrace: (o1, ...args) => combineStrings(o1, "(", joinStrings(args, ", "), ")"),300 };301}302/** buildBuckGet 303 * interpret this as $("objLabel")304 * by creating a function ast node305 * 306 * "$" %varName 307 */308function buildBuckGet(operands) {309 var functionName = operands[0].text;310 var functionNode = operands[0]; // never gets executed because "$" is built-in311 var functionArgs = [wrapUnquotedString([operands[1]])];312 return {313 isLiteral: false,314 opNodes: functionArgs,315 command: new FunctionCallCommand(functionName, functionNode, functionArgs),316 clone: function() {317 return buildBuckGet(cloneOperands(operands));318 },319 toString: () => "buildBuckGet",320 text: "$" + operands[1].text,321 formatTrace: (op) => combineStrings("$", op),322 };323}324/**325 *326 * "$" %varName _ "=" _ expr 327 */328function buildBuckSet(operands) {329 var functionName = operands[0].text;330 var functionNode = operands[0];331 var functionArgs = [wrapUnquotedString([operands[1]]), operands[5]];332 return {333 isLiteral: false,334 opNodes: functionArgs,335 command: new FunctionCallCommand(functionName, functionNode, functionArgs),336 clone: function() {337 return buildBuckSet(cloneOperands(operands));338 },339 toString: () => "buildBuckSet",340 text: "$" + operands[1].text + " = " + operands[5].text,341 formatTrace: (o1, o2) => combineStrings("$", o1, " = ", o2),342 };343}344/** buildFunctionArguments345 * returns an array of nodes for use346 * in building function Command node347 *348 * pattern: 349 * args -> funcarg (_ "," _ funcarg):* 350 * funcarg -> expr 351 */352function buildFunctionArguments(operands) {353 var argNodes = [operands[0]];354 for (var idx in operands[1]) 355 argNodes.push(operands[1][idx][3]);356 return argNodes;357}358function wrapNumber(operands) {359 return {360 isLiteral: true,361 opNodes: [],362 command: { 363 execute: function() { return Number(operands[0]); },364 undo: function() {},365 },366 clone: function() {367 return this;368 },369 toString: () => "wrapNumber",370 text: operands[0].text,371 }372}373/** wrapString374 * 375 * pattern:376 * "\"" [.]:* "\""377 */378function wrapString(operands) {379 return {380 isLiteral: true,381 opNodes: [],382 command: {383 execute: function() { 384 return operands[1].join("");385 },386 undo: function() {},387 },388 clone: function() {389 return this;390 },391 toString: () => "wrapString",392 text: '"' + operands[1].join("") + '"',393 };394}395function wrapUnquotedString(operands) {396 return {397 isLiteral: true,398 opNodes: [],399 command: {400 execute: function() { 401 return operands[0].text;402 },403 undo: function() {},404 },405 clone: function() {406 return this;407 },408 toString: () => "wrapUnquotedString",409 text: operands[0].text,410 };411}412/** wrapBool413 * create boolean evaluation node414 * pattern: %TRUE | %FALSE415 */416function wrapBool(operands) {417 return {418 isLiteral: true,419 opNodes: [],420 command: {421 execute: function() { return operands[0] == "true"; },422 undo: function() {},423 },424 clone: function() {425 return this;426 },427 toString: () => "wrapBool",428 text: operands[0].text,429 };430}431/** wrapNull432 * create null eval node433 * pattern: %NULL434 */435function wrapNull(operands) {436 return {437 isLiteral: true,438 opNodes: [],439 command: {440 execute: function() { return null; },441 undo: function() {},442 },443 clone: function() {444 return this;445 },446 toString: () => "wrapNull",447 text: "null",448 }449}450/** buildVariable451 * create getVariable node452 *453 * pattern:454 * varName -> %varName455 */456function buildVariable(operands) {457 var varName = operands[0].text;458 return {459 varName: varName,460 isLiteral: false,461 opNodes: [],462 command: new GetVariableCommand(varName),463 clone: function() {464 return buildVariable(cloneOperands(operands));465 },466 toString: () => "buildVariable",467 text: operands[0].text,468 }469}470/** buildAssignment471 * create assignment node472 *473 * pattern:474 * assignment -> %varName _ "=" _ math475 */476function buildAssignment(operands) {477 var lValue = operands[0].text;478 var rValue = operands[4];479 return {480 isLiteral: false,481 opNodes: [],482 command: new AssignVariableCommand(lValue, rValue),483 clone: function() {484 return buildAssignment(cloneOperands(operands));485 },486 toString: () => "buildAssignment",487 text: lValue + " = " + rValue.text,488 formatTrace: (op) => combineStrings(lValue, " = ", op),489 };490}491/** buildRangePropertyAssignment492 * create a RangeConfig node 493 * pattern:494 * assignment -> expr %DOT %varName _ "=" _ expr 495 */496function buildRangePropertyAssignment(operands) {497 var receiverNode = operands[0];498 var propName = operands[2].text;499 var rValueNode = operands[6];500 return {501 isLiteral: false,502 opNodes: [],503 command: new RangeConfigCommand(receiverNode, propName, rValueNode),504 clone: function() {505 return buildRangePropertyAssignment(cloneOperands(operands));506 },507 toString: () => "buildRangePropertyAssignment",508 text: operands[0].text + "." + propName + " = " + operands[6].text,509 formatTrace: (o1, o2) => combineStrings(o1, ".", propName, " = ", o2),510 };511}512/** buildComparison513 * create comparison (<, >, <=, >=) node514 * 515 * pattern:516 * comp -> bool _ comparator _ bool 517 */518function buildComparison(operands) {519 var opNode1 = operands[0];520 var opNode2 = operands[4];521 var comp = operands[2];522 var compCommand;523 if (comp == "<")524 compCommand = LessThanCommand;525 else if (comp == "<=")526 compCommand = LessEqualThanCommand;527 else if (comp == ">")528 compCommand = GreaterThanCommand;529 else if (comp == ">=")530 compCommand = GreaterEqualThanCommand;531 // wrap comp for react to avoid532 //Error: Invariant Violation: Objects are not valid as a React child (found: <). 533 // If you meant to render a collection of children, use an array instead or wrap the object 534 // using createFragment(object) from the React add-ons. 535 var wrappedComp = " " + comp + " " 536 return {537 isLiteral: opNode1.isLiteral && opNode2.isLiteral,538 opNodes: [opNode1, opNode2],539 command: new compCommand(opNode1, opNode2),540 clone: function() {541 return buildComparison(cloneOperands(operands));542 },543 toString: () => "buildComparison",544 text: opNode1.text + " " + comp + " " + opNode2.text,545 formatTrace: (o1, o2) => combineStrings(o1, wrappedComp, o2),546 }547}548/** buildCommaSepStatements549 * return array of comma separated statement550 * nodes551 *552 * pattern:553 * commaSepStatement -> statement (_ "," _ statement):*554 */555function buildCommaSepStatements(operands) {556 var statements = [operands[0]];557 for (var idx in operands[1]) 558 statements.push(operands[1][idx][3]);559 return statements; 560}561/** buildBlock562 * return array of line opNodes563 * pattern: 564 * block -> "{" _ (line _):* "}" 565 */566function buildBlock(operands) { 567 var lines = [];568 for (var idx in operands[2])569 lines.push(operands[2][idx][0]);570 return lines;571}572/** buildForPars573 * return a 2d array of statements574 *575 * pattern:576 * forPars -> 577 * "(" _ (commaSepStatements _ ):? ";" _ (bool _):? ";" _ (commaSepStatements _):? ")" 578 * 579 */580function buildForPars(operands) {581 var initStatements = operands[2] ? operands[2][0] : [];582 var condition = operands[5] ? operands[5][0] : wrapBool(["true"]); // empty condition always evaluates to true583 var incrStatements = operands[8] ? operands[8][0] : [];584 return [initStatements, condition, incrStatements];585}586/** buildForLoop587 * create for loop node with588 * statement subtrees or empty arrays as 'arguments'589 * i.e. setup statements, test condition, increment statements590 *591 * pattern:592 * forLoop 593 -> %FOR _ forPars _ block594 */595function buildForLoop(operands) {596 var initStatements = operands[2][0];597 var condition = operands[2][1];598 var incrStatements = operands[2][2];599 var loopStatements = operands[4];600 return {601 isLiteral: false,602 opNodes: loopStatements,603 command: new ForLoopCommand(initStatements, condition, 604 incrStatements, loopStatements),605 clone: function() {606 return buildForLoop(cloneOperands(operands));607 },608 toString: () => "buildForLoop",609 text: forLoopText(initStatements, condition, incrStatements, loopStatements),610 };611}612/** buildWhileLoop613 * create while loop node (single condition)614 *615 * pattern:616 * whileLoop ->617 * %WHILE _ "(" _ bool _ ")" _ block618 */619function buildWhileLoop(operands) {620 var condition = operands[4];621 622 var loopStatements = operands[8];623 return {624 isLiteral: false,625 opNodes: loopStatements,626 command: new WhileLoopCommand(condition, loopStatements),627 clone: function() {628 return buildWhileLoop(cloneOperands(operands));629 },630 toString: () => "buildWhileLoop",631 // text: `while ( ${condition.text} ) { `632 // + loopStatements.map(x => x.text).join(";\n") + "\n}",633 text: whileLoopText(condition, loopStatements),634 };635}636/** buildSingleAccess637 * create 638 * accessor -> expr "[" _ expr _ "] 639 *640 */641function buildSingleAccess(operands) {642 var receiver = operands[0];643 var keyNode = operands[3]; 644 return {645 isLiteral: false,646 opNodes: [],647 command: new GetChildCommand(receiver, keyNode),648 clone: function() {649 return buildSingleAccess(cloneOperands(operands));650 },651 toString: () => "buildSingleAccess",652 text: receiver.text + "[ " + keyNode.text + " ]",653 formatTrace: (o1, o2) => combineStrings(o1, "[", o2, "]"),654 };655}656/** buildRangeAccess657 * create GetChildren node. When evaluated,658 * this node returns an array of children659 *660 * syntax: 661 * arr[3:] - get children from index 3 to end (inclusive)662 * arr[:3] - get children from starting index up to 2663 * arr[3:5] - get children from index 3 to 4664 * arr[:] - get all children665 *666 * pattern:667 * accessor -> %varName "[" _ (expr _):? ":" _ (expr _):? "]" 668 */669function buildRangeAccess(operands) {670 var receiver = operands[0];671 var low = operands[3] ? operands[3][0] : wrapNull();672 var high = operands[6] ? operands[6][0] : wrapNull();673 return {674 isLiteral: false,675 opNodes: [],676 command: new GetChildrenCommand(receiver, low, high),677 clone: function() {678 return buildRangeAccess(cloneOperands(operands));679 },680 toString: () => "buildRangeAccess",681 text: operands[0].text + "[ " + low.text + ":" + high.text + " ]",682 formatTrace: (o1, o2) => combineStrings(operands[0].text, "[", o1, ":", o2, "]"),683 };684}685/** buildList686 * create op node that just returns an array. List elements687 * get evaluated upon instantiation,688 * so the following sequence won't change the list:689 *690 * x = 3691 * list = [x, 4, 5]692 * x = 4693 *694 * pattern:695 * list -> "[" _ "]" 696 * list -> "[" _ args _ "]" 697 * 698 * buildList clones opnodes so function calls get re-evaluated699 * when list is cloned700 */701function buildList(operands) {702 var elements = [];703 if (operands.length > 3)704 elements = operands[2];705 return {706 isLiteral: elements.every(x => x.isLiteral),707 opNodes: elements,708 command: new BuildListCommand(...elements),709 clone: function() {710 return buildList(cloneOperands(operands));711 },712 toString: () => "buildList",713 text: "[" + elements.map(x => x.text).join(", ") + "]",714 formatTrace: (...xs) => combineStrings("[", joinStrings(xs, ", "), "]"),715 };716}717/** buildListAssignment718 * create op node that assigns719 * a value to a list720 *721 * pattern:722 * assignment -> expr "[" _ expr _ "]" _ "=" _ expr 723 */724function buildListAssignment(operands) {725 var listNode = operands[0];726 var indexNode = operands[3];727 var rValueNode = operands[9];728 return {729 isLiteral: false,730 opNodes: [],731 command: new AssignListElementCommand(listNode, indexNode, rValueNode),732 clone: function() {733 return buildListAssignment(cloneOperands(operands));734 },735 toString: () => "buildListAssignment",736 text: operands[0].text + "[" + operands[3].text + "] = " + operands[9].text, 737 formatTrace: (o1, o2, o3) => combineStrings(o1, "[", o2, "] = ", o),738 };739}740/** buildPropGet741 * create node that performs property access742 * on result of expression743 *744 * pattern:745 * propGet -> expr "." %varName 746 */747function buildPropGet(operands) {748 var receiverNode = operands[0];749 var propName = operands[2].text;750 return { 751 isLiteral: false,752 opNodes: [],753 command: new GetPropertyCommand(receiverNode, propName),754 clone: function() {755 return buildPropGet(cloneOperands(operands));756 },757 toString: () => "buildPropGet",758 text: operands[0].text + "." + propName,759 formatTrace: (op) => combineStrings(op, ".", propName),760 };761}762/** buildConjunction763 * pattern: 764 * bool -> bool _ %AND _ disj 765 */766function buildConjunction(operands) {767 var opNode1 = operands[0];768 var opNode2 = operands[4];769 return {770 isLiteral: opNode1.isLiteral && opNode2.isLiteral,771 opNodes: [opNode1, opNode2],772 command: new ConjunctionCommand(opNode1, opNode2),773 clone: function() {774 return buildConjunction(cloneOperands(operands));775 },776 toString: () => "buildConjunction",777 text: opNode1.text + " && " + opNode2.text,778 formatTrace: (o1, o2) => combineStrings(o1, " && ", o2),779 };780}781/** buildDisjunction782 * pattern:783 * disj -> disj _ %OR _ not 784 */785function buildDisjunction(operands) {786 var opNode1 = operands[0];787 var opNode2 = operands[4];788 return {789 isLiteral: opNode1.isLiteral && opNode2.isLiteral,790 opNodes: [opNode1, opNode2],791 command: new DisjunctionCommand(opNode1, opNode2),792 clone: function() {793 return buildDisjunction(cloneOperands(operands));794 },795 toString: () => "buildDisjunction",796 text: opNode1.text + " || " + opNode2.text,797 formatTrace: (o1, o2) => combineStrings(o1, " || ", o2),798 };799}800/** buildLogicalNot801 * pattern:802 * not -> %NOT _ boolTerminal 803 */804function buildLogicalNot(operands) {805 var opNode1 = operands[2];806 return {807 isLiteral: opNode1.isLiteral,808 opNodes: [opNode1],809 command: new LogicalNotCommand(opNode1),810 clone: function() {811 return buildLogicalNot(cloneOperands(operands));812 },813 toString: () => "buildLogicalNot",814 text: "! " + opNode1.text,815 formatTrace: op => combineStrings("! ", op),816 };817}818/**819 * pattern:820 * eqcomp -> eqcomp _ %EQEQ _ noteqcomp 821 */822function buildEquals(operands) {823 var opNode1 = operands[0];824 var opNode2 = operands[4];825 return {826 isLiteral: opNode1.isLiteral && opNode2.isLiteral,827 opNodes: [opNode1, opNode2],828 command: new LogicalEqualsCommand(opNode1, opNode2),829 clone: function() {830 return buildEquals(cloneOperands(operands));831 },832 toString: () => "buildEquals",833 text: opNode1.text + " == " + opNode2.text,834 formatTrace: (o1, o2) => combineStrings(o1, " == ", o2),835 };836}837/** buildNotEquals838 * pattern:839 * noteqcomp -> noteqcomp _ %NOTEQ _ lcomp 840 */841function buildNotEquals(operands) {842 var opNode1 = operands[0];843 var opNode2 = operands[4];844 return {845 isLiteral: opNode1.isLiteral && opNode2.isLiteral,846 opNodes: [opNode1, opNode2],847 command: new LogicalNotEqualsCommand(opNode1, opNode2),848 clone: function() {849 return buildNotEquals(cloneOperands(operands));850 },851 toString: () => "buildNotEquals",852 text: opNode1.text + " != " + opNode2.text,853 formatTrace: (o1, o2) => combineStrings(o1, " != ", o2),854 };855}856/** buildDictArgs857 * return array of [key, value] pair (arrays)858 * 859 * dictPair -> %varName _ ":" _ expr [d[0], d[4]]860 * 861 * dictArgs -> dictPair (_ "," _ dictPair):* 862 * 863 * safe to execute because keys must be864 * number or str865 */866function buildDictArgs(operands) {867 var keys = [operands[0][0].command.execute()];868 var values = [operands[0][1]];869 for (var idx in operands[1]) {870 keys.push(operands[1][idx][3][0].command.execute());871 values.push(operands[1][idx][3][1]);872 }873 return [keys, values];874}875/** buildDict876 * build dictionary AST node877 * 878 * for now, dictionary keys must be literals or879 * variables, which are evaluated once and 880 * those literals values are used. 881 * For instance:882 * i = 3883 * d = { i : "asdf" } 884 * i = 5885 * d[3] still == "asdf" (not d[5])886 *887 */888function buildDict(operands) {889 var keys = [];890 var values = [];891 if (operands.length > 3) {892 keys = operands[2][0];893 values = operands[2][1];894 }895 return {896 isLiteral: values.every(x => x.isLiteral),897 opNodes: values,898 command: new BuildDictCommand(keys, ...values),899 clone: function() {900 return buildDict(cloneOperands(operands));901 },902 toString: () => "buildDict",903 text: "{ " 904 + keys.map((x, i) => stringify(x) + " : " + values[i].text).join(", ")905 + " }",906 formatTrace: (...vs) => { 907 return combineStrings("{ ", 908 ...joinStrings(keys.map((k, i) => combineStrings(...joinStrings([k, " : ", vs[i]]))), ", "),909 "}");910 },911 };912}913/** buildFunctionDefinition914 * build AST node for function definition915 * when executed it binds the name to 916 * a new UserFunctionCommand object917 * 918 * pattern:919 * funcdef -> 920 * %DEF " " %varName _ "(" _ funcdefargs _ ")" _ block921 * %DEF " " %varName _ "(" ")" _ block922 */923function buildFunctionDefinition(operands) {924 var funcName = operands[2].text;925 var argNames = [];926 if (operands.length > 8) 927 argNames = operands[6].map(x => x.text);928 var funcStatements = operands[operands.length - 1];929 return {930 isFunctionDef: true,931 isLiteral: false,932 opNodes: funcStatements,933 command: { 934 execute: function() {935 createFunctionDefinition(funcName, argNames, funcStatements);936 this.defined = true;937 },938 undo: function() {939 if (this.defined) // don't undo unless it was successfully defined940 undoFunctionDefinition(funcName);941 }942 },943 clone: function() {944 return buildFunctionDefinition(cloneOperands(operands));945 },946 toString: () => "buildFunctionDefinition",947 text: `define ${funcName}(${argNames.join(", ")}) {\n ${funcStatements.map(x => x.text).join(";\n")} \n}`,948 };949}950/** buildReturn951 * build AST node for return statement952 * pattern:953 * return -> %RET " " expr954 */955function buildReturn(operands) {956 var exprNode = operands[2];957 return {958 isLiteral: false,959 opNodes: [exprNode],960 command: new ReturnCommand(exprNode),961 clone: function() {962 return buildReturn(cloneOperands(operands));963 },964 toString: () => "buildReturn",965 text: "return " + exprNode.text,966 formatTrace: op => combineStrings("return ", op),967 };968}969/** buildIf970 * build AST node (opNode) for if-else if-else block.971 * note elseIf and else return arrays of pairs (2 element arrays)972 * [bool expr, [lines]]973 * If block command object is parameterized with complete 974 * array of [bool expr, [lines]], so if, else if, and else 975 * arrays must be combined976 *977 * pattern:978 * %IF _ "(" _ bool _ ")" _ block (_ elseIf):* (_ else):? 979 */980function buildIf(operands) {981 var condBlockPairs = [];982 condBlockPairs.push([operands[4], operands[8]]);983 var elseIfIdx = 9;984 for (var idx in operands[elseIfIdx])985 condBlockPairs.push(operands[elseIfIdx][idx][1]);986 987 // if final else block988 var finalElse = false; 989 if (operands[operands.length - 1]) {990 condBlockPairs.push(operands[operands.length - 1][1]);991 finalElse = true;992 }993 return {994 isLiteral: false,995 opNodes: condBlockPairs,996 command: new IfBlockCommand(condBlockPairs, finalElse),997 clone: function() {998 return buildIf(cloneOperands(operands));999 },1000 toString: () => "buildIf",1001 text: breakLines(...ifBlockText(condBlockPairs, finalElse)),1002 };1003}1004/** buildElseIf1005 * return arrays of pairs (2 element arrays)1006 * [bool expr, [lines]]1007 *1008 * pattern:1009 * elseIf -> %ELIF _ "(" _ bool _ ")" _ block 1010 */1011function buildElseIf(operands) {1012 return [operands[4], operands[8]];1013}1014/** buildElse1015 * return arrays of pairs (2 element arrays)1016 * [bool expr, [lines]]1017 *1018 * pattern:1019 * else -> %ELSE _ block 1020 */1021function buildElse(operands) {1022 return [wrapBool(["true"]), operands[2]];1023}1024/** buildCodeBlock1025 * return array of line opNodes1026 * pattern: 1027 * block -> (line _):* 1028 */1029function buildCodeBlock(operands) { 1030 var lines = [];1031 for (var idx in operands[0])1032 lines.push(operands[0][idx][0]);1033 return { 1034 isLiteral: false,1035 opNodes: lines,1036 command: new CodeBlockCommand(lines),1037 clone: function() {1038 return buildCodeBlock(cloneOperands(operands));1039 },1040 toString: () => "buildCodeBlock",1041 text: lines.map(x => x.text).join(";\n"),1042 }1043}1044var grammar = {1045 Lexer: lexer,1046 ParserRules: [1047 {"name": "unsigned_int$ebnf$1", "symbols": [/[0-9]/]},1048 {"name": "unsigned_int$ebnf$1", "symbols": ["unsigned_int$ebnf$1", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1049 {"name": "unsigned_int", "symbols": ["unsigned_int$ebnf$1"], "postprocess": 1050 function(d) {1051 return parseInt(d[0].join(""));1052 }1053 },1054 {"name": "int$ebnf$1$subexpression$1", "symbols": [{"literal":"-"}]},1055 {"name": "int$ebnf$1$subexpression$1", "symbols": [{"literal":"+"}]},1056 {"name": "int$ebnf$1", "symbols": ["int$ebnf$1$subexpression$1"], "postprocess": id},1057 {"name": "int$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},1058 {"name": "int$ebnf$2", "symbols": [/[0-9]/]},1059 {"name": "int$ebnf$2", "symbols": ["int$ebnf$2", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1060 {"name": "int", "symbols": ["int$ebnf$1", "int$ebnf$2"], "postprocess": 1061 function(d) {1062 if (d[0]) {1063 return parseInt(d[0][0]+d[1].join(""));1064 } else {1065 return parseInt(d[1].join(""));1066 }1067 }1068 },1069 {"name": "unsigned_decimal$ebnf$1", "symbols": [/[0-9]/]},1070 {"name": "unsigned_decimal$ebnf$1", "symbols": ["unsigned_decimal$ebnf$1", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1071 {"name": "unsigned_decimal$ebnf$2$subexpression$1$ebnf$1", "symbols": [/[0-9]/]},1072 {"name": "unsigned_decimal$ebnf$2$subexpression$1$ebnf$1", "symbols": ["unsigned_decimal$ebnf$2$subexpression$1$ebnf$1", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1073 {"name": "unsigned_decimal$ebnf$2$subexpression$1", "symbols": [{"literal":"."}, "unsigned_decimal$ebnf$2$subexpression$1$ebnf$1"]},1074 {"name": "unsigned_decimal$ebnf$2", "symbols": ["unsigned_decimal$ebnf$2$subexpression$1"], "postprocess": id},1075 {"name": "unsigned_decimal$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},1076 {"name": "unsigned_decimal", "symbols": ["unsigned_decimal$ebnf$1", "unsigned_decimal$ebnf$2"], "postprocess": 1077 function(d) {1078 return parseFloat(1079 d[0].join("") +1080 (d[1] ? "."+d[1][1].join("") : "")1081 );1082 }1083 },1084 {"name": "decimal$ebnf$1", "symbols": [{"literal":"-"}], "postprocess": id},1085 {"name": "decimal$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},1086 {"name": "decimal$ebnf$2", "symbols": [/[0-9]/]},1087 {"name": "decimal$ebnf$2", "symbols": ["decimal$ebnf$2", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1088 {"name": "decimal$ebnf$3$subexpression$1$ebnf$1", "symbols": [/[0-9]/]},1089 {"name": "decimal$ebnf$3$subexpression$1$ebnf$1", "symbols": ["decimal$ebnf$3$subexpression$1$ebnf$1", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1090 {"name": "decimal$ebnf$3$subexpression$1", "symbols": [{"literal":"."}, "decimal$ebnf$3$subexpression$1$ebnf$1"]},1091 {"name": "decimal$ebnf$3", "symbols": ["decimal$ebnf$3$subexpression$1"], "postprocess": id},1092 {"name": "decimal$ebnf$3", "symbols": [], "postprocess": function(d) {return null;}},1093 {"name": "decimal", "symbols": ["decimal$ebnf$1", "decimal$ebnf$2", "decimal$ebnf$3"], "postprocess": 1094 function(d) {1095 return parseFloat(1096 (d[0] || "") +1097 d[1].join("") +1098 (d[2] ? "."+d[2][1].join("") : "")1099 );1100 }1101 },1102 {"name": "percentage", "symbols": ["decimal", {"literal":"%"}], "postprocess": 1103 function(d) {1104 return d[0]/100;1105 }1106 },1107 {"name": "jsonfloat$ebnf$1", "symbols": [{"literal":"-"}], "postprocess": id},1108 {"name": "jsonfloat$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},1109 {"name": "jsonfloat$ebnf$2", "symbols": [/[0-9]/]},1110 {"name": "jsonfloat$ebnf$2", "symbols": ["jsonfloat$ebnf$2", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1111 {"name": "jsonfloat$ebnf$3$subexpression$1$ebnf$1", "symbols": [/[0-9]/]},1112 {"name": "jsonfloat$ebnf$3$subexpression$1$ebnf$1", "symbols": ["jsonfloat$ebnf$3$subexpression$1$ebnf$1", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1113 {"name": "jsonfloat$ebnf$3$subexpression$1", "symbols": [{"literal":"."}, "jsonfloat$ebnf$3$subexpression$1$ebnf$1"]},1114 {"name": "jsonfloat$ebnf$3", "symbols": ["jsonfloat$ebnf$3$subexpression$1"], "postprocess": id},1115 {"name": "jsonfloat$ebnf$3", "symbols": [], "postprocess": function(d) {return null;}},1116 {"name": "jsonfloat$ebnf$4$subexpression$1$ebnf$1", "symbols": [/[+-]/], "postprocess": id},1117 {"name": "jsonfloat$ebnf$4$subexpression$1$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},1118 {"name": "jsonfloat$ebnf$4$subexpression$1$ebnf$2", "symbols": [/[0-9]/]},1119 {"name": "jsonfloat$ebnf$4$subexpression$1$ebnf$2", "symbols": ["jsonfloat$ebnf$4$subexpression$1$ebnf$2", /[0-9]/], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1120 {"name": "jsonfloat$ebnf$4$subexpression$1", "symbols": [/[eE]/, "jsonfloat$ebnf$4$subexpression$1$ebnf$1", "jsonfloat$ebnf$4$subexpression$1$ebnf$2"]},1121 {"name": "jsonfloat$ebnf$4", "symbols": ["jsonfloat$ebnf$4$subexpression$1"], "postprocess": id},1122 {"name": "jsonfloat$ebnf$4", "symbols": [], "postprocess": function(d) {return null;}},1123 {"name": "jsonfloat", "symbols": ["jsonfloat$ebnf$1", "jsonfloat$ebnf$2", "jsonfloat$ebnf$3", "jsonfloat$ebnf$4"], "postprocess": 1124 function(d) {1125 return parseFloat(1126 (d[0] || "") +1127 d[1].join("") +1128 (d[2] ? "."+d[2][1].join("") : "") +1129 (d[3] ? "e" + (d[3][1] || "+") + d[3][2].join("") : "")1130 );1131 }1132 },1133 {"name": "_$ebnf$1", "symbols": []},1134 {"name": "_$ebnf$1", "symbols": ["_$ebnf$1", "wschar"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1135 {"name": "_", "symbols": ["_$ebnf$1"], "postprocess": function(d) {return null;}},1136 {"name": "__$ebnf$1", "symbols": ["wschar"]},1137 {"name": "__$ebnf$1", "symbols": ["__$ebnf$1", "wschar"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1138 {"name": "__", "symbols": ["__$ebnf$1"], "postprocess": function(d) {return null;}},1139 {"name": "wschar", "symbols": [/[ \t\n\v\f]/], "postprocess": id},1140 {"name": "codeblock", "symbols": ["statement"], "postprocess": d => buildCodeBlock([d.map(x => [x, null])])},1141 {"name": "codeblock$ebnf$1$subexpression$1", "symbols": ["code", "_"]},1142 {"name": "codeblock$ebnf$1", "symbols": ["codeblock$ebnf$1$subexpression$1"]},1143 {"name": "codeblock$ebnf$1$subexpression$2", "symbols": ["code", "_"]},1144 {"name": "codeblock$ebnf$1", "symbols": ["codeblock$ebnf$1", "codeblock$ebnf$1$subexpression$2"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1145 {"name": "codeblock", "symbols": ["codeblock$ebnf$1"], "postprocess": buildCodeBlock},1146 {"name": "code", "symbols": ["line"], "postprocess": id},1147 {"name": "code", "symbols": ["funcdef"], "postprocess": id},1148 {"name": "line", "symbols": ["statement", "_", {"literal":";"}], "postprocess": id},1149 {"name": "line", "symbols": ["controlBlock"], "postprocess": id},1150 {"name": "controlBlock", "symbols": ["forLoop"], "postprocess": id},1151 {"name": "controlBlock", "symbols": ["whileLoop"], "postprocess": id},1152 {"name": "controlBlock", "symbols": ["if"], "postprocess": id},1153 {"name": "statement", "symbols": ["assignment"], "postprocess": id},1154 {"name": "statement", "symbols": ["expr"], "postprocess": id},1155 {"name": "statement", "symbols": ["return"], "postprocess": id},1156 {"name": "assignment", "symbols": [(lexer.has("varName") ? {type: "varName"} : varName), "_", {"literal":"="}, "_", "expr"], "postprocess": buildAssignment},1157 {"name": "assignment", "symbols": ["expr", (lexer.has("DOT") ? {type: "DOT"} : DOT), (lexer.has("varName") ? {type: "varName"} : varName), "_", {"literal":"="}, "_", "expr"], "postprocess": buildRangePropertyAssignment},1158 {"name": "assignment", "symbols": ["expr", {"literal":"["}, "_", "expr", "_", {"literal":"]"}, "_", {"literal":"="}, "_", "expr"], "postprocess": buildListAssignment},1159 {"name": "assignment", "symbols": [{"literal":"$"}, (lexer.has("varName") ? {type: "varName"} : varName), "_", {"literal":"="}, "_", "expr"], "postprocess": buildBuckSet},1160 {"name": "expr", "symbols": ["bool"], "postprocess": id},1161 {"name": "bool", "symbols": ["bool", "_", (lexer.has("AND") ? {type: "AND"} : AND), "_", "disj"], "postprocess": buildConjunction},1162 {"name": "bool", "symbols": ["disj"], "postprocess": id},1163 {"name": "disj", "symbols": ["disj", "_", (lexer.has("OR") ? {type: "OR"} : OR), "_", "not"], "postprocess": buildDisjunction},1164 {"name": "disj", "symbols": ["eqcomp"], "postprocess": id},1165 {"name": "eqcomp", "symbols": ["eqcomp", "_", (lexer.has("EQEQ") ? {type: "EQEQ"} : EQEQ), "_", "noteqcomp"], "postprocess": buildEquals},1166 {"name": "eqcomp", "symbols": ["noteqcomp"], "postprocess": id},1167 {"name": "noteqcomp", "symbols": ["noteqcomp", "_", (lexer.has("NOTEQ") ? {type: "NOTEQ"} : NOTEQ), "_", "lcomp"], "postprocess": buildNotEquals},1168 {"name": "noteqcomp", "symbols": ["lcomp"], "postprocess": id},1169 {"name": "lcomp", "symbols": ["lcomp", "_", {"literal":"<"}, "_", "gcomp"], "postprocess": buildComparison},1170 {"name": "lcomp", "symbols": ["gcomp"], "postprocess": id},1171 {"name": "gcomp", "symbols": ["gcomp", "_", {"literal":">"}, "_", "lecomp"], "postprocess": buildComparison},1172 {"name": "gcomp", "symbols": ["lecomp"], "postprocess": id},1173 {"name": "lecomp", "symbols": ["lecomp", "_", (lexer.has("LESSEQ") ? {type: "LESSEQ"} : LESSEQ), "_", "gecomp"], "postprocess": buildComparison},1174 {"name": "lecomp", "symbols": ["gecomp"], "postprocess": id},1175 {"name": "gecomp", "symbols": ["gecomp", "_", (lexer.has("GREATEQ") ? {type: "GREATEQ"} : GREATEQ), "_", "not"], "postprocess": buildComparison},1176 {"name": "gecomp", "symbols": ["not"], "postprocess": id},1177 {"name": "not", "symbols": [(lexer.has("NOT") ? {type: "NOT"} : NOT), "_", "boolTerminal"], "postprocess": buildLogicalNot},1178 {"name": "not", "symbols": ["boolTerminal"], "postprocess": id},1179 {"name": "boolTerminal", "symbols": ["math"], "postprocess": id},1180 {"name": "boolTerminal", "symbols": [(lexer.has("TRUE") ? {type: "TRUE"} : TRUE)], "postprocess": wrapBool},1181 {"name": "boolTerminal", "symbols": [(lexer.has("FALSE") ? {type: "FALSE"} : FALSE)], "postprocess": wrapBool},1182 {"name": "comparator$subexpression$1", "symbols": [{"literal":"<"}]},1183 {"name": "comparator$subexpression$1", "symbols": [{"literal":">"}]},1184 {"name": "comparator$subexpression$1", "symbols": [(lexer.has("LESSEQ") ? {type: "LESSEQ"} : LESSEQ)]},1185 {"name": "comparator$subexpression$1", "symbols": [(lexer.has("GREATEQ") ? {type: "GREATEQ"} : GREATEQ)]},1186 {"name": "comparator$subexpression$1", "symbols": [(lexer.has("EQEQ") ? {type: "EQEQ"} : EQEQ)]},1187 {"name": "comparator$subexpression$1", "symbols": [(lexer.has("NOTEQ") ? {type: "NOTEQ"} : NOTEQ)]},1188 {"name": "comparator", "symbols": ["comparator$subexpression$1"], "postprocess": id},1189 {"name": "comp", "symbols": ["bool", "_", "comparator", "_", "bool"], "postprocess": buildComparison},1190 {"name": "math$subexpression$1", "symbols": [{"literal":"+"}]},1191 {"name": "math$subexpression$1", "symbols": [{"literal":"-"}]},1192 {"name": "math", "symbols": ["math", "_", "math$subexpression$1", "_", "product"], "postprocess": buildAddSub},1193 {"name": "math", "symbols": ["product"], "postprocess": id},1194 {"name": "product$subexpression$1", "symbols": [{"literal":"*"}]},1195 {"name": "product$subexpression$1", "symbols": [{"literal":"/"}]},1196 {"name": "product$subexpression$1", "symbols": [{"literal":"//"}]},1197 {"name": "product$subexpression$1", "symbols": [(lexer.has("MOD") ? {type: "MOD"} : MOD)]},1198 {"name": "product", "symbols": ["product", "_", "product$subexpression$1", "_", "exp"], "postprocess": buildMultDiv},1199 {"name": "product", "symbols": ["exp"], "postprocess": id},1200 {"name": "exp", "symbols": ["unaryNeg", "_", {"literal":"^"}, "_", "exp"], "postprocess": buildExp},1201 {"name": "exp", "symbols": ["unaryNeg"], "postprocess": id},1202 {"name": "unaryNeg", "symbols": [{"literal":"-"}, "mathTerminal"], "postprocess": buildNegate},1203 {"name": "unaryNeg", "symbols": ["mathTerminal"], "postprocess": id},1204 {"name": "nonQuote", "symbols": [{"literal":" "}]},1205 {"name": "nonQuote", "symbols": [{"literal":"\t"}]},1206 {"name": "nonQuote", "symbols": [{"literal":"\n"}]},1207 {"name": "nonQuote", "symbols": [{"literal":"-"}]},1208 {"name": "nonQuote", "symbols": [{"literal":"+"}]},1209 {"name": "nonQuote", "symbols": [{"literal":"*"}]},1210 {"name": "nonQuote", "symbols": [{"literal":"/"}]},1211 {"name": "nonQuote", "symbols": [{"literal":"//"}]},1212 {"name": "nonQuote", "symbols": [{"literal":"^"}]},1213 {"name": "nonQuote", "symbols": [(lexer.has("MOD") ? {type: "MOD"} : MOD)]},1214 {"name": "nonQuote", "symbols": [(lexer.has("LESSEQ") ? {type: "LESSEQ"} : LESSEQ)]},1215 {"name": "nonQuote", "symbols": [(lexer.has("GREATEQ") ? {type: "GREATEQ"} : GREATEQ)]},1216 {"name": "nonQuote", "symbols": [(lexer.has("EQEQ") ? {type: "EQEQ"} : EQEQ)]},1217 {"name": "nonQuote", "symbols": [(lexer.has("DOT") ? {type: "DOT"} : DOT)]},1218 {"name": "nonQuote", "symbols": [(lexer.has("NOTEQ") ? {type: "NOTEQ"} : NOTEQ)]},1219 {"name": "nonQuote", "symbols": [(lexer.has("TRUE") ? {type: "TRUE"} : TRUE)]},1220 {"name": "nonQuote", "symbols": [(lexer.has("FALSE") ? {type: "FALSE"} : FALSE)]},1221 {"name": "nonQuote", "symbols": [{"literal":">"}]},1222 {"name": "nonQuote", "symbols": [{"literal":"<"}]},1223 {"name": "nonQuote", "symbols": [{"literal":","}]},1224 {"name": "nonQuote", "symbols": [{"literal":"("}]},1225 {"name": "nonQuote", "symbols": [{"literal":")"}]},1226 {"name": "nonQuote", "symbols": [{"literal":"="}]},1227 {"name": "nonQuote", "symbols": [{"literal":"{"}]},1228 {"name": "nonQuote", "symbols": [(lexer.has("OR") ? {type: "OR"} : OR)]},1229 {"name": "nonQuote", "symbols": [(lexer.has("AND") ? {type: "AND"} : AND)]},1230 {"name": "nonQuote", "symbols": [(lexer.has("NOT") ? {type: "NOT"} : NOT)]},1231 {"name": "nonQuote", "symbols": [{"literal":"}"}]},1232 {"name": "nonQuote", "symbols": [{"literal":"["}]},1233 {"name": "nonQuote", "symbols": [{"literal":"]"}]},1234 {"name": "nonQuote", "symbols": [{"literal":";"}]},1235 {"name": "nonQuote", "symbols": [{"literal":":"}]},1236 {"name": "nonQuote", "symbols": [{"literal":"$"}]},1237 {"name": "nonQuote", "symbols": [(lexer.has("FOR") ? {type: "FOR"} : FOR)]},1238 {"name": "nonQuote", "symbols": [(lexer.has("WHILE") ? {type: "WHILE"} : WHILE)]},1239 {"name": "nonQuote", "symbols": [(lexer.has("IF") ? {type: "IF"} : IF)]},1240 {"name": "nonQuote", "symbols": [(lexer.has("ELSE") ? {type: "ELSE"} : ELSE)]},1241 {"name": "nonQuote", "symbols": [(lexer.has("ELIF") ? {type: "ELIF"} : ELIF)]},1242 {"name": "nonQuote", "symbols": [(lexer.has("DEF") ? {type: "DEF"} : DEF)]},1243 {"name": "nonQuote", "symbols": [(lexer.has("RET") ? {type: "RET"} : RET)]},1244 {"name": "nonQuote", "symbols": [(lexer.has("NULL") ? {type: "NULL"} : NULL)]},1245 {"name": "nonQuote", "symbols": [(lexer.has("number") ? {type: "number"} : number)]},1246 {"name": "nonQuote", "symbols": [(lexer.has("varName") ? {type: "varName"} : varName)]},1247 {"name": "nonQuote", "symbols": [(lexer.has("character") ? {type: "character"} : character)]},1248 {"name": "string$ebnf$1", "symbols": []},1249 {"name": "string$ebnf$1", "symbols": ["string$ebnf$1", "nonQuote"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1250 {"name": "string", "symbols": [(lexer.has("QUOTE") ? {type: "QUOTE"} : QUOTE), "string$ebnf$1", (lexer.has("QUOTE") ? {type: "QUOTE"} : QUOTE)], "postprocess": wrapString},1251 {"name": "mathTerminal", "symbols": ["number"], "postprocess": id},1252 {"name": "mathTerminal", "symbols": ["callable"], "postprocess": id},1253 {"name": "mathTerminal", "symbols": ["accessor"], "postprocess": id},1254 {"name": "mathTerminal", "symbols": ["list"], "postprocess": id},1255 {"name": "mathTerminal", "symbols": ["dict"], "postprocess": id},1256 {"name": "mathTerminal", "symbols": ["string"], "postprocess": id},1257 {"name": "mathTerminal", "symbols": [(lexer.has("NULL") ? {type: "NULL"} : NULL)], "postprocess": wrapNull},1258 {"name": "mathTerminal", "symbols": [(lexer.has("varName") ? {type: "varName"} : varName)], "postprocess": buildVariable},1259 {"name": "mathTerminal", "symbols": [{"literal":"$"}, (lexer.has("varName") ? {type: "varName"} : varName)], "postprocess": buildBuckGet},1260 {"name": "mathTerminal", "symbols": [{"literal":"("}, "_", "bool", "_", {"literal":")"}], "postprocess": d => d[2]},1261 {"name": "mathTerminal", "symbols": ["propGet"], "postprocess": id},1262 {"name": "number", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": wrapNumber},1263 {"name": "list", "symbols": [{"literal":"["}, "_", {"literal":"]"}], "postprocess": buildList},1264 {"name": "list", "symbols": [{"literal":"["}, "_", "args", "_", {"literal":"]"}], "postprocess": buildList},1265 {"name": "accessor", "symbols": ["objExpr", {"literal":"["}, "_", "expr", "_", {"literal":"]"}], "postprocess": buildSingleAccess},1266 {"name": "accessor$ebnf$1$subexpression$1", "symbols": ["expr", "_"]},1267 {"name": "accessor$ebnf$1", "symbols": ["accessor$ebnf$1$subexpression$1"], "postprocess": id},1268 {"name": "accessor$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},1269 {"name": "accessor$ebnf$2$subexpression$1", "symbols": ["expr", "_"]},1270 {"name": "accessor$ebnf$2", "symbols": ["accessor$ebnf$2$subexpression$1"], "postprocess": id},1271 {"name": "accessor$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},1272 {"name": "accessor", "symbols": ["objExpr", {"literal":"["}, "_", "accessor$ebnf$1", {"literal":":"}, "_", "accessor$ebnf$2", {"literal":"]"}], "postprocess": buildRangeAccess},1273 {"name": "objExpr", "symbols": ["callable"], "postprocess": id},1274 {"name": "objExpr", "symbols": ["dict"], "postprocess": id},1275 {"name": "objExpr", "symbols": ["accessor"], "postprocess": id},1276 {"name": "objExpr", "symbols": ["list"], "postprocess": id},1277 {"name": "objExpr", "symbols": ["propGet"], "postprocess": id},1278 {"name": "objExpr", "symbols": [(lexer.has("varName") ? {type: "varName"} : varName)], "postprocess": buildVariable},1279 {"name": "objExpr", "symbols": [{"literal":"$"}, (lexer.has("varName") ? {type: "varName"} : varName)], "postprocess": buildBuckGet},1280 {"name": "propGet", "symbols": ["objExpr", (lexer.has("DOT") ? {type: "DOT"} : DOT), (lexer.has("varName") ? {type: "varName"} : varName)], "postprocess": buildPropGet},1281 {"name": "callable", "symbols": ["function"], "postprocess": id},1282 {"name": "buck", "symbols": [{"literal":"$"}, {"literal":"("}, "_", "args", "_", {"literal":")"}], "postprocess": buildFunctionCall},1283 {"name": "function", "symbols": ["objExpr", {"literal":"("}, "_", "args", "_", {"literal":")"}], "postprocess": buildFunctionCall},1284 {"name": "function", "symbols": ["objExpr", {"literal":"("}, {"literal":")"}], "postprocess": buildFunctionCall},1285 {"name": "function", "symbols": ["buck"], "postprocess": id},1286 {"name": "args$ebnf$1", "symbols": []},1287 {"name": "args$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", "funcarg"]},1288 {"name": "args$ebnf$1", "symbols": ["args$ebnf$1", "args$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1289 {"name": "args", "symbols": ["funcarg", "args$ebnf$1"], "postprocess": buildFunctionArguments},1290 {"name": "funcarg", "symbols": ["expr"], "postprocess": id},1291 {"name": "unquotedString", "symbols": [(lexer.has("varName") ? {type: "varName"} : varName)], "postprocess": wrapUnquotedString},1292 {"name": "strOrNum", "symbols": ["unquotedString"], "postprocess": id},1293 {"name": "strOrNum", "symbols": ["number"], "postprocess": id},1294 {"name": "strOrNum", "symbols": ["string"], "postprocess": id},1295 {"name": "dictArgs$ebnf$1", "symbols": []},1296 {"name": "dictArgs$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", "dictPair"]},1297 {"name": "dictArgs$ebnf$1", "symbols": ["dictArgs$ebnf$1", "dictArgs$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1298 {"name": "dictArgs", "symbols": ["dictPair", "dictArgs$ebnf$1"], "postprocess": buildDictArgs},1299 {"name": "dictPair", "symbols": ["strOrNum", "_", {"literal":":"}, "_", "expr"], "postprocess": d => [d[0], d[4]]},1300 {"name": "dict", "symbols": [{"literal":"{"}, {"literal":"}"}], "postprocess": buildDict},1301 {"name": "dict", "symbols": [{"literal":"{"}, "_", "dictArgs", "_", {"literal":"}"}], "postprocess": buildDict},1302 {"name": "commaSepStatements$ebnf$1", "symbols": []},1303 {"name": "commaSepStatements$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", "statement"]},1304 {"name": "commaSepStatements$ebnf$1", "symbols": ["commaSepStatements$ebnf$1", "commaSepStatements$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1305 {"name": "commaSepStatements", "symbols": ["statement", "commaSepStatements$ebnf$1"], "postprocess": buildCommaSepStatements},1306 {"name": "forPars$ebnf$1$subexpression$1", "symbols": ["commaSepStatements", "_"]},1307 {"name": "forPars$ebnf$1", "symbols": ["forPars$ebnf$1$subexpression$1"], "postprocess": id},1308 {"name": "forPars$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}},1309 {"name": "forPars$ebnf$2$subexpression$1", "symbols": ["bool", "_"]},1310 {"name": "forPars$ebnf$2", "symbols": ["forPars$ebnf$2$subexpression$1"], "postprocess": id},1311 {"name": "forPars$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},1312 {"name": "forPars$ebnf$3$subexpression$1", "symbols": ["commaSepStatements", "_"]},1313 {"name": "forPars$ebnf$3", "symbols": ["forPars$ebnf$3$subexpression$1"], "postprocess": id},1314 {"name": "forPars$ebnf$3", "symbols": [], "postprocess": function(d) {return null;}},1315 {"name": "forPars", "symbols": [{"literal":"("}, "_", "forPars$ebnf$1", {"literal":";"}, "_", "forPars$ebnf$2", {"literal":";"}, "_", "forPars$ebnf$3", {"literal":")"}], "postprocess": buildForPars},1316 {"name": "forLoop", "symbols": [(lexer.has("FOR") ? {type: "FOR"} : FOR), "_", "forPars", "_", "block"], "postprocess": buildForLoop},1317 {"name": "whileLoop", "symbols": [(lexer.has("WHILE") ? {type: "WHILE"} : WHILE), "_", {"literal":"("}, "_", "bool", "_", {"literal":")"}, "_", "block"], "postprocess": buildWhileLoop},1318 {"name": "block$ebnf$1", "symbols": []},1319 {"name": "block$ebnf$1$subexpression$1", "symbols": ["line", "_"]},1320 {"name": "block$ebnf$1", "symbols": ["block$ebnf$1", "block$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1321 {"name": "block", "symbols": [{"literal":"{"}, "_", "block$ebnf$1", {"literal":"}"}], "postprocess": buildBlock},1322 {"name": "if$ebnf$1", "symbols": []},1323 {"name": "if$ebnf$1$subexpression$1", "symbols": ["_", "elseIf"]},1324 {"name": "if$ebnf$1", "symbols": ["if$ebnf$1", "if$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1325 {"name": "if$ebnf$2$subexpression$1", "symbols": ["_", "else"]},1326 {"name": "if$ebnf$2", "symbols": ["if$ebnf$2$subexpression$1"], "postprocess": id},1327 {"name": "if$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}},1328 {"name": "if", "symbols": [(lexer.has("IF") ? {type: "IF"} : IF), "_", {"literal":"("}, "_", "bool", "_", {"literal":")"}, "_", "block", "if$ebnf$1", "if$ebnf$2"], "postprocess": buildIf},1329 {"name": "elseIf", "symbols": [(lexer.has("ELIF") ? {type: "ELIF"} : ELIF), "_", {"literal":"("}, "_", "bool", "_", {"literal":")"}, "_", "block"], "postprocess": buildElseIf},1330 {"name": "else", "symbols": [(lexer.has("ELSE") ? {type: "ELSE"} : ELSE), "_", "block"], "postprocess": buildElse},1331 {"name": "funcdefargs$ebnf$1", "symbols": []},1332 {"name": "funcdefargs$ebnf$1$subexpression$1", "symbols": ["_", {"literal":","}, "_", (lexer.has("varName") ? {type: "varName"} : varName)]},1333 {"name": "funcdefargs$ebnf$1", "symbols": ["funcdefargs$ebnf$1", "funcdefargs$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}},1334 {"name": "funcdefargs", "symbols": [(lexer.has("varName") ? {type: "varName"} : varName), "funcdefargs$ebnf$1"], "postprocess": buildCommaSepStatements},1335 {"name": "funcdef", "symbols": [(lexer.has("DEF") ? {type: "DEF"} : DEF), {"literal":" "}, (lexer.has("varName") ? {type: "varName"} : varName), "_", {"literal":"("}, "_", "funcdefargs", "_", {"literal":")"}, "_", "block"], "postprocess": buildFunctionDefinition},1336 {"name": "funcdef", "symbols": [(lexer.has("DEF") ? {type: "DEF"} : DEF), {"literal":" "}, (lexer.has("varName") ? {type: "varName"} : varName), "_", {"literal":"("}, {"literal":")"}, "_", "block"], "postprocess": buildFunctionDefinition},1337 {"name": "return", "symbols": [(lexer.has("RET") ? {type: "RET"} : RET), {"literal":" "}, "expr"], "postprocess": buildReturn}1338]1339 , ParserStart: "codeblock"1340}1341if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') {1342 module.exports = grammar;1343} else {1344 window.grammar = grammar;1345}...

Full Screen

Full Screen

HttpLogger.js

Source:HttpLogger.js Github

copy

Full Screen

1"use strict";2function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }3function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }4function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }5function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }6function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }7function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }8function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }9function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }10function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }11function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }12function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }13function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }14function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }15/* eslint-disable no-undef */16var globalFetch = typeof window !== 'undefined' && window.fetch || typeof global !== 'undefined' && global.fetch; // eslint-disable-next-line global-require17var fetch = globalFetch || require('node-fetch');18var _require = require('zipkin'),19 JSON_V1 = _require.jsonEncoder.JSON_V1;20var _require2 = require('events'),21 EventEmitter = _require2.EventEmitter;22var defaultFetchImpl = fetch;23var HttpLogger = /*#__PURE__*/function (_EventEmitter) {24 _inherits(HttpLogger, _EventEmitter);25 var _super = _createSuper(HttpLogger);26 /**27 * @constructor28 * @param {Object} options29 * @param {string} options.endpoint HTTP endpoint which spans will be sent30 * @param {number} options.httpInterval How often to sync spans.31 * @param {JsonEncoder} options.jsonEncoder JSON encoder to use when sending spans.32 * @param {number} options.timeout Timeout for HTTP Post when sending spans.33 * @param {number} options.maxPayloadSize Max payload size for zipkin span.34 * @param {Object<string, string>} options.headers Additional HTTP headers to be sent with span.35 * @param {Agent|Function} options.agent HTTP(S) agent to use for any networking related options.36 * @param {ErrorLogger} options.log Internal error logger used within the transport.37 * @param {(url: string, options: object) => Promise<Response>} options.fetchImplementation38 */39 function HttpLogger(_ref) {40 var _this;41 var endpoint = _ref.endpoint,42 _ref$headers = _ref.headers,43 headers = _ref$headers === void 0 ? {} : _ref$headers,44 _ref$agent = _ref.agent,45 agent = _ref$agent === void 0 ? null : _ref$agent,46 _ref$httpInterval = _ref.httpInterval,47 httpInterval = _ref$httpInterval === void 0 ? 1000 : _ref$httpInterval,48 _ref$jsonEncoder = _ref.jsonEncoder,49 jsonEncoder = _ref$jsonEncoder === void 0 ? JSON_V1 : _ref$jsonEncoder,50 _ref$timeout = _ref.timeout,51 timeout = _ref$timeout === void 0 ? 0 : _ref$timeout,52 _ref$maxPayloadSize = _ref.maxPayloadSize,53 maxPayloadSize = _ref$maxPayloadSize === void 0 ? 0 : _ref$maxPayloadSize,54 _ref$log = _ref.log,55 log = _ref$log === void 0 ? console : _ref$log,56 _ref$fetchImplementat = _ref.fetchImplementation,57 fetchImplementation = _ref$fetchImplementat === void 0 ? defaultFetchImpl : _ref$fetchImplementat;58 _classCallCheck(this, HttpLogger);59 _this = _super.call(this); // must be before any reference to *this*60 _this.log = log;61 _this.endpoint = endpoint;62 _this.agent = agent;63 _this.maxPayloadSize = maxPayloadSize;64 _this.queue = [];65 _this.queueBytes = 0;66 _this.jsonEncoder = jsonEncoder;67 _this.fetchImplementation = fetchImplementation;68 _this.errorListenerSet = false;69 _this.headers = Object.assign({70 'Content-Type': 'application/json'71 }, headers); // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)72 // only supported by node-fetch; silently ignored by browser fetch clients73 // @see https://github.com/bitinn/node-fetch#fetch-options74 _this.timeout = timeout;75 var timer = setInterval(function () {76 _this.processQueue(_this.fetchImplementation);77 }, httpInterval);78 if (timer.unref) {79 // unref might not be available in browsers80 timer.unref(); // Allows Node to terminate instead of blocking on timer81 }82 return _this;83 }84 _createClass(HttpLogger, [{85 key: "_getPayloadSize",86 value: function _getPayloadSize(nextSpan) {87 // Our payload is in format '[s1,s2,s3]', so we need to add 2 brackets and88 // one comma separator for each payload, including the next span if defined89 return nextSpan ? this.queueBytes + 2 + this.queue.length + nextSpan.length : this.queueBytes + 2 + Math.min(this.queue.length - 1, 0);90 }91 }, {92 key: "on",93 value: function on() {94 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {95 args[_key] = arguments[_key];96 }97 var eventName = args[0]; // if the instance has an error handler set then we don't need to98 // skips error logging99 if (eventName.toLowerCase() === 'error') this.errorListenerSet = true;100 _get(_getPrototypeOf(HttpLogger.prototype), "on", this).apply(this, args);101 }102 }, {103 key: "logSpan",104 value: function logSpan(span) {105 var encodedSpan = this.jsonEncoder.encode(span);106 if (this.maxPayloadSize && this._getPayloadSize(encodedSpan) > this.maxPayloadSize) {107 this.processQueue(this.fetchImplementation);108 if (this._getPayloadSize(encodedSpan) > this.maxPayloadSize) {109 // Payload size is too large even with an empty queue, we can only drop110 var err = 'Zipkin span got dropped, reason: payload too large';111 if (this.errorListenerSet) this.emit('error', new Error(err));else this.log.error(err);112 return;113 }114 }115 this.queue.push(encodedSpan);116 this.queueBytes += encodedSpan.length;117 } // We need to receive the fetch implementation as argument to avoid the118 // lose of context when compiling this with webpack and babel. See this119 // PR for more details https://github.com/openzipkin/zipkin-js/pull/497120 }, {121 key: "processQueue",122 value: function processQueue(fetchImpl) {123 var _this2 = this;124 var self = this;125 if (self.queue.length > 0) {126 const formattedQueue = self.queue.map((trace) => {127 const formatTrace = JSON.parse(trace)128 129 if (formatTrace.annotations[0].endpoint) {130 formatTrace.localEndpoint = {}131 formatTrace.localEndpoint.serviceName = formatTrace.annotations[0].endpoint.serviceName132 delete formatTrace['annotations']133 }134 135 return JSON.stringify(formatTrace)136 })137 // console.log(typeof logger.queue[0])138 139 const postBody = `[${formattedQueue.join(',')}]`140 // var postBody = "[".concat(self.queue.join(','), "]");141 var fetchOptions = {142 method: 'POST',143 body: postBody,144 headers: self.headers,145 timeout: self.timeout,146 agent: self.agent147 };148 console.log(self.headers)149 fetchImpl(self.endpoint, fetchOptions).then(function (response) {150 if (response.status !== 202 && response.status !== 200) {151 var err = 'Unexpected response while sending Zipkin data, status:' + "".concat(response.status, ", body: ").concat(postBody);152 if (self.errorListenerSet) _this2.emit('error', new Error(err));else _this2.log.error(err);153 } else {154 _this2.emit('success', response);155 }156 })["catch"](function (error) {157 var err = "Error sending Zipkin data ".concat(error);158 if (self.errorListenerSet) _this2.emit('error', new Error(err));else _this2.log.error(err);159 });160 self.queue.length = 0;161 self.queueBytes = 0;162 }163 }164 }]);165 return HttpLogger;166}(EventEmitter);...

Full Screen

Full Screen

threaddump.controller.js

Source:threaddump.controller.js Github

copy

Full Screen

2 'use strict';3 angular4 .module('viModule')5 .controller('ThreadDumpController', ThreadDumpController);6 function formatTrace(trace) {7 var methodDetail = 'Native method';8 if (trace.lineNumber > 0) {9 var ns = trace.declaringClass.substr(0, trace.declaringClass.lastIndexOf('.'));10 methodDetail = '<span jns="' + ns + '" ng-click="vm.viewSource($event)" class="link">' + trace.fileName + ':' + trace.lineNumber + '</span>';11 }12 return trace.declaringClass + '.' + trace.methodName + '(' + methodDetail + ')';13 }14 function ThreadModalController($scope, data, $uibModalInstance) {15 $scope.close = function() {16 $uibModalInstance.dismiss('cancel');17 };18 $scope.title = data.title;19 $scope.rawCollection = data.items;20 $scope.formatTrace = formatTrace;...

Full Screen

Full Screen

zipkin-local.js

Source:zipkin-local.js Github

copy

Full Screen

1'use strict';2const _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');3exports.__esModule = true;4exports.stop = exports.create = void 0;5const _zipkin = _interopRequireDefault(require('zipkin'));6const _zipkinTransportHttp = require('zipkin-transport-newrelic');7const _zipkinJavascriptOpentracing = _interopRequireDefault(8 require('zipkin-javascript-opentracing')9);10const constants = require('./constants');11const _nodeFetch = _interopRequireDefault(require('node-fetch'));12let logger;13let recorder;14/**15 * Create and return an open-tracing compatible tracer. See16 * https://github.com/opentracing/opentracing-javascript/blob/master/src/tracer.ts17 */18const create = () => {19 logger = new _zipkinTransportHttp.HttpLogger({20 // endpoint of local docker zipkin instance21 endpoint: `https://trace-api.newrelic.com/trace/v1`,22 headers: {23 'Api-Key': constants.NR_KEY,24 'Data-Format': 'zipkin',25 'Data-Format-Version': 2,26 },27 });28 recorder = new _zipkin.BatchRecorder({29 logger,30 // timeout = 60 hours, must be longer than site's build time31 timeout: 60 * 60 * 60 * 1000000,32 });33 // console.log(recorder)34 const tracer = new _zipkinJavascriptOpentracing.default({35 localServiceName: constants.SITE_NAME,36 serviceName: constants.SITE_NAME,37 // Sample 1 out of 1 spans (100%). When tracing production38 // services, it is normal to sample 1 out of 10 requests so that39 // tracing information doesn't impact site performance. But Gatsby40 // is a build tool and only has "1" request (the41 // build). Therefore, we must set this to 100% so that spans42 // aren't missing43 sampler: new _zipkin.sampler.CountingSampler(1),44 traceId128Bit: true,45 recorder,46 kind: `client`,47 });48 return tracer;49}; // Workaround for issue in Zipkin HTTP Logger where Spans are not50// cleared off their processing queue before the node.js process51// exits. Code is mostly the same as the zipkin processQueue52// implementation.53exports.create = create;54const _processQueue = async () => {55 if (logger.queue.length > 0) {56 console.log(logger.queue[0]);57 const formattedQueue = logger.queue.map((trace) => {58 const formatTrace = JSON.parse(trace)59 if (formatTrace.annotations[0].endpoint) {60 formatTrace.localEndpoint = {}61 formatTrace.localEndpoint.serviceName = formatTrace.annotations[0].endpoint.serviceName62 formatTrace.gatsbySite = constants ? constants.SITE_NAME : 'gatsby-site'63 if (formatTrace.binaryAnnotations) {64 formatTrace.tags = {}65 for (let anno of formatTrace.binaryAnnotations) {66 formatTrace.tags[anno.key] = anno.value67 }68 delete formatTrace['binaryAnnotations']69 }70 delete formatTrace['annotations']71 }72 73 return JSON.stringify(formatTrace)74 })75 // console.log(typeof logger.queue[0])76 77 const postBody = `[${formattedQueue.join(',')}]`78 try {79 const response = await (0, _nodeFetch.default)(logger.endpoint, {80 method: `POST`,81 body: postBody,82 headers: {83 'Content-Type': 'application/json',84 'Api-Key': process.env.NR_KEY,85 'Data-Format': 'zipkin',86 'Data-Format-Version': 2,87 },88 });89 if (response.status !== 202) {90 const err =91 `Unexpected response while sending Zipkin data, status:` +92 `${response.status}, body: ${postBody}`;93 if (logger.errorListenerSet) logger.emit(`error`, new Error(err));94 else console.error(err);95 }96 } catch (error) {97 const err = `Error sending Zipkin data ${error}`;98 if (logger.errorListenerSet) logger.emit(`error`, new Error(err));99 console.error(err);100 }101 }102};103/**104 * Run any tracer cleanup required before the node.js process105 * exits. For Zipkin HTTP, we must manually process any spans still on106 * the queue107 */108const stop = async () => {109 // First, write all partial spans to the http logger110 // recorder.partialSpans.forEach((span, id) => {111 // console.log(recorder)112 // if (recorder._timedOut(span)) {113 // recorder._writeSpan(id);114 // }115 // }); // Then tell http logger to process all spans in its queue116 await _processQueue();117};118exports.stop = stop;...

Full Screen

Full Screen

stream.js

Source:stream.js Github

copy

Full Screen

2'use strict';3var system = require('system'); // eslint-disable-line import/no-extraneous-dependencies4var page = require('webpage').create(); // eslint-disable-line import/no-extraneous-dependencies5var opts = JSON.parse(system.args[1]);6function formatTrace(trace) {7 var src = trace.file || trace.sourceURL;8 var fn = (trace.function ? ' in function ' + trace.function : '');9 return ' → ' + src + ' on line ' + trace.line + fn;10}11console.log = console.error = function () {12 system.stderr.writeLine([].slice.call(arguments).join(' '));13};14phantom.onError = function (err, trace) {15 console.error('PHANTOM ERROR: ' + err + formatTrace(trace[0]));16 phantom.exit(1);17};18page.onError = function (err, trace) {19 console.error('WARN: ' + err + formatTrace(trace[0]));20};21page.open(opts.url || 'file://' + page.libraryPath + '/index.html', function (status) {22 if (status === 'fail') {23 console.error('Couldn\'t load url: ' + opts.url);24 phantom.exit(1);25 return;26 }27 if (opts.content) {28 page.evaluate(function (content) {29 var body = document.querySelector('body');30 body.innerHTML = content;31 }, opts.content);32 }33 var paperSize = opts.paperSize || page.paperSize;...

Full Screen

Full Screen

jsErrYLT.js

Source:jsErrYLT.js Github

copy

Full Screen

...6 'use strict';7 8 phantomas.setMetric('jsErrors'); // @desc number of JavaScript errors9 10 function formatTrace(trace) {11 var ret = [];12 if(Array.isArray(trace)) {13 trace.forEach(function(entry) {14 ret.push((entry.function ? entry.function + ' ' : '') + (entry.sourceURL || entry.file) + ':' + entry.line);15 });16 }17 return ret;18 }19 phantomas.on('jserror', function(msg, trace) {20 trace = formatTrace(trace);21 phantomas.log(msg);22 phantomas.log('Backtrace: ' + trace.join(' / '));23 phantomas.incrMetric('jsErrors');24 phantomas.addOffender('jsErrors', msg + ' - ' + trace.join(' / '));25 // Yeah, this is weird, i'm sending the error back to the browser...26 phantomas.evaluate(function(msg, caller, trace) {27 (function(phantomas) {28 phantomas.pushContext({29 type: 'error',30 callDetails: {31 arguments: [msg]32 },33 caller: caller,34 backtrace: trace...

Full Screen

Full Screen

slow-query.js

Source:slow-query.js Github

copy

Full Screen

...13 this.id = normalizedHash(this.normalized)14 this.segment = segment15 this.query = query16 this.metric = segment.name17 this.trace = formatTrace(trace)18 this.duration = segment.getDurationInMillis()19}20function normalizedHash(value) {21 // We leverage the last 15 hex digits which will fit in a signed long22 return parseInt(crypto.createHash('sha1').update(value).digest('hex').slice(-15), 16)23}24function formatTrace(trace) {25 // remove error message and instrumentation frames from stack trace26 return trace ? trace.split('\n').slice(1).filter(notNR).join('\n') : ''27}28function notNR(frame) {29 return frame.indexOf(NR_ROOT) === -130}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...17 /**18 * Start trace.19 */20 start(tags, args) {21 this.stream.write(formatTrace('>', this.id, tags, args))22 }23 /**24 * Stop trace.25 */26 stop(tags, args) {27 this.stream.write(formatTrace('<', this.id, tags, args))28 }29}30/**31 * Trace.32 */33function formatTrace(dir, id, tags, args) {34 return `${dir}:${id}:${tags}:${formatArgs(args)}:`35}36/**37 * Arguments.38 */39function formatArgs(args) {40 if (!args) return ''41 return Object.keys(args).map(k => formatArg(k, args[k])).join(',')42}43/**44 * Argument.45 */46function formatArg(k, v) {47 return `${escape(k)}=${escape(v)}`...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { formatTrace } = require('playwright/lib/utils/stackTrace');2const { test } = require('@playwright/test');3test('example', async ({ page }) => {4});5const { formatTrace } = require('playwright/lib/utils/stackTrace');6const { test } = require('@playwright/test');7test('example', async ({ page }) => {8});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { formatTrace } = require('playwright/lib/utils/traceViewer/traceModel');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();10const { chromium } = require('playwright');11const { formatTrace } = require('playwright/lib/utils/traceViewer/traceModel');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.screenshot({ path: 'example.png' });17 await browser.close();18})();19const { chromium } = require('playwright');20const { formatTrace } = require('playwright/lib/utils/traceViewer/traceModel');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.screenshot({ path: 'example.png' });26 await browser.close();27})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');2const error = new Error('test');3console.log(formatTrace(error));4const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');5const error = new Error('test');6console.log(formatTrace(error));7const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');8const error = new Error('test');9console.log(formatTrace(error));10const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');11const error = new Error('test');12console.log(formatTrace(error));13const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');14const error = new Error('test');15console.log(formatTrace(error));16const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');17const error = new Error('test');18console.log(formatTrace(error));19const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');20const error = new Error('test');21console.log(formatTrace(error));22const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');23const error = new Error('test');24console.log(formatTrace(error));25const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');26const error = new Error('test');27console.log(formatTrace(error));28const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');29const error = new Error('test');30console.log(formatTrace(error));

Full Screen

Using AI Code Generation

copy

Full Screen

1const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');2const { InternalError } = require('@playwright/test/lib/utils/stackTrace');3const internalError = new InternalError('some message', new Error().stack);4console.log(formatTrace(internalError.stack));5const { formatTrace } = require('@playwright/test/lib/utils/stackTrace');6const { InternalError } = require('@playwright/test/lib/utils/stackTrace');7const internalError = new InternalError('some message', new Error().stack);8console.log(formatTrace(internalError.stack));

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful