feat(News): refactor news service and add sentiment tracking

This commit is contained in:
2026-08-09 21:01:41 +02:00
parent 605e41cfeb
commit aff831cf58
390 changed files with 115094 additions and 9 deletions
@@ -0,0 +1,267 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AriaKeyError = void 0;
exports.parseAriaKey = parseAriaKey;
exports.parseYamlTemplate = parseYamlTemplate;
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// https://www.w3.org/TR/wai-aria-1.2/#role_definitions
function parseYamlTemplate(fragment) {
const result = {
kind: 'role',
role: 'fragment'
};
populateNode(result, fragment);
if (result.children && result.children.length === 1) return result.children[0];
return result;
}
function populateNode(node, container) {
for (const object of container) {
if (typeof object === 'string') {
const childNode = KeyParser.parse(object);
node.children = node.children || [];
node.children.push(childNode);
continue;
}
for (const key of Object.keys(object)) {
node.children = node.children || [];
const value = object[key];
if (key === 'text') {
node.children.push({
kind: 'text',
text: valueOrRegex(value)
});
continue;
}
const childNode = KeyParser.parse(key);
if (childNode.kind === 'text') {
node.children.push({
kind: 'text',
text: valueOrRegex(value)
});
continue;
}
if (typeof value === 'string') {
node.children.push({
...childNode,
children: [{
kind: 'text',
text: valueOrRegex(value)
}]
});
continue;
}
node.children.push(childNode);
populateNode(childNode, value);
}
}
}
function normalizeWhitespace(text) {
return text.replace(/[\r\n\s\t]+/g, ' ').trim();
}
function valueOrRegex(value) {
return value.startsWith('/') && value.endsWith('/') ? new RegExp(value.slice(1, -1)) : normalizeWhitespace(value);
}
class KeyParser {
static parse(input) {
return new KeyParser(input)._parse();
}
constructor(input) {
this._input = void 0;
this._pos = void 0;
this._length = void 0;
this._input = input;
this._pos = 0;
this._length = input.length;
}
_peek() {
return this._input[this._pos] || '';
}
_next() {
if (this._pos < this._length) return this._input[this._pos++];
return null;
}
_eof() {
return this._pos >= this._length;
}
_isWhitespace() {
return !this._eof() && /\s/.test(this._peek());
}
_skipWhitespace() {
while (this._isWhitespace()) this._pos++;
}
_readIdentifier(type) {
if (this._eof()) this._throwError(`Unexpected end of input when expecting ${type}`);
const start = this._pos;
while (!this._eof() && /[a-zA-Z]/.test(this._peek())) this._pos++;
return this._input.slice(start, this._pos);
}
_readString() {
let result = '';
let escaped = false;
while (!this._eof()) {
const ch = this._next();
if (escaped) {
result += ch;
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === '"') {
return result;
} else {
result += ch;
}
}
this._throwError('Unterminated string');
}
_throwError(message, pos) {
throw new AriaKeyError(message, this._input, pos || this._pos);
}
_readRegex() {
let result = '';
let escaped = false;
let insideClass = false;
while (!this._eof()) {
const ch = this._next();
if (escaped) {
result += ch;
escaped = false;
} else if (ch === '\\') {
escaped = true;
result += ch;
} else if (ch === '/' && !insideClass) {
return result;
} else if (ch === '[') {
insideClass = true;
result += ch;
} else if (ch === ']' && insideClass) {
result += ch;
insideClass = false;
} else {
result += ch;
}
}
this._throwError('Unterminated regex');
}
_readStringOrRegex() {
const ch = this._peek();
if (ch === '"') {
this._next();
return this._readString();
}
if (ch === '/') {
this._next();
return new RegExp(this._readRegex());
}
return null;
}
_readAttributes(result) {
let errorPos = this._pos;
while (true) {
this._skipWhitespace();
if (this._peek() === '[') {
this._next();
this._skipWhitespace();
errorPos = this._pos;
const flagName = this._readIdentifier('attribute');
this._skipWhitespace();
let flagValue = '';
if (this._peek() === '=') {
this._next();
this._skipWhitespace();
errorPos = this._pos;
while (this._peek() !== ']' && !this._isWhitespace() && !this._eof()) flagValue += this._next();
}
this._skipWhitespace();
if (this._peek() !== ']') this._throwError('Expected ]');
this._next(); // Consume ']'
this._applyAttribute(result, flagName, flagValue || 'true', errorPos);
} else {
break;
}
}
}
_parse() {
this._skipWhitespace();
const role = this._readIdentifier('role');
this._skipWhitespace();
const name = this._readStringOrRegex() || '';
const result = {
kind: 'role',
role,
name
};
this._readAttributes(result);
this._skipWhitespace();
if (!this._eof()) this._throwError('Unexpected input');
return result;
}
_applyAttribute(node, key, value, errorPos) {
if (key === 'checked') {
this._assert(value === 'true' || value === 'false' || value === 'mixed', 'Value of "checked\" attribute must be a boolean or "mixed"', errorPos);
node.checked = value === 'true' ? true : value === 'false' ? false : 'mixed';
return;
}
if (key === 'disabled') {
this._assert(value === 'true' || value === 'false', 'Value of "disabled" attribute must be a boolean', errorPos);
node.disabled = value === 'true';
return;
}
if (key === 'expanded') {
this._assert(value === 'true' || value === 'false', 'Value of "expanded" attribute must be a boolean', errorPos);
node.expanded = value === 'true';
return;
}
if (key === 'level') {
this._assert(!isNaN(Number(value)), 'Value of "level" attribute must be a number', errorPos);
node.level = Number(value);
return;
}
if (key === 'pressed') {
this._assert(value === 'true' || value === 'false' || value === 'mixed', 'Value of "pressed" attribute must be a boolean or "mixed"', errorPos);
node.pressed = value === 'true' ? true : value === 'false' ? false : 'mixed';
return;
}
if (key === 'selected') {
this._assert(value === 'true' || value === 'false', 'Value of "selected" attribute must be a boolean', errorPos);
node.selected = value === 'true';
return;
}
this._assert(false, `Unsupported attribute [${key}]`, errorPos);
}
_assert(value, message, valuePos) {
if (!value) this._throwError(message || 'Assertion error', valuePos);
}
}
function parseAriaKey(key) {
return KeyParser.parse(key);
}
class AriaKeyError extends Error {
constructor(message, input, pos) {
super(message + ':\n\n' + input + '\n' + ' '.repeat(pos) + '^\n');
this.shortMessage = void 0;
this.pos = void 0;
this.shortMessage = message;
this.pos = pos;
this.stack = undefined;
}
}
exports.AriaKeyError = AriaKeyError;
@@ -0,0 +1,250 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InvalidSelectorError = void 0;
exports.isInvalidSelectorError = isInvalidSelectorError;
exports.parseCSS = parseCSS;
exports.serializeSelector = serializeSelector;
var css = _interopRequireWildcard(require("./cssTokenizer"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class InvalidSelectorError extends Error {}
exports.InvalidSelectorError = InvalidSelectorError;
function isInvalidSelectorError(error) {
return error instanceof InvalidSelectorError;
}
// Note: '>=' is used internally for text engine to preserve backwards compatibility.
// TODO: consider
// - key=value
// - operators like `=`, `|=`, `~=`, `*=`, `/`
// - <empty>~=value
// - argument modes: "parse all", "parse commas", "just a string"
function parseCSS(selector, customNames) {
let tokens;
try {
tokens = css.tokenize(selector);
if (!(tokens[tokens.length - 1] instanceof css.EOFToken)) tokens.push(new css.EOFToken());
} catch (e) {
const newMessage = e.message + ` while parsing selector "${selector}"`;
const index = (e.stack || '').indexOf(e.message);
if (index !== -1) e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);
e.message = newMessage;
throw e;
}
const unsupportedToken = tokens.find(token => {
return token instanceof css.AtKeywordToken || token instanceof css.BadStringToken || token instanceof css.BadURLToken || token instanceof css.ColumnToken || token instanceof css.CDOToken || token instanceof css.CDCToken || token instanceof css.SemicolonToken ||
// TODO: Consider using these for something, e.g. to escape complex strings.
// For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }
// Or this way :xpath( {complex-xpath-goes-here("hello")} )
token instanceof css.OpenCurlyToken || token instanceof css.CloseCurlyToken ||
// TODO: Consider treating these as strings?
token instanceof css.URLToken || token instanceof css.PercentageToken;
});
if (unsupportedToken) throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing selector "${selector}"`);
let pos = 0;
const names = new Set();
function unexpected() {
return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing selector "${selector}"`);
}
function skipWhitespace() {
while (tokens[pos] instanceof css.WhitespaceToken) pos++;
}
function isIdent(p = pos) {
return tokens[p] instanceof css.IdentToken;
}
function isString(p = pos) {
return tokens[p] instanceof css.StringToken;
}
function isNumber(p = pos) {
return tokens[p] instanceof css.NumberToken;
}
function isComma(p = pos) {
return tokens[p] instanceof css.CommaToken;
}
function isOpenParen(p = pos) {
return tokens[p] instanceof css.OpenParenToken;
}
function isCloseParen(p = pos) {
return tokens[p] instanceof css.CloseParenToken;
}
function isFunction(p = pos) {
return tokens[p] instanceof css.FunctionToken;
}
function isStar(p = pos) {
return tokens[p] instanceof css.DelimToken && tokens[p].value === '*';
}
function isEOF(p = pos) {
return tokens[p] instanceof css.EOFToken;
}
function isClauseCombinator(p = pos) {
return tokens[p] instanceof css.DelimToken && ['>', '+', '~'].includes(tokens[p].value);
}
function isSelectorClauseEnd(p = pos) {
return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof css.WhitespaceToken;
}
function consumeFunctionArguments() {
const result = [consumeArgument()];
while (true) {
skipWhitespace();
if (!isComma()) break;
pos++;
result.push(consumeArgument());
}
return result;
}
function consumeArgument() {
skipWhitespace();
if (isNumber()) return tokens[pos++].value;
if (isString()) return tokens[pos++].value;
return consumeComplexSelector();
}
function consumeComplexSelector() {
const result = {
simples: []
};
skipWhitespace();
if (isClauseCombinator()) {
// Put implicit ":scope" at the start. https://drafts.csswg.org/selectors-4/#relative
result.simples.push({
selector: {
functions: [{
name: 'scope',
args: []
}]
},
combinator: ''
});
} else {
result.simples.push({
selector: consumeSimpleSelector(),
combinator: ''
});
}
while (true) {
skipWhitespace();
if (isClauseCombinator()) {
result.simples[result.simples.length - 1].combinator = tokens[pos++].value;
skipWhitespace();
} else if (isSelectorClauseEnd()) {
break;
}
result.simples.push({
combinator: '',
selector: consumeSimpleSelector()
});
}
return result;
}
function consumeSimpleSelector() {
let rawCSSString = '';
const functions = [];
while (!isSelectorClauseEnd()) {
if (isIdent() || isStar()) {
rawCSSString += tokens[pos++].toSource();
} else if (tokens[pos] instanceof css.HashToken) {
rawCSSString += tokens[pos++].toSource();
} else if (tokens[pos] instanceof css.DelimToken && tokens[pos].value === '.') {
pos++;
if (isIdent()) rawCSSString += '.' + tokens[pos++].toSource();else throw unexpected();
} else if (tokens[pos] instanceof css.ColonToken) {
pos++;
if (isIdent()) {
if (!customNames.has(tokens[pos].value.toLowerCase())) {
rawCSSString += ':' + tokens[pos++].toSource();
} else {
const name = tokens[pos++].value.toLowerCase();
functions.push({
name,
args: []
});
names.add(name);
}
} else if (isFunction()) {
const name = tokens[pos++].value.toLowerCase();
if (!customNames.has(name)) {
rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;
} else {
functions.push({
name,
args: consumeFunctionArguments()
});
names.add(name);
}
skipWhitespace();
if (!isCloseParen()) throw unexpected();
pos++;
} else {
throw unexpected();
}
} else if (tokens[pos] instanceof css.OpenSquareToken) {
rawCSSString += '[';
pos++;
while (!(tokens[pos] instanceof css.CloseSquareToken) && !isEOF()) rawCSSString += tokens[pos++].toSource();
if (!(tokens[pos] instanceof css.CloseSquareToken)) throw unexpected();
rawCSSString += ']';
pos++;
} else {
throw unexpected();
}
}
if (!rawCSSString && !functions.length) throw unexpected();
return {
css: rawCSSString || undefined,
functions
};
}
function consumeBuiltinFunctionArguments() {
let s = '';
let balance = 1; // First open paren is a part of a function token.
while (!isEOF()) {
if (isOpenParen() || isFunction()) balance++;
if (isCloseParen()) balance--;
if (!balance) break;
s += tokens[pos++].toSource();
}
return s;
}
const result = consumeFunctionArguments();
if (!isEOF()) throw unexpected();
if (result.some(arg => typeof arg !== 'object' || !('simples' in arg))) throw new InvalidSelectorError(`Error while parsing selector "${selector}"`);
return {
selector: result,
names: Array.from(names)
};
}
function serializeSelector(args) {
return args.map(arg => {
if (typeof arg === 'string') return `"${arg}"`;
if (typeof arg === 'number') return String(arg);
return arg.simples.map(({
selector,
combinator
}) => {
let s = selector.css || '';
s = s + selector.functions.map(func => `:${func.name}(${serializeSelector(func.args)})`).join('');
if (combinator) s += ' ' + combinator;
return s;
}).join(' ');
}).join(', ');
}
@@ -0,0 +1,979 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WhitespaceToken = exports.URLToken = exports.SuffixMatchToken = exports.SubstringMatchToken = exports.StringValuedToken = exports.StringToken = exports.SemicolonToken = exports.PrefixMatchToken = exports.PercentageToken = exports.OpenSquareToken = exports.OpenParenToken = exports.OpenCurlyToken = exports.NumberToken = exports.InvalidCharacterError = exports.IncludeMatchToken = exports.IdentToken = exports.HashToken = exports.GroupingToken = exports.FunctionToken = exports.EOFToken = exports.DimensionToken = exports.DelimToken = exports.DashMatchToken = exports.CommaToken = exports.ColumnToken = exports.ColonToken = exports.CloseSquareToken = exports.CloseParenToken = exports.CloseCurlyToken = exports.CSSParserToken = exports.CDOToken = exports.CDCToken = exports.BadURLToken = exports.BadStringToken = exports.AtKeywordToken = void 0;
exports.tokenize = tokenize;
/* eslint-disable notice/notice */
/*
* The code in this file is licensed under the CC0 license.
* http://creativecommons.org/publicdomain/zero/1.0/
* It is free to use for any purpose. No attribution, permission, or reproduction of this license is required.
*/
// Original at https://github.com/tabatkins/parse-css
// Changes:
// - JS is replaced with TS.
// - Universal Module Definition wrapper is removed.
// - Everything not related to tokenizing - below the first exports block - is removed.
const between = function (num, first, last) {
return num >= first && num <= last;
};
function digit(code) {
return between(code, 0x30, 0x39);
}
function hexdigit(code) {
return digit(code) || between(code, 0x41, 0x46) || between(code, 0x61, 0x66);
}
function uppercaseletter(code) {
return between(code, 0x41, 0x5a);
}
function lowercaseletter(code) {
return between(code, 0x61, 0x7a);
}
function letter(code) {
return uppercaseletter(code) || lowercaseletter(code);
}
function nonascii(code) {
return code >= 0x80;
}
function namestartchar(code) {
return letter(code) || nonascii(code) || code === 0x5f;
}
function namechar(code) {
return namestartchar(code) || digit(code) || code === 0x2d;
}
function nonprintable(code) {
return between(code, 0, 8) || code === 0xb || between(code, 0xe, 0x1f) || code === 0x7f;
}
function newline(code) {
return code === 0xa;
}
function whitespace(code) {
return newline(code) || code === 9 || code === 0x20;
}
const maximumallowedcodepoint = 0x10ffff;
class InvalidCharacterError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidCharacterError';
}
}
exports.InvalidCharacterError = InvalidCharacterError;
function preprocess(str) {
// Turn a string into an array of code points,
// following the preprocessing cleanup rules.
const codepoints = [];
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i);
if (code === 0xd && str.charCodeAt(i + 1) === 0xa) {
code = 0xa;
i++;
}
if (code === 0xd || code === 0xc) code = 0xa;
if (code === 0x0) code = 0xfffd;
if (between(code, 0xd800, 0xdbff) && between(str.charCodeAt(i + 1), 0xdc00, 0xdfff)) {
// Decode a surrogate pair into an astral codepoint.
const lead = code - 0xd800;
const trail = str.charCodeAt(i + 1) - 0xdc00;
code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail;
i++;
}
codepoints.push(code);
}
return codepoints;
}
function stringFromCode(code) {
if (code <= 0xffff) return String.fromCharCode(code);
// Otherwise, encode astral char as surrogate pair.
code -= Math.pow(2, 16);
const lead = Math.floor(code / Math.pow(2, 10)) + 0xd800;
const trail = code % Math.pow(2, 10) + 0xdc00;
return String.fromCharCode(lead) + String.fromCharCode(trail);
}
function tokenize(str1) {
const str = preprocess(str1);
let i = -1;
const tokens = [];
let code;
// Line number information.
let line = 0;
let column = 0;
// The only use of lastLineLength is in reconsume().
let lastLineLength = 0;
const incrLineno = function () {
line += 1;
lastLineLength = column;
column = 0;
};
const locStart = {
line: line,
column: column
};
const codepoint = function (i) {
if (i >= str.length) return -1;
return str[i];
};
const next = function (num) {
if (num === undefined) num = 1;
if (num > 3) throw 'Spec Error: no more than three codepoints of lookahead.';
return codepoint(i + num);
};
const consume = function (num) {
if (num === undefined) num = 1;
i += num;
code = codepoint(i);
if (newline(code)) incrLineno();else column += num;
// console.log('Consume '+i+' '+String.fromCharCode(code) + ' 0x' + code.toString(16));
return true;
};
const reconsume = function () {
i -= 1;
if (newline(code)) {
line -= 1;
column = lastLineLength;
} else {
column -= 1;
}
locStart.line = line;
locStart.column = column;
return true;
};
const eof = function (codepoint) {
if (codepoint === undefined) codepoint = code;
return codepoint === -1;
};
const donothing = function () {};
const parseerror = function () {
// Language bindings don't like writing to stdout!
// console.log('Parse error at index ' + i + ', processing codepoint 0x' + code.toString(16) + '.'); return true;
};
const consumeAToken = function () {
consumeComments();
consume();
if (whitespace(code)) {
while (whitespace(next())) consume();
return new WhitespaceToken();
} else if (code === 0x22) {
return consumeAStringToken();
} else if (code === 0x23) {
if (namechar(next()) || areAValidEscape(next(1), next(2))) {
const token = new HashToken('');
if (wouldStartAnIdentifier(next(1), next(2), next(3))) token.type = 'id';
token.value = consumeAName();
return token;
} else {
return new DelimToken(code);
}
} else if (code === 0x24) {
if (next() === 0x3d) {
consume();
return new SuffixMatchToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x27) {
return consumeAStringToken();
} else if (code === 0x28) {
return new OpenParenToken();
} else if (code === 0x29) {
return new CloseParenToken();
} else if (code === 0x2a) {
if (next() === 0x3d) {
consume();
return new SubstringMatchToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x2b) {
if (startsWithANumber()) {
reconsume();
return consumeANumericToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x2c) {
return new CommaToken();
} else if (code === 0x2d) {
if (startsWithANumber()) {
reconsume();
return consumeANumericToken();
} else if (next(1) === 0x2d && next(2) === 0x3e) {
consume(2);
return new CDCToken();
} else if (startsWithAnIdentifier()) {
reconsume();
return consumeAnIdentlikeToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x2e) {
if (startsWithANumber()) {
reconsume();
return consumeANumericToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x3a) {
return new ColonToken();
} else if (code === 0x3b) {
return new SemicolonToken();
} else if (code === 0x3c) {
if (next(1) === 0x21 && next(2) === 0x2d && next(3) === 0x2d) {
consume(3);
return new CDOToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x40) {
if (wouldStartAnIdentifier(next(1), next(2), next(3))) return new AtKeywordToken(consumeAName());else return new DelimToken(code);
} else if (code === 0x5b) {
return new OpenSquareToken();
} else if (code === 0x5c) {
if (startsWithAValidEscape()) {
reconsume();
return consumeAnIdentlikeToken();
} else {
parseerror();
return new DelimToken(code);
}
} else if (code === 0x5d) {
return new CloseSquareToken();
} else if (code === 0x5e) {
if (next() === 0x3d) {
consume();
return new PrefixMatchToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x7b) {
return new OpenCurlyToken();
} else if (code === 0x7c) {
if (next() === 0x3d) {
consume();
return new DashMatchToken();
} else if (next() === 0x7c) {
consume();
return new ColumnToken();
} else {
return new DelimToken(code);
}
} else if (code === 0x7d) {
return new CloseCurlyToken();
} else if (code === 0x7e) {
if (next() === 0x3d) {
consume();
return new IncludeMatchToken();
} else {
return new DelimToken(code);
}
} else if (digit(code)) {
reconsume();
return consumeANumericToken();
} else if (namestartchar(code)) {
reconsume();
return consumeAnIdentlikeToken();
} else if (eof()) {
return new EOFToken();
} else {
return new DelimToken(code);
}
};
const consumeComments = function () {
while (next(1) === 0x2f && next(2) === 0x2a) {
consume(2);
while (true) {
consume();
if (code === 0x2a && next() === 0x2f) {
consume();
break;
} else if (eof()) {
parseerror();
return;
}
}
}
};
const consumeANumericToken = function () {
const num = consumeANumber();
if (wouldStartAnIdentifier(next(1), next(2), next(3))) {
const token = new DimensionToken();
token.value = num.value;
token.repr = num.repr;
token.type = num.type;
token.unit = consumeAName();
return token;
} else if (next() === 0x25) {
consume();
const token = new PercentageToken();
token.value = num.value;
token.repr = num.repr;
return token;
} else {
const token = new NumberToken();
token.value = num.value;
token.repr = num.repr;
token.type = num.type;
return token;
}
};
const consumeAnIdentlikeToken = function () {
const str = consumeAName();
if (str.toLowerCase() === 'url' && next() === 0x28) {
consume();
while (whitespace(next(1)) && whitespace(next(2))) consume();
if (next() === 0x22 || next() === 0x27) return new FunctionToken(str);else if (whitespace(next()) && (next(2) === 0x22 || next(2) === 0x27)) return new FunctionToken(str);else return consumeAURLToken();
} else if (next() === 0x28) {
consume();
return new FunctionToken(str);
} else {
return new IdentToken(str);
}
};
const consumeAStringToken = function (endingCodePoint) {
if (endingCodePoint === undefined) endingCodePoint = code;
let string = '';
while (consume()) {
if (code === endingCodePoint || eof()) {
return new StringToken(string);
} else if (newline(code)) {
parseerror();
reconsume();
return new BadStringToken();
} else if (code === 0x5c) {
if (eof(next())) donothing();else if (newline(next())) consume();else string += stringFromCode(consumeEscape());
} else {
string += stringFromCode(code);
}
}
throw new Error('Internal error');
};
const consumeAURLToken = function () {
const token = new URLToken('');
while (whitespace(next())) consume();
if (eof(next())) return token;
while (consume()) {
if (code === 0x29 || eof()) {
return token;
} else if (whitespace(code)) {
while (whitespace(next())) consume();
if (next() === 0x29 || eof(next())) {
consume();
return token;
} else {
consumeTheRemnantsOfABadURL();
return new BadURLToken();
}
} else if (code === 0x22 || code === 0x27 || code === 0x28 || nonprintable(code)) {
parseerror();
consumeTheRemnantsOfABadURL();
return new BadURLToken();
} else if (code === 0x5c) {
if (startsWithAValidEscape()) {
token.value += stringFromCode(consumeEscape());
} else {
parseerror();
consumeTheRemnantsOfABadURL();
return new BadURLToken();
}
} else {
token.value += stringFromCode(code);
}
}
throw new Error('Internal error');
};
const consumeEscape = function () {
// Assume the current character is the \
// and the next code point is not a newline.
consume();
if (hexdigit(code)) {
// Consume 1-6 hex digits
const digits = [code];
for (let total = 0; total < 5; total++) {
if (hexdigit(next())) {
consume();
digits.push(code);
} else {
break;
}
}
if (whitespace(next())) consume();
let value = parseInt(digits.map(function (x) {
return String.fromCharCode(x);
}).join(''), 16);
if (value > maximumallowedcodepoint) value = 0xfffd;
return value;
} else if (eof()) {
return 0xfffd;
} else {
return code;
}
};
const areAValidEscape = function (c1, c2) {
if (c1 !== 0x5c) return false;
if (newline(c2)) return false;
return true;
};
const startsWithAValidEscape = function () {
return areAValidEscape(code, next());
};
const wouldStartAnIdentifier = function (c1, c2, c3) {
if (c1 === 0x2d) return namestartchar(c2) || c2 === 0x2d || areAValidEscape(c2, c3);else if (namestartchar(c1)) return true;else if (c1 === 0x5c) return areAValidEscape(c1, c2);else return false;
};
const startsWithAnIdentifier = function () {
return wouldStartAnIdentifier(code, next(1), next(2));
};
const wouldStartANumber = function (c1, c2, c3) {
if (c1 === 0x2b || c1 === 0x2d) {
if (digit(c2)) return true;
if (c2 === 0x2e && digit(c3)) return true;
return false;
} else if (c1 === 0x2e) {
if (digit(c2)) return true;
return false;
} else if (digit(c1)) {
return true;
} else {
return false;
}
};
const startsWithANumber = function () {
return wouldStartANumber(code, next(1), next(2));
};
const consumeAName = function () {
let result = '';
while (consume()) {
if (namechar(code)) {
result += stringFromCode(code);
} else if (startsWithAValidEscape()) {
result += stringFromCode(consumeEscape());
} else {
reconsume();
return result;
}
}
throw new Error('Internal parse error');
};
const consumeANumber = function () {
let repr = '';
let type = 'integer';
if (next() === 0x2b || next() === 0x2d) {
consume();
repr += stringFromCode(code);
}
while (digit(next())) {
consume();
repr += stringFromCode(code);
}
if (next(1) === 0x2e && digit(next(2))) {
consume();
repr += stringFromCode(code);
consume();
repr += stringFromCode(code);
type = 'number';
while (digit(next())) {
consume();
repr += stringFromCode(code);
}
}
const c1 = next(1),
c2 = next(2),
c3 = next(3);
if ((c1 === 0x45 || c1 === 0x65) && digit(c2)) {
consume();
repr += stringFromCode(code);
consume();
repr += stringFromCode(code);
type = 'number';
while (digit(next())) {
consume();
repr += stringFromCode(code);
}
} else if ((c1 === 0x45 || c1 === 0x65) && (c2 === 0x2b || c2 === 0x2d) && digit(c3)) {
consume();
repr += stringFromCode(code);
consume();
repr += stringFromCode(code);
consume();
repr += stringFromCode(code);
type = 'number';
while (digit(next())) {
consume();
repr += stringFromCode(code);
}
}
const value = convertAStringToANumber(repr);
return {
type: type,
value: value,
repr: repr
};
};
const convertAStringToANumber = function (string) {
// CSS's number rules are identical to JS, afaik.
return +string;
};
const consumeTheRemnantsOfABadURL = function () {
while (consume()) {
if (code === 0x29 || eof()) {
return;
} else if (startsWithAValidEscape()) {
consumeEscape();
donothing();
} else {
donothing();
}
}
};
let iterationCount = 0;
while (!eof(next())) {
tokens.push(consumeAToken());
iterationCount++;
if (iterationCount > str.length * 2) throw new Error("I'm infinite-looping!");
}
return tokens;
}
class CSSParserToken {
constructor() {
this.tokenType = '';
this.value = void 0;
}
toJSON() {
return {
token: this.tokenType
};
}
toString() {
return this.tokenType;
}
toSource() {
return '' + this;
}
}
exports.CSSParserToken = CSSParserToken;
class BadStringToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = 'BADSTRING';
}
}
exports.BadStringToken = BadStringToken;
class BadURLToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = 'BADURL';
}
}
exports.BadURLToken = BadURLToken;
class WhitespaceToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = 'WHITESPACE';
}
toString() {
return 'WS';
}
toSource() {
return ' ';
}
}
exports.WhitespaceToken = WhitespaceToken;
class CDOToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = 'CDO';
}
toSource() {
return '<!--';
}
}
exports.CDOToken = CDOToken;
class CDCToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = 'CDC';
}
toSource() {
return '-->';
}
}
exports.CDCToken = CDCToken;
class ColonToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = ':';
}
}
exports.ColonToken = ColonToken;
class SemicolonToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = ';';
}
}
exports.SemicolonToken = SemicolonToken;
class CommaToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = ',';
}
}
exports.CommaToken = CommaToken;
class GroupingToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.value = '';
this.mirror = '';
}
}
exports.GroupingToken = GroupingToken;
class OpenCurlyToken extends GroupingToken {
constructor() {
super();
this.tokenType = '{';
this.value = '{';
this.mirror = '}';
}
}
exports.OpenCurlyToken = OpenCurlyToken;
class CloseCurlyToken extends GroupingToken {
constructor() {
super();
this.tokenType = '}';
this.value = '}';
this.mirror = '{';
}
}
exports.CloseCurlyToken = CloseCurlyToken;
class OpenSquareToken extends GroupingToken {
constructor() {
super();
this.tokenType = '[';
this.value = '[';
this.mirror = ']';
}
}
exports.OpenSquareToken = OpenSquareToken;
class CloseSquareToken extends GroupingToken {
constructor() {
super();
this.tokenType = ']';
this.value = ']';
this.mirror = '[';
}
}
exports.CloseSquareToken = CloseSquareToken;
class OpenParenToken extends GroupingToken {
constructor() {
super();
this.tokenType = '(';
this.value = '(';
this.mirror = ')';
}
}
exports.OpenParenToken = OpenParenToken;
class CloseParenToken extends GroupingToken {
constructor() {
super();
this.tokenType = ')';
this.value = ')';
this.mirror = '(';
}
}
exports.CloseParenToken = CloseParenToken;
class IncludeMatchToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = '~=';
}
}
exports.IncludeMatchToken = IncludeMatchToken;
class DashMatchToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = '|=';
}
}
exports.DashMatchToken = DashMatchToken;
class PrefixMatchToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = '^=';
}
}
exports.PrefixMatchToken = PrefixMatchToken;
class SuffixMatchToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = '$=';
}
}
exports.SuffixMatchToken = SuffixMatchToken;
class SubstringMatchToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = '*=';
}
}
exports.SubstringMatchToken = SubstringMatchToken;
class ColumnToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = '||';
}
}
exports.ColumnToken = ColumnToken;
class EOFToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.tokenType = 'EOF';
}
toSource() {
return '';
}
}
exports.EOFToken = EOFToken;
class DelimToken extends CSSParserToken {
constructor(code) {
super();
this.tokenType = 'DELIM';
this.value = '';
this.value = stringFromCode(code);
}
toString() {
return 'DELIM(' + this.value + ')';
}
toJSON() {
const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);
json.value = this.value;
return json;
}
toSource() {
if (this.value === '\\') return '\\\n';else return this.value;
}
}
exports.DelimToken = DelimToken;
class StringValuedToken extends CSSParserToken {
constructor(...args) {
super(...args);
this.value = '';
}
ASCIIMatch(str) {
return this.value.toLowerCase() === str.toLowerCase();
}
toJSON() {
const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);
json.value = this.value;
return json;
}
}
exports.StringValuedToken = StringValuedToken;
class IdentToken extends StringValuedToken {
constructor(val) {
super();
this.tokenType = 'IDENT';
this.value = val;
}
toString() {
return 'IDENT(' + this.value + ')';
}
toSource() {
return escapeIdent(this.value);
}
}
exports.IdentToken = IdentToken;
class FunctionToken extends StringValuedToken {
constructor(val) {
super();
this.tokenType = 'FUNCTION';
this.mirror = void 0;
this.value = val;
this.mirror = ')';
}
toString() {
return 'FUNCTION(' + this.value + ')';
}
toSource() {
return escapeIdent(this.value) + '(';
}
}
exports.FunctionToken = FunctionToken;
class AtKeywordToken extends StringValuedToken {
constructor(val) {
super();
this.tokenType = 'AT-KEYWORD';
this.value = val;
}
toString() {
return 'AT(' + this.value + ')';
}
toSource() {
return '@' + escapeIdent(this.value);
}
}
exports.AtKeywordToken = AtKeywordToken;
class HashToken extends StringValuedToken {
constructor(val) {
super();
this.tokenType = 'HASH';
this.type = void 0;
this.value = val;
this.type = 'unrestricted';
}
toString() {
return 'HASH(' + this.value + ')';
}
toJSON() {
const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);
json.value = this.value;
json.type = this.type;
return json;
}
toSource() {
if (this.type === 'id') return '#' + escapeIdent(this.value);else return '#' + escapeHash(this.value);
}
}
exports.HashToken = HashToken;
class StringToken extends StringValuedToken {
constructor(val) {
super();
this.tokenType = 'STRING';
this.value = val;
}
toString() {
return '"' + escapeString(this.value) + '"';
}
}
exports.StringToken = StringToken;
class URLToken extends StringValuedToken {
constructor(val) {
super();
this.tokenType = 'URL';
this.value = val;
}
toString() {
return 'URL(' + this.value + ')';
}
toSource() {
return 'url("' + escapeString(this.value) + '")';
}
}
exports.URLToken = URLToken;
class NumberToken extends CSSParserToken {
constructor() {
super();
this.tokenType = 'NUMBER';
this.type = void 0;
this.repr = void 0;
this.type = 'integer';
this.repr = '';
}
toString() {
if (this.type === 'integer') return 'INT(' + this.value + ')';
return 'NUMBER(' + this.value + ')';
}
toJSON() {
const json = super.toJSON();
json.value = this.value;
json.type = this.type;
json.repr = this.repr;
return json;
}
toSource() {
return this.repr;
}
}
exports.NumberToken = NumberToken;
class PercentageToken extends CSSParserToken {
constructor() {
super();
this.tokenType = 'PERCENTAGE';
this.repr = void 0;
this.repr = '';
}
toString() {
return 'PERCENTAGE(' + this.value + ')';
}
toJSON() {
const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);
json.value = this.value;
json.repr = this.repr;
return json;
}
toSource() {
return this.repr + '%';
}
}
exports.PercentageToken = PercentageToken;
class DimensionToken extends CSSParserToken {
constructor() {
super();
this.tokenType = 'DIMENSION';
this.type = void 0;
this.repr = void 0;
this.unit = void 0;
this.type = 'integer';
this.repr = '';
this.unit = '';
}
toString() {
return 'DIM(' + this.value + ',' + this.unit + ')';
}
toJSON() {
const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);
json.value = this.value;
json.type = this.type;
json.repr = this.repr;
json.unit = this.unit;
return json;
}
toSource() {
const source = this.repr;
let unit = escapeIdent(this.unit);
if (unit[0].toLowerCase() === 'e' && (unit[1] === '-' || between(unit.charCodeAt(1), 0x30, 0x39))) {
// Unit is ambiguous with scinot
// Remove the leading "e", replace with escape.
unit = '\\65 ' + unit.slice(1, unit.length);
}
return source + unit;
}
}
exports.DimensionToken = DimensionToken;
function escapeIdent(string) {
string = '' + string;
let result = '';
const firstcode = string.charCodeAt(0);
for (let i = 0; i < string.length; i++) {
const code = string.charCodeAt(i);
if (code === 0x0) throw new InvalidCharacterError('Invalid character: the input contains U+0000.');
if (between(code, 0x1, 0x1f) || code === 0x7f || i === 0 && between(code, 0x30, 0x39) || i === 1 && between(code, 0x30, 0x39) && firstcode === 0x2d) result += '\\' + code.toString(16) + ' ';else if (code >= 0x80 || code === 0x2d || code === 0x5f || between(code, 0x30, 0x39) || between(code, 0x41, 0x5a) || between(code, 0x61, 0x7a)) result += string[i];else result += '\\' + string[i];
}
return result;
}
function escapeHash(string) {
// Escapes the contents of "unrestricted"-type hash tokens.
// Won't preserve the ID-ness of "id"-type hash tokens;
// use escapeIdent() for that.
string = '' + string;
let result = '';
for (let i = 0; i < string.length; i++) {
const code = string.charCodeAt(i);
if (code === 0x0) throw new InvalidCharacterError('Invalid character: the input contains U+0000.');
if (code >= 0x80 || code === 0x2d || code === 0x5f || between(code, 0x30, 0x39) || between(code, 0x41, 0x5a) || between(code, 0x61, 0x7a)) result += string[i];else result += '\\' + code.toString(16) + ' ';
}
return result;
}
function escapeString(string) {
string = '' + string;
let result = '';
for (let i = 0; i < string.length; i++) {
const code = string.charCodeAt(i);
if (code === 0x0) throw new InvalidCharacterError('Invalid character: the input contains U+0000.');
if (between(code, 0x1, 0x1f) || code === 0x7f) result += '\\' + code.toString(16) + ' ';else if (code === 0x22 || code === 0x5c) result += '\\' + string[i];else result += string[i];
}
return result;
}
@@ -0,0 +1,660 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PythonLocatorFactory = exports.JsonlLocatorFactory = exports.JavaScriptLocatorFactory = exports.JavaLocatorFactory = exports.CSharpLocatorFactory = void 0;
exports.asLocator = asLocator;
exports.asLocators = asLocators;
var _stringUtils = require("./stringUtils");
var _selectorParser = require("./selectorParser");
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function asLocator(lang, selector, isFrameLocator = false) {
return asLocators(lang, selector, isFrameLocator)[0];
}
function asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) {
try {
return innerAsLocators(new generators[lang](preferredQuote), (0, _selectorParser.parseSelector)(selector), isFrameLocator, maxOutputSize);
} catch (e) {
// Tolerate invalid input.
return [selector];
}
}
function innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) {
const parts = [...parsed.parts];
const tokens = [];
let nextBase = isFrameLocator ? 'frame-locator' : 'page';
for (let index = 0; index < parts.length; index++) {
const part = parts[index];
const base = nextBase;
nextBase = 'locator';
if (part.name === 'nth') {
if (part.body === '0') tokens.push([factory.generateLocator(base, 'first', ''), factory.generateLocator(base, 'nth', '0')]);else if (part.body === '-1') tokens.push([factory.generateLocator(base, 'last', ''), factory.generateLocator(base, 'nth', '-1')]);else tokens.push([factory.generateLocator(base, 'nth', part.body)]);
continue;
}
if (part.name === 'internal:text') {
const {
exact,
text
} = detectExact(part.body);
tokens.push([factory.generateLocator(base, 'text', text, {
exact
})]);
continue;
}
if (part.name === 'internal:has-text') {
const {
exact,
text
} = detectExact(part.body);
// There is no locator equivalent for strict has-text, leave it as is.
if (!exact) {
tokens.push([factory.generateLocator(base, 'has-text', text, {
exact
})]);
continue;
}
}
if (part.name === 'internal:has-not-text') {
const {
exact,
text
} = detectExact(part.body);
// There is no locator equivalent for strict has-not-text, leave it as is.
if (!exact) {
tokens.push([factory.generateLocator(base, 'has-not-text', text, {
exact
})]);
continue;
}
}
if (part.name === 'internal:has') {
const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);
tokens.push(inners.map(inner => factory.generateLocator(base, 'has', inner)));
continue;
}
if (part.name === 'internal:has-not') {
const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);
tokens.push(inners.map(inner => factory.generateLocator(base, 'hasNot', inner)));
continue;
}
if (part.name === 'internal:and') {
const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);
tokens.push(inners.map(inner => factory.generateLocator(base, 'and', inner)));
continue;
}
if (part.name === 'internal:or') {
const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);
tokens.push(inners.map(inner => factory.generateLocator(base, 'or', inner)));
continue;
}
if (part.name === 'internal:chain') {
const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);
tokens.push(inners.map(inner => factory.generateLocator(base, 'chain', inner)));
continue;
}
if (part.name === 'internal:label') {
const {
exact,
text
} = detectExact(part.body);
tokens.push([factory.generateLocator(base, 'label', text, {
exact
})]);
continue;
}
if (part.name === 'internal:role') {
const attrSelector = (0, _selectorParser.parseAttributeSelector)(part.body, true);
const options = {
attrs: []
};
for (const attr of attrSelector.attributes) {
if (attr.name === 'name') {
options.exact = attr.caseSensitive;
options.name = attr.value;
} else {
if (attr.name === 'level' && typeof attr.value === 'string') attr.value = +attr.value;
options.attrs.push({
name: attr.name === 'include-hidden' ? 'includeHidden' : attr.name,
value: attr.value
});
}
}
tokens.push([factory.generateLocator(base, 'role', attrSelector.name, options)]);
continue;
}
if (part.name === 'internal:testid') {
const attrSelector = (0, _selectorParser.parseAttributeSelector)(part.body, true);
const {
value
} = attrSelector.attributes[0];
tokens.push([factory.generateLocator(base, 'test-id', value)]);
continue;
}
if (part.name === 'internal:attr') {
const attrSelector = (0, _selectorParser.parseAttributeSelector)(part.body, true);
const {
name,
value,
caseSensitive
} = attrSelector.attributes[0];
const text = value;
const exact = !!caseSensitive;
if (name === 'placeholder') {
tokens.push([factory.generateLocator(base, 'placeholder', text, {
exact
})]);
continue;
}
if (name === 'alt') {
tokens.push([factory.generateLocator(base, 'alt', text, {
exact
})]);
continue;
}
if (name === 'title') {
tokens.push([factory.generateLocator(base, 'title', text, {
exact
})]);
continue;
}
}
if (part.name === 'internal:control' && part.body === 'enter-frame') {
// transform last tokens from `${selector}` into `${selector}.contentFrame()` and `frameLocator(${selector})`
const lastTokens = tokens[tokens.length - 1];
const lastPart = parts[index - 1];
const transformed = lastTokens.map(token => factory.chainLocators([token, factory.generateLocator(base, 'frame', '')]));
if (['xpath', 'css'].includes(lastPart.name)) {
transformed.push(factory.generateLocator(base, 'frame-locator', (0, _selectorParser.stringifySelector)({
parts: [lastPart]
})), factory.generateLocator(base, 'frame-locator', (0, _selectorParser.stringifySelector)({
parts: [lastPart]
}, true)));
}
lastTokens.splice(0, lastTokens.length, ...transformed);
nextBase = 'frame-locator';
continue;
}
const nextPart = parts[index + 1];
const selectorPart = (0, _selectorParser.stringifySelector)({
parts: [part]
});
const locatorPart = factory.generateLocator(base, 'default', selectorPart);
if (nextPart && ['internal:has-text', 'internal:has-not-text'].includes(nextPart.name)) {
const {
exact,
text
} = detectExact(nextPart.body);
// There is no locator equivalent for strict has-text and has-not-text, leave it as is.
if (!exact) {
const nextLocatorPart = factory.generateLocator('locator', nextPart.name === 'internal:has-text' ? 'has-text' : 'has-not-text', text, {
exact
});
const options = {};
if (nextPart.name === 'internal:has-text') options.hasText = text;else options.hasNotText = text;
const combinedPart = factory.generateLocator(base, 'default', selectorPart, options);
// Two options:
// - locator('div').filter({ hasText: 'foo' })
// - locator('div', { hasText: 'foo' })
tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]);
index++;
continue;
}
}
// Selectors can be prefixed with engine name, e.g. xpath=//foo
let locatorPartWithEngine;
if (['xpath', 'css'].includes(part.name)) {
const selectorPart = (0, _selectorParser.stringifySelector)({
parts: [part]
}, /* forceEngineName */true);
locatorPartWithEngine = factory.generateLocator(base, 'default', selectorPart);
}
tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean));
}
return combineTokens(factory, tokens, maxOutputSize);
}
function combineTokens(factory, tokens, maxOutputSize) {
const currentTokens = tokens.map(() => '');
const result = [];
const visit = index => {
if (index === tokens.length) {
result.push(factory.chainLocators(currentTokens));
return currentTokens.length < maxOutputSize;
}
for (const taken of tokens[index]) {
currentTokens[index] = taken;
if (!visit(index + 1)) return false;
}
return true;
};
visit(0);
return result;
}
function detectExact(text) {
let exact = false;
const match = text.match(/^\/(.*)\/([igm]*)$/);
if (match) return {
text: new RegExp(match[1], match[2])
};
if (text.endsWith('"')) {
text = JSON.parse(text);
exact = true;
} else if (text.endsWith('"s')) {
text = JSON.parse(text.substring(0, text.length - 1));
exact = true;
} else if (text.endsWith('"i')) {
text = JSON.parse(text.substring(0, text.length - 1));
exact = false;
}
return {
exact,
text
};
}
class JavaScriptLocatorFactory {
constructor(preferredQuote) {
this.preferredQuote = preferredQuote;
}
generateLocator(base, kind, body, options = {}) {
switch (kind) {
case 'default':
if (options.hasText !== undefined) return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`;
if (options.hasNotText !== undefined) return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`;
return `locator(${this.quote(body)})`;
case 'frame-locator':
return `frameLocator(${this.quote(body)})`;
case 'frame':
return `contentFrame()`;
case 'nth':
return `nth(${body})`;
case 'first':
return `first()`;
case 'last':
return `last()`;
case 'role':
const attrs = [];
if (isRegExp(options.name)) {
attrs.push(`name: ${this.regexToSourceString(options.name)}`);
} else if (typeof options.name === 'string') {
attrs.push(`name: ${this.quote(options.name)}`);
if (options.exact) attrs.push(`exact: true`);
}
for (const {
name,
value
} of options.attrs) attrs.push(`${name}: ${typeof value === 'string' ? this.quote(value) : value}`);
const attrString = attrs.length ? `, { ${attrs.join(', ')} }` : '';
return `getByRole(${this.quote(body)}${attrString})`;
case 'has-text':
return `filter({ hasText: ${this.toHasText(body)} })`;
case 'has-not-text':
return `filter({ hasNotText: ${this.toHasText(body)} })`;
case 'has':
return `filter({ has: ${body} })`;
case 'hasNot':
return `filter({ hasNot: ${body} })`;
case 'and':
return `and(${body})`;
case 'or':
return `or(${body})`;
case 'chain':
return `locator(${body})`;
case 'test-id':
return `getByTestId(${this.toTestIdValue(body)})`;
case 'text':
return this.toCallWithExact('getByText', body, !!options.exact);
case 'alt':
return this.toCallWithExact('getByAltText', body, !!options.exact);
case 'placeholder':
return this.toCallWithExact('getByPlaceholder', body, !!options.exact);
case 'label':
return this.toCallWithExact('getByLabel', body, !!options.exact);
case 'title':
return this.toCallWithExact('getByTitle', body, !!options.exact);
default:
throw new Error('Unknown selector kind ' + kind);
}
}
chainLocators(locators) {
return locators.join('.');
}
regexToSourceString(re) {
return (0, _stringUtils.normalizeEscapedRegexQuotes)(String(re));
}
toCallWithExact(method, body, exact) {
if (isRegExp(body)) return `${method}(${this.regexToSourceString(body)})`;
return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`;
}
toHasText(body) {
if (isRegExp(body)) return this.regexToSourceString(body);
return this.quote(body);
}
toTestIdValue(value) {
if (isRegExp(value)) return this.regexToSourceString(value);
return this.quote(value);
}
quote(text) {
var _this$preferredQuote;
return (0, _stringUtils.escapeWithQuotes)(text, (_this$preferredQuote = this.preferredQuote) !== null && _this$preferredQuote !== void 0 ? _this$preferredQuote : '\'');
}
}
exports.JavaScriptLocatorFactory = JavaScriptLocatorFactory;
class PythonLocatorFactory {
generateLocator(base, kind, body, options = {}) {
switch (kind) {
case 'default':
if (options.hasText !== undefined) return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;
if (options.hasNotText !== undefined) return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;
return `locator(${this.quote(body)})`;
case 'frame-locator':
return `frame_locator(${this.quote(body)})`;
case 'frame':
return `content_frame`;
case 'nth':
return `nth(${body})`;
case 'first':
return `first`;
case 'last':
return `last`;
case 'role':
const attrs = [];
if (isRegExp(options.name)) {
attrs.push(`name=${this.regexToString(options.name)}`);
} else if (typeof options.name === 'string') {
attrs.push(`name=${this.quote(options.name)}`);
if (options.exact) attrs.push(`exact=True`);
}
for (const {
name,
value
} of options.attrs) {
let valueString = typeof value === 'string' ? this.quote(value) : value;
if (typeof value === 'boolean') valueString = value ? 'True' : 'False';
attrs.push(`${(0, _stringUtils.toSnakeCase)(name)}=${valueString}`);
}
const attrString = attrs.length ? `, ${attrs.join(', ')}` : '';
return `get_by_role(${this.quote(body)}${attrString})`;
case 'has-text':
return `filter(has_text=${this.toHasText(body)})`;
case 'has-not-text':
return `filter(has_not_text=${this.toHasText(body)})`;
case 'has':
return `filter(has=${body})`;
case 'hasNot':
return `filter(has_not=${body})`;
case 'and':
return `and_(${body})`;
case 'or':
return `or_(${body})`;
case 'chain':
return `locator(${body})`;
case 'test-id':
return `get_by_test_id(${this.toTestIdValue(body)})`;
case 'text':
return this.toCallWithExact('get_by_text', body, !!options.exact);
case 'alt':
return this.toCallWithExact('get_by_alt_text', body, !!options.exact);
case 'placeholder':
return this.toCallWithExact('get_by_placeholder', body, !!options.exact);
case 'label':
return this.toCallWithExact('get_by_label', body, !!options.exact);
case 'title':
return this.toCallWithExact('get_by_title', body, !!options.exact);
default:
throw new Error('Unknown selector kind ' + kind);
}
}
chainLocators(locators) {
return locators.join('.');
}
regexToString(body) {
const suffix = body.flags.includes('i') ? ', re.IGNORECASE' : '';
return `re.compile(r"${(0, _stringUtils.normalizeEscapedRegexQuotes)(body.source).replace(/\\\//, '/').replace(/"/g, '\\"')}"${suffix})`;
}
toCallWithExact(method, body, exact) {
if (isRegExp(body)) return `${method}(${this.regexToString(body)})`;
if (exact) return `${method}(${this.quote(body)}, exact=True)`;
return `${method}(${this.quote(body)})`;
}
toHasText(body) {
if (isRegExp(body)) return this.regexToString(body);
return `${this.quote(body)}`;
}
toTestIdValue(value) {
if (isRegExp(value)) return this.regexToString(value);
return this.quote(value);
}
quote(text) {
return (0, _stringUtils.escapeWithQuotes)(text, '\"');
}
}
exports.PythonLocatorFactory = PythonLocatorFactory;
class JavaLocatorFactory {
generateLocator(base, kind, body, options = {}) {
let clazz;
switch (base) {
case 'page':
clazz = 'Page';
break;
case 'frame-locator':
clazz = 'FrameLocator';
break;
case 'locator':
clazz = 'Locator';
break;
}
switch (kind) {
case 'default':
if (options.hasText !== undefined) return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`;
if (options.hasNotText !== undefined) return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`;
return `locator(${this.quote(body)})`;
case 'frame-locator':
return `frameLocator(${this.quote(body)})`;
case 'frame':
return `contentFrame()`;
case 'nth':
return `nth(${body})`;
case 'first':
return `first()`;
case 'last':
return `last()`;
case 'role':
const attrs = [];
if (isRegExp(options.name)) {
attrs.push(`.setName(${this.regexToString(options.name)})`);
} else if (typeof options.name === 'string') {
attrs.push(`.setName(${this.quote(options.name)})`);
if (options.exact) attrs.push(`.setExact(true)`);
}
for (const {
name,
value
} of options.attrs) attrs.push(`.set${(0, _stringUtils.toTitleCase)(name)}(${typeof value === 'string' ? this.quote(value) : value})`);
const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join('')}` : '';
return `getByRole(AriaRole.${(0, _stringUtils.toSnakeCase)(body).toUpperCase()}${attrString})`;
case 'has-text':
return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`;
case 'has-not-text':
return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`;
case 'has':
return `filter(new ${clazz}.FilterOptions().setHas(${body}))`;
case 'hasNot':
return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`;
case 'and':
return `and(${body})`;
case 'or':
return `or(${body})`;
case 'chain':
return `locator(${body})`;
case 'test-id':
return `getByTestId(${this.toTestIdValue(body)})`;
case 'text':
return this.toCallWithExact(clazz, 'getByText', body, !!options.exact);
case 'alt':
return this.toCallWithExact(clazz, 'getByAltText', body, !!options.exact);
case 'placeholder':
return this.toCallWithExact(clazz, 'getByPlaceholder', body, !!options.exact);
case 'label':
return this.toCallWithExact(clazz, 'getByLabel', body, !!options.exact);
case 'title':
return this.toCallWithExact(clazz, 'getByTitle', body, !!options.exact);
default:
throw new Error('Unknown selector kind ' + kind);
}
}
chainLocators(locators) {
return locators.join('.');
}
regexToString(body) {
const suffix = body.flags.includes('i') ? ', Pattern.CASE_INSENSITIVE' : '';
return `Pattern.compile(${this.quote((0, _stringUtils.normalizeEscapedRegexQuotes)(body.source))}${suffix})`;
}
toCallWithExact(clazz, method, body, exact) {
if (isRegExp(body)) return `${method}(${this.regexToString(body)})`;
if (exact) return `${method}(${this.quote(body)}, new ${clazz}.${(0, _stringUtils.toTitleCase)(method)}Options().setExact(true))`;
return `${method}(${this.quote(body)})`;
}
toHasText(body) {
if (isRegExp(body)) return this.regexToString(body);
return this.quote(body);
}
toTestIdValue(value) {
if (isRegExp(value)) return this.regexToString(value);
return this.quote(value);
}
quote(text) {
return (0, _stringUtils.escapeWithQuotes)(text, '\"');
}
}
exports.JavaLocatorFactory = JavaLocatorFactory;
class CSharpLocatorFactory {
generateLocator(base, kind, body, options = {}) {
switch (kind) {
case 'default':
if (options.hasText !== undefined) return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`;
if (options.hasNotText !== undefined) return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`;
return `Locator(${this.quote(body)})`;
case 'frame-locator':
return `FrameLocator(${this.quote(body)})`;
case 'frame':
return `ContentFrame`;
case 'nth':
return `Nth(${body})`;
case 'first':
return `First`;
case 'last':
return `Last`;
case 'role':
const attrs = [];
if (isRegExp(options.name)) {
attrs.push(`NameRegex = ${this.regexToString(options.name)}`);
} else if (typeof options.name === 'string') {
attrs.push(`Name = ${this.quote(options.name)}`);
if (options.exact) attrs.push(`Exact = true`);
}
for (const {
name,
value
} of options.attrs) attrs.push(`${(0, _stringUtils.toTitleCase)(name)} = ${typeof value === 'string' ? this.quote(value) : value}`);
const attrString = attrs.length ? `, new() { ${attrs.join(', ')} }` : '';
return `GetByRole(AriaRole.${(0, _stringUtils.toTitleCase)(body)}${attrString})`;
case 'has-text':
return `Filter(new() { ${this.toHasText(body)} })`;
case 'has-not-text':
return `Filter(new() { ${this.toHasNotText(body)} })`;
case 'has':
return `Filter(new() { Has = ${body} })`;
case 'hasNot':
return `Filter(new() { HasNot = ${body} })`;
case 'and':
return `And(${body})`;
case 'or':
return `Or(${body})`;
case 'chain':
return `Locator(${body})`;
case 'test-id':
return `GetByTestId(${this.toTestIdValue(body)})`;
case 'text':
return this.toCallWithExact('GetByText', body, !!options.exact);
case 'alt':
return this.toCallWithExact('GetByAltText', body, !!options.exact);
case 'placeholder':
return this.toCallWithExact('GetByPlaceholder', body, !!options.exact);
case 'label':
return this.toCallWithExact('GetByLabel', body, !!options.exact);
case 'title':
return this.toCallWithExact('GetByTitle', body, !!options.exact);
default:
throw new Error('Unknown selector kind ' + kind);
}
}
chainLocators(locators) {
return locators.join('.');
}
regexToString(body) {
const suffix = body.flags.includes('i') ? ', RegexOptions.IgnoreCase' : '';
return `new Regex(${this.quote((0, _stringUtils.normalizeEscapedRegexQuotes)(body.source))}${suffix})`;
}
toCallWithExact(method, body, exact) {
if (isRegExp(body)) return `${method}(${this.regexToString(body)})`;
if (exact) return `${method}(${this.quote(body)}, new() { Exact = true })`;
return `${method}(${this.quote(body)})`;
}
toHasText(body) {
if (isRegExp(body)) return `HasTextRegex = ${this.regexToString(body)}`;
return `HasText = ${this.quote(body)}`;
}
toTestIdValue(value) {
if (isRegExp(value)) return this.regexToString(value);
return this.quote(value);
}
toHasNotText(body) {
if (isRegExp(body)) return `HasNotTextRegex = ${this.regexToString(body)}`;
return `HasNotText = ${this.quote(body)}`;
}
quote(text) {
return (0, _stringUtils.escapeWithQuotes)(text, '\"');
}
}
exports.CSharpLocatorFactory = CSharpLocatorFactory;
class JsonlLocatorFactory {
generateLocator(base, kind, body, options = {}) {
return JSON.stringify({
kind,
body,
options
});
}
chainLocators(locators) {
const objects = locators.map(l => JSON.parse(l));
for (let i = 0; i < objects.length - 1; ++i) objects[i].next = objects[i + 1];
return JSON.stringify(objects[0]);
}
}
exports.JsonlLocatorFactory = JsonlLocatorFactory;
const generators = {
javascript: JavaScriptLocatorFactory,
python: PythonLocatorFactory,
java: JavaLocatorFactory,
csharp: CSharpLocatorFactory,
jsonl: JsonlLocatorFactory
};
function isRegExp(obj) {
return obj instanceof RegExp;
}
@@ -0,0 +1,179 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.locatorOrSelectorAsSelector = locatorOrSelectorAsSelector;
var _stringUtils = require("./stringUtils");
var _locatorGenerators = require("./locatorGenerators");
var _selectorParser = require("./selectorParser");
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function parseLocator(locator, testIdAttributeName) {
locator = locator.replace(/AriaRole\s*\.\s*([\w]+)/g, (_, group) => group.toLowerCase()).replace(/(get_by_role|getByRole)\s*\(\s*(?:["'`])([^'"`]+)['"`]/g, (_, group1, group2) => `${group1}(${group2.toLowerCase()}`);
const params = [];
let template = '';
for (let i = 0; i < locator.length; ++i) {
const quote = locator[i];
if (quote !== '"' && quote !== '\'' && quote !== '`' && quote !== '/') {
template += quote;
continue;
}
const isRegexEscaping = locator[i - 1] === 'r' || locator[i] === '/';
++i;
let text = '';
while (i < locator.length) {
if (locator[i] === '\\') {
if (isRegexEscaping) {
if (locator[i + 1] !== quote) text += locator[i];
++i;
text += locator[i];
} else {
++i;
if (locator[i] === 'n') text += '\n';else if (locator[i] === 'r') text += '\r';else if (locator[i] === 't') text += '\t';else text += locator[i];
}
++i;
continue;
}
if (locator[i] !== quote) {
text += locator[i++];
continue;
}
break;
}
params.push({
quote,
text
});
template += (quote === '/' ? 'r' : '') + '$' + params.length;
}
// Equalize languages.
template = template.toLowerCase().replace(/get_by_alt_text/g, 'getbyalttext').replace(/get_by_test_id/g, 'getbytestid').replace(/get_by_([\w]+)/g, 'getby$1').replace(/has_not_text/g, 'hasnottext').replace(/has_text/g, 'hastext').replace(/has_not/g, 'hasnot').replace(/frame_locator/g, 'framelocator').replace(/content_frame/g, 'contentframe').replace(/[{}\s]/g, '').replace(/new\(\)/g, '').replace(/new[\w]+\.[\w]+options\(\)/g, '').replace(/\.set/g, ',set').replace(/\.or_\(/g, 'or(') // Python has "or_" instead of "or".
.replace(/\.and_\(/g, 'and(') // Python has "and_" instead of "and".
.replace(/:/g, '=').replace(/,re\.ignorecase/g, 'i').replace(/,pattern.case_insensitive/g, 'i').replace(/,regexoptions.ignorecase/g, 'i').replace(/re.compile\(([^)]+)\)/g, '$1') // Python has regex strings as r"foo"
.replace(/pattern.compile\(([^)]+)\)/g, 'r$1').replace(/newregex\(([^)]+)\)/g, 'r$1').replace(/string=/g, '=').replace(/regex=/g, '=').replace(/,,/g, ',');
const preferredQuote = params.map(p => p.quote).filter(quote => '\'"`'.includes(quote))[0];
return {
selector: transform(template, params, testIdAttributeName),
preferredQuote
};
}
function countParams(template) {
return [...template.matchAll(/\$\d+/g)].length;
}
function shiftParams(template, sub) {
return template.replace(/\$(\d+)/g, (_, ordinal) => `$${ordinal - sub}`);
}
function transform(template, params, testIdAttributeName) {
// Recursively handle filter(has=, hasnot=, sethas(), sethasnot()).
// TODO: handle and(locator), or(locator), locator(locator), locator(has=, hasnot=, sethas(), sethasnot()).
while (true) {
const hasMatch = template.match(/filter\(,?(has=|hasnot=|sethas\(|sethasnot\()/);
if (!hasMatch) break;
// Extract inner locator based on balanced parens.
const start = hasMatch.index + hasMatch[0].length;
let balance = 0;
let end = start;
for (; end < template.length; end++) {
if (template[end] === '(') balance++;else if (template[end] === ')') balance--;
if (balance < 0) break;
}
// Replace Java sethas(...) and sethasnot(...) with has=... and hasnot=...
let prefix = template.substring(0, start);
let extraSymbol = 0;
if (['sethas(', 'sethasnot('].includes(hasMatch[1])) {
// Eat extra ) symbol at the end of sethas(...)
extraSymbol = 1;
prefix = prefix.replace(/sethas\($/, 'has=').replace(/sethasnot\($/, 'hasnot=');
}
const paramsCountBeforeHas = countParams(template.substring(0, start));
const hasTemplate = shiftParams(template.substring(start, end), paramsCountBeforeHas);
const paramsCountInHas = countParams(hasTemplate);
const hasParams = params.slice(paramsCountBeforeHas, paramsCountBeforeHas + paramsCountInHas);
const hasSelector = JSON.stringify(transform(hasTemplate, hasParams, testIdAttributeName));
// Replace filter(has=...) with filter(has2=$5). Use has2 to avoid matching the same filter again.
// Replace filter(hasnot=...) with filter(hasnot2=$5). Use hasnot2 to avoid matching the same filter again.
template = prefix.replace(/=$/, '2=') + `$${paramsCountBeforeHas + 1}` + shiftParams(template.substring(end + extraSymbol), paramsCountInHas - 1);
// Replace inner params with $5 value.
const paramsBeforeHas = params.slice(0, paramsCountBeforeHas);
const paramsAfterHas = params.slice(paramsCountBeforeHas + paramsCountInHas);
params = paramsBeforeHas.concat([{
quote: '"',
text: hasSelector
}]).concat(paramsAfterHas);
}
// Transform to selector engines.
template = template.replace(/\,set([\w]+)\(([^)]+)\)/g, (_, group1, group2) => ',' + group1.toLowerCase() + '=' + group2.toLowerCase()).replace(/framelocator\(([^)]+)\)/g, '$1.internal:control=enter-frame').replace(/contentframe(\(\))?/g, 'internal:control=enter-frame').replace(/locator\(([^)]+),hastext=([^),]+)\)/g, 'locator($1).internal:has-text=$2').replace(/locator\(([^)]+),hasnottext=([^),]+)\)/g, 'locator($1).internal:has-not-text=$2').replace(/locator\(([^)]+),hastext=([^),]+)\)/g, 'locator($1).internal:has-text=$2').replace(/locator\(([^)]+)\)/g, '$1').replace(/getbyrole\(([^)]+)\)/g, 'internal:role=$1').replace(/getbytext\(([^)]+)\)/g, 'internal:text=$1').replace(/getbylabel\(([^)]+)\)/g, 'internal:label=$1').replace(/getbytestid\(([^)]+)\)/g, `internal:testid=[${testIdAttributeName}=$1]`).replace(/getby(placeholder|alt|title)(?:text)?\(([^)]+)\)/g, 'internal:attr=[$1=$2]').replace(/first(\(\))?/g, 'nth=0').replace(/last(\(\))?/g, 'nth=-1').replace(/nth\(([^)]+)\)/g, 'nth=$1').replace(/filter\(,?hastext=([^)]+)\)/g, 'internal:has-text=$1').replace(/filter\(,?hasnottext=([^)]+)\)/g, 'internal:has-not-text=$1').replace(/filter\(,?has2=([^)]+)\)/g, 'internal:has=$1').replace(/filter\(,?hasnot2=([^)]+)\)/g, 'internal:has-not=$1').replace(/,exact=false/g, '').replace(/,exact=true/g, 's').replace(/\,/g, '][');
const parts = template.split('.');
// Turn "internal:control=enter-frame >> nth=0" into "nth=0 >> internal:control=enter-frame"
// because these are swapped in locators vs selectors.
for (let index = 0; index < parts.length - 1; index++) {
if (parts[index] === 'internal:control=enter-frame' && parts[index + 1].startsWith('nth=')) {
// Swap nth and enter-frame.
const [nth] = parts.splice(index, 1);
parts.splice(index + 1, 0, nth);
}
}
// Substitute params.
return parts.map(t => {
if (!t.startsWith('internal:') || t === 'internal:control') return t.replace(/\$(\d+)/g, (_, ordinal) => {
const param = params[+ordinal - 1];
return param.text;
});
t = t.includes('[') ? t.replace(/\]/, '') + ']' : t;
t = t.replace(/(?:r)\$(\d+)(i)?/g, (_, ordinal, suffix) => {
const param = params[+ordinal - 1];
if (t.startsWith('internal:attr') || t.startsWith('internal:testid') || t.startsWith('internal:role')) return (0, _stringUtils.escapeForAttributeSelector)(new RegExp(param.text), false) + (suffix || '');
return (0, _stringUtils.escapeForTextSelector)(new RegExp(param.text, suffix), false);
}).replace(/\$(\d+)(i|s)?/g, (_, ordinal, suffix) => {
const param = params[+ordinal - 1];
if (t.startsWith('internal:has=') || t.startsWith('internal:has-not=')) return param.text;
if (t.startsWith('internal:testid')) return (0, _stringUtils.escapeForAttributeSelector)(param.text, true);
if (t.startsWith('internal:attr') || t.startsWith('internal:role')) return (0, _stringUtils.escapeForAttributeSelector)(param.text, suffix === 's');
return (0, _stringUtils.escapeForTextSelector)(param.text, suffix === 's');
});
return t;
}).join(' >> ');
}
function locatorOrSelectorAsSelector(language, locator, testIdAttributeName) {
try {
(0, _selectorParser.parseSelector)(locator);
return locator;
} catch (e) {}
try {
const {
selector,
preferredQuote
} = parseLocator(locator, testIdAttributeName);
const locators = (0, _locatorGenerators.asLocators)(language, selector, undefined, undefined, preferredQuote);
const digest = digestForComparison(language, locator);
if (locators.some(candidate => digestForComparison(language, candidate) === digest)) return selector;
} catch (e) {}
return '';
}
function digestForComparison(language, locator) {
locator = locator.replace(/\s/g, '');
if (language === 'javascript') locator = locator.replace(/\\?["`]/g, '\'');
return locator;
}
@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getByAltTextSelector = getByAltTextSelector;
exports.getByLabelSelector = getByLabelSelector;
exports.getByPlaceholderSelector = getByPlaceholderSelector;
exports.getByRoleSelector = getByRoleSelector;
exports.getByTestIdSelector = getByTestIdSelector;
exports.getByTextSelector = getByTextSelector;
exports.getByTitleSelector = getByTitleSelector;
var _stringUtils = require("./stringUtils");
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function getByAttributeTextSelector(attrName, text, options) {
return `internal:attr=[${attrName}=${(0, _stringUtils.escapeForAttributeSelector)(text, (options === null || options === void 0 ? void 0 : options.exact) || false)}]`;
}
function getByTestIdSelector(testIdAttributeName, testId) {
return `internal:testid=[${testIdAttributeName}=${(0, _stringUtils.escapeForAttributeSelector)(testId, true)}]`;
}
function getByLabelSelector(text, options) {
return 'internal:label=' + (0, _stringUtils.escapeForTextSelector)(text, !!(options !== null && options !== void 0 && options.exact));
}
function getByAltTextSelector(text, options) {
return getByAttributeTextSelector('alt', text, options);
}
function getByTitleSelector(text, options) {
return getByAttributeTextSelector('title', text, options);
}
function getByPlaceholderSelector(text, options) {
return getByAttributeTextSelector('placeholder', text, options);
}
function getByTextSelector(text, options) {
return 'internal:text=' + (0, _stringUtils.escapeForTextSelector)(text, !!(options !== null && options !== void 0 && options.exact));
}
function getByRoleSelector(role, options = {}) {
const props = [];
if (options.checked !== undefined) props.push(['checked', String(options.checked)]);
if (options.disabled !== undefined) props.push(['disabled', String(options.disabled)]);
if (options.selected !== undefined) props.push(['selected', String(options.selected)]);
if (options.expanded !== undefined) props.push(['expanded', String(options.expanded)]);
if (options.includeHidden !== undefined) props.push(['include-hidden', String(options.includeHidden)]);
if (options.level !== undefined) props.push(['level', String(options.level)]);
if (options.name !== undefined) props.push(['name', (0, _stringUtils.escapeForAttributeSelector)(options.name, !!options.exact)]);
if (options.pressed !== undefined) props.push(['pressed', String(options.pressed)]);
return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join('')}`;
}
@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isJsonMimeType = isJsonMimeType;
exports.isTextualMimeType = isTextualMimeType;
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function isJsonMimeType(mimeType) {
return !!mimeType.match(/^(application\/json|application\/.*?\+json|text\/(x-)?json)(;\s*charset=.*)?$/);
}
function isTextualMimeType(mimeType) {
return !!mimeType.match(/^(text\/.*?|application\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\/svg(\+xml)?|application\/.*?(\+json|\+xml))(;\s*charset=.*)?$/);
}
@@ -0,0 +1,227 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildFullSelector = buildFullSelector;
exports.toKeyboardModifiers = toKeyboardModifiers;
exports.traceParamsForAction = traceParamsForAction;
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function buildFullSelector(framePath, selector) {
return [...framePath, selector].join(' >> internal:control=enter-frame >> ');
}
const kDefaultTimeout = 5_000;
function traceParamsForAction(actionInContext) {
const {
action
} = actionInContext;
switch (action.name) {
case 'navigate':
{
const params = {
url: action.url
};
return {
method: 'goto',
apiName: 'page.goto',
params
};
}
case 'openPage':
case 'closePage':
throw new Error('Not reached');
}
const selector = buildFullSelector(actionInContext.frame.framePath, action.selector);
switch (action.name) {
case 'click':
{
const params = {
selector,
strict: true,
modifiers: toKeyboardModifiers(action.modifiers),
button: action.button,
clickCount: action.clickCount,
position: action.position
};
return {
method: 'click',
apiName: 'locator.click',
params
};
}
case 'press':
{
const params = {
selector,
strict: true,
key: [...toKeyboardModifiers(action.modifiers), action.key].join('+')
};
return {
method: 'press',
apiName: 'locator.press',
params
};
}
case 'fill':
{
const params = {
selector,
strict: true,
value: action.text
};
return {
method: 'fill',
apiName: 'locator.fill',
params
};
}
case 'setInputFiles':
{
const params = {
selector,
strict: true,
localPaths: action.files
};
return {
method: 'setInputFiles',
apiName: 'locator.setInputFiles',
params
};
}
case 'check':
{
const params = {
selector,
strict: true
};
return {
method: 'check',
apiName: 'locator.check',
params
};
}
case 'uncheck':
{
const params = {
selector,
strict: true
};
return {
method: 'uncheck',
apiName: 'locator.uncheck',
params
};
}
case 'select':
{
const params = {
selector,
strict: true,
options: action.options.map(option => ({
value: option
}))
};
return {
method: 'selectOption',
apiName: 'locator.selectOption',
params
};
}
case 'assertChecked':
{
const params = {
selector: action.selector,
expression: 'to.be.checked',
isNot: !action.checked,
timeout: kDefaultTimeout
};
return {
method: 'expect',
apiName: 'expect.toBeChecked',
params
};
}
case 'assertText':
{
const params = {
selector,
expression: 'to.have.text',
expectedText: [],
isNot: false,
timeout: kDefaultTimeout
};
return {
method: 'expect',
apiName: 'expect.toContainText',
params
};
}
case 'assertValue':
{
const params = {
selector,
expression: 'to.have.value',
expectedValue: undefined,
isNot: false,
timeout: kDefaultTimeout
};
return {
method: 'expect',
apiName: 'expect.toHaveValue',
params
};
}
case 'assertVisible':
{
const params = {
selector,
expression: 'to.be.visible',
isNot: false,
timeout: kDefaultTimeout
};
return {
method: 'expect',
apiName: 'expect.toBeVisible',
params
};
}
case 'assertSnapshot':
{
const params = {
selector,
expression: 'to.match.snapshot',
expectedText: [],
isNot: false,
timeout: kDefaultTimeout
};
return {
method: 'expect',
apiName: 'expect.toMatchAriaSnapshot',
params
};
}
}
}
function toKeyboardModifiers(modifiers) {
const result = [];
if (modifiers & 1) result.push('Alt');
if (modifiers & 2) result.push('ControlOrMeta');
if (modifiers & 4) result.push('ControlOrMeta');
if (modifiers & 8) result.push('Shift');
return result;
}
@@ -0,0 +1,397 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "InvalidSelectorError", {
enumerable: true,
get: function () {
return _cssParser.InvalidSelectorError;
}
});
exports.customCSSNames = void 0;
Object.defineProperty(exports, "isInvalidSelectorError", {
enumerable: true,
get: function () {
return _cssParser.isInvalidSelectorError;
}
});
exports.parseAttributeSelector = parseAttributeSelector;
exports.parseSelector = parseSelector;
exports.splitSelectorByFrame = splitSelectorByFrame;
exports.stringifySelector = stringifySelector;
exports.visitAllSelectorParts = visitAllSelectorParts;
var _cssParser = require("./cssParser");
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const kNestedSelectorNames = new Set(['internal:has', 'internal:has-not', 'internal:and', 'internal:or', 'internal:chain', 'left-of', 'right-of', 'above', 'below', 'near']);
const kNestedSelectorNamesWithDistance = new Set(['left-of', 'right-of', 'above', 'below', 'near']);
const customCSSNames = exports.customCSSNames = new Set(['not', 'is', 'where', 'has', 'scope', 'light', 'visible', 'text', 'text-matches', 'text-is', 'has-text', 'above', 'below', 'right-of', 'left-of', 'near', 'nth-match']);
function parseSelector(selector) {
const parsedStrings = parseSelectorString(selector);
const parts = [];
for (const part of parsedStrings.parts) {
if (part.name === 'css' || part.name === 'css:light') {
if (part.name === 'css:light') part.body = ':light(' + part.body + ')';
const parsedCSS = (0, _cssParser.parseCSS)(part.body, customCSSNames);
parts.push({
name: 'css',
body: parsedCSS.selector,
source: part.body
});
continue;
}
if (kNestedSelectorNames.has(part.name)) {
let innerSelector;
let distance;
try {
const unescaped = JSON.parse('[' + part.body + ']');
if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== 'string') throw new _cssParser.InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);
innerSelector = unescaped[0];
if (unescaped.length === 2) {
if (typeof unescaped[1] !== 'number' || !kNestedSelectorNamesWithDistance.has(part.name)) throw new _cssParser.InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);
distance = unescaped[1];
}
} catch (e) {
throw new _cssParser.InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);
}
const nested = {
name: part.name,
source: part.body,
body: {
parsed: parseSelector(innerSelector),
distance
}
};
const lastFrame = [...nested.body.parsed.parts].reverse().find(part => part.name === 'internal:control' && part.body === 'enter-frame');
const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1;
// Allow nested selectors to start with the same frame selector.
if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), parts.slice(0, lastFrameIndex + 1))) nested.body.parsed.parts.splice(0, lastFrameIndex + 1);
parts.push(nested);
continue;
}
parts.push({
...part,
source: part.body
});
}
if (kNestedSelectorNames.has(parts[0].name)) throw new _cssParser.InvalidSelectorError(`"${parts[0].name}" selector cannot be first`);
return {
capture: parsedStrings.capture,
parts
};
}
function splitSelectorByFrame(selectorText) {
const selector = parseSelector(selectorText);
const result = [];
let chunk = {
parts: []
};
let chunkStartIndex = 0;
for (let i = 0; i < selector.parts.length; ++i) {
const part = selector.parts[i];
if (part.name === 'internal:control' && part.body === 'enter-frame') {
if (!chunk.parts.length) throw new _cssParser.InvalidSelectorError('Selector cannot start with entering frame, select the iframe first');
result.push(chunk);
chunk = {
parts: []
};
chunkStartIndex = i + 1;
continue;
}
if (selector.capture === i) chunk.capture = i - chunkStartIndex;
chunk.parts.push(part);
}
if (!chunk.parts.length) throw new _cssParser.InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${selectorText}`);
result.push(chunk);
if (typeof selector.capture === 'number' && typeof result[result.length - 1].capture !== 'number') throw new _cssParser.InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`);
return result;
}
function selectorPartsEqual(list1, list2) {
return stringifySelector({
parts: list1
}) === stringifySelector({
parts: list2
});
}
function stringifySelector(selector, forceEngineName) {
if (typeof selector === 'string') return selector;
return selector.parts.map((p, i) => {
let includeEngine = true;
if (!forceEngineName && i !== selector.capture) {
if (p.name === 'css') includeEngine = false;else if (p.name === 'xpath' && p.source.startsWith('//') || p.source.startsWith('..')) includeEngine = false;
}
const prefix = includeEngine ? p.name + '=' : '';
return `${i === selector.capture ? '*' : ''}${prefix}${p.source}`;
}).join(' >> ');
}
function visitAllSelectorParts(selector, visitor) {
const visit = (selector, nested) => {
for (const part of selector.parts) {
visitor(part, nested);
if (kNestedSelectorNames.has(part.name)) visit(part.body.parsed, true);
}
};
visit(selector, false);
}
function parseSelectorString(selector) {
let index = 0;
let quote;
let start = 0;
const result = {
parts: []
};
const append = () => {
const part = selector.substring(start, index).trim();
const eqIndex = part.indexOf('=');
let name;
let body;
if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {
name = part.substring(0, eqIndex).trim();
body = part.substring(eqIndex + 1);
} else if (part.length > 1 && part[0] === '"' && part[part.length - 1] === '"') {
name = 'text';
body = part;
} else if (part.length > 1 && part[0] === "'" && part[part.length - 1] === "'") {
name = 'text';
body = part;
} else if (/^\(*\/\//.test(part) || part.startsWith('..')) {
// If selector starts with '//' or '//' prefixed with multiple opening
// parenthesis, consider xpath. @see https://github.com/microsoft/playwright/issues/817
// If selector starts with '..', consider xpath as well.
name = 'xpath';
body = part;
} else {
name = 'css';
body = part;
}
let capture = false;
if (name[0] === '*') {
capture = true;
name = name.substring(1);
}
result.parts.push({
name,
body
});
if (capture) {
if (result.capture !== undefined) throw new _cssParser.InvalidSelectorError(`Only one of the selectors can capture using * modifier`);
result.capture = result.parts.length - 1;
}
};
if (!selector.includes('>>')) {
index = selector.length;
append();
return result;
}
const shouldIgnoreTextSelectorQuote = () => {
const prefix = selector.substring(start, index);
const match = prefix.match(/^\s*text\s*=(.*)$/);
// Must be a text selector with some text before the quote.
return !!match && !!match[1];
};
while (index < selector.length) {
const c = selector[index];
if (c === '\\' && index + 1 < selector.length) {
index += 2;
} else if (c === quote) {
quote = undefined;
index++;
} else if (!quote && (c === '"' || c === '\'' || c === '`') && !shouldIgnoreTextSelectorQuote()) {
quote = c;
index++;
} else if (!quote && c === '>' && selector[index + 1] === '>') {
append();
index += 2;
start = index;
} else {
index++;
}
}
append();
return result;
}
function parseAttributeSelector(selector, allowUnquotedStrings) {
let wp = 0;
let EOL = selector.length === 0;
const next = () => selector[wp] || '';
const eat1 = () => {
const result = next();
++wp;
EOL = wp >= selector.length;
return result;
};
const syntaxError = stage => {
if (EOL) throw new _cssParser.InvalidSelectorError(`Unexpected end of selector while parsing selector \`${selector}\``);
throw new _cssParser.InvalidSelectorError(`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? ' during ' + stage : ''));
};
function skipSpaces() {
while (!EOL && /\s/.test(next())) eat1();
}
function isCSSNameChar(char) {
// https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
return char >= '\u0080' // non-ascii
|| char >= '\u0030' && char <= '\u0039' // digit
|| char >= '\u0041' && char <= '\u005a' // uppercase letter
|| char >= '\u0061' && char <= '\u007a' // lowercase letter
|| char >= '\u0030' && char <= '\u0039' // digit
|| char === '\u005f' // "_"
|| char === '\u002d'; // "-"
}
function readIdentifier() {
let result = '';
skipSpaces();
while (!EOL && isCSSNameChar(next())) result += eat1();
return result;
}
function readQuotedString(quote) {
let result = eat1();
if (result !== quote) syntaxError('parsing quoted string');
while (!EOL && next() !== quote) {
if (next() === '\\') eat1();
result += eat1();
}
if (next() !== quote) syntaxError('parsing quoted string');
result += eat1();
return result;
}
function readRegularExpression() {
if (eat1() !== '/') syntaxError('parsing regular expression');
let source = '';
let inClass = false;
// https://262.ecma-international.org/11.0/#sec-literals-regular-expression-literals
while (!EOL) {
if (next() === '\\') {
source += eat1();
if (EOL) syntaxError('parsing regular expression');
} else if (inClass && next() === ']') {
inClass = false;
} else if (!inClass && next() === '[') {
inClass = true;
} else if (!inClass && next() === '/') {
break;
}
source += eat1();
}
if (eat1() !== '/') syntaxError('parsing regular expression');
let flags = '';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
while (!EOL && next().match(/[dgimsuy]/)) flags += eat1();
try {
return new RegExp(source, flags);
} catch (e) {
throw new _cssParser.InvalidSelectorError(`Error while parsing selector \`${selector}\`: ${e.message}`);
}
}
function readAttributeToken() {
let token = '';
skipSpaces();
if (next() === `'` || next() === `"`) token = readQuotedString(next()).slice(1, -1);else token = readIdentifier();
if (!token) syntaxError('parsing property path');
return token;
}
function readOperator() {
skipSpaces();
let op = '';
if (!EOL) op += eat1();
if (!EOL && op !== '=') op += eat1();
if (!['=', '*=', '^=', '$=', '|=', '~='].includes(op)) syntaxError('parsing operator');
return op;
}
function readAttribute() {
// skip leading [
eat1();
// read attribute name:
// foo.bar
// 'foo' . "ba zz"
const jsonPath = [];
jsonPath.push(readAttributeToken());
skipSpaces();
while (next() === '.') {
eat1();
jsonPath.push(readAttributeToken());
skipSpaces();
}
// check property is truthy: [enabled]
if (next() === ']') {
eat1();
return {
name: jsonPath.join('.'),
jsonPath,
op: '<truthy>',
value: null,
caseSensitive: false
};
}
const operator = readOperator();
let value = undefined;
let caseSensitive = true;
skipSpaces();
if (next() === '/') {
if (operator !== '=') throw new _cssParser.InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with regular expression`);
value = readRegularExpression();
} else if (next() === `'` || next() === `"`) {
value = readQuotedString(next()).slice(1, -1);
skipSpaces();
if (next() === 'i' || next() === 'I') {
caseSensitive = false;
eat1();
} else if (next() === 's' || next() === 'S') {
caseSensitive = true;
eat1();
}
} else {
value = '';
while (!EOL && (isCSSNameChar(next()) || next() === '+' || next() === '.')) value += eat1();
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else {
if (!allowUnquotedStrings) {
value = +value;
if (Number.isNaN(value)) syntaxError('parsing attribute value');
}
}
}
skipSpaces();
if (next() !== ']') syntaxError('parsing attribute value');
eat1();
if (operator !== '=' && typeof value !== 'string') throw new _cssParser.InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);
return {
name: jsonPath.join('.'),
jsonPath,
op: operator,
value,
caseSensitive
};
}
const result = {
name: '',
attributes: []
};
result.name = readIdentifier();
skipSpaces();
while (next() === '[') {
result.attributes.push(readAttribute());
skipSpaces();
}
if (!EOL) syntaxError(undefined);
if (!result.name && !result.attributes.length) throw new _cssParser.InvalidSelectorError(`Error while parsing selector \`${selector}\` - selector cannot be empty`);
return result;
}
@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cacheNormalizedWhitespaces = cacheNormalizedWhitespaces;
exports.cssEscape = cssEscape;
exports.escapeForAttributeSelector = escapeForAttributeSelector;
exports.escapeForTextSelector = escapeForTextSelector;
exports.escapeHTML = escapeHTML;
exports.escapeHTMLAttribute = escapeHTMLAttribute;
exports.escapeRegExp = escapeRegExp;
exports.escapeTemplateString = escapeTemplateString;
exports.escapeWithQuotes = escapeWithQuotes;
exports.isString = isString;
exports.longestCommonSubstring = longestCommonSubstring;
exports.normalizeEscapedRegexQuotes = normalizeEscapedRegexQuotes;
exports.normalizeWhiteSpace = normalizeWhiteSpace;
exports.quoteCSSAttributeValue = quoteCSSAttributeValue;
exports.toSnakeCase = toSnakeCase;
exports.toTitleCase = toTitleCase;
exports.trimString = trimString;
exports.trimStringWithEllipsis = trimStringWithEllipsis;
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// NOTE: this function should not be used to escape any selectors.
function escapeWithQuotes(text, char = '\'') {
const stringified = JSON.stringify(text);
const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"');
if (char === '\'') return char + escapedText.replace(/[']/g, '\\\'') + char;
if (char === '"') return char + escapedText.replace(/["]/g, '\\"') + char;
if (char === '`') return char + escapedText.replace(/[`]/g, '`') + char;
throw new Error('Invalid escape char');
}
function escapeTemplateString(text) {
return text.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
}
function isString(obj) {
return typeof obj === 'string' || obj instanceof String;
}
function toTitleCase(name) {
return name.charAt(0).toUpperCase() + name.substring(1);
}
function toSnakeCase(name) {
// E.g. ignoreHTTPSErrors => ignore_https_errors.
return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/([A-Z])([A-Z][a-z])/g, '$1_$2').toLowerCase();
}
function cssEscape(s) {
let result = '';
for (let i = 0; i < s.length; i++) result += cssEscapeOne(s, i);
return result;
}
function quoteCSSAttributeValue(text) {
return `"${cssEscape(text).replace(/\\ /g, ' ')}"`;
}
function cssEscapeOne(s, i) {
// https://drafts.csswg.org/cssom/#serialize-an-identifier
const c = s.charCodeAt(i);
if (c === 0x0000) return '\uFFFD';
if (c >= 0x0001 && c <= 0x001f || c >= 0x0030 && c <= 0x0039 && (i === 0 || i === 1 && s.charCodeAt(0) === 0x002d)) return '\\' + c.toString(16) + ' ';
if (i === 0 && c === 0x002d && s.length === 1) return '\\' + s.charAt(i);
if (c >= 0x0080 || c === 0x002d || c === 0x005f || c >= 0x0030 && c <= 0x0039 || c >= 0x0041 && c <= 0x005a || c >= 0x0061 && c <= 0x007a) return s.charAt(i);
return '\\' + s.charAt(i);
}
let normalizedWhitespaceCache;
function cacheNormalizedWhitespaces() {
normalizedWhitespaceCache = new Map();
}
function normalizeWhiteSpace(text) {
var _normalizedWhitespace;
let result = (_normalizedWhitespace = normalizedWhitespaceCache) === null || _normalizedWhitespace === void 0 ? void 0 : _normalizedWhitespace.get(text);
if (result === undefined) {
var _normalizedWhitespace2;
result = text.replace(/\u200b/g, '').trim().replace(/\s+/g, ' ');
(_normalizedWhitespace2 = normalizedWhitespaceCache) === null || _normalizedWhitespace2 === void 0 || _normalizedWhitespace2.set(text, result);
}
return result;
}
function normalizeEscapedRegexQuotes(source) {
// This function reverses the effect of escapeRegexForSelector below.
// Odd number of backslashes followed by the quote -> remove unneeded backslash.
return source.replace(/(^|[^\\])(\\\\)*\\(['"`])/g, '$1$2$3');
}
function escapeRegexForSelector(re) {
// Unicode mode does not allow "identity character escapes", so we do not escape and
// hope that it does not contain quotes and/or >> signs.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape
// TODO: rework RE usages in internal selectors away from literal representation to json, e.g. {source,flags}.
if (re.unicode || re.unicodeSets) return String(re);
// Even number of backslashes followed by the quote -> insert a backslash.
return String(re).replace(/(^|[^\\])(\\\\)*(["'`])/g, '$1$2\\$3').replace(/>>/g, '\\>\\>');
}
function escapeForTextSelector(text, exact) {
if (typeof text !== 'string') return escapeRegexForSelector(text);
return `${JSON.stringify(text)}${exact ? 's' : 'i'}`;
}
function escapeForAttributeSelector(value, exact) {
if (typeof value !== 'string') return escapeRegexForSelector(value);
// TODO: this should actually be
// cssEscape(value).replace(/\\ /g, ' ')
// However, our attribute selectors do not conform to CSS parsing spec,
// so we escape them differently.
return `"${value.replace(/\\/g, '\\\\').replace(/["]/g, '\\"')}"${exact ? 's' : 'i'}`;
}
function trimString(input, cap, suffix = '') {
if (input.length <= cap) return input;
const chars = [...input];
if (chars.length > cap) return chars.slice(0, cap - suffix.length).join('') + suffix;
return chars.join('');
}
function trimStringWithEllipsis(input, cap) {
return trimString(input, cap, '\u2026');
}
function escapeRegExp(s) {
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
const escaped = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#39;'
};
function escapeHTMLAttribute(s) {
return s.replace(/[&<>"']/ug, char => escaped[char]);
}
function escapeHTML(s) {
return s.replace(/[&<]/ug, char => escaped[char]);
}
function longestCommonSubstring(s1, s2) {
const n = s1.length;
const m = s2.length;
let maxLen = 0;
let endingIndex = 0;
// Initialize a 2D array with zeros
const dp = Array(n + 1).fill(null).map(() => Array(m + 1).fill(0));
// Build the dp table
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (s1[i - 1] === s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
endingIndex = i;
}
}
}
}
// Extract the longest common substring
return s1.slice(endingIndex - maxLen, endingIndex);
}
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseClientSideCallMetadata = parseClientSideCallMetadata;
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function parseClientSideCallMetadata(data) {
const result = new Map();
const {
files,
stacks
} = data;
for (const s of stacks) {
const [id, ff] = s;
result.set(`call@${id}`, ff.map(f => ({
file: files[f[0]],
line: f[1],
column: f[2],
function: f[3]
})));
}
return result;
}
@@ -0,0 +1,124 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.constructURLBasedOnBaseURL = constructURLBasedOnBaseURL;
exports.globToRegex = globToRegex;
exports.urlMatches = urlMatches;
exports.urlMatchesEqual = urlMatchesEqual;
var _stringUtils = require("./stringUtils");
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping
const escapedChars = new Set(['$', '^', '+', '.', '*', '(', ')', '|', '\\', '?', '{', '}', '[', ']']);
function globToRegex(glob) {
const tokens = ['^'];
let inGroup = false;
for (let i = 0; i < glob.length; ++i) {
const c = glob[i];
if (c === '\\' && i + 1 < glob.length) {
const char = glob[++i];
tokens.push(escapedChars.has(char) ? '\\' + char : char);
continue;
}
if (c === '*') {
const beforeDeep = glob[i - 1];
let starCount = 1;
while (glob[i + 1] === '*') {
starCount++;
i++;
}
const afterDeep = glob[i + 1];
const isDeep = starCount > 1 && (beforeDeep === '/' || beforeDeep === undefined) && (afterDeep === '/' || afterDeep === undefined);
if (isDeep) {
tokens.push('((?:[^/]*(?:\/|$))*)');
i++;
} else {
tokens.push('([^/]*)');
}
continue;
}
switch (c) {
case '?':
tokens.push('.');
break;
case '[':
tokens.push('[');
break;
case ']':
tokens.push(']');
break;
case '{':
inGroup = true;
tokens.push('(');
break;
case '}':
inGroup = false;
tokens.push(')');
break;
case ',':
if (inGroup) {
tokens.push('|');
break;
}
tokens.push('\\' + c);
break;
default:
tokens.push(escapedChars.has(c) ? '\\' + c : c);
}
}
tokens.push('$');
return new RegExp(tokens.join(''));
}
function isRegExp(obj) {
return obj instanceof RegExp || Object.prototype.toString.call(obj) === '[object RegExp]';
}
function urlMatchesEqual(match1, match2) {
if (isRegExp(match1) && isRegExp(match2)) return match1.source === match2.source && match1.flags === match2.flags;
return match1 === match2;
}
function urlMatches(baseURL, urlString, match) {
if (match === undefined || match === '') return true;
if ((0, _stringUtils.isString)(match) && !match.startsWith('*')) {
// Allow http(s) baseURL to match ws(s) urls.
if (baseURL && /^https?:\/\//.test(baseURL) && /^wss?:\/\//.test(urlString)) baseURL = baseURL.replace(/^http/, 'ws');
match = constructURLBasedOnBaseURL(baseURL, match);
}
if ((0, _stringUtils.isString)(match)) match = globToRegex(match);
if (isRegExp(match)) return match.test(urlString);
if (typeof match === 'string' && match === urlString) return true;
const url = parsedURL(urlString);
if (!url) return false;
if (typeof match === 'string') return url.pathname === match;
if (typeof match !== 'function') throw new Error('url parameter should be string, RegExp or function');
return match(url);
}
function parsedURL(url) {
try {
return new URL(url);
} catch (e) {
return null;
}
}
function constructURLBasedOnBaseURL(baseURL, givenURL) {
try {
return new URL(givenURL, baseURL).toString();
} catch (e) {
return givenURL;
}
}