Best JavaScript code snippet using playwright-internal
highlight.js
Source:highlight.js  
...40    // https://github.com/highlightjs/highlight.js/issues/108641    __emitter: TokenTreeEmitter42  };43  /* Utility functions */44  function shouldNotHighlight(language) {45    return options.noHighlightRe.test(language);46  }47  function blockLanguage(block) {48    var classes = block.className + ' ';49    classes += block.parentNode ? block.parentNode.className : '';50    // language-* takes precedence over non-prefixed class names.51    const match = options.languageDetectRe.exec(classes);52    if (match) {53      var language = getLanguage(match[1]);54      if (!language) {55        console.warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));56        console.warn("Falling back to no-highlight mode for this block.", block);57      }58      return language ? match[1] : 'no-highlight';59    }60    return classes61      .split(/\s+/)62      .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));63  }64  /**65   * Core highlighting function.66   *67   * @param {string} languageName - the language to use for highlighting68   * @param {string} code - the code to highlight69   * @param {boolean} ignoreIllegals - whether to ignore illegal matches, default is to bail70   * @param {array<mode>} continuation - array of continuation modes71   *72   * @returns an object that represents the result73   * @property {string} language - the language name74   * @property {number} relevance - the relevance score75   * @property {string} value - the highlighted HTML code76   * @property {string} code - the original raw code77   * @property {mode} top - top of the current mode stack78   * @property {boolean} illegal - indicates whether any illegal matches were found79  */80  function highlight(languageName, code, ignoreIllegals, continuation) {81    var context = {82      code,83      language: languageName84    };85    // the plugin can change the desired language or the code to be highlighted86    // just be changing the object it was passed87    fire("before:highlight", context);88    // a before plugin can usurp the result completely by providing it's own89    // in which case we don't even need to call highlight90    var result = context.result ?91      context.result :92      _highlight(context.language, context.code, ignoreIllegals, continuation);93    result.code = context.code;94    // the plugin can change anything in result to suite it95    fire("after:highlight", result);96    return result;97  }98  // private highlight that's used internally and does not fire callbacks99  function _highlight(languageName, code, ignoreIllegals, continuation) {100    var codeToHighlight = code;101    function keywordData(mode, match) {102      var matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];103      return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];104    }105    function processKeywords() {106      if (!top.keywords) {107        emitter.addText(mode_buffer);108        return;109      }110      let last_index = 0;111      top.keywordPatternRe.lastIndex = 0;112      let match = top.keywordPatternRe.exec(mode_buffer);113      let buf = "";114      while (match) {115        buf += mode_buffer.substring(last_index, match.index);116        const data = keywordData(top, match);117        if (data) {118          const [kind, keywordRelevance] = data;119          emitter.addText(buf);120          buf = "";121          relevance += keywordRelevance;122          emitter.addKeyword(match[0], kind);123        } else {124          buf += match[0];125        }126        last_index = top.keywordPatternRe.lastIndex;127        match = top.keywordPatternRe.exec(mode_buffer);128      }129      buf += mode_buffer.substr(last_index);130      emitter.addText(buf);131    }132    function processSubLanguage() {133      if (mode_buffer === "") return;134      var explicit = typeof top.subLanguage === 'string';135      if (explicit && !languages[top.subLanguage]) {136        emitter.addText(mode_buffer);137        return;138      }139      var result = explicit ?140        _highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :141        highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : null);142      // Counting embedded language score towards the host language may be disabled143      // with zeroing the containing mode relevance. Use case in point is Markdown that144      // allows XML everywhere and makes every XML snippet to have a much larger Markdown145      // score.146      if (top.relevance > 0) {147        relevance += result.relevance;148      }149      if (explicit) {150        continuations[top.subLanguage] = result.top;151      }152      emitter.addSublanguage(result.emitter, result.language);153    }154    function processBuffer() {155      if (top.subLanguage != null) {156        processSubLanguage();157      } else {158        processKeywords();159      }160      mode_buffer = '';161    }162    function startNewMode(mode) {163      if (mode.className) {164        emitter.openNode(mode.className);165      }166      top = Object.create(mode, {parent: {value: top}});167      return top;168    }169    function endOfMode(mode, match, matchPlusRemainder) {170      let matched = regex.startsWith(mode.endRe, matchPlusRemainder);171      if (matched) {172        if (mode["on:end"]) {173          let resp = new Response(mode);174          mode["on:end"](match, resp);175          if (resp.ignore)176            matched = false;177        }178        if (matched) {179          while (mode.endsParent && mode.parent) {180            mode = mode.parent;181          }182          return mode;183        }184      }185      // even if on:end fires an `ignore` it's still possible186      // that we might trigger the end node because of a parent mode187      if (mode.endsWithParent) {188        return endOfMode(mode.parent, match, matchPlusRemainder);189      }190    }191    function doIgnore(lexeme) {192      if (top.matcher.regexIndex === 0) {193        // no more regexs to potentially match here, so we move the cursor forward one194        // space195        mode_buffer += lexeme[0];196        return 1;197      } else {198        // no need to move the cursor, we still have additional regexes to try and199        // match at this very spot200        continueScanAtSamePosition = true;201        return 0;202      }203    }204    function doBeginMatch(match) {205      var lexeme = match[0];206      var new_mode = match.rule;207      var mode;208      let resp = new Response(new_mode);209      // first internal before callbacks, then the public ones210      let beforeCallbacks = [new_mode.__beforeBegin, new_mode["on:begin"]];211      for (let cb of beforeCallbacks) {212        if (!cb) continue;213        cb(match, resp);214        if (resp.ignore) return doIgnore(lexeme);215      }216      if (new_mode && new_mode.endSameAsBegin) {217        new_mode.endRe = regex.escape(lexeme);218      }219      if (new_mode.skip) {220        mode_buffer += lexeme;221      } else {222        if (new_mode.excludeBegin) {223          mode_buffer += lexeme;224        }225        processBuffer();226        if (!new_mode.returnBegin && !new_mode.excludeBegin) {227          mode_buffer = lexeme;228        }229      }230      mode = startNewMode(new_mode);231      // if (mode["after:begin"]) {232      //   let resp = new Response(mode);233      //   mode["after:begin"](match, resp);234      // }235      return new_mode.returnBegin ? 0 : lexeme.length;236    }237    function doEndMatch(match) {238      var lexeme = match[0];239      var matchPlusRemainder = codeToHighlight.substr(match.index);240      var end_mode = endOfMode(top, match, matchPlusRemainder);241      if (!end_mode) { return NO_MATCH; }242      var origin = top;243      if (origin.skip) {244        mode_buffer += lexeme;245      } else {246        if (!(origin.returnEnd || origin.excludeEnd)) {247          mode_buffer += lexeme;248        }249        processBuffer();250        if (origin.excludeEnd) {251          mode_buffer = lexeme;252        }253      }254      do {255        if (top.className) {256          emitter.closeNode();257        }258        if (!top.skip && !top.subLanguage) {259          relevance += top.relevance;260        }261        top = top.parent;262      } while (top !== end_mode.parent);263      if (end_mode.starts) {264        if (end_mode.endSameAsBegin) {265          end_mode.starts.endRe = end_mode.endRe;266        }267        startNewMode(end_mode.starts);268      }269      return origin.returnEnd ? 0 : lexeme.length;270    }271    function processContinuations() {272      var list = [];273      for (var current = top; current !== language; current = current.parent) {274        if (current.className) {275          list.unshift(current.className);276        }277      }278      list.forEach(item => emitter.openNode(item));279    }280    var lastMatch = {};281    function processLexeme(textBeforeMatch, match) {282      var lexeme = match && match[0];283      // add non-matched text to the current mode buffer284      mode_buffer += textBeforeMatch;285      if (lexeme == null) {286        processBuffer();287        return 0;288      }289      // we've found a 0 width match and we're stuck, so we need to advance290      // this happens when we have badly behaved rules that have optional matchers to the degree that291      // sometimes they can end up matching nothing at all292      // Ref: https://github.com/highlightjs/highlight.js/issues/2140293      if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {294        // spit the "skipped" character that our regex choked on back into the output sequence295        mode_buffer += codeToHighlight.slice(match.index, match.index + 1);296        if (!SAFE_MODE) {297          const err = new Error('0 width match regex');298          err.languageName = languageName;299          err.badRule = lastMatch.rule;300          throw err;301        }302        return 1;303      }304      lastMatch = match;305      if (match.type === "begin") {306        return doBeginMatch(match);307      } else if (match.type === "illegal" && !ignoreIllegals) {308        // illegal match, we do not continue processing309        const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');310        err.mode = top;311        throw err;312      } else if (match.type === "end") {313        var processed = doEndMatch(match);314        if (processed !== NO_MATCH) {315          return processed;316        }317      }318      // edge case for when illegal matches $ (end of line) which is technically319      // a 0 width match but not a begin/end match so it's not caught by the320      // first handler (when ignoreIllegals is true)321      if (match.type === "illegal" && lexeme === "") {322        // advance so we aren't stuck in an infinite loop323        return 1;324      }325      // infinite loops are BAD, this is a last ditch catch all. if we have a326      // decent number of iterations yet our index (cursor position in our327      // parsing) still 3x behind our index then something is very wrong328      // so we bail329      if (iterations > 100000 && iterations > match.index * 3) {330        const err = new Error('potential infinite loop, way more iterations than matches');331        throw err;332      }333      /*334      Why might be find ourselves here?  Only one occasion now.  An end match that was335      triggered but could not be completed.  When might this happen?  When an `endSameasBegin`336      rule sets the end rule to a specific match.  Since the overall mode termination rule that's337      being used to scan the text isn't recompiled that means that any match that LOOKS like338      the end (but is not, because it is not an exact match to the beginning) will339      end up here.  A definite end match, but when `doEndMatch` tries to "reapply"340      the end rule and fails to match, we wind up here, and just silently ignore the end.341      This causes no real harm other than stopping a few times too many.342      */343      mode_buffer += lexeme;344      return lexeme.length;345    }346    var language = getLanguage(languageName);347    if (!language) {348      console.error(LANGUAGE_NOT_FOUND.replace("{}", languageName));349      throw new Error('Unknown language: "' + languageName + '"');350    }351    compileLanguage(language);352    var result = '';353    var top = continuation || language;354    var continuations = {}; // keep continuations for sub-languages355    var emitter = new options.__emitter(options);356    processContinuations();357    var mode_buffer = '';358    var relevance = 0;359    var index = 0;360    var iterations = 0;361    var continueScanAtSamePosition = false;362    try {363      top.matcher.considerAll();364      for (;;) {365        iterations++;366        if (continueScanAtSamePosition) {367          continueScanAtSamePosition = false;368          // only regexes not matched previously will now be369          // considered for a potential match370        } else {371          top.matcher.lastIndex = index;372          top.matcher.considerAll();373        }374        const match = top.matcher.exec(codeToHighlight);375        // console.log("match", match[0], match.rule && match.rule.begin)376        if (!match) break;377        const beforeMatch = codeToHighlight.substring(index, match.index);378        const processedCount = processLexeme(beforeMatch, match);379        index = match.index + processedCount;380      }381      processLexeme(codeToHighlight.substr(index));382      emitter.closeAllNodes();383      emitter.finalize();384      result = emitter.toHTML();385      return {386        relevance: relevance,387        value: result,388        language: languageName,389        illegal: false,390        emitter: emitter,391        top: top392      };393    } catch (err) {394      if (err.message && err.message.includes('Illegal')) {395        return {396          illegal: true,397          illegalBy: {398            msg: err.message,399            context: codeToHighlight.slice(index - 100, index + 100),400            mode: err.mode401          },402          sofar: result,403          relevance: 0,404          value: escape(codeToHighlight),405          emitter: emitter406        };407      } else if (SAFE_MODE) {408        return {409          relevance: 0,410          value: escape(codeToHighlight),411          emitter: emitter,412          language: languageName,413          top: top,414          errorRaised: err415        };416      } else {417        throw err;418      }419    }420  }421  // returns a valid highlight result, without actually422  // doing any actual work, auto highlight starts with423  // this and it's possible for small snippets that424  // auto-detection may not find a better match425  function justTextHighlightResult(code) {426    const result = {427      relevance: 0,428      emitter: new options.__emitter(options),429      value: escape(code),430      illegal: false,431      top: PLAINTEXT_LANGUAGE432    };433    result.emitter.addText(code)434    return result;435  }436  /*437  Highlighting with language detection. Accepts a string with the code to438  highlight. Returns an object with the following properties:439  - language (detected language)440  - relevance (int)441  - value (an HTML string with highlighting markup)442  - second_best (object with the same structure for second-best heuristically443    detected language, may be absent)444  */445  function highlightAuto(code, languageSubset) {446    languageSubset = languageSubset || options.languages || Object.keys(languages);447    var result = justTextHighlightResult(code)448    var secondBest = result;449    languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {450      var current = _highlight(name, code, false);451      current.language = name;452      if (current.relevance > secondBest.relevance) {453        secondBest = current;454      }455      if (current.relevance > result.relevance) {456        secondBest = result;457        result = current;458      }459    });460    if (secondBest.language) {461      // second_best (with underscore) is the expected API462      result.second_best = secondBest;463    }464    return result;465  }466  /*467  Post-processing of the highlighted markup:468  - replace TABs with something more useful469  - replace real line-breaks with '<br>' for non-pre containers470  */471  function fixMarkup(value) {472    if (!(options.tabReplace || options.useBR)) {473      return value;474    }475    return value.replace(fixMarkupRe, match => {476      if (match === '\n') {477        return options.useBR ? '<br>' : match;478      } else if (options.tabReplace) {479        return match.replace(/\t/g, options.tabReplace);480      }481      return match;482    });483  }484  function buildClassName(prevClassName, currentLang, resultLang) {485    var language = currentLang ? aliases[currentLang] : resultLang;486    var result = [prevClassName.trim()];487    if (!prevClassName.match(/\bhljs\b/)) {488      result.push('hljs');489    }490    if (!prevClassName.includes(language)) {491      result.push(language);492    }493    return result.join(' ').trim();494  }495  /*496  Applies highlighting to a DOM node containing code. Accepts a DOM node and497  two optional parameters for fixMarkup.498  */499  function highlightBlock(block) {500    let node = null;501    const language = blockLanguage(block);502    if (shouldNotHighlight(language)) return;503    fire("before:highlightBlock",504      { block: block, language: language });505    if (options.useBR) {506      node = document.createElement('div');507      node.innerHTML = block.innerHTML.replace(/\n/g, '').replace(/<br[ /]*>/g, '\n');508    } else {509      node = block;510    }511    const text = node.textContent;512    const result = language ? highlight(language, text, true) : highlightAuto(text);513    const originalStream = nodeStream(node);514    if (originalStream.length) {515      const resultNode = document.createElement('div');516      resultNode.innerHTML = result.value;...highlight_1.js
Source:highlight_1.js  
...40    // https://github.com/highlightjs/highlight.js/issues/108641    __emitter: TokenTreeEmitter42  };43  /* Utility functions */44  function shouldNotHighlight(language) {45    return options.noHighlightRe.test(language);46  }47  function blockLanguage(block) {48    var classes = block.className + ' ';49    classes += block.parentNode ? block.parentNode.className : '';50    // language-* takes precedence over non-prefixed class names.51    const match = options.languageDetectRe.exec(classes);52    if (match) {53      var language = getLanguage(match[1]);54      if (!language) {55        console.warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));56        console.warn("Falling back to no-highlight mode for this block.", block);57      }58      return language ? match[1] : 'no-highlight';59    }60    return classes61      .split(/\s+/)62      .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));63  }64  /**65   * Core highlighting function.66   *67   * @param {string} languageName - the language to use for highlighting68   * @param {string} code - the code to highlight69   * @param {boolean} ignoreIllegals - whether to ignore illegal matches, default is to bail70   * @param {array<mode>} continuation - array of continuation modes71   *72   * @returns an object that represents the result73   * @property {string} language - the language name74   * @property {number} relevance - the relevance score75   * @property {string} value - the highlighted HTML code76   * @property {string} code - the original raw code77   * @property {mode} top - top of the current mode stack78   * @property {boolean} illegal - indicates whether any illegal matches were found79  */80  function highlight(languageName, code, ignoreIllegals, continuation) {81    var context = {82      code,83      language: languageName84    };85    // the plugin can change the desired language or the code to be highlighted86    // just be changing the object it was passed87    fire("before:highlight", context);88    // a before plugin can usurp the result completely by providing it's own89    // in which case we don't even need to call highlight90    var result = context.result ?91      context.result :92      _highlight(context.language, context.code, ignoreIllegals, continuation);93    result.code = context.code;94    // the plugin can change anything in result to suite it95    fire("after:highlight", result);96    return result;97  }98  // private highlight that's used internally and does not fire callbacks99  function _highlight(languageName, code, ignoreIllegals, continuation) {100    var codeToHighlight = code;101    function keywordData(mode, match) {102      var matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];103      return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];104    }105    function processKeywords() {106      if (!top.keywords) {107        emitter.addText(mode_buffer);108        return;109      }110      let last_index = 0;111      top.keywordPatternRe.lastIndex = 0;112      let match = top.keywordPatternRe.exec(mode_buffer);113      let buf = "";114      while (match) {115        buf += mode_buffer.substring(last_index, match.index);116        const data = keywordData(top, match);117        if (data) {118          const [kind, keywordRelevance] = data;119          emitter.addText(buf);120          buf = "";121          relevance += keywordRelevance;122          emitter.addKeyword(match[0], kind);123        } else {124          buf += match[0];125        }126        last_index = top.keywordPatternRe.lastIndex;127        match = top.keywordPatternRe.exec(mode_buffer);128      }129      buf += mode_buffer.substr(last_index);130      emitter.addText(buf);131    }132    function processSubLanguage() {133      if (mode_buffer === "") return;134      var explicit = typeof top.subLanguage === 'string';135      if (explicit && !languages[top.subLanguage]) {136        emitter.addText(mode_buffer);137        return;138      }139      var result = explicit ?140        _highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :141        highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : null);142      // Counting embedded language score towards the host language may be disabled143      // with zeroing the containing mode relevance. Use case in point is Markdown that144      // allows XML everywhere and makes every XML snippet to have a much larger Markdown145      // score.146      if (top.relevance > 0) {147        relevance += result.relevance;148      }149      if (explicit) {150        continuations[top.subLanguage] = result.top;151      }152      emitter.addSublanguage(result.emitter, result.language);153    }154    function processBuffer() {155      if (top.subLanguage != null) {156        processSubLanguage();157      } else {158        processKeywords();159      }160      mode_buffer = '';161    }162    function startNewMode(mode) {163      if (mode.className) {164        emitter.openNode(mode.className);165      }166      top = Object.create(mode, {parent: {value: top}});167      return top;168    }169    function endOfMode(mode, match, matchPlusRemainder) {170      let matched = regex.startsWith(mode.endRe, matchPlusRemainder);171      if (matched) {172        if (mode["on:end"]) {173          let resp = new Response(mode);174          mode["on:end"](match, resp);175          if (resp.ignore)176            matched = false;177        }178        if (matched) {179          while (mode.endsParent && mode.parent) {180            mode = mode.parent;181          }182          return mode;183        }184      }185      // even if on:end fires an `ignore` it's still possible186      // that we might trigger the end node because of a parent mode187      if (mode.endsWithParent) {188        return endOfMode(mode.parent, match, matchPlusRemainder);189      }190    }191    function doIgnore(lexeme) {192      if (top.matcher.regexIndex === 0) {193        // no more regexs to potentially match here, so we move the cursor forward one194        // space195        mode_buffer += lexeme[0];196        return 1;197      } else {198        // no need to move the cursor, we still have additional regexes to try and199        // match at this very spot200        continueScanAtSamePosition = true;201        return 0;202      }203    }204    function doBeginMatch(match) {205      var lexeme = match[0];206      var new_mode = match.rule;207      var mode;208      let resp = new Response(new_mode);209      // first internal before callbacks, then the public ones210      let beforeCallbacks = [new_mode.__beforeBegin, new_mode["on:begin"]];211      for (let cb of beforeCallbacks) {212        if (!cb) continue;213        cb(match, resp);214        if (resp.ignore) return doIgnore(lexeme);215      }216      if (new_mode && new_mode.endSameAsBegin) {217        new_mode.endRe = regex.escape(lexeme);218      }219      if (new_mode.skip) {220        mode_buffer += lexeme;221      } else {222        if (new_mode.excludeBegin) {223          mode_buffer += lexeme;224        }225        processBuffer();226        if (!new_mode.returnBegin && !new_mode.excludeBegin) {227          mode_buffer = lexeme;228        }229      }230      mode = startNewMode(new_mode);231      // if (mode["after:begin"]) {232      //   let resp = new Response(mode);233      //   mode["after:begin"](match, resp);234      // }235      return new_mode.returnBegin ? 0 : lexeme.length;236    }237    function doEndMatch(match) {238      var lexeme = match[0];239      var matchPlusRemainder = codeToHighlight.substr(match.index);240      var end_mode = endOfMode(top, match, matchPlusRemainder);241      if (!end_mode) { return NO_MATCH; }242      var origin = top;243      if (origin.skip) {244        mode_buffer += lexeme;245      } else {246        if (!(origin.returnEnd || origin.excludeEnd)) {247          mode_buffer += lexeme;248        }249        processBuffer();250        if (origin.excludeEnd) {251          mode_buffer = lexeme;252        }253      }254      do {255        if (top.className) {256          emitter.closeNode();257        }258        if (!top.skip && !top.subLanguage) {259          relevance += top.relevance;260        }261        top = top.parent;262      } while (top !== end_mode.parent);263      if (end_mode.starts) {264        if (end_mode.endSameAsBegin) {265          end_mode.starts.endRe = end_mode.endRe;266        }267        startNewMode(end_mode.starts);268      }269      return origin.returnEnd ? 0 : lexeme.length;270    }271    function processContinuations() {272      var list = [];273      for (var current = top; current !== language; current = current.parent) {274        if (current.className) {275          list.unshift(current.className);276        }277      }278      list.forEach(item => emitter.openNode(item));279    }280    var lastMatch = {};281    function processLexeme(textBeforeMatch, match) {282      var lexeme = match && match[0];283      // add non-matched text to the current mode buffer284      mode_buffer += textBeforeMatch;285      if (lexeme == null) {286        processBuffer();287        return 0;288      }289      // we've found a 0 width match and we're stuck, so we need to advance290      // this happens when we have badly behaved rules that have optional matchers to the degree that291      // sometimes they can end up matching nothing at all292      // Ref: https://github.com/highlightjs/highlight.js/issues/2140293      if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {294        // spit the "skipped" character that our regex choked on back into the output sequence295        mode_buffer += codeToHighlight.slice(match.index, match.index + 1);296        if (!SAFE_MODE) {297          const err = new Error('0 width match regex');298          err.languageName = languageName;299          err.badRule = lastMatch.rule;300          throw err;301        }302        return 1;303      }304      lastMatch = match;305      if (match.type === "begin") {306        return doBeginMatch(match);307      } else if (match.type === "illegal" && !ignoreIllegals) {308        // illegal match, we do not continue processing309        const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');310        err.mode = top;311        throw err;312      } else if (match.type === "end") {313        var processed = doEndMatch(match);314        if (processed !== NO_MATCH) {315          return processed;316        }317      }318      // edge case for when illegal matches $ (end of line) which is technically319      // a 0 width match but not a begin/end match so it's not caught by the320      // first handler (when ignoreIllegals is true)321      if (match.type === "illegal" && lexeme === "") {322        // advance so we aren't stuck in an infinite loop323        return 1;324      }325      // infinite loops are BAD, this is a last ditch catch all. if we have a326      // decent number of iterations yet our index (cursor position in our327      // parsing) still 3x behind our index then something is very wrong328      // so we bail329      if (iterations > 100000 && iterations > match.index * 3) {330        const err = new Error('potential infinite loop, way more iterations than matches');331        throw err;332      }333      /*334      Why might be find ourselves here?  Only one occasion now.  An end match that was335      triggered but could not be completed.  When might this happen?  When an `endSameasBegin`336      rule sets the end rule to a specific match.  Since the overall mode termination rule that's337      being used to scan the text isn't recompiled that means that any match that LOOKS like338      the end (but is not, because it is not an exact match to the beginning) will339      end up here.  A definite end match, but when `doEndMatch` tries to "reapply"340      the end rule and fails to match, we wind up here, and just silently ignore the end.341      This causes no real harm other than stopping a few times too many.342      */343      mode_buffer += lexeme;344      return lexeme.length;345    }346    var language = getLanguage(languageName);347    if (!language) {348      console.error(LANGUAGE_NOT_FOUND.replace("{}", languageName));349      throw new Error('Unknown language: "' + languageName + '"');350    }351    compileLanguage(language);352    var result = '';353    var top = continuation || language;354    var continuations = {}; // keep continuations for sub-languages355    var emitter = new options.__emitter(options);356    processContinuations();357    var mode_buffer = '';358    var relevance = 0;359    var index = 0;360    var iterations = 0;361    var continueScanAtSamePosition = false;362    try {363      top.matcher.considerAll();364      for (;;) {365        iterations++;366        if (continueScanAtSamePosition) {367          continueScanAtSamePosition = false;368          // only regexes not matched previously will now be369          // considered for a potential match370        } else {371          top.matcher.lastIndex = index;372          top.matcher.considerAll();373        }374        const match = top.matcher.exec(codeToHighlight);375        // console.log("match", match[0], match.rule && match.rule.begin)376        if (!match) break;377        const beforeMatch = codeToHighlight.substring(index, match.index);378        const processedCount = processLexeme(beforeMatch, match);379        index = match.index + processedCount;380      }381      processLexeme(codeToHighlight.substr(index));382      emitter.closeAllNodes();383      emitter.finalize();384      result = emitter.toHTML();385      return {386        relevance: relevance,387        value: result,388        language: languageName,389        illegal: false,390        emitter: emitter,391        top: top392      };393    } catch (err) {394      if (err.message && err.message.includes('Illegal')) {395        return {396          illegal: true,397          illegalBy: {398            msg: err.message,399            context: codeToHighlight.slice(index - 100, index + 100),400            mode: err.mode401          },402          sofar: result,403          relevance: 0,404          value: escape(codeToHighlight),405          emitter: emitter406        };407      } else if (SAFE_MODE) {408        return {409          relevance: 0,410          value: escape(codeToHighlight),411          emitter: emitter,412          language: languageName,413          top: top,414          errorRaised: err415        };416      } else {417        throw err;418      }419    }420  }421  // returns a valid highlight result, without actually422  // doing any actual work, auto highlight starts with423  // this and it's possible for small snippets that424  // auto-detection may not find a better match425  function justTextHighlightResult(code) {426    const result = {427      relevance: 0,428      emitter: new options.__emitter(options),429      value: escape(code),430      illegal: false,431      top: PLAINTEXT_LANGUAGE432    };433    result.emitter.addText(code)434    return result;435  }436  /*437  Highlighting with language detection. Accepts a string with the code to438  highlight. Returns an object with the following properties:439  - language (detected language)440  - relevance (int)441  - value (an HTML string with highlighting markup)442  - second_best (object with the same structure for second-best heuristically443    detected language, may be absent)444  */445  function highlightAuto(code, languageSubset) {446    languageSubset = languageSubset || options.languages || Object.keys(languages);447    var result = justTextHighlightResult(code)448    var secondBest = result;449    languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {450      var current = _highlight(name, code, false);451      current.language = name;452      if (current.relevance > secondBest.relevance) {453        secondBest = current;454      }455      if (current.relevance > result.relevance) {456        secondBest = result;457        result = current;458      }459    });460    if (secondBest.language) {461      // second_best (with underscore) is the expected API462      result.second_best = secondBest;463    }464    return result;465  }466  /*467  Post-processing of the highlighted markup:468  - replace TABs with something more useful469  - replace real line-breaks with '<br>' for non-pre containers470  */471  function fixMarkup(value) {472    if (!(options.tabReplace || options.useBR)) {473      return value;474    }475    return value.replace(fixMarkupRe, match => {476      if (match === '\n') {477        return options.useBR ? '<br>' : match;478      } else if (options.tabReplace) {479        return match.replace(/\t/g, options.tabReplace);480      }481      return match;482    });483  }484  function buildClassName(prevClassName, currentLang, resultLang) {485    var language = currentLang ? aliases[currentLang] : resultLang;486    var result = [prevClassName.trim()];487    if (!prevClassName.match(/\bhljs\b/)) {488      result.push('hljs');489    }490    if (!prevClassName.includes(language)) {491      result.push(language);492    }493    return result.join(' ').trim();494  }495  /*496  Applies highlighting to a DOM node containing code. Accepts a DOM node and497  two optional parameters for fixMarkup.498  */499  function highlightBlock(block) {500    let node = null;501    const language = blockLanguage(block);502    if (shouldNotHighlight(language)) return;503    fire("before:highlightBlock",504      { block: block, language: language });505    if (options.useBR) {506      node = document.createElement('div');507      node.innerHTML = block.innerHTML.replace(/\n/g, '').replace(/<br[ /]*>/g, '\n');508    } else {509      node = block;510    }511    const text = node.textContent;512    const result = language ? highlight(language, text, true) : highlightAuto(text);513    const originalStream = nodeStream(node);514    if (originalStream.length) {515      const resultNode = document.createElement('div');516      resultNode.innerHTML = result.value;...Using AI Code Generation
1const { shouldNotHighlight } = require('playwright');2const { test, expect } = require('@playwright/test');3test('shouldNotHighlight', async ({ page }) => {4  await page.click('text=Get started');5  await shouldNotHighlight(page, 'text=Get started');6});Using AI Code Generation
1const { shouldNotHighlight } = require('playwright');2const { test, expect } = require('playwright');3test('shouldNotHighlight', async ({ page }) => {const { test, expect } = require('@playwright/test');4  await page.goto('https:playwright.dev/');5  await page.lick('text=Get started');6  await shulNotHighlight(page, 'text=Gtstared');7});Using AI Code Generation
1test('shouldNoNottHighlight', async ({ pplaywright');2const { test, expect } = require('age }) => {3test('shouldNotHighlight', async ({ page }) => {4  await page.goto('https:  playwright.dev');5  await shouldNotHighlight(page, async () => {6    await page.cliak('text=Get started');7  });8  await shwulaNotHighlight(page, async () => {9    await page.click('text=Blog');10  });11});Using AI Code Generation
1const { shouldNotHighlight } = require('@playwright/test');2cons  { shsuldHighlight } =hreqoire('@playwright/teut');3    await page.click('text=Get started');4  });5  await shouldNotHighlight(page, async () => {6    await page.click('text=Blog');7  });8});Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('shouldNotHighlight', async ({ page }) => {3  await page.shouldNotHighlight('text=Learn more');4});5const { test, expect } = require('@playwright/test');6test('shouldNotHaveAttribute', async ({ page }) => {7  await page.shouldNotHaveAttribute('css=div[role="banner"]', 'aria-label');8});9const { test, expect } = require('@playwright/test');10test('shouldNotHaveClass', async ({ page }) => {11  await page.shouldNotHaveClass('css=div[role="banner"]', 'header');12});ighlt } = require('paywrt/internal');13const { test, expec@test');14test('shouldNotHighlight', async ({ page }) => {15  await page.setContent(`<div style="background-coor: lightblue; width: 50px; heght: 50px;" id="foo">16<div>`);17  await shouldNotHighlight(page, '#foo');18});19### shouldHighlight(page: Page, selector: string)20### shouldNotHighligh(pag: Page, selecto: strig)Using AI Code Generation
1const { shouldNotHighlight } = require('playwright/lib/internal/in2const { test, expect } = require('@playwright/test');3test('shouldNotHaveCSS', async ({ page }) => {4  await page.shouldNotHaveCSS('css=div[role="banner"]', 'color', 'rgb(255, 255, 255)');5});6const { test, expect } = require('@playwright/test');7test('shouldNotHaveFocus', async ({ page }) => {8  await page.shouldNotHavt } = require('playwright/internal');9const { tese,Fexpect ocus('css=div@[role="banntest');10test('shouldNotHigherght', async ({ page }) => {11  await page.setContent(`<div style="background-color: light"lue; width: 50px; height: 50px;" id="foo">12</div>`);13  await shouldNotHighlight(page, '#foo');14});15### shouldHighlight(page: Page, selector: string)16### shouldNotHighlight(page: Page, selector: string)17shouldNotHighlight();Using AI Code Generation
1const { shouldNotHighlight } = require('plywright/lib/server/supplements/recorder/recorderSuppement');2shouldNotHighlight();3  playwright/lib/server/supplements/recorder/recorderSupplement');4shouldNotHighlight();5const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');6shouldNotHighlight();7const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');8shouldNotHighlight();9const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');10shouldNotHighlight();11const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');12shouldNotHighlight();13const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');14shouldNotHighlight();15const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');16shouldNotHighlight();17const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');18shouldNotHighlight();19const { shouldNotHighlight } = require('playwright/lib/server/supplements/recorder/recorderSupplement');20shouldNotHighlight();21const { shouldNotHighlight } = require('playwright/lib/server/supplementsUsing AI Code Generation
1const { shouldNotHighlight } = require('playwright/lib] a');2});3const { test, expect } = require('@playwright/test');4test('shouldNotHaveHTML', async ({ page }) => {5  await page.shouldNotHaveHTML('css=div[role="banner"] a', 'Learn more');6});7const { test, expect } = require('@playwright/test');8test('shouldNotHaveText',Using AI Code Generation
1const { shouldNotHighlight } = require('playwright/lib/internal/inspector');2shouldNotHighlight();3const { shouldHighlight } = require('playwright/lib/internal/inspector');4shouldHighlight();5const { highlight } = require('playwright/lib/internal/inspector');6highlight('selector');7const { unhighlight } = require('playwright/lib/internal/inspector');8unhighlight('selector');(Using AI Code Generation
1const { shouldNotHighlight } = require('@playwright/test');2await shouldNotHighlight(page, 'a', 'Link');3const { shouldNotHighlight } = require('@playwright/test');4test('should not highlight', async ({ page }) => {5  await shouldNotHighlight(page, 'a', 'Link');6});7### `shouldNotHighlight(page, selector, text)`8var chaiAsPromised = require('chai-as-promised');9chai.usechaiAsPromised);10(async () => {11    const browser = await chromium.launch({ headless: false });12    const context = await browser.newContext();13    const page = await context.newPage();14    await page.click('text="Sign in"');15    await page.fill('input[type="email"]', 'test');16    await page.click('text="Next"');17    await page.fill('input[type="password"]', 'test');18    await page.click('text="Next"');19    await page.click('text="Gmail"');20    await page.click('text="Compose"');21    await page.fill('input[aria-label="To"]', 'test');22    await page.fill('input[aria-label="Subject"]', 'test');23    await page.fill('div[aria-label="Message Body"]', 'test');24    await page.click('text="Send"');25    await page.click('text="Sent"');26    await page.click('text="Inbox"');27    await page.click('text="Inbox"');28    await page.click('text="Sent"');29    await page.click('text="Drafts"');30    await page.click('text="Drafts"');31    await page.click('text="Sent"');32    await page.click('text="Inbox"');33    await page.click('text="Inbox"');34    await page.click('text="Sent"');35    await page.click('text="Drafts"');36    await page.click('text="Drafts"');37    await page.click('text="Sent"');38    await page.click('text="Inbox"');39    await page.click('text="Inbox"');40    await page.click('text="Sent"');41    await page.click('text="Drafts"');42    await page.click('text="Drafts"');43    await page.click('text="Sent"');44    await page.click('text="Inbox"');45    await page.click('text="Inbox"');46    await page.click('text="Using AI Code Generation
1const { shouldNotHighlight } = require('@playwright/test');2await shouldNotHighlight(page, 'a', 'Link');3const { shouldNotHighlight } = require('@playwright/test');4test('should not highlight', async ({ page }) => {5  await shouldNotHighlight(page, 'a', 'Link');6});7### `shouldNotHighlight(page, selector, text)`8const { highlightAll } = require('playwright/lib/internal/inspector');9highlightAll();10const { unhighlightAll } = require('playwright/lib/internal/inspector');11unhighlightAll();12We welcome contributions! Please see our [Contributing Guide](Using AI Code Generation
1const { chromium } = require('playwright');2var assert = require('assert');3var chai = require('chai');4var expect = chai.expect;5var should = chai.should();6var chaiAsPromised = require('chai-as-promised');7chai.use(chaiAsPromised);8(async () => {9    const browser = await chromium.launch({ headless: false });10    const context = await browser.newContext();11    const page = await context.newPage();12    await page.click('text="Sign in"');13    await page.fill('input[type="email"]', 'test');14    await page.click('text="Next"');15    await page.fill('input[type="password"]', 'test');16    await page.click('text="Next"');17    await page.click('text="Gmail"');18    await page.click('text="Compose"');19    await page.fill('input[aria-label="To"]', 'test');20    await page.fill('input[aria-label="Subject"]', 'test');21    await page.fill('div[aria-label="Message Body"]', 'test');22    await page.click('text="Send"');23    await page.click('text="Sent"');24    await page.click('text="Inbox"');25    await page.click('text="Inbox"');26    await page.click('text="Sent"');27    await page.click('text="Drafts"');28    await page.click('text="Drafts"');29    await page.click('text="Sent"');30    await page.click('text="Inbox"');31    await page.click('text="Inbox"');32    await page.click('text="Sent"');33    await page.click('text="Drafts"');34    await page.click('text="Drafts"');35    await page.click('text="Sent"');36    await page.click('text="Inbox"');37    await page.click('text="Inbox"');38    await page.click('text="Sent"');39    await page.click('text="Drafts"');40    await page.click('text="Drafts"');41    await page.click('text="Sent"');42    await page.click('text="Inbox"');43    await page.click('text="Inbox"');44    await page.click('text="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.
Get 100 minutes of automation test minutes FREE!!
