Best JavaScript code snippet using playwright-internal
highlight.js
Source:highlight.js
...731 /**732 * provides the default 1 relevance to all modes733 * @type {CompilerExt}734 */735 function compileRelevance(mode, _parent) {736 // eslint-disable-next-line no-undefined737 if (mode.relevance === undefined) mode.relevance = 1;738 }739 // allow beforeMatch to act as a "qualifier" for the match740 // the full match begin must be [beforeMatch][begin]741 const beforeMatchExt = (mode, parent) => {742 if (!mode.beforeMatch) return;743 // starts conflicts with endsParent which we need to make sure the child744 // rule is not matched multiple times745 if (mode.starts) throw new Error("beforeMatch cannot be used with starts");746 const originalMode = Object.assign({}, mode);747 Object.keys(mode).forEach((key) => { delete mode[key]; });748 mode.keywords = originalMode.keywords;749 mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));...
highlight.js_v11.3.1-0C5csJSkMVgQyOMzmIlU_dist_es2020_mode_imports_optimized_common_core-da5e7eef_1b12fcb113193245855a.js
Source:highlight.js_v11.3.1-0C5csJSkMVgQyOMzmIlU_dist_es2020_mode_imports_optimized_common_core-da5e7eef_1b12fcb113193245855a.js
...442 throw new Error("begin & end are not supported with match");443 mode.begin = mode.match;444 delete mode.match;445}446function compileRelevance(mode, _parent) {447 if (mode.relevance === void 0)448 mode.relevance = 1;449}450const beforeMatchExt = (mode, parent) => {451 if (!mode.beforeMatch)452 return;453 if (mode.starts)454 throw new Error("beforeMatch cannot be used with starts");455 const originalMode = Object.assign({}, mode);456 Object.keys(mode).forEach((key) => {457 delete mode[key];458 });459 mode.keywords = originalMode.keywords;460 mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));...
coder.js
Source:coder.js
...444 445 mode.begin = mode.match;446 delete mode.match;447}448function compileRelevance(mode, _parent) {449 // eslint-disable-next-line no-undefined450 if (mode.relevance === undefined) mode.relevance = 1;451}452// keywords that should have no default relevance value453const COMMON_KEYWORDS = [454 'of',455 'and',456 'for',457 'in',458 'not',459 'or',460 'if',461 'then',462 'parent', // common variable name...
core.js
Source:core.js
...454 if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");455 mode.begin = mode.match;456 delete mode.match;457}458function compileRelevance(mode, _parent) {459 // eslint-disable-next-line no-undefined460 if (mode.relevance === undefined) mode.relevance = 1;461}462const beforeMatchExt = (mode, parent) => {463 if (!mode.beforeMatch) return;464 if (mode.starts) throw new Error("beforeMatch cannot be used with starts");465 const originalMode = Object.assign({}, mode);466 Object.keys(mode).forEach((key) => { delete mode[key]; });467 mode.keywords = originalMode.keywords;468 mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));469 mode.starts = {470 relevance: 0,471 contains: [472 Object.assign(originalMode, { endsParent: true })...
mode_compiler_20210105153356.js
Source:mode_compiler_20210105153356.js
1import * as regex from './regex.js';2import { inherit } from './utils.js';3import * as EXT from "./compiler_extensions.js";4import { compileKeywords } from "./compile_keywords.js";5// compilation6/**7 * Compiles a language definition result8 *9 * Given the raw result of a language definition (Language), compiles this so10 * that it is ready for highlighting code.11 * @param {Language} language12 * @param {{plugins: HLJSPlugin[]}} opts13 * @returns {CompiledLanguage}14 */15export function compileLanguage(language, { plugins }) {16 /**17 * Builds a regex with the case sensativility of the current language18 *19 * @param {RegExp | string} value20 * @param {boolean} [global]21 */22 function langRe(value, global) {23 return new RegExp(24 regex.source(value),25 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')26 );27 }28 /**29 Stores multiple regular expressions and allows you to quickly search for30 them all in a string simultaneously - returning the first match. It does31 this by creating a huge (a|b|c) regex - each individual item wrapped with ()32 and joined by `|` - using match groups to track position. When a match is33 found checking which position in the array has content allows us to figure34 out which of the original regexes / match groups triggered the match.35 The match object itself (the result of `Regex.exec`) is returned but also36 enhanced by merging in any meta-data that was registered with the regex.37 This is how we keep track of which mode matched, and what type of rule38 (`illegal`, `begin`, end, etc).39 */40 class MultiRegex {41 constructor() {42 this.matchIndexes = {};43 // @ts-ignore44 this.regexes = [];45 this.matchAt = 1;46 this.position = 0;47 }48 // @ts-ignore49 addRule(re, opts) {50 opts.position = this.position++;51 // @ts-ignore52 this.matchIndexes[this.matchAt] = opts;53 this.regexes.push([opts, re]);54 this.matchAt += regex.countMatchGroups(re) + 1;55 }56 compile() {57 if (this.regexes.length === 0) {58 // avoids the need to check length every time exec is called59 // @ts-ignore60 this.exec = () => null;61 }62 const terminators = this.regexes.map(el => el[1]);63 this.matcherRe = langRe(regex.join(terminators), true);64 this.lastIndex = 0;65 }66 /** @param {string} s */67 exec(s) {68 this.matcherRe.lastIndex = this.lastIndex;69 const match = this.matcherRe.exec(s);70 if (!match) { return null; }71 // eslint-disable-next-line no-undefined72 const i = match.findIndex((el, i) => i > 0 && el !== undefined);73 // @ts-ignore74 const matchData = this.matchIndexes[i];75 // trim off any earlier non-relevant match groups (ie, the other regex76 // match groups that make up the multi-matcher)77 match.splice(0, i);78 return Object.assign(match, matchData);79 }80 }81 /*82 Created to solve the key deficiently with MultiRegex - there is no way to83 test for multiple matches at a single location. Why would we need to do84 that? In the future a more dynamic engine will allow certain matches to be85 ignored. An example: if we matched say the 3rd regex in a large group but86 decided to ignore it - we'd need to started testing again at the 4th87 regex... but MultiRegex itself gives us no real way to do that.88 So what this class creates MultiRegexs on the fly for whatever search89 position they are needed.90 NOTE: These additional MultiRegex objects are created dynamically. For most91 grammars most of the time we will never actually need anything more than the92 first MultiRegex - so this shouldn't have too much overhead.93 Say this is our search group, and we match regex3, but wish to ignore it.94 regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 095 What we need is a new MultiRegex that only includes the remaining96 possibilities:97 regex4 | regex5 ' ie, startAt = 398 This class wraps all that complexity up in a simple API... `startAt` decides99 where in the array of expressions to start doing the matching. It100 auto-increments, so if a match is found at position 2, then startAt will be101 set to 3. If the end is reached startAt will return to 0.102 MOST of the time the parser will be setting startAt manually to 0.103 */104 class ResumableMultiRegex {105 constructor() {106 // @ts-ignore107 this.rules = [];108 // @ts-ignore109 this.multiRegexes = [];110 this.count = 0;111 this.lastIndex = 0;112 this.regexIndex = 0;113 }114 // @ts-ignore115 getMatcher(index) {116 if (this.multiRegexes[index]) return this.multiRegexes[index];117 const matcher = new MultiRegex();118 this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));119 matcher.compile();120 this.multiRegexes[index] = matcher;121 return matcher;122 }123 resumingScanAtSamePosition() {124 return this.regexIndex !== 0;125 }126 considerAll() {127 this.regexIndex = 0;128 }129 // @ts-ignore130 addRule(re, opts) {131 this.rules.push([re, opts]);132 if (opts.type === "begin") this.count++;133 }134 /** @param {string} s */135 exec(s) {136 const m = this.getMatcher(this.regexIndex);137 m.lastIndex = this.lastIndex;138 let result = m.exec(s);139 // The following is because we have no easy way to say "resume scanning at the140 // existing position but also skip the current rule ONLY". What happens is141 // all prior rules are also skipped which can result in matching the wrong142 // thing. Example of matching "booger":143 // our matcher is [string, "booger", number]144 //145 // ....booger....146 // if "booger" is ignored then we'd really need a regex to scan from the147 // SAME position for only: [string, number] but ignoring "booger" (if it148 // was the first match), a simple resume would scan ahead who knows how149 // far looking only for "number", ignoring potential string matches (or150 // future "booger" matches that might be valid.)151 // So what we do: We execute two matchers, one resuming at the same152 // position, but the second full matcher starting at the position after:153 // /--- resume first regex match here (for [number])154 // |/---- full match here for [string, "booger", number]155 // vv156 // ....booger....157 // Which ever results in a match first is then used. So this 3-4 step158 // process essentially allows us to say "match at this position, excluding159 // a prior rule that was ignored".160 //161 // 1. Match "booger" first, ignore. Also proves that [string] does non match.162 // 2. Resume matching for [number]163 // 3. Match at index + 1 for [string, "booger", number]164 // 4. If #2 and #3 result in matches, which came first?165 if (this.resumingScanAtSamePosition()) {166 if (result && result.index === this.lastIndex) {167 // result is position +0 and therefore a valid168 // "resume" match so result stays result169 } else { // use the second matcher result170 const m2 = this.getMatcher(0);171 m2.lastIndex = this.lastIndex + 1;172 result = m2.exec(s);173 }174 }175 if (result) {176 this.regexIndex += result.position + 1;177 if (this.regexIndex === this.count) {178 // wrap-around to considering all matches again179 this.considerAll();180 }181 }182 return result;183 }184 }185 /**186 * Given a mode, builds a huge ResumableMultiRegex that can be used to walk187 * the content and find matches.188 *189 * @param {CompiledMode} mode190 * @returns {ResumableMultiRegex}191 */192 function buildModeRegex(mode) {193 const mm = new ResumableMultiRegex();194 mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));195 if (mode.terminatorEnd) {196 mm.addRule(mode.terminatorEnd, { type: "end" });197 }198 if (mode.illegal) {199 mm.addRule(mode.illegal, { type: "illegal" });200 }201 return mm;202 }203 /** skip vs abort vs ignore204 *205 * @skip - The mode is still entered and exited normally (and contains rules apply),206 * but all content is held and added to the parent buffer rather than being207 * output when the mode ends. Mostly used with `sublanguage` to build up208 * a single large buffer than can be parsed by sublanguage.209 *210 * - The mode begin ands ends normally.211 * - Content matched is added to the parent mode buffer.212 * - The parser cursor is moved forward normally.213 *214 * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it215 * never matched) but DOES NOT continue to match subsequent `contains`216 * modes. Abort is bad/suboptimal because it can result in modes217 * farther down not getting applied because an earlier rule eats the218 * content but then aborts.219 *220 * - The mode does not begin.221 * - Content matched by `begin` is added to the mode buffer.222 * - The parser cursor is moved forward accordingly.223 *224 * @ignore - Ignores the mode (as if it never matched) and continues to match any225 * subsequent `contains` modes. Ignore isn't technically possible with226 * the current parser implementation.227 *228 * - The mode does not begin.229 * - Content matched by `begin` is ignored.230 * - The parser cursor is not moved forward.231 */232 /**233 * Compiles an individual mode234 *235 * This can raise an error if the mode contains certain detectable known logic236 * issues.237 * @param {Mode} mode238 * @param {CompiledMode | null} [parent]239 * @returns {CompiledMode | never}240 */241 function compileMode(mode, parent) {242 const cmode = /** @type CompiledMode */ (mode);243 if (mode.compiled) return cmode;244 [245 // do this early so compiler extensions generally don't have to worry about246 // the distinction between match/begin247 EXT.compileMatch248 ].forEach(ext => ext(mode, parent));249 language.compilerExtensions.forEach(ext => ext(mode, parent));250 // __beforeBegin is considered private API, internal use only251 mode.__beforeBegin = null;252 [253 EXT.beginKeywords,254 // do this later so compiler extensions that come earlier have access to the255 // raw array if they wanted to perhaps manipulate it, etc.256 EXT.compileIllegal,257 // default to 1 relevance if not specified258 EXT.compileRelevance259 ].forEach(ext => ext(mode, parent));260 mode.compiled = true;261 let keywordPattern = null;262 if (typeof mode.keywords === "object") {263 keywordPattern = mode.keywords.$pattern;264 delete mode.keywords.$pattern;265 }266 if (mode.keywords) {267 mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);268 }269 // both are not allowed270 if (mode.lexemes && keywordPattern) {271 throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");272 }273 // `mode.lexemes` was the old standard before we added and now recommend274 // using `keywords.$pattern` to pass the keyword pattern275 keywordPattern = keywordPattern || mode.lexemes || /\w+/;276 cmode.keywordPatternRe = langRe(keywordPattern, true);277 if (parent) {278 if (!mode.begin) mode.begin = /\B|\b/;279 cmode.beginRe = langRe(mode.begin);280 if (mode.endSameAsBegin) mode.end = mode.begin;281 if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;282 if (mode.end) cmode.endRe = langRe(mode.end);283 cmode.terminatorEnd = regex.source(mode.end) || '';284 if (mode.endsWithParent && parent.terminatorEnd) {285 cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd;286 }287 }288 if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal));289 if (!mode.contains) mode.contains = [];290 mode.contains = [].concat(...mode.contains.map(function(c) {291 return expandOrCloneMode(c === 'self' ? mode : c);292 }));293 mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });294 if (mode.starts) {295 compileMode(mode.starts, parent);296 }297 cmode.matcher = buildModeRegex(cmode);298 return cmode;299 }300 if (!language.compilerExtensions) language.compilerExtensions = [];301 // self is not valid at the top-level302 if (language.contains && language.contains.includes('self')) {303 throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");304 }305 // we need a null object, which inherit will guarantee306 language.classNameAliases = inherit(language.classNameAliases || {});307 return compileMode(/** @type Mode */ (language));308}309/**310 * Determines if a mode has a dependency on it's parent or not311 *312 * If a mode does have a parent dependency then often we need to clone it if313 * it's used in multiple places so that each copy points to the correct parent,314 * where-as modes without a parent can often safely be re-used at the bottom of315 * a mode chain.316 *317 * @param {Mode | null} mode318 * @returns {boolean} - is there a dependency on the parent?319 * */320function dependencyOnParent(mode) {321 if (!mode) return false;322 return mode.endsWithParent || dependencyOnParent(mode.starts);323}324/**325 * Expands a mode or clones it if necessary326 *327 * This is necessary for modes with parental dependenceis (see notes on328 * `dependencyOnParent`) and for nodes that have `variants` - which must then be329 * exploded into their own individual modes at compile time.330 *331 * @param {Mode} mode332 * @returns {Mode | Mode[]}333 * */334function expandOrCloneMode(mode) {335 if (mode.variants && !mode.cachedVariants) {336 mode.cachedVariants = mode.variants.map(function(variant) {337 return inherit(mode, { variants: null }, variant);338 });339 }340 // EXPAND341 // if we have variants then essentially "replace" the mode with the variants342 // this happens in compileMode, where this function is called from343 if (mode.cachedVariants) {344 return mode.cachedVariants;345 }346 // CLONE347 // if we have dependencies on parents then we need a unique348 // instance of ourselves, so we can be reused with many349 // different parents without issue350 if (dependencyOnParent(mode)) {351 return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });352 }353 if (Object.isFrozen(mode)) {354 return inherit(mode);355 }356 // no special dependency issues, just return ourselves357 return mode;...
mode_compiler.js
Source:mode_compiler.js
1import * as regex from './regex.js';2import { inherit } from './utils.js';3import * as EXT from "./compiler_extensions.js";4import { compileKeywords } from "./compile_keywords.js";5// compilation6/**7 * Compiles a language definition result8 *9 * Given the raw result of a language definition (Language), compiles this so10 * that it is ready for highlighting code.11 * @param {Language} language12 * @param {{plugins: HLJSPlugin[]}} opts13 * @returns {CompiledLanguage}14 */15export function compileLanguage(language, { plugins }) {16 /**17 * Builds a regex with the case sensativility of the current language18 *19 * @param {RegExp | string} value20 * @param {boolean} [global]21 */22 function langRe(value, global) {23 return new RegExp(24 regex.source(value),25 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')26 );27 }28 /**29 Stores multiple regular expressions and allows you to quickly search for30 them all in a string simultaneously - returning the first match. It does31 this by creating a huge (a|b|c) regex - each individual item wrapped with ()32 and joined by `|` - using match groups to track position. When a match is33 found checking which position in the array has content allows us to figure34 out which of the original regexes / match groups triggered the match.35 The match object itself (the result of `Regex.exec`) is returned but also36 enhanced by merging in any meta-data that was registered with the regex.37 This is how we keep track of which mode matched, and what type of rule38 (`illegal`, `begin`, end, etc).39 */40 class MultiRegex {41 constructor() {42 this.matchIndexes = {};43 // @ts-ignore44 this.regexes = [];45 this.matchAt = 1;46 this.position = 0;47 }48 // @ts-ignore49 addRule(re, opts) {50 opts.position = this.position++;51 // @ts-ignore52 this.matchIndexes[this.matchAt] = opts;53 this.regexes.push([opts, re]);54 this.matchAt += regex.countMatchGroups(re) + 1;55 }56 compile() {57 if (this.regexes.length === 0) {58 // avoids the need to check length every time exec is called59 // @ts-ignore60 this.exec = () => null;61 }62 const terminators = this.regexes.map(el => el[1]);63 this.matcherRe = langRe(regex.join(terminators), true);64 this.lastIndex = 0;65 }66 /** @param {string} s */67 exec(s) {68 this.matcherRe.lastIndex = this.lastIndex;69 const match = this.matcherRe.exec(s);70 if (!match) { return null; }71 // eslint-disable-next-line no-undefined72 const i = match.findIndex((el, i) => i > 0 && el !== undefined);73 // @ts-ignore74 const matchData = this.matchIndexes[i];75 // trim off any earlier non-relevant match groups (ie, the other regex76 // match groups that make up the multi-matcher)77 match.splice(0, i);78 return Object.assign(match, matchData);79 }80 }81 /*82 Created to solve the key deficiently with MultiRegex - there is no way to83 test for multiple matches at a single location. Why would we need to do84 that? In the future a more dynamic engine will allow certain matches to be85 ignored. An example: if we matched say the 3rd regex in a large group but86 decided to ignore it - we'd need to started testing again at the 4th87 regex... but MultiRegex itself gives us no real way to do that.88 So what this class creates MultiRegexs on the fly for whatever search89 position they are needed.90 NOTE: These additional MultiRegex objects are created dynamically. For most91 grammars most of the time we will never actually need anything more than the92 first MultiRegex - so this shouldn't have too much overhead.93 Say this is our search group, and we match regex3, but wish to ignore it.94 regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 095 What we need is a new MultiRegex that only includes the remaining96 possibilities:97 regex4 | regex5 ' ie, startAt = 398 This class wraps all that complexity up in a simple API... `startAt` decides99 where in the array of expressions to start doing the matching. It100 auto-increments, so if a match is found at position 2, then startAt will be101 set to 3. If the end is reached startAt will return to 0.102 MOST of the time the parser will be setting startAt manually to 0.103 */104 class ResumableMultiRegex {105 constructor() {106 // @ts-ignore107 this.rules = [];108 // @ts-ignore109 this.multiRegexes = [];110 this.count = 0;111 this.lastIndex = 0;112 this.regexIndex = 0;113 }114 // @ts-ignore115 getMatcher(index) {116 if (this.multiRegexes[index]) return this.multiRegexes[index];117 const matcher = new MultiRegex();118 this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));119 matcher.compile();120 this.multiRegexes[index] = matcher;121 return matcher;122 }123 resumingScanAtSamePosition() {124 return this.regexIndex !== 0;125 }126 considerAll() {127 this.regexIndex = 0;128 }129 // @ts-ignore130 addRule(re, opts) {131 this.rules.push([re, opts]);132 if (opts.type === "begin") this.count++;133 }134 /** @param {string} s */135 exec(s) {136 const m = this.getMatcher(this.regexIndex);137 m.lastIndex = this.lastIndex;138 let result = m.exec(s);139 // The following is because we have no easy way to say "resume scanning at the140 // existing position but also skip the current rule ONLY". What happens is141 // all prior rules are also skipped which can result in matching the wrong142 // thing. Example of matching "booger":143 // our matcher is [string, "booger", number]144 //145 // ....booger....146 // if "booger" is ignored then we'd really need a regex to scan from the147 // SAME position for only: [string, number] but ignoring "booger" (if it148 // was the first match), a simple resume would scan ahead who knows how149 // far looking only for "number", ignoring potential string matches (or150 // future "booger" matches that might be valid.)151 // So what we do: We execute two matchers, one resuming at the same152 // position, but the second full matcher starting at the position after:153 // /--- resume first regex match here (for [number])154 // |/---- full match here for [string, "booger", number]155 // vv156 // ....booger....157 // Which ever results in a match first is then used. So this 3-4 step158 // process essentially allows us to say "match at this position, excluding159 // a prior rule that was ignored".160 //161 // 1. Match "booger" first, ignore. Also proves that [string] does non match.162 // 2. Resume matching for [number]163 // 3. Match at index + 1 for [string, "booger", number]164 // 4. If #2 and #3 result in matches, which came first?165 if (this.resumingScanAtSamePosition()) {166 if (result && result.index === this.lastIndex) {167 // result is position +0 and therefore a valid168 // "resume" match so result stays result169 } else { // use the second matcher result170 const m2 = this.getMatcher(0);171 m2.lastIndex = this.lastIndex + 1;172 result = m2.exec(s);173 }174 }175 if (result) {176 this.regexIndex += result.position + 1;177 if (this.regexIndex === this.count) {178 // wrap-around to considering all matches again179 this.considerAll();180 }181 }182 return result;183 }184 }185 /**186 * Given a mode, builds a huge ResumableMultiRegex that can be used to walk187 * the content and find matches.188 *189 * @param {CompiledMode} mode190 * @returns {ResumableMultiRegex}191 */192 function buildModeRegex(mode) {193 const mm = new ResumableMultiRegex();194 mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));195 if (mode.terminatorEnd) {196 mm.addRule(mode.terminatorEnd, { type: "end" });197 }198 if (mode.illegal) {199 mm.addRule(mode.illegal, { type: "illegal" });200 }201 return mm;202 }203 /** skip vs abort vs ignore204 *205 * @skip - The mode is still entered and exited normally (and contains rules apply),206 * but all content is held and added to the parent buffer rather than being207 * output when the mode ends. Mostly used with `sublanguage` to build up208 * a single large buffer than can be parsed by sublanguage.209 *210 * - The mode begin ands ends normally.211 * - Content matched is added to the parent mode buffer.212 * - The parser cursor is moved forward normally.213 *214 * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it215 * never matched) but DOES NOT continue to match subsequent `contains`216 * modes. Abort is bad/suboptimal because it can result in modes217 * farther down not getting applied because an earlier rule eats the218 * content but then aborts.219 *220 * - The mode does not begin.221 * - Content matched by `begin` is added to the mode buffer.222 * - The parser cursor is moved forward accordingly.223 *224 * @ignore - Ignores the mode (as if it never matched) and continues to match any225 * subsequent `contains` modes. Ignore isn't technically possible with226 * the current parser implementation.227 *228 * - The mode does not begin.229 * - Content matched by `begin` is ignored.230 * - The parser cursor is not moved forward.231 */232 /**233 * Compiles an individual mode234 *235 * This can raise an error if the mode contains certain detectable known logic236 * issues.237 * @param {Mode} mode238 * @param {CompiledMode | null} [parent]239 * @returns {CompiledMode | never}240 */241 function compileMode(mode, parent) {242 const cmode = /** @type CompiledMode */ (mode);243 if (mode.compiled) return cmode;244 [245 // do this early so compiler extensions generally don't have to worry about246 // the distinction between match/begin247 EXT.compileMatch248 ].forEach(ext => ext(mode, parent));249 language.compilerExtensions.forEach(ext => ext(mode, parent));250 // __beforeBegin is considered public API, internal use only251 mode.__beforeBegin = null;252 [253 EXT.beginKeywords,254 // do this later so compiler extensions that come earlier have access to the255 // raw array if they wanted to perhaps manipulate it, etc.256 EXT.compileIllegal,257 // default to 1 relevance if not specified258 EXT.compileRelevance259 ].forEach(ext => ext(mode, parent));260 mode.compiled = true;261 let keywordPattern = null;262 if (typeof mode.keywords === "object") {263 keywordPattern = mode.keywords.$pattern;264 delete mode.keywords.$pattern;265 }266 if (mode.keywords) {267 mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);268 }269 // both are not allowed270 if (mode.lexemes && keywordPattern) {271 throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");272 }273 // `mode.lexemes` was the old standard before we added and now recommend274 // using `keywords.$pattern` to pass the keyword pattern275 keywordPattern = keywordPattern || mode.lexemes || /\w+/;276 cmode.keywordPatternRe = langRe(keywordPattern, true);277 if (parent) {278 if (!mode.begin) mode.begin = /\B|\b/;279 cmode.beginRe = langRe(mode.begin);280 if (mode.endSameAsBegin) mode.end = mode.begin;281 if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;282 if (mode.end) cmode.endRe = langRe(mode.end);283 cmode.terminatorEnd = regex.source(mode.end) || '';284 if (mode.endsWithParent && parent.terminatorEnd) {285 cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd;286 }287 }288 if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal));289 if (!mode.contains) mode.contains = [];290 mode.contains = [].concat(...mode.contains.map(function(c) {291 return expandOrCloneMode(c === 'self' ? mode : c);292 }));293 mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });294 if (mode.starts) {295 compileMode(mode.starts, parent);296 }297 cmode.matcher = buildModeRegex(cmode);298 return cmode;299 }300 if (!language.compilerExtensions) language.compilerExtensions = [];301 // self is not valid at the top-level302 if (language.contains && language.contains.includes('self')) {303 throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");304 }305 // we need a null object, which inherit will guarantee306 language.classNameAliases = inherit(language.classNameAliases || {});307 return compileMode(/** @type Mode */ (language));308}309/**310 * Determines if a mode has a dependency on it's parent or not311 *312 * If a mode does have a parent dependency then often we need to clone it if313 * it's used in multiple places so that each copy points to the correct parent,314 * where-as modes without a parent can often safely be re-used at the bottom of315 * a mode chain.316 *317 * @param {Mode | null} mode318 * @returns {boolean} - is there a dependency on the parent?319 * */320function dependencyOnParent(mode) {321 if (!mode) return false;322 return mode.endsWithParent || dependencyOnParent(mode.starts);323}324/**325 * Expands a mode or clones it if necessary326 *327 * This is necessary for modes with parental dependenceis (see notes on328 * `dependencyOnParent`) and for nodes that have `variants` - which must then be329 * exploded into their own individual modes at compile time.330 *331 * @param {Mode} mode332 * @returns {Mode | Mode[]}333 * */334function expandOrCloneMode(mode) {335 if (mode.variants && !mode.cachedVariants) {336 mode.cachedVariants = mode.variants.map(function(variant) {337 return inherit(mode, { variants: null }, variant);338 });339 }340 // EXPAND341 // if we have variants then essentially "replace" the mode with the variants342 // this happens in compileMode, where this function is called from343 if (mode.cachedVariants) {344 return mode.cachedVariants;345 }346 // CLONE347 // if we have dependencies on parents then we need a unique348 // instance of ourselves, so we can be reused with many349 // different parents without issue350 if (dependencyOnParent(mode)) {351 return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });352 }353 if (Object.isFrozen(mode)) {354 return inherit(mode);355 }356 // no special dependency issues, just return ourselves357 return mode;...
compiler_extensions.js
Source:compiler_extensions.js
...63/**64 * provides the default 1 relevance to all modes65 * @type {CompilerExt}66 */67export function compileRelevance(mode, _parent) {68 // eslint-disable-next-line no-undefined69 if (mode.relevance === undefined) mode.relevance = 1;...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const relevance = await page.evaluate(() => {6 const { compileRelevance } = window['playwright'].internal;7 return compileRelevance('Hello World');8 });9 console.log(relevance);10 await browser.close();11})();12{13 compiled: {14 compiled: { relevance: 'Hello World', compiled: 'Hello World' },15 },16}17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();
Using AI Code Generation
1const { chrhrium } = require('olaywrmght');2const { compiium } = require('playwright');corderSuppment');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 console.log(relevance);const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement');7 await browser.close();8})();
Using AI Code Generation
1(async () => {2 const browser = await chromium.launch();3 const page = await browser.newPage();4 console.log(relevance);5 await browser.close();6})();
Using AI Code Generation
1const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');2const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');3const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');4const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');5const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');6const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');7 require('playwright/lib/server/supplements/recorder/relevance');8const { compileRelevance } c9onst {= compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');10const { chromium } = require('playwright');11const { compileRelevance } = require('playwright/lib/internal/protocol/protocol.js');12(async () => {13 const browser = await chromium.launch();14 const page = await browser.newPage();15 const relevance = await compileRelevance(page, 'hello');16 console.log(relevance);17 await browser.close();18})();
Using AI Code Generation
1const playwright = require('playwright');2const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');3console.log(selector);4const playwright = require('playwright');5const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');6console.log(selector);7const playwright = require('playwright');8const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');9console.log(selector);10const playwright = require('playwright');11const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');12console.log(selector);13const playwright = require('playwright');14const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');15console.log(selector);16const playwright = require('playwright');17const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');
Using AI Code Generation
1const { InternalApi } = require('@playwright/test/lib/internal/api');2const { test } = require('@playwright/test');3test.use({4 async _beforeTest(testInfo) {5 const internalApi = new InternalApi(testInfo);6 const { compileRelevance } = internalApi;7 const relevance = compileRelevance('input[role="search"]');8 console.log(relevance);9 }10});11test('test', async ({ page }) => {12 await page.click('input[role="search"]');13});14"devDependencies": {15 }16 ✓ test (2s)17 1 passed (3s)
Using AI Code Generation
1const { InternalApi } = require('@playwright/test/lib/internal/api');2const { test } = require('@playwright/test');3test.use({4 async _beforeTest(testInfo) {5 const internalApi = new InternalApi(testInfo);6 const { compileRelevance } = internalApi;7 const relevance = compileRelevance('input[role="search"]');8 console.log(relevance);9 }10});11test('test', async ({ page }) => {12 await page.click('input[role="search"]');13});14"devDependencies": {15 }16 ✓ test (2s)17 1 passed (3s)
Using AI Code Generation
1const { compileRelevance } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');2const relevance = compileRelevance('button', 'Click me');3console.logcrelevance);4const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');5const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');6const { compileRelevance } = require('playwright/lib/server/supplements/recorder/relevance');7const { compileRelevance } =
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!!