How to use node.getTokens method in Cucumber-gherkin

Best JavaScript code snippet using cucumber-gherkin

ParserRuleContext.js

Source:ParserRuleContext.js Github

copy

Full Screen

1/*2 * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.3 * Use of this file is governed by the BSD 3-clause license that4 * can be found in the LICENSE.txt file in the project root.5 */6goog.module('org.antlr.v4.runtime.ParserRuleContext');7goog.module.declareLegacyNamespace();8const Interval = goog.require('org.antlr.v4.runtime.misc.Interval');9const Token = goog.require('org.antlr.v4.runtime.Token');10const RuleContext = goog.require('org.antlr.v4.runtime.RuleContext');11const ErrorNode = goog.require('org.antlr.v4.runtime.tree.ErrorNode');12const ErrorNodeImpl = goog.require('org.antlr.v4.runtime.tree.ErrorNodeImpl');13const TerminalNode = goog.require('org.antlr.v4.runtime.tree.TerminalNode');14const TerminalNodeImpl = goog.require('org.antlr.v4.runtime.tree.TerminalNodeImpl');15const {filter, find} = goog.require('goog.array');16/**17 * A rule invocation record for parsing.18 *19 * Contains all of the information about the current rule not stored in the20 * RuleContext. It handles parse tree children list, Any ATN state21 * tracing, and the default values available for rule invocations:22 * start, stop, rule index, current alt number.23 *24 * Subclasses made for each rule and grammar track the parameters,25 * return values, locals, and labels specific to that rule. These26 * are the objects that are returned from rules.27 *28 * Note text is not an actual field of a rule return value; it is computed29 * from start and stop using the input stream's toString() method. I30 * could add a ctor to this so that we can pass in and store the input31 * stream, but I'm not sure we want to do that. It would seem to be undefined32 * to get the .text property anyway if the rule matches tokens from multiple33 * input streams.34 *35 * I do not use getters for fields of objects that are used simply to36 * group values such as this aggregate. The getters/setters are there to37 * satisfy the superclass interface.38 */39class ParserRuleContext extends RuleContext {40 /**41 * @param {RuleContext=} parent42 * @param {number=} invokingStateNumber43 */44 constructor(parent, invokingStateNumber) {45 super(parent, invokingStateNumber);46 /**47 * If we are debugging or building a parse tree for a visitor,48 * we need to track all of the tokens and rule invocations associated49 * with this rule's context. This is empty for parsing w/o tree constr.50 * operation because we don't the need to track the details about51 * how we parse this rule.52 *53 * @type {!Array<org.antlr.v4.runtime.tree.ParseTree>}54 */55 this.children = [];56 /**57 * For debugging/tracing purposes, we want to track all of the nodes in58 * the ATN traversed by the parser for a particular rule.59 * This list indicates the sequence of ATN nodes used to match60 * the elements of the children list. This list does not include61 * ATN nodes and other rules used to match rule invocations. It62 * traces the rule invocation node itself but nothing inside that63 * other rule's ATN submachine.64 *65 * There is NOT a one-to-one correspondence between the children and66 * states list. There are typically many nodes in the ATN traversed67 * for each element in the children list. For example, for a rule68 * invocation there is the invoking state and the following state.69 *70 * The parser setState() method updates field s and adds it to this list71 * if we are debugging/tracing.72 *73 * This does not trace states visited during prediction.74 *75 * @type {Token}76 */77 this.start = null;78 /**79 * @type {Token}80 */81 this.stop = null;82 /**83 * The exception that forced this rule to return. If the rule successfully84 * completed, this is {@code null}.85 *86 * @type {org.antlr.v4.runtime.RecognitionException}87 */88 this.exception = null;89 }90 /**91 * COPY a ctx (I'm deliberately not using copy constructor) to avoid92 * confusion with creating node with parent. Does not copy children93 * (except error leaves).94 *95 * This is used in the generated parser code to flip a generic XContext96 * node for rule X to a YContext for alt label Y. In that sense, it is97 * not really a generic copy function.98 *99 * If we do an error sync() at start of a rule, we might add error nodes100 * to the generic XContext so this function must copy those nodes to101 * the YContext as well else they are lost!102 *103 * @param {ParserRuleContext} ctx104 * @return {void}105 */106 copyFrom(ctx) {107 this.parent = ctx.parent;108 this.invokingState = ctx.invokingState;109 this.start = ctx.start;110 this.stop = ctx.stop;111 // copy any error nodes to alt label node112 this.children = [];113 // reset parent pointer for any error nodes114 ctx.children.forEach(function (child) {115 if (child instanceof ErrorNodeImpl) {116 this.children.push(child);117 }118 }, this);119 }120 /**121 * Add a parse tree node to this as a child. Works for122 * internal and leaf nodes. Does not set parent link;123 * other add methods must do that. Other addChild methods124 * call this.125 *126 * We cannot set the parent pointer of the incoming node127 * because the existing interfaces do not have a setParent()128 * method and I don't want to break backward compatibility for this.129 *130 * @since 4.7131 *132 * @template T133 * @param {T} child134 * @return {T}135 */136 addAnyChild(child) {137 this.children.push(child);138 return child;139 }140 /**141 * @param {RuleContext|TerminalNode} child142 * @return {RuleContext|TerminalNode}143 */144 addChild(child) {145 if (child instanceof TerminalNodeImpl) {146 child.setParent(this);147 }148 return this.addAnyChild(child);149 }150 /**151 * Add an error node child and force its parent to be this node.152 *153 * @since 4.7154 *155 * @param {ErrorNode} errorNode156 * @return {ErrorNode}157 */158 addErrorNode(errorNode) {159 errorNode.setParent(this);160 return this.addAnyChild(errorNode);161 }162 /**163 * Used by enterOuterAlt to toss out a RuleContext previously added as164 * we entered a rule. If we have # label, we will need to remove165 * generic ruleContext object.166 *167 * @return {void}168 */169 removeLastChild() {170 this.children.pop();171 }172 /**173 * @param {org.antlr.v4.runtime.tree.ParseTreeListener} listener174 * @return {void}175 */176 enterRule(listener) {}177 /**178 * @param {org.antlr.v4.runtime.tree.ParseTreeListener} listener179 * @return {void}180 */181 exitRule(listener) {}182 getParent() {183 return super.getParent();184 }185 /**186 * @override187 * @param {!Function|number} ctxTypeOrIndex188 * @param {number=} i189 * @return {org.antlr.v4.runtime.tree.ParseTree}190 */191 getChild(ctxTypeOrIndex, i) {192 if (!goog.isDef(i)) {193 var j = /** @type {number} */ (ctxTypeOrIndex);194 return this.children[j] || null;195 }196 var ctxType = /** @type {!Function} */ (ctxTypeOrIndex);197 return find(this.children, function (child) {198 return child instanceof ctxType && i-- === 0;199 }) || null;200 }201 /**202 * @param {number} ttype203 * @param {number} i204 * @return {TerminalNode}205 */206 getToken(ttype, i) {207 if (i < 0 || i >= this.children.length) {208 return null;209 }210 var found = find(this.children, function (child) {211 return child instanceof TerminalNodeImpl && /** @type {TerminalNode} */ (child).getSymbol().getType() === ttype && i-- === 0;212 }) || null;213 return /** @type {TerminalNode} */ (found);214 }215 /**216 * @param {number} ttype217 * @return {!Array<TerminalNode>}218 */219 getTokens(ttype) {220 var filtered = filter(this.children, function (child) {221 return child instanceof TerminalNodeImpl && /** @type {TerminalNode} */ (child).getSymbol().getType() === ttype;222 });223 return /** @type {!Array<TerminalNode>} */ (filtered);224 }225 /**226 * @param {!Function} ctxType227 * @param {number} i228 * @return {ParserRuleContext}229 */230 getRuleContext(ctxType, i) {231 return /** @type {ParserRuleContext} */ (this.getChild(ctxType, i));232 }233 /**234 * @param {!Function} ctxType235 * @return {!Array<ParserRuleContext>}236 */237 getRuleContexts(ctxType) {238 return filter(this.children, function (child) {239 return child instanceof ctxType;240 });241 }242 getChildCount() {243 return this.children.length;244 }245 getSourceInterval() {246 if (this.start === null) {247 return Interval.INVALID;248 }249 if (this.stop === null || this.stop.getTokenIndex() < this.start.getTokenIndex()) {250 return Interval.of(this.start.getTokenIndex(), this.start.getTokenIndex() - 1);251 }252 return Interval.of(this.start.getTokenIndex(), this.stop.getTokenIndex());253 }254 /**255 * Get the initial token in this context.256 * Note that the range from start to stop is inclusive, so for rules that do not consume anything257 * (for example, zero length or error productions) this token may exceed stop.258 *259 * @return {Token}260 */261 getStart() {262 return this.start;263 }264 /**265 * Get the final token in this context.266 * Note that the range from start to stop is inclusive, so for rules that do not consume anything267 * (for example, zero length or error productions) this token may precede start.268 *269 * @return {Token}270 */271 getStop() {272 return this.stop;273 }274 /**275 * Used for rule context info debugging during parse-time, not so much for ATN debugging276 *277 * @param {org.antlr.v4.runtime.Parser} recognizer278 * @return {string}279 */280 toInfoString(recognizer) {281 let rules = recognizer.getRuleInvocationStack(this);282 return "ParserRuleContext"+rules.reverse()+"{" +283 "start=" + this.start +284 ", stop=" + this.stop +285 '}';286 }287}288ParserRuleContext.EMPTY = new ParserRuleContext();...

Full Screen

Full Screen

gherkin_document_builder.js

Source:gherkin_document_builder.js Github

copy

Full Screen

...66 function getSteps(node) {67 return node.getItems('Step');68 }69 function getTableRows(node) {70 var rows = node.getTokens('TableRow').map(function (token) {71 return {72 type: 'TableRow',73 location: getLocation(token),74 cells: getCells(token)75 };76 });77 ensureCellCount(rows);78 return rows;79 }80 function ensureCellCount(rows) {81 if (rows.length === 0) return;82 var cellCount = rows[0].cells.length;83 rows.forEach(function (row) {84 if (row.cells.length !== cellCount) {85 throw Errors.GherkinDocumentBuilderException.create("inconsistent cell count within the table", row.location);86 }87 });88 }89 function transformNode(node) {90 switch (node.ruleType) {91 case 'Step':92 var stepLine = node.getToken('StepLine');93 var dataTable = node.getSingle('DataTable')94 var docString = node.getSingle('DocString')95 var step = m.Step.fromObject({96 type: node.ruleType,97 location: getLocation(stepLine),98 keyword: stepLine.matchedKeyword,99 text: stepLine.matchedText,100 dataTable: dataTable,101 docString: docString102 });103 return step104 case 'DocString':105 var separatorToken = node.getTokens('DocStringSeparator')[0];106 var contentType = separatorToken.matchedText.length > 0 ? separatorToken.matchedText : undefined;107 var lineTokens = node.getTokens('Other');108 var content = lineTokens.map(function (t) {109 return t.matchedText110 }).join("\n");111 var result = {112 location: getLocation(separatorToken),113 content: content,114 delimiter: separatorToken.matchedKeyword115 };116 // conditionally add this like this (needed to make tests pass on node 0.10 as well as 4.0)117 if (contentType) {118 result.contentType = contentType;119 }120 return m.DocString.fromObject(result);121 case 'DataTable':122 var rows = getTableRows(node);123 return m.DataTable.fromObject({124 location: rows[0].location,125 rows: rows,126 })127 case 'Background':128 var backgroundLine = node.getToken('BackgroundLine');129 var description = getDescription(node);130 var steps = getSteps(node);131 return m.Background.fromObject({132 location: getLocation(backgroundLine),133 keyword: backgroundLine.matchedKeyword,134 name: backgroundLine.matchedText === "" ? null : backgroundLine.matchedText,135 description: description,136 steps: steps137 });138 case 'ScenarioDefinition':139 var tags = getTags(node);140 var scenarioNode = node.getSingle('Scenario');141 var scenarioLine = scenarioNode.getToken('ScenarioLine');142 var description = getDescription(scenarioNode);143 var steps = getSteps(scenarioNode);144 var examples = scenarioNode.getItems('ExamplesDefinition');145 return m.Scenario.fromObject({146 tags: tags,147 location: getLocation(scenarioLine),148 keyword: scenarioLine.matchedKeyword,149 name: scenarioLine.matchedText === "" ? null : scenarioLine.matchedText,150 description: description,151 steps: steps,152 examples: examples153 });154 case 'ExamplesDefinition':155 var tags = getTags(node);156 var examplesNode = node.getSingle('Examples');157 var examplesLine = examplesNode.getToken('ExamplesLine');158 var description = getDescription(examplesNode);159 var exampleTable = examplesNode.getSingle('ExamplesTable')160 return m.Examples.fromObject({161 tags: tags,162 location: getLocation(examplesLine),163 keyword: examplesLine.matchedKeyword,164 name: examplesLine.matchedText === "" ? null : examplesLine.matchedText,165 description: description,166 tableHeader: exampleTable != undefined ? exampleTable.tableHeader : undefined,167 tableBody: exampleTable != undefined ? exampleTable.tableBody : undefined168 });169 case 'ExamplesTable':170 var rows = getTableRows(node)171 return {172 tableHeader: rows != undefined ? rows[0] : undefined,173 tableBody: rows != undefined ? rows.slice(1) : undefined174 };175 case 'Description':176 var lineTokens = node.getTokens('Other');177 // Trim trailing empty lines178 var end = lineTokens.length;179 while (end > 0 && lineTokens[end - 1].line.trimmedLineText === '') {180 end--;181 }182 lineTokens = lineTokens.slice(0, end);183 var description = lineTokens.map(function (token) {184 return token.matchedText185 }).join("\n");186 return description;187 case 'Feature':188 var header = node.getSingle('FeatureHeader');189 if (!header) return null;190 var tags = getTags(header);...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import StorageService from '../StorageService';2import randomUUID from 'uuid/v4';3import TronWeb from 'tronweb';4import Logger from '@ezpay/lib/logger';5import { BigNumber } from 'bignumber.js';6const logger = new Logger('NodeService');7const NodeService = {8 _nodes: {9 'f0b1e38e-7bee-485e-9d3f-69410bf30681': {10 type: 'TRON',11 endPoint: 'https://api.trongrid.io',12 exploreUlr: 'https://tronscan.org/#/transaction/',13 txUlr: 'https://apilist.tronscan.org'14 },15 '0f22e40f-a004-4c5a-99ef-004c8e6769bf': {16 type: 'TRON_SHASTA',17 endPoint: 'https://api.shasta.trongrid.io',18 exploreUlr: 'https://shasta.tronscan.org/#/transaction/',19 txUlr: ''20 },21 '6739be94-ee43-46af-9a62-690cf0947280': {22 type: 'ETH',23 rpc: 'mainnet',24 endPoint: 'https://mainnet.infura.io/v3/f2ffee3e3500452fad9b02f935fe0032',25 exploreUlr: 'https://etherscan.io/tx/',26 txUlr: 'https://blockscout.com/eth/mainnet'27 },28 '6739be94-ee43-46af-9a62-690cf0947281': {29 type: 'ETH_RINKEBY',30 rpc: 'rinkeby',31 endPoint: 'https://rinkeby.infura.io/v3/f2ffee3e3500452fad9b02f935fe0032',32 exploreUlr: 'https://rinkeby.etherscan.io/tx/',33 txUlr: 'https://blockscout.com/eth/rinkeby'34 },35 '6739be94-ee43-46af-9a62-690cf0947282': {36 type: 'NTY',37 endPoint: 'https://rpc.nexty.io',38 exploreUlr: 'https://explorer.nexty.io/tx/',39 txUlr: 'https://explorer.nexty.io'40 },41 '6739be94-ee43-46af-9a62-690cf0947283': {42 type: 'BTC',43 endPoint: '',44 exploreUlr: '',45 txUlr: ''46 }47 },48 _tokens: {49 'f0b1e38e-7bee-485e-9d3f-69410bf30683': {50 node: 'f0b1e38e-7bee-485e-9d3f-69410bf30681',51 name: 'Tron',52 symbol: 'TRX',53 decimal: 6,54 isShow: true,55 logo: '../src/assets/images/tron.svg'56 },57 'f0b1e38e-7bee-485e-9d3f-69410bf30684': {58 node: '0f22e40f-a004-4c5a-99ef-004c8e6769bf',59 name: 'Tron Test',60 symbol: 'TRX',61 decimal: 6,62 isShow: false,63 logo: '../src/assets/images/tron.svg'64 },65 'f0b1e38e-7bee-485e-9d3f-69410bf30685': {66 node: '6739be94-ee43-46af-9a62-690cf0947280',67 name: 'Ethereum',68 symbol: 'ETH',69 decimal: 18,70 isShow: true,71 logo: '../src/assets/images/eth.svg'72 },73 'f0b1e38e-7bee-485e-9d3f-69410bf30686': {74 node: '6739be94-ee43-46af-9a62-690cf0947282',75 name: 'Nexty',76 symbol: 'NTY',77 decimal: 18,78 isShow: true,79 logo: '../src/assets/images/nty.svg'80 },81 // 'f0b1e38e-7bee-485e-9d3f-69410bf30687': {82 // node: '6739be94-ee43-46af-9a62-690cf0947283',83 // name: 'Bitcoin',84 // symbol: 'BTC-TEST',85 // decimal: 8,86 // typeCoinInfo: 'BTC-TEST',87 // isShow: true,88 // logo: '../src/assets/images/btc.svg'89 // },90 // 'f0b1e38e-7bee-485e-9d3f-69410bf30688': {91 // node: '6739be94-ee43-46af-9a62-690cf0947283',92 // name: 'Litecoin',93 // symbol: 'LTC-TEST',94 // decimal: 8,95 // typeCoinInfo: 'LTC-TEST',96 // isShow: false,97 // logo: '../src/assets/images/btc.svg'98 // },99 'f0b1e38e-7bee-485e-9d3f-69410bf30689': {100 node: '6739be94-ee43-46af-9a62-690cf0947281',101 name: 'Rinkeby',102 symbol: 'ETH',103 decimal: 18,104 isShow: true,105 logo: '../src/assets/images/eth.svg'106 },107 },108 _selectedNode: 'f0b1e38e-7bee-485e-9d3f-69410bf30681',109 _read() {110 logger.info('Reading nodes from storage');111 const {112 nodeList = {},113 selectedNode = false114 } = StorageService.nodes;115 this._nodes = {116 ...this._nodes,117 ...nodeList118 };119 if(selectedNode)120 this._selectedNode = selectedNode;121 },122 init() {123 this._read();124 this._updateTronWeb();125 },126 _updateTronWeb(skipAddress = false) {127 const {128 fullNode,129 solidityNode,130 eventServer131 } = this.getCurrentNode();132 this.tronWeb = new TronWeb(133 fullNode,134 solidityNode,135 eventServer136 );137 if(!skipAddress)138 this.setAddress();139 },140 setAddress() {141 if(!this.tronWeb)142 this._updateTronWeb();143 if(!StorageService.selectedAccount)144 return this._updateTronWeb(true);145 this.tronWeb.setAddress(146 StorageService.selectedAccount147 );148 },149 save() {150 Object.entries(this._nodes).forEach(([ nodeID, node ]) => (151 StorageService.saveNode(nodeID, node)152 ));153 StorageService.selectNode(this._selectedNode);154 this._updateTronWeb();155 },156 getNodes() {157 return {158 nodes: this._nodes,159 selected: this._selectedNode160 };161 },162 getTokens() {163 return this._tokens164 },165 getCurrentNode() {166 return this._nodes[ this._selectedNode ];167 },168 selectNode(nodeID) {169 StorageService.selectNode(nodeID);170 this._selectedNode = nodeID;171 this._updateTronWeb();172 },173 addNode(node) {174 const nodeID = randomUUID();175 this._nodes[ nodeID ] = {176 ...node,177 default: false178 };179 this.save();180 return nodeID;181 },182 async getSmartToken(address) {183 try {184 let balance;185 const contract = await this.tronWeb.contract().at(address);186 if(!contract.name && !contract.symbol && !contract.decimals)187 return false;188 const d = await contract.decimals().call();189 const name = await contract.name().call();190 const symbol = await contract.symbol().call();191 const decimals = typeof d === 'object' && d._decimals ? d : new BigNumber(d).toNumber();192 const number = await contract.balanceOf(address).call();193 if (number.balance) {194 balance = new BigNumber(number.balance).toString();195 } else {196 balance = new BigNumber(number).toString();197 }198 return {199 name: typeof name === 'object' ? name._name: name,200 symbol: typeof symbol === 'object' ? symbol._symbol: symbol,201 decimals: typeof decimals === 'object' ? decimals._decimals: decimals,202 balance203 };204 } catch(ex) {205 logger.error(`Failed to fetch token ${ address }:`, ex);206 return false;207 }208 }209};...

Full Screen

Full Screen

ast_builder.js

Source:ast_builder.js Github

copy

Full Screen

...52 function getSteps (node) {53 return node.getItems('Step');54 }55 function getTableRows(node) {56 var rows = node.getTokens('TableRow').map(function (token) {57 return {58 type: 'TableRow',59 location: getLocation(token),60 cells: getCells(token)61 };62 });63 ensureCellCount(rows);64 return rows;65 }66 function ensureCellCount(rows) {67 if(rows.length == 0) return;68 var cellCount = rows[0].cells.length;69 rows.forEach(function (row) {70 if (row.cells.length != cellCount) {71 throw Errors.AstBuilderException.create("inconsistent cell count within the table", row.location);72 }73 });74 }75 function transformNode(node) {76 switch(node.ruleType) {77 case 'Step':78 var stepLine = node.getToken('StepLine');79 var stepArgument = node.getSingle('DataTable') || node.getSingle('DocString') || undefined;80 return {81 type: node.ruleType,82 location: getLocation(stepLine),83 keyword: stepLine.matchedKeyword,84 name: stepLine.matchedText,85 argument: stepArgument86 }87 case 'DocString':88 var separatorToken = node.getTokens('DocStringSeparator')[0];89 var contentType = separatorToken.matchedText;90 var lineTokens = node.getTokens('Other');91 var content = lineTokens.map(function (t) {return t.matchedText}).join("\n");92 return {93 type: node.ruleType,94 location: getLocation(separatorToken),95 contentType: contentType,96 content: content97 };98 case 'DataTable':99 var rows = getTableRows(node);100 return {101 type: node.ruleType,102 location: rows[0].location,103 rows: rows,104 }105 case 'Background':106 var backgroundLine = node.getToken('BackgroundLine');107 var description = getDescription(node);108 var steps = getSteps(node);109 return {110 type: node.ruleType,111 location: getLocation(backgroundLine),112 keyword: backgroundLine.matchedKeyword,113 name: backgroundLine.matchedText,114 description: description,115 steps: steps116 };117 case 'Scenario_Definition':118 var tags = getTags(node);119 var scenarioNode = node.getSingle('Scenario');120 if(scenarioNode) {121 var scenarioLine = scenarioNode.getToken('ScenarioLine');122 var description = getDescription(scenarioNode);123 var steps = getSteps(scenarioNode);124 return {125 type: scenarioNode.ruleType,126 tags: tags,127 location: getLocation(scenarioLine),128 keyword: scenarioLine.matchedKeyword,129 name: scenarioLine.matchedText,130 description: description,131 steps: steps132 };133 } else {134 var scenarioOutlineNode = node.getSingle('ScenarioOutline');135 if(!scenarioOutlineNode) throw new Error('Internal grammar error');136 var scenarioOutlineLine = scenarioOutlineNode.getToken('ScenarioOutlineLine');137 var description = getDescription(scenarioOutlineNode);138 var steps = getSteps(scenarioOutlineNode);139 var examples = scenarioOutlineNode.getItems('Examples');140 return {141 type: scenarioOutlineNode.ruleType,142 tags: tags,143 location: getLocation(scenarioOutlineLine),144 keyword: scenarioOutlineLine.matchedKeyword,145 name: scenarioOutlineLine.matchedText,146 description: description,147 steps: steps,148 examples: examples149 };150 }151 case 'Examples':152 var tags = getTags(node);153 var examplesLine = node.getToken('ExamplesLine');154 var description = getDescription(node);155 var allRows = getTableRows(node);156 var header = allRows[0];157 var rows = allRows.slice(1);158 return {159 type: node.ruleType,160 tags: tags,161 location: getLocation(examplesLine),162 keyword: examplesLine.matchedKeyword,163 name: examplesLine.matchedText,164 description: description,165 header: header,166 rows: rows167 };168 case 'Description':169 var lineTokens = node.getTokens('Other');170 // Trim trailing empty lines171 var end = lineTokens.length;172 while (end > 0 && lineTokens[end-1].line.trimmedLineText === '') {173 end--;174 }175 lineTokens = lineTokens.slice(0, end);176 var description = lineTokens.map(function (token) { return token.matchedText}).join("\n");177 return description;178 case 'Feature':179 var header = node.getSingle('Feature_Header');180 var tags = getTags(header);181 var featureLine = header.getToken('FeatureLine');182 var background = node.getSingle('Background');183 var scenariodefinitions = node.getItems('Scenario_Definition');...

Full Screen

Full Screen

home-connect-auth.js

Source:home-connect-auth.js Github

copy

Full Screen

1module.exports = function (RED) {2 const request = require('request');3 const fs = require('fs');4 function OAuth2(config) {5 RED.nodes.createNode(this, config);6 this.name = config.name;7 this.simulation_mode = config.simulation_mode;8 this.client_id = this.credentials.client_id;9 this.client_secret = this.credentials.client_secret;10 this.context().flow.set('homeconnect_simulation', this.simulation_mode);11 const auth = {12 tokenHost: {13 simulation: 'https://simulator.home-connect.com',14 production: 'https://api.home-connect.com'15 },16 tokenPath: '/security/oauth/token',17 authorizePath: '/security/oauth/authorize'18 }19 const id = this.id;20 this.status({ fill: 'red', shape: 'ring', text: 'unauthorized' });21 const node = this;22 node.getAuthorizationUrl = (protocol, hostname, port, client_id) => {23 node.status({ fill: 'yellow', shape: 'ring', text: 'authorizing...' });24 let callbackUrl = protocol + '//' + hostname + (port ? ':' + port : '')25 + '/oauth2/auth/callback';26 node.context().set('callback_url', callbackUrl);27 let tokenHost = node.context().flow.get('homeconnect_simulation') ? auth.tokenHost.simulation : auth.tokenHost.production;28 return tokenHost + auth.authorizePath + 29 '?client_id=' + client_id + 30 '&response_type=code&redirect_uri=' + callbackUrl;31 };32 node.getTokens = (authCode) => {33 let n = RED.nodes.getNode(id);34 let tokenHost = node.context().flow.get('homeconnect_simulation') ? auth.tokenHost.simulation : auth.tokenHost.production;35 request.post({36 headers: {'content-type' : 'application/x-www-form-urlencoded'},37 url: tokenHost + auth.tokenPath,38 body: 'client_id=' + n.client_id + 39 '&client_secret=' + n.client_secret + 40 '&grant_type=authorization_code&code=' + authCode +41 '&redirect_uri=' + node.context().get('callback_url')42 }, (error, response, body) => {43 if (error || response.statusCode != 200) {44 n.status({ fill: 'red', shape:'dot', text: 'getTokens failed' });45 return;46 }47 n.status({ fill: 'green', shape:'dot', text: 'authorized' });48 n.tokens = { ...JSON.parse(body), timestamp: Date.now() };49 50 fs.writeFile('homeconnect_tokens.json', JSON.stringify(n.tokens), (err) => {51 if (err) {52 console.log(err);53 }54 });55 n.send({56 topic: 'oauth2',57 payload: {58 access_token: n.tokens.access_token59 }60 });61 });62 }63 node.refreshTokens = () => {64 let n = RED.nodes.getNode(id);65 let tokenHost = node.context().flow.get('homeconnect_simulation') ? auth.tokenHost.simulation : auth.tokenHost.production;66 request.post({67 headers: {'content-type' : 'application/x-www-form-urlencoded'},68 url: tokenHost + auth.tokenPath,69 body: 'grant_type=refresh_token&client_secret=' + n.client_secret + '&refresh_token=' + n.tokens.refresh_token70 }, (error, response, body) => {71 if (error || response.statusCode != 200) {72 return;73 }74 n.status({ fill: 'green', shape:'dot', text: 'authorized' });75 n.tokens = { ...JSON.parse(body), timestamp: Date.now() };76 77 fs.writeFile('homeconnect_tokens.json', JSON.stringify(n.tokens), (err) => {78 if (err) {79 console.log(err);80 }81 });82 n.send({83 topic: 'oauth2',84 payload: {85 access_token: n.tokens.access_token86 }87 });88 });89 };90 node.loadTokenFile = () => {91 try {92 let content = fs.readFileSync('homeconnect_tokens.json', 'utf8');93 node.tokens = JSON.parse(content);94 if (node.tokens != undefined) {95 node.refreshTokens();96 }97 } catch (err) {98 }99 };100 RED.events.on("nodes-started", () => {101 node.loadTokenFile();102 });103 RED.httpAdmin.get('/oauth2/auth/callback', (req, res) => {104 let n = RED.nodes.getNode(id);105 n.getTokens(req.query.code);106 res.sendStatus(200);107 });108 }109 RED.nodes.registerType('OAuth2', OAuth2, {110 credentials: {111 client_id: { type: 'text' },112 client_secret: { type: 'text' }113 }114 });115 RED.httpAdmin.get('/oauth2/:id/auth/url', (req, res) => {116 if (!req.query.protocol || !req.query.hostname) {117 res.sendStatus(400);118 return;119 }120 let node = RED.nodes.getNode(req.params.id);121 if (!node) {122 res.sendStatus(404);123 return;124 }125 let client_id = node.client_id;126 const url = node.getAuthorizationUrl(req.query.protocol, req.query.hostname, req.query.port, client_id);127 res.send({128 'url': url129 });130 });...

Full Screen

Full Screen

reducers.js

Source:reducers.js Github

copy

Full Screen

...112 if(state.app.walletMode == 'cold')113 return false;114 if(!force && (Date.now() - state.witnesses.lastSync) < 30000)115 return false;116 const tokenList = await Utils.node.getTokens();117 store.dispatch(tokens.saveTokens(tokenList));118 return false;...

Full Screen

Full Screen

template.js

Source:template.js Github

copy

Full Screen

1/**2 * This is an implementation-in-progress of a WHATWG/HTML proposal #22543 * Standardize <template> variables and event handlers4 * https://github.com/whatwg/html/issues/22545 *6 * MIT License7 *8 * Mev-Rael (mevrael@gmail.com)9 *10 * Please provide your feedback, PRs should be submitted here11 * https://github.com/Mevrael/html-template12 *13 * Adds a .parse(data) method to a Template prototype14 *15 * Currently doest not support any statements like if/endif blocks16 */17Object.assign(HTMLTemplateElement.prototype, {18 tokenTypes: {19 UNDEFINED: 0,20 VAR: 1,21 NESTED_VAR: 2,22 IF: 3,23 ENDIF: 424 },25 parse(data) {26 let html = this.getRootNodeAsHtml();27 const tokens = this.getTokens(html);28 let delta = 0; // when replacing tokens, increase/decrease delta length so next token would be replaced in correct position of html29 tokens.forEach(token => {30 const replaceWith = this.parseToken(token, data);31 html = html.substr(0, token.startsAt - delta) + replaceWith + html.substr(token.endsAt - delta);32 delta += token.length - replaceWith.length;33 });34 return this.htmlToNode(html);35 },36 htmlToNode(html) {37 return document.createRange().createContextualFragment(html).firstChild;38 },39 getRootNode() {40 const nodes = this.content.childNodes;41 const l = nodes.length;42 for (let k = 0; k < l; k++) {43 const node = nodes[k];44 if (node.nodeType === Node.ELEMENT_NODE) {45 return node;46 }47 }48 throw new SyntaxError('Template has no root element node');49 },50 getRootNodeAsHtml() {51 return this.getRootNode().outerHTML;52 },53 // get all the strings within {{ }} in template root node54 getTokens(html) {55 let tokens = [];56 let startAt = 0;57 while(token = this.getNextToken(html, startAt)) {58 tokens.push(token);59 startAt = token.endsAt;60 }61 return tokens;62 },63 // gets next token from an HTML string starting at startAt position64 // if no more tokens found - returns false65 // if token is not closed with }} - throws a SyntaxError66 // if token is found - returns an object:67 // {68 // value: string - contents of expression between {{ }},69 // startsAt: position of {{70 // endsAt: position of }}71 // length: total length of expression starting from the first "{" and ending with last "}"72 // }73 getNextToken(html, startAt = 0) {74 let startPos = html.indexOf('{{', startAt);75 if (startPos === -1) {76 return false;77 }78 let endPos = html.indexOf('}}', startPos);79 if (endPos === -1) {80 throw new SyntaxError('Template expression is not closed with }}');81 }82 startPos += 2;83 const value = html.substr(startPos, endPos - startPos).trim();84 startPos -= 2;85 endPos += 2;86 return {87 type: this.getTokenTypeByValue(value),88 value: value,89 startsAt: startPos,90 endsAt: endPos,91 length: endPos - startPos92 }93 },94 getTokenTypeByValue(value) {95 if (value.indexOf('if') === 0) {96 return this.tokenTypes.IF;97 } else if (value === 'endif') {98 return this.tokenTypes.ENDIF;99 } else if (value.indexOf('.') !== -1) {100 return this.tokenTypes.NESTED_VAR;101 } else {102 return this.tokenTypes.VAR;103 }104 },105 parseToken(token, data) {106 return this['parseToken' + token.type](token.value, data);107 },108 // VAR109 parseToken1(value, data) {110 if (data[value] === undefined) {111 return '';112 } else {113 return data[value].toString();114 }115 },116 // NESTED_VAR117 parseToken2(value, data) {118 let parts = value.split('.');119 const l = parts.length;120 let curNestData = data;121 for (let k = 0; k < l; k++) {122 if (curNestData[parts[k]] === undefined) {123 return '';124 } else {125 curNestData = curNestData[parts[k]];126 }127 }128 return curNestData;129 },130 // IF131 parseToken3(value, data) {132 return 'if';133 },134 // ENDIF135 parseToken4(value, data) {136 return 'endif';137 },...

Full Screen

Full Screen

visualize.js

Source:visualize.js Github

copy

Full Screen

1const parser = require("../../dist/index.js").tree;2const pos = require("en-pos");3const chalk = require("chalk");45678module.exports = function(tokens,index,deep){9 var tags = new pos.Tag(tokens).initial().smooth().tags;10 var parsed = parser(tags,tokens);11 console.log(JSON.stringify(parsed));12 console.log(chalk.red(" @ Sentence:",index));13 console.log(chalk.red("LENGTH",parsed.length));14 console.log(chalk.green(tokens.join(" ")));15 console.log(chalk.green(tokens.map((x,i)=>x+"/"+i).join(" ")));16 console.log(chalk.green(tags.join(" ")));17 if(!deep) recursiveConsole(parsed[0],0,tokens);18 else parsed.forEach((x)=>recursiveConsole(x,0,tokens));19};2021function recursiveConsole(node,i,tokens) {22 var pads = chalk.green(" | ".repeat(i));23 var type = chalk.yellow("Tag/Type: ") + node.tags + "/" + node.type;24 var indexes = chalk.yellow("Indexes: ") + node.index.join(":");25 var vtokens = chalk.red(" @ Node: ",getTokens(node.index,tokens));26 var label = chalk.yellow("Label: ") + node.label;27 console.log(pads,vtokens);28 console.log(pads," ",type);29 console.log(pads," ",indexes);30 console.log(pads," ",label);31 if(node.left.length) console.log(pads," ",chalk.green("# LEFT NODES"));32 node.left.forEach((node)=>recursiveConsole(node,i+1,tokens));33 if(node.right.length) console.log(pads," ",chalk.green("# RIGHT NODES"));34 if(node.right.length) node.right.forEach((node)=>recursiveConsole(node,i+1,tokens));35}3637function getTokens(indices,tokens){38 return tokens.filter((x,i)=>i>=indices[0]&&i<=indices[1]).join(" "); ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Cucumber = require('cucumber');2var gherkin = Cucumber.Gherkin;3var fs = require('fs');4var source = fs.readFileSync('test.feature', 'utf8');5var parser = new gherkin.Parser();6var tokens = parser.getTokens(source);7console.log(tokens);8[ { comment: null,9 tags: [] },10 { comment: null,11 tags: [] },12 { comment: null,13 tags: [] },14 { comment: null,15 tags: [] } ]

Full Screen

Using AI Code Generation

copy

Full Screen

1var gherkin = require('cucumber-gherkin');2var fs = require('fs');3var feature = fs.readFileSync('test.feature', 'utf8');4var tokens = gherkin.getTokens(feature);5console.log(tokens);6[ { line: 1,7 tags: [] },8 { line: 2,9 tags: [] },10 { line: 3,11 tags: [] },12 { line: 4,13 tags: [] },14 { line: 5,15 tags: [] } ]16var featureTokens = tokens.filter(function(token) {17 return token.type === 'Feature';18});19console.log(featureTokens);20[ { line: 1,21 tags: [] } ]22var scenarioTokens = tokens.filter(function(token) {23 return token.type === 'Scenario';24});25console.log(scenarioTokens);26var stepTokens = tokens.filter(function(token) {27 return token.type === 'Step';

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require('fs');2var gherkin = require('cucumber-gherkin');3var feature = fs.readFileSync('test.feature', 'utf8');4var tokens = gherkin.getTokens(feature);5console.log(tokens);6[ { line: 1, column: 1, type: 'FeatureLine' },7 { line: 1, column: 9, type: 'TagLine' },8 { line: 1, column: 10, type: 'Tag' },9 { line: 1, column: 11, type: 'Feature' },10 { line: 2, column: 3, type: 'BackgroundLine' },11 { line: 2, column: 12, type: 'Background' },12 { line: 3, column: 5, type: 'ScenarioLine' },13 { line: 3, column: 14, type: 'TagLine' },14 { line: 3, column: 15, type: 'Tag' },15 { line: 3, column: 16, type: 'Scenario' },16 { line: 4, column: 7, type: 'StepLine' },17 { line: 4, column: 10, type: 'Step' },18 { line: 4, column: 11, type: 'StepArg' },19 { line: 5, column: 7, type: 'StepLine' },20 { line: 5, column: 10, type: 'Step' },21 { line: 5, column: 11, type: 'StepArg' },22 { line: 6, column: 7, type: 'StepLine' },23 { line: 6, column: 10, type: 'Step' },24 { line: 6, column: 11, type: 'StepArg' } ]

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require("fs");2var gherkin = require("gherkin");3var parser = new gherkin.Parser();4var feature = fs.readFileSync("test.feature", "utf-8");5var tokens = parser.getTokens(feature);6for (var i = 0; i < tokens.length; i++) {7 if (tokens[i].type == "FeatureLine") {8 console.log("Feature");9 } else if (tokens[i].type == "BackgroundLine") {10 console.log("Background");11 } else if (tokens[i].type == "ScenarioLine") {12 console.log("Scenario");13 } else if (tokens[i].type == "StepLine") {14 console.log("Step");15 } else if (tokens[i].type == "PyString") {16 console.log("PyString");17 } else if (tokens[i].type == "DataTable") {18 console.log("DataTable");19 } else if (tokens[i].type == "DocStringSeparator") {20 console.log("DocStringSeparator");21 } else if (tokens[i].type == "TableRow") {22 console.log("TableRow");23 } else if (tokens[i].type == "Language") {24 console.log("Language");25 } else if (tokens[i].type == "TagLine") {26 console.log("TagLine");27 } else if (tokens[i].type == "Comment") {28 console.log("Comment");29 } else if (tokens[i].type == "Empty") {30 console.log("Empty");31 } else {32 console.log("Unknown");33 }34}

Full Screen

Cucumber Tutorial:

LambdaTest offers a detailed Cucumber testing tutorial, explaining its features, importance, best practices, and more to help you get started with running your automation testing scripts.

Cucumber Tutorial Chapters:

Here are the detailed Cucumber testing chapters to help you get started:

  • Importance of Cucumber - Learn why Cucumber is important in Selenium automation testing during the development phase to identify bugs and errors.
  • Setting Up Cucumber in Eclipse and IntelliJ - Learn how to set up Cucumber in Eclipse and IntelliJ.
  • Running First Cucumber.js Test Script - After successfully setting up your Cucumber in Eclipse or IntelliJ, this chapter will help you get started with Selenium Cucumber testing in no time.
  • Annotations in Cucumber - To handle multiple feature files and the multiple scenarios in each file, you need to use functionality to execute these scenarios. This chapter will help you learn about a handful of Cucumber annotations ranging from tags, Cucumber hooks, and more to ease the maintenance of the framework.
  • Automation Testing With Cucumber And Nightwatch JS - Learn how to build a robust BDD framework setup for performing Selenium automation testing by integrating Cucumber into the Nightwatch.js framework.
  • Automation Testing With Selenium, Cucumber & TestNG - Learn how to perform Selenium automation testing by integrating Cucumber with the TestNG framework.
  • Integrate Cucumber With Jenkins - By using Cucumber with Jenkins integration, you can schedule test case executions remotely and take advantage of the benefits of Jenkins. Learn how to integrate Cucumber with Jenkins with this detailed chapter.
  • Cucumber Best Practices For Selenium Automation - Take a deep dive into the advanced use cases, such as creating a feature file, separating feature files, and more for Cucumber testing.

Run Cucumber-gherkin 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