From 36d22d82aa202bb199967e9512281e9a53db42c9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 21:33:14 +0200 Subject: Adding upstream version 115.7.0esr. Signed-off-by: Daniel Baumann --- .../shared/webconsole/GenerateDataFromWebIdls.py | 176 +++++ .../shared/webconsole/GenerateReservedWordsJS.py | 40 + devtools/shared/webconsole/analyze-input-string.js | 406 +++++++++++ devtools/shared/webconsole/js-property-provider.js | 803 +++++++++++++++++++++ devtools/shared/webconsole/messages.js | 55 ++ devtools/shared/webconsole/moz.build | 33 + devtools/shared/webconsole/parser-helper.js | 66 ++ .../shared/webconsole/test/browser/browser.ini | 13 + .../test/browser/browser_commands_registration.js | 78 ++ .../test/browser/browser_network_longstring.js | 183 +++++ devtools/shared/webconsole/test/browser/data.json | 3 + .../webconsole/test/browser/data.json^headers^ | 3 + devtools/shared/webconsole/test/browser/head.js | 61 ++ .../test/browser/network_requests_iframe.html | 66 ++ devtools/shared/webconsole/test/chrome/chrome.ini | 34 + devtools/shared/webconsole/test/chrome/common.js | 274 +++++++ .../webconsole/test/chrome/console-test-worker.js | 21 + devtools/shared/webconsole/test/chrome/data.json | 5 + .../webconsole/test/chrome/data.json^headers^ | 3 + .../webconsole/test/chrome/helper_serviceworker.js | 21 + .../test/chrome/network_requests_iframe.html | 66 ++ .../webconsole/test/chrome/sandboxed_iframe.html | 8 + .../shared/webconsole/test/chrome/test_basics.html | 61 ++ .../test/chrome/test_cached_messages.html | 217 ++++++ .../test/chrome/test_console_assert.html | 106 +++ .../test/chrome/test_console_group_styling.html | 121 ++++ .../test/chrome/test_console_serviceworker.html | 202 ++++++ .../chrome/test_console_serviceworker_cached.html | 119 +++ .../test/chrome/test_console_styling.html | 134 ++++ .../test/chrome/test_console_timestamp.html | 48 ++ .../test/chrome/test_console_worker.html | 73 ++ .../webconsole/test/chrome/test_consoleapi.html | 225 ++++++ .../test/chrome/test_consoleapi_innerID.html | 157 ++++ .../webconsole/test/chrome/test_file_uri.html | 110 +++ .../test/chrome/test_jsterm_autocomplete.html | 635 ++++++++++++++++ .../webconsole/test/chrome/test_network_get.html | 132 ++++ .../webconsole/test/chrome/test_network_post.html | 143 ++++ .../test/chrome/test_network_security-hsts.html | 89 +++ .../test/chrome/test_nsiconsolemessage.html | 74 ++ .../webconsole/test/chrome/test_object_actor.html | 158 ++++ .../chrome/test_object_actor_native_getters.html | 75 ++ ...t_object_actor_native_getters_lenient_this.html | 54 ++ .../webconsole/test/chrome/test_page_errors.html | 224 ++++++ .../shared/webconsole/test/xpcshell/.eslintrc.js | 6 + devtools/shared/webconsole/test/xpcshell/head.js | 10 + .../test/xpcshell/test_analyze_input_string.js | 225 ++++++ .../test/xpcshell/test_js_property_provider.js | 746 +++++++++++++++++++ .../shared/webconsole/test/xpcshell/xpcshell.ini | 9 + 48 files changed, 6571 insertions(+) create mode 100644 devtools/shared/webconsole/GenerateDataFromWebIdls.py create mode 100644 devtools/shared/webconsole/GenerateReservedWordsJS.py create mode 100644 devtools/shared/webconsole/analyze-input-string.js create mode 100644 devtools/shared/webconsole/js-property-provider.js create mode 100644 devtools/shared/webconsole/messages.js create mode 100644 devtools/shared/webconsole/moz.build create mode 100644 devtools/shared/webconsole/parser-helper.js create mode 100644 devtools/shared/webconsole/test/browser/browser.ini create mode 100644 devtools/shared/webconsole/test/browser/browser_commands_registration.js create mode 100644 devtools/shared/webconsole/test/browser/browser_network_longstring.js create mode 100644 devtools/shared/webconsole/test/browser/data.json create mode 100644 devtools/shared/webconsole/test/browser/data.json^headers^ create mode 100644 devtools/shared/webconsole/test/browser/head.js create mode 100644 devtools/shared/webconsole/test/browser/network_requests_iframe.html create mode 100644 devtools/shared/webconsole/test/chrome/chrome.ini create mode 100644 devtools/shared/webconsole/test/chrome/common.js create mode 100644 devtools/shared/webconsole/test/chrome/console-test-worker.js create mode 100644 devtools/shared/webconsole/test/chrome/data.json create mode 100644 devtools/shared/webconsole/test/chrome/data.json^headers^ create mode 100644 devtools/shared/webconsole/test/chrome/helper_serviceworker.js create mode 100644 devtools/shared/webconsole/test/chrome/network_requests_iframe.html create mode 100644 devtools/shared/webconsole/test/chrome/sandboxed_iframe.html create mode 100644 devtools/shared/webconsole/test/chrome/test_basics.html create mode 100644 devtools/shared/webconsole/test/chrome/test_cached_messages.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_assert.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_group_styling.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_serviceworker.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_styling.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_timestamp.html create mode 100644 devtools/shared/webconsole/test/chrome/test_console_worker.html create mode 100644 devtools/shared/webconsole/test/chrome/test_consoleapi.html create mode 100644 devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html create mode 100644 devtools/shared/webconsole/test/chrome/test_file_uri.html create mode 100644 devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html create mode 100644 devtools/shared/webconsole/test/chrome/test_network_get.html create mode 100644 devtools/shared/webconsole/test/chrome/test_network_post.html create mode 100644 devtools/shared/webconsole/test/chrome/test_network_security-hsts.html create mode 100644 devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html create mode 100644 devtools/shared/webconsole/test/chrome/test_object_actor.html create mode 100644 devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html create mode 100644 devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html create mode 100644 devtools/shared/webconsole/test/chrome/test_page_errors.html create mode 100644 devtools/shared/webconsole/test/xpcshell/.eslintrc.js create mode 100644 devtools/shared/webconsole/test/xpcshell/head.js create mode 100644 devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js create mode 100644 devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js create mode 100644 devtools/shared/webconsole/test/xpcshell/xpcshell.ini (limited to 'devtools/shared/webconsole') diff --git a/devtools/shared/webconsole/GenerateDataFromWebIdls.py b/devtools/shared/webconsole/GenerateDataFromWebIdls.py new file mode 100644 index 0000000000..467f30faa8 --- /dev/null +++ b/devtools/shared/webconsole/GenerateDataFromWebIdls.py @@ -0,0 +1,176 @@ +""" +This script parses mozilla-central's WebIDL bindings and writes a JSON-formatted +subset of the function bindings to several files: +- "devtools/server/actors/webconsole/webidl-pure-allowlist.js" (for eager evaluation processing) +- "devtools/server/actors/webconsole/webidl-unsafe-getters-names.js" (for preventing automatically call getters that could emit warnings) + +Run this script via + +> ./mach python devtools/shared/webconsole/GenerateDataFromWebIdls.py + +with a mozconfig that references a built non-artifact build. +""" + +from os import path, remove, system +import json +import WebIDL +import buildconfig + +# This is an explicit list of interfaces to load [Pure] and [Constant] +# annotation for. There are a bunch of things that are pure in other interfaces +# that we don't care about in the context of the devtools. +PURE_INTERFACE_ALLOWLIST = set( + [ + "Document", + "Node", + "DOMTokenList", + "Element", + "Performance", + "URLSearchParams", + "FormData", + "Headers", + ] +) + +# This is an explicit list of interfaces to exclude. +DEPRECATED_INTERFACE__EXCLUDE_LIST = set( + [ + "External", + "TestExampleInterface", + "TestInterface", + "TestJSImplInterface", + "TestingDeprecatedInterface", + ] +) + +FILE_TEMPLATE = """\ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// This file is automatically generated by the GenerateDataFromWebIdls.py +// script. Do not modify it manually. +"use strict"; + +module.exports = %(data)s; +""" + +pure_output_file = path.join( + buildconfig.topsrcdir, "devtools/server/actors/webconsole/webidl-pure-allowlist.js" +) +unsafe_getters_names_file = path.join( + buildconfig.topsrcdir, + "devtools/server/actors/webconsole/webidl-unsafe-getters-names.js", +) + +input_file = path.join(buildconfig.topobjdir, "dom/bindings/file-lists.json") + +if not path.isfile(input_file): + raise Exception( + "Script must be run with a mozconfig referencing a non-artifact OBJDIR" + ) + +file_list = json.load(open(input_file)) + +parser = WebIDL.Parser() +for filepath in file_list["webidls"]: + with open(filepath, "r", encoding="utf8") as f: + parser.parse(f.read(), filepath) +results = parser.finish() + +# TODO: Bug 1616013 - Move more of these to be part of the pure list. +pure_output = { + "Document": { + "prototype": [ + "getSelection", + "hasStorageAccess", + ], + }, + "Range": { + "prototype": [ + "isPointInRange", + "comparePoint", + "intersectsNode", + # These two functions aren't pure because they do trigger + # layout when they are called, but in the context of eager + # evaluation, that should be a totally fine thing to do. + "getClientRects", + "getBoundingClientRect", + ], + }, + "Selection": { + "prototype": ["getRangeAt", "containsNode"], + }, +} +unsafe_getters_names = [] +for result in results: + if isinstance(result, WebIDL.IDLInterface): + iface = result.identifier.name + + is_global = result.getExtendedAttribute("Global") + + for member in result.members: + name = member.identifier.name + + if member.isMethod() and member.affects == "Nothing": + if ( + PURE_INTERFACE_ALLOWLIST and not iface in PURE_INTERFACE_ALLOWLIST + ) or name.startswith("_"): + continue + + if is_global: + raise Exception( + "Global methods and accessors are not supported: " + iface + ) + + if iface not in pure_output: + pure_output[iface] = {} + + if member.isStatic(): + owner_type = "static" + else: + owner_type = "prototype" + + if owner_type not in pure_output[iface]: + pure_output[iface][owner_type] = [] + + # All DOM getters are considered eagerly-evaluate-able. + # Collect methods only. + # + # NOTE: We still need to calculate unsafe_getters_names for + # object preview. + if member.isMethod(): + pure_output[iface][owner_type].append(name) + + if ( + not iface in DEPRECATED_INTERFACE__EXCLUDE_LIST + and not name in unsafe_getters_names + and member.isAttr() + and ( + member.getExtendedAttribute("Deprecated") + or member.getExtendedAttribute("LegacyLenientThis") + ) + ): + unsafe_getters_names.append(name) + + +with open(pure_output_file, "w") as f: + f.write(FILE_TEMPLATE % {"data": json.dumps(pure_output, indent=2, sort_keys=True)}) +print("Successfully generated", pure_output_file) + +unsafe_getters_names.sort() +with open(unsafe_getters_names_file, "w") as f: + f.write( + FILE_TEMPLATE + % {"data": json.dumps(unsafe_getters_names, indent=2, sort_keys=True)} + ) +print("Successfully generated", unsafe_getters_names_file) + +print("Formatting files...") +system("./mach eslint --fix " + pure_output_file + " " + unsafe_getters_names_file) +print("Files are now properly formatted") + +# Parsing the idls generate a parser.out file that we don't have any use of. +if path.exists("parser.out"): + remove("parser.out") +print("DONE") diff --git a/devtools/shared/webconsole/GenerateReservedWordsJS.py b/devtools/shared/webconsole/GenerateReservedWordsJS.py new file mode 100644 index 0000000000..cd8a47b648 --- /dev/null +++ b/devtools/shared/webconsole/GenerateReservedWordsJS.py @@ -0,0 +1,40 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import re +import sys + + +def read_reserved_word_list(filename): + macro_pat = re.compile(r"^\s*MACRO\(([^,]+), *[^,]+, *[^\)]+\)\s*\\?$") + + reserved_word_list = [] + with open(filename, "r") as f: + for line in f: + m = macro_pat.search(line) + if m: + reserved_word_list.append(m.group(1)) + + assert len(reserved_word_list) != 0 + + return reserved_word_list + + +def line(opt, s): + opt["output"].write("{}\n".format(s)) + + +def main(output, reserved_words_h): + reserved_word_list = read_reserved_word_list(reserved_words_h) + opt = {"output": output} + + line(opt, "const JS_RESERVED_WORDS = [") + for word in reserved_word_list: + line(opt, ' "{}",'.format(word)) + line(opt, "];") + line(opt, "module.exports = JS_RESERVED_WORDS;") + + +if __name__ == "__main__": + main(sys.stdout, *sys.argv[1:]) diff --git a/devtools/shared/webconsole/analyze-input-string.js b/devtools/shared/webconsole/analyze-input-string.js new file mode 100644 index 0000000000..a0e36247e3 --- /dev/null +++ b/devtools/shared/webconsole/analyze-input-string.js @@ -0,0 +1,406 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const STATE_NORMAL = Symbol("STATE_NORMAL"); +const STATE_QUOTE = Symbol("STATE_QUOTE"); +const STATE_DQUOTE = Symbol("STATE_DQUOTE"); +const STATE_TEMPLATE_LITERAL = Symbol("STATE_TEMPLATE_LITERAL"); +const STATE_ESCAPE_QUOTE = Symbol("STATE_ESCAPE_QUOTE"); +const STATE_ESCAPE_DQUOTE = Symbol("STATE_ESCAPE_DQUOTE"); +const STATE_ESCAPE_TEMPLATE_LITERAL = Symbol("STATE_ESCAPE_TEMPLATE_LITERAL"); +const STATE_SLASH = Symbol("STATE_SLASH"); +const STATE_INLINE_COMMENT = Symbol("STATE_INLINE_COMMENT"); +const STATE_MULTILINE_COMMENT = Symbol("STATE_MULTILINE_COMMENT"); +const STATE_MULTILINE_COMMENT_CLOSE = Symbol("STATE_MULTILINE_COMMENT_CLOSE"); +const STATE_QUESTION_MARK = Symbol("STATE_QUESTION_MARK"); + +const OPEN_BODY = "{[(".split(""); +const CLOSE_BODY = "}])".split(""); +const OPEN_CLOSE_BODY = { + "{": "}", + "[": "]", + "(": ")", +}; + +const NO_AUTOCOMPLETE_PREFIXES = ["var", "const", "let", "function", "class"]; +const OPERATOR_CHARS_SET = new Set(";,:=<>+-*%|&^~!".split("")); + +/** + * Analyses a given string to find the last statement that is interesting for + * later completion. + * + * @param string str + * A string to analyse. + * + * @returns object + * If there was an error in the string detected, then a object like + * + * { err: "ErrorMesssage" } + * + * is returned, otherwise a object like + * + * { + * state: STATE_NORMAL|STATE_QUOTE|STATE_DQUOTE, + * lastStatement: the last statement in the string, + * isElementAccess: boolean that indicates if the lastStatement has an open + * element access (e.g. `x["match`). + * isPropertyAccess: boolean indicating if we are accessing property + * (e.g `true` in `var a = {b: 1};a.b`) + * matchProp: The part of the expression that should match the properties + * on the mainExpression (e.g. `que` when expression is `document.body.que`) + * mainExpression: The part of the expression before any property access, + * (e.g. `a.b` if expression is `a.b.`) + * expressionBeforePropertyAccess: The part of the expression before property access + * (e.g `var a = {b: 1};a` if expression is `var a = {b: 1};a.b`) + * } + */ +// eslint-disable-next-line complexity +exports.analyzeInputString = function (str, timeout = 2500) { + // work variables. + const bodyStack = []; + let state = STATE_NORMAL; + let previousNonWhitespaceChar; + let lastStatement = ""; + let currentIndex = -1; + let dotIndex; + let pendingWhitespaceChars = ""; + const startingTime = Date.now(); + + // Use a string iterator in order to handle character with a length >= 2 (e.g. 😎). + for (const c of str) { + // We are possibly dealing with a very large string that would take a long time to + // analyze (and freeze the process). If the function has been running for more than + // a given time, we stop the analysis (this isn't too bad because the only + // consequence is that we won't provide autocompletion items). + if (Date.now() - startingTime > timeout) { + return { + err: "timeout", + }; + } + + currentIndex += 1; + let resetLastStatement = false; + const isWhitespaceChar = c.trim() === ""; + switch (state) { + // Normal JS state. + case STATE_NORMAL: + if (lastStatement.endsWith("?.") && /\d/.test(c)) { + // If the current char is a number, the engine will consider we're not + // performing an optional chaining, but a ternary (e.g. x ?.4 : 2). + lastStatement = ""; + } + + // Storing the index of dot of the input string + if (c === ".") { + dotIndex = currentIndex; + } + + // If the last characters were spaces, and the current one is not. + if (pendingWhitespaceChars && !isWhitespaceChar) { + // If we have a legitimate property/element access, or potential optional + // chaining call, we append the spaces. + if (c === "[" || c === "." || c === "?") { + lastStatement = lastStatement + pendingWhitespaceChars; + } else { + // if not, we can be sure the statement was over, and we can start a new one. + lastStatement = ""; + } + pendingWhitespaceChars = ""; + } + + if (c == '"') { + state = STATE_DQUOTE; + } else if (c == "'") { + state = STATE_QUOTE; + } else if (c == "`") { + state = STATE_TEMPLATE_LITERAL; + } else if (c == "/") { + state = STATE_SLASH; + } else if (c == "?") { + state = STATE_QUESTION_MARK; + } else if (OPERATOR_CHARS_SET.has(c)) { + // If the character is an operator, we can update the current statement. + resetLastStatement = true; + } else if (isWhitespaceChar) { + // If the previous char isn't a dot or opening bracket, and the current computed + // statement is not a variable/function/class declaration, we track the number + // of consecutive spaces, so we can re-use them at some point (or drop them). + if ( + previousNonWhitespaceChar !== "." && + previousNonWhitespaceChar !== "[" && + !NO_AUTOCOMPLETE_PREFIXES.includes(lastStatement) + ) { + pendingWhitespaceChars += c; + continue; + } + } else if (OPEN_BODY.includes(c)) { + // When opening a bracket or a parens, we store the current statement, in order + // to be able to retrieve it later. + bodyStack.push({ + token: c, + lastStatement, + index: currentIndex, + }); + // And we compute a new statement. + resetLastStatement = true; + } else if (CLOSE_BODY.includes(c)) { + const last = bodyStack.pop(); + if (!last || OPEN_CLOSE_BODY[last.token] != c) { + return { + err: "syntax error", + }; + } + if (c == "}") { + resetLastStatement = true; + } else { + lastStatement = last.lastStatement; + } + } + break; + + // Escaped quote + case STATE_ESCAPE_QUOTE: + state = STATE_QUOTE; + break; + case STATE_ESCAPE_DQUOTE: + state = STATE_DQUOTE; + break; + case STATE_ESCAPE_TEMPLATE_LITERAL: + state = STATE_TEMPLATE_LITERAL; + break; + + // Double quote state > " < + case STATE_DQUOTE: + if (c == "\\") { + state = STATE_ESCAPE_DQUOTE; + } else if (c == "\n") { + return { + err: "unterminated string literal", + }; + } else if (c == '"') { + state = STATE_NORMAL; + } + break; + + // Template literal state > ` < + case STATE_TEMPLATE_LITERAL: + if (c == "\\") { + state = STATE_ESCAPE_TEMPLATE_LITERAL; + } else if (c == "`") { + state = STATE_NORMAL; + } + break; + + // Single quote state > ' < + case STATE_QUOTE: + if (c == "\\") { + state = STATE_ESCAPE_QUOTE; + } else if (c == "\n") { + return { + err: "unterminated string literal", + }; + } else if (c == "'") { + state = STATE_NORMAL; + } + break; + case STATE_SLASH: + if (c == "/") { + state = STATE_INLINE_COMMENT; + } else if (c == "*") { + state = STATE_MULTILINE_COMMENT; + } else { + lastStatement = ""; + state = STATE_NORMAL; + } + break; + + case STATE_INLINE_COMMENT: + if (c === "\n") { + state = STATE_NORMAL; + resetLastStatement = true; + } + break; + + case STATE_MULTILINE_COMMENT: + if (c === "*") { + state = STATE_MULTILINE_COMMENT_CLOSE; + } + break; + + case STATE_MULTILINE_COMMENT_CLOSE: + if (c === "/") { + state = STATE_NORMAL; + resetLastStatement = true; + } else { + state = STATE_MULTILINE_COMMENT; + } + break; + + case STATE_QUESTION_MARK: + state = STATE_NORMAL; + if (c === "?") { + // If we have a nullish coalescing operator, we start a new statement + resetLastStatement = true; + } else if (c !== ".") { + // If we're not dealing with optional chaining (?.), it means we have a ternary, + // so we are starting a new statement that includes the current character. + lastStatement = ""; + } else { + dotIndex = currentIndex; + } + break; + } + + if (!isWhitespaceChar) { + previousNonWhitespaceChar = c; + } + if (resetLastStatement) { + lastStatement = ""; + } else { + lastStatement = lastStatement + c; + } + + // We update all the open stacks lastStatement so they are up-to-date. + bodyStack.forEach(stack => { + if (stack.token !== "}") { + stack.lastStatement = stack.lastStatement + c; + } + }); + } + + let isElementAccess = false; + let lastOpeningBracketIndex = -1; + if (bodyStack.length === 1 && bodyStack[0].token === "[") { + lastStatement = bodyStack[0].lastStatement; + lastOpeningBracketIndex = bodyStack[0].index; + isElementAccess = true; + + if ( + state === STATE_DQUOTE || + state === STATE_QUOTE || + state === STATE_TEMPLATE_LITERAL || + state === STATE_ESCAPE_QUOTE || + state === STATE_ESCAPE_DQUOTE || + state === STATE_ESCAPE_TEMPLATE_LITERAL + ) { + state = STATE_NORMAL; + } + } else if (pendingWhitespaceChars) { + lastStatement = ""; + } + + const lastCompletionCharIndex = isElementAccess + ? lastOpeningBracketIndex + : dotIndex; + + const stringBeforeLastCompletionChar = str.slice(0, lastCompletionCharIndex); + + const isPropertyAccess = + lastCompletionCharIndex && lastCompletionCharIndex > 0; + + // Compute `isOptionalAccess`, so that we can use it + // later for computing `expressionBeforePropertyAccess`. + //Check `?.` before `[` for element access ( e.g `a?.["b` or `a ?. ["b` ) + // and `?` before `.` for regular property access ( e.g `a?.b` or `a ?. b` ) + const optionalElementAccessRegex = /\?\.\s*$/; + const isOptionalAccess = isElementAccess + ? optionalElementAccessRegex.test(stringBeforeLastCompletionChar) + : isPropertyAccess && + str.slice(lastCompletionCharIndex - 1, lastCompletionCharIndex + 1) === + "?."; + + // Get the filtered string for the properties (e.g if `document.qu` then `qu`) + const matchProp = isPropertyAccess + ? str.slice(lastCompletionCharIndex + 1).trimLeft() + : null; + + const expressionBeforePropertyAccess = isPropertyAccess + ? str.slice( + 0, + // For optional access, we can take all the chars before the last "?" char. + isOptionalAccess + ? stringBeforeLastCompletionChar.lastIndexOf("?") + : lastCompletionCharIndex + ) + : str; + + let mainExpression = lastStatement; + if (isPropertyAccess) { + if (isOptionalAccess) { + // Strip anything before the last `?`. + mainExpression = mainExpression.slice(0, mainExpression.lastIndexOf("?")); + } else { + mainExpression = mainExpression.slice( + 0, + -1 * (str.length - lastCompletionCharIndex) + ); + } + } + + mainExpression = mainExpression.trim(); + + return { + state, + isElementAccess, + isPropertyAccess, + expressionBeforePropertyAccess, + lastStatement, + mainExpression, + matchProp, + }; +}; + +/** + * Checks whether the analyzed input string is in an appropriate state to autocomplete, e.g. not + * inside a string, or declaring a variable. + * @param {object} inputAnalysisState The analyzed string to check + * @returns {boolean} Whether the input should be autocompleted + */ +exports.shouldInputBeAutocompleted = function (inputAnalysisState) { + const { err, state, lastStatement } = inputAnalysisState; + + // There was an error analysing the string. + if (err) { + return false; + } + + // If the current state is not STATE_NORMAL, then we are inside string, + // which means that no completion is possible. + if (state != STATE_NORMAL) { + return false; + } + + // Don't complete on just an empty string. + if (lastStatement.trim() == "") { + return false; + } + + if ( + NO_AUTOCOMPLETE_PREFIXES.some(prefix => + lastStatement.startsWith(prefix + " ") + ) + ) { + return false; + } + + return true; +}; + +/** + * Checks whether the analyzed input string is in an appropriate state to be eagerly evaluated. + * @param {object} inputAnalysisState + * @returns {boolean} Whether the input should be eagerly evaluated + */ +exports.shouldInputBeEagerlyEvaluated = function ({ lastStatement }) { + const inComputedProperty = + lastStatement.lastIndexOf("[") !== -1 && + lastStatement.lastIndexOf("[") > lastStatement.lastIndexOf("]"); + + const hasPropertyAccess = + lastStatement.includes(".") || lastStatement.includes("["); + + return hasPropertyAccess && !inComputedProperty; +}; diff --git a/devtools/shared/webconsole/js-property-provider.js b/devtools/shared/webconsole/js-property-provider.js new file mode 100644 index 0000000000..c261fed40d --- /dev/null +++ b/devtools/shared/webconsole/js-property-provider.js @@ -0,0 +1,803 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const DevToolsUtils = require("resource://devtools/shared/DevToolsUtils.js"); + +const { + evalWithDebugger, +} = require("resource://devtools/server/actors/webconsole/eval-with-debugger.js"); + +if (!isWorker) { + loader.lazyRequireGetter( + this, + "getSyntaxTrees", + "resource://devtools/shared/webconsole/parser-helper.js", + true + ); +} +const lazy = {}; +ChromeUtils.defineESModuleGetters(lazy, { + Reflect: "resource://gre/modules/reflect.sys.mjs", +}); +loader.lazyRequireGetter( + this, + [ + "analyzeInputString", + "shouldInputBeAutocompleted", + "shouldInputBeEagerlyEvaluated", + ], + "resource://devtools/shared/webconsole/analyze-input-string.js", + true +); + +// Provide an easy way to bail out of even attempting an autocompletion +// if an object has way too many properties. Protects against large objects +// with numeric values that wouldn't be tallied towards MAX_AUTOCOMPLETIONS. +const MAX_AUTOCOMPLETE_ATTEMPTS = (exports.MAX_AUTOCOMPLETE_ATTEMPTS = 100000); +// Prevent iterating over too many properties during autocomplete suggestions. +const MAX_AUTOCOMPLETIONS = (exports.MAX_AUTOCOMPLETIONS = 1500); + +/** + * Provides a list of properties, that are possible matches based on the passed + * Debugger.Environment/Debugger.Object and inputValue. + * + * @param {Object} An object of the following shape: + * - {Object} dbgObject + * When the debugger is not paused this Debugger.Object wraps + * the scope for autocompletion. + * It is null if the debugger is paused. + * - {Object} environment + * When the debugger is paused this Debugger.Environment is the + * scope for autocompletion. + * It is null if the debugger is not paused. + * - {String} inputValue + * Value that should be completed. + * - {Number} cursor (defaults to inputValue.length). + * Optional offset in the input where the cursor is located. If this is + * omitted then the cursor is assumed to be at the end of the input + * value. + * - {Array} authorizedEvaluations (defaults to []). + * Optional array containing all the different properties access that the engine + * can execute in order to retrieve its result's properties. + * ⚠️ This should be set to true *ONLY* on user action as it may cause side-effects + * in the content page ⚠️ + * - {WebconsoleActor} webconsoleActor + * A reference to a webconsole actor which we can use to retrieve the last + * evaluation result or create a debuggee value. + * - {String}: selectedNodeActor + * The actor id of the selected node in the inspector. + * - {Array}: expressionVars + * Optional array containing variable defined in the expression. Those variables + * are extracted from CodeMirror state. + * @returns null or object + * If the inputValue is an unsafe getter and invokeUnsafeGetter is false, the + * following form is returned: + * + * { + * isUnsafeGetter: true, + * getterPath: {Array} An array of the property chain leading to the + * getter. Example: ["x", "myGetter"] + * } + * + * If no completion valued could be computed, and the input is not an unsafe + * getter, null is returned. + * + * Otherwise an object with the following form is returned: + * { + * matches: Set + * matchProp: Last part of the inputValue that was used to find + * the matches-strings. + * isElementAccess: Boolean set to true if the evaluation is an element + * access (e.g. `window["addEvent`). + * } + */ +// eslint-disable-next-line complexity +function JSPropertyProvider({ + dbgObject, + environment, + frameActorId, + inputValue, + cursor, + authorizedEvaluations = [], + webconsoleActor, + selectedNodeActor, + expressionVars = [], +}) { + if (cursor === undefined) { + cursor = inputValue.length; + } + + inputValue = inputValue.substring(0, cursor); + + // Analyse the inputValue and find the beginning of the last part that + // should be completed. + const inputAnalysis = analyzeInputString(inputValue); + + if (!shouldInputBeAutocompleted(inputAnalysis)) { + return null; + } + + let { + lastStatement, + isElementAccess, + mainExpression, + matchProp, + isPropertyAccess, + } = inputAnalysis; + + // Eagerly evaluate the main expression and return the results properties. + // e.g. `obj.func().a` will evaluate `obj.func()` and return properties matching `a`. + // NOTE: this is only useful when the input has a property access. + if (webconsoleActor && shouldInputBeEagerlyEvaluated(inputAnalysis)) { + const eagerResponse = evalWithDebugger( + mainExpression, + { eager: true, selectedNodeActor, frameActor: frameActorId }, + webconsoleActor + ); + + const ret = eagerResponse?.result?.return; + + // Only send matches if eager evaluation returned something meaningful + if (ret && ret !== undefined) { + const matches = + typeof ret != "object" + ? getMatchedProps(ret, matchProp) + : getMatchedPropsInDbgObject(ret, matchProp); + + return prepareReturnedObject({ + matches, + search: matchProp, + isElementAccess, + }); + } + } + + // AST representation of the expression before the last access char (`.` or `[`). + let astExpression; + const startQuoteRegex = /^('|"|`)/; + const env = environment || dbgObject.asEnvironment(); + + // Catch literals like [1,2,3] or "foo" and return the matches from + // their prototypes. + // Don't run this is a worker, migrating to acorn should allow this + // to run in a worker - Bug 1217198. + if (!isWorker && isPropertyAccess) { + const syntaxTrees = getSyntaxTrees(mainExpression); + const lastTree = syntaxTrees[syntaxTrees.length - 1]; + const lastBody = lastTree?.body[lastTree.body.length - 1]; + + // Finding the last expression since we've sliced up until the dot. + // If there were parse errors this won't exist. + if (lastBody) { + if (!lastBody.expression) { + return null; + } + + astExpression = lastBody.expression; + let matchingObject; + + if (astExpression.type === "ArrayExpression") { + matchingObject = getContentPrototypeObject(env, "Array"); + } else if ( + astExpression.type === "Literal" && + typeof astExpression.value === "string" + ) { + matchingObject = getContentPrototypeObject(env, "String"); + } else if ( + astExpression.type === "Literal" && + Number.isFinite(astExpression.value) + ) { + // The parser rightfuly indicates that we have a number in some cases (e.g. `1.`), + // but we don't want to return Number proto properties in that case since + // the result would be invalid (i.e. `1.toFixed()` throws). + // So if the expression value is an integer, it should not end with `{Number}.` + // (but the following are fine: `1..`, `(1.).`). + if ( + !Number.isInteger(astExpression.value) || + /\d[^\.]{0}\.$/.test(lastStatement) === false + ) { + matchingObject = getContentPrototypeObject(env, "Number"); + } else { + return null; + } + } + + if (matchingObject) { + let search = matchProp; + + let elementAccessQuote; + if (isElementAccess && startQuoteRegex.test(matchProp)) { + elementAccessQuote = matchProp[0]; + search = matchProp.replace(startQuoteRegex, ""); + } + + let props = getMatchedPropsInDbgObject(matchingObject, search); + + if (isElementAccess) { + props = wrapMatchesInQuotes(props, elementAccessQuote); + } + + return { + isElementAccess, + matchProp, + matches: props, + }; + } + } + } + + // We are completing a variable / a property lookup. + let properties = []; + + if (astExpression) { + if (isPropertyAccess) { + properties = getPropertiesFromAstExpression(astExpression); + + if (properties === null) { + return null; + } + } + } else { + properties = lastStatement.split("."); + if (isElementAccess) { + const lastPart = properties[properties.length - 1]; + const openBracketIndex = lastPart.lastIndexOf("["); + matchProp = lastPart.substr(openBracketIndex + 1); + properties[properties.length - 1] = lastPart.substring( + 0, + openBracketIndex + ); + } else { + matchProp = properties.pop().trimLeft(); + } + } + + let search = matchProp; + let elementAccessQuote; + if (isElementAccess && startQuoteRegex.test(search)) { + elementAccessQuote = search[0]; + search = search.replace(startQuoteRegex, ""); + } + + let obj = dbgObject; + if (properties.length === 0) { + const environmentProperties = getMatchedPropsInEnvironment(env, search); + const expressionVariables = new Set( + expressionVars.filter(variableName => variableName.startsWith(matchProp)) + ); + + for (const prop of environmentProperties) { + expressionVariables.add(prop); + } + + return { + isElementAccess, + matchProp, + matches: expressionVariables, + }; + } + + let firstProp = properties.shift(); + if (typeof firstProp == "string") { + firstProp = firstProp.trim(); + } + + if (firstProp === "this") { + // Special case for 'this' - try to get the Object from the Environment. + // No problem if it throws, we will just not autocomplete. + try { + obj = env.object; + } catch (e) { + // Ignore. + } + } else if (firstProp === "$_" && webconsoleActor) { + obj = webconsoleActor.getLastConsoleInputEvaluation(); + } else if (firstProp === "$0" && selectedNodeActor && webconsoleActor) { + const actor = webconsoleActor.conn.getActor(selectedNodeActor); + if (actor) { + try { + obj = webconsoleActor.makeDebuggeeValue(actor.rawNode); + } catch (e) { + // Ignore. + } + } + } else if (hasArrayIndex(firstProp)) { + obj = getArrayMemberProperty(null, env, firstProp); + } else { + obj = getVariableInEnvironment(env, firstProp); + } + + if (!isObjectUsable(obj)) { + return null; + } + + // We get the rest of the properties recursively starting from the + // Debugger.Object that wraps the first property + for (let [index, prop] of properties.entries()) { + if (typeof prop === "string") { + prop = prop.trim(); + } + + if (prop === undefined || prop === null || prop === "") { + return null; + } + + const propPath = [firstProp].concat(properties.slice(0, index + 1)); + const authorized = authorizedEvaluations.some( + x => JSON.stringify(x) === JSON.stringify(propPath) + ); + + if (!authorized && DevToolsUtils.isUnsafeGetter(obj, prop)) { + // If we try to access an unsafe getter, return its name so we can consume that + // on the frontend. + return { + isUnsafeGetter: true, + getterPath: propPath, + }; + } + + if (hasArrayIndex(prop)) { + // The property to autocomplete is a member of array. For example + // list[i][j]..[n]. Traverse the array to get the actual element. + obj = getArrayMemberProperty(obj, null, prop); + } else { + obj = DevToolsUtils.getProperty(obj, prop, authorized); + } + + if (!isObjectUsable(obj)) { + return null; + } + } + + const matches = + typeof obj != "object" + ? getMatchedProps(obj, search) + : getMatchedPropsInDbgObject(obj, search); + return prepareReturnedObject({ + matches, + search, + isElementAccess, + elementAccessQuote, + }); +} + +function hasArrayIndex(str) { + return /\[\d+\]$/.test(str); +} + +/** + * For a given environment and constructor name, returns its Debugger.Object wrapped + * prototype. + * + * @param {Environment} env + * @param {String} name: Name of the constructor object we want the prototype of. + * @returns {Debugger.Object|null} the prototype, or null if it not found. + */ +function getContentPrototypeObject(env, name) { + // Retrieve the outermost environment to get the global object. + let outermostEnv = env; + while (outermostEnv?.parent) { + outermostEnv = outermostEnv.parent; + } + + const constructorObj = DevToolsUtils.getProperty(outermostEnv.object, name); + if (!constructorObj) { + return null; + } + + return DevToolsUtils.getProperty(constructorObj, "prototype"); +} + +/** + * @param {Object} ast: An AST representing a property access (e.g. `foo.bar["baz"].x`) + * @returns {Array|null} An array representing the property access + * (e.g. ["foo", "bar", "baz", "x"]). + */ +function getPropertiesFromAstExpression(ast) { + let result = []; + if (!ast) { + return result; + } + const { type, property, object, name, expression } = ast; + if (type === "ThisExpression") { + result.unshift("this"); + } else if (type === "Identifier" && name) { + result.unshift(name); + } else if (type === "OptionalExpression" && expression) { + result = (getPropertiesFromAstExpression(expression) || []).concat(result); + } else if ( + type === "MemberExpression" || + type === "OptionalMemberExpression" + ) { + if (property) { + if (property.type === "Identifier" && property.name) { + result.unshift(property.name); + } else if (property.type === "Literal") { + result.unshift(property.value); + } + } + if (object) { + result = (getPropertiesFromAstExpression(object) || []).concat(result); + } + } else { + return null; + } + return result; +} + +function wrapMatchesInQuotes(matches, quote = `"`) { + return new Set( + [...matches].map(p => { + // Escape as a double-quoted string literal + p = JSON.stringify(p); + + // We don't have to do anything more when using double quotes + if (quote == `"`) { + return p; + } + + // Remove surrounding double quotes + p = p.slice(1, -1); + + // Unescape inner double quotes (all must be escaped, so no need to count backslashes) + p = p.replace(/\\(?=")/g, ""); + + // Escape the specified quote (assuming ' or `, which are treated literally in regex) + p = p.replace(new RegExp(quote, "g"), "\\$&"); + + // Template literals treat ${ specially, escape it + if (quote == "`") { + p = p.replace(/\${/g, "\\$&"); + } + + // Surround the result with quotes + return `${quote}${p}${quote}`; + }) + ); +} + +/** + * Get the array member of obj for the given prop. For example, given + * prop='list[0][1]' the element at [0][1] of obj.list is returned. + * + * @param object obj + * The object to operate on. Should be null if env is passed. + * @param object env + * The Environment to operate in. Should be null if obj is passed. + * @param string prop + * The property to return. + * @return null or Object + * Returns null if the property couldn't be located. Otherwise the array + * member identified by prop. + */ +function getArrayMemberProperty(obj, env, prop) { + // First get the array. + const propWithoutIndices = prop.substr(0, prop.indexOf("[")); + + if (env) { + obj = getVariableInEnvironment(env, propWithoutIndices); + } else { + obj = DevToolsUtils.getProperty(obj, propWithoutIndices); + } + + if (!isObjectUsable(obj)) { + return null; + } + + // Then traverse the list of indices to get the actual element. + let result; + const arrayIndicesRegex = /\[[^\]]*\]/g; + while ((result = arrayIndicesRegex.exec(prop)) !== null) { + const indexWithBrackets = result[0]; + const indexAsText = indexWithBrackets.substr( + 1, + indexWithBrackets.length - 2 + ); + const index = parseInt(indexAsText, 10); + + if (isNaN(index)) { + return null; + } + + obj = DevToolsUtils.getProperty(obj, index); + + if (!isObjectUsable(obj)) { + return null; + } + } + + return obj; +} + +/** + * Check if the given Debugger.Object can be used for autocomplete. + * + * @param Debugger.Object object + * The Debugger.Object to check. + * @return boolean + * True if further inspection into the object is possible, or false + * otherwise. + */ +function isObjectUsable(object) { + if (object == null) { + return false; + } + + if (typeof object == "object" && object.class == "DeadObject") { + return false; + } + + return true; +} + +/** + * @see getExactMatchImpl() + */ +function getVariableInEnvironment(environment, name) { + return getExactMatchImpl(environment, name, DebuggerEnvironmentSupport); +} + +function prepareReturnedObject({ + matches, + search, + isElementAccess, + elementAccessQuote, +}) { + if (isElementAccess) { + // If it's an element access, we need to wrap properties in quotes (either the one + // the user already typed, or `"`). + + matches = wrapMatchesInQuotes(matches, elementAccessQuote); + } else if (!isWorker) { + // If we're not performing an element access, we need to check that the property + // are suited for a dot access. (reflect.sys.mjs is not available in worker context yet, + // see Bug 1507181). + for (const match of matches) { + try { + // In order to know if the property is suited for dot notation, we use Reflect + // to parse an expression where we try to access the property with a dot. If it + // throws, this means that we need to do an element access instead. + lazy.Reflect.parse(`({${match}: true})`); + } catch (e) { + matches.delete(match); + } + } + } + + return { isElementAccess, matchProp: search, matches }; +} + +/** + * @see getMatchedPropsImpl() + */ +function getMatchedPropsInEnvironment(environment, match) { + return getMatchedPropsImpl(environment, match, DebuggerEnvironmentSupport); +} + +/** + * @see getMatchedPropsImpl() + */ +function getMatchedPropsInDbgObject(dbgObject, match) { + return getMatchedPropsImpl(dbgObject, match, DebuggerObjectSupport); +} + +/** + * @see getMatchedPropsImpl() + */ +function getMatchedProps(obj, match) { + if (typeof obj != "object") { + obj = obj.constructor.prototype; + } + return getMatchedPropsImpl(obj, match, JSObjectSupport); +} + +/** + * Get all properties in the given object (and its parent prototype chain) that + * match a given prefix. + * + * @param {Mixed} obj + * Object whose properties we want to filter. + * @param {string} match + * Filter for properties that match this string. + * @returns {Set} List of matched properties. + */ +function getMatchedPropsImpl(obj, match, { chainIterator, getProperties }) { + const matches = new Set(); + let numProps = 0; + + const insensitiveMatching = match && match[0].toUpperCase() !== match[0]; + const propertyMatches = prop => { + return insensitiveMatching + ? prop.toLocaleLowerCase().startsWith(match.toLocaleLowerCase()) + : prop.startsWith(match); + }; + + // We need to go up the prototype chain. + const iter = chainIterator(obj); + for (obj of iter) { + const props = getProperties(obj); + if (!props) { + continue; + } + numProps += props.length; + + // If there are too many properties to event attempt autocompletion, + // or if we have already added the max number, then stop looping + // and return the partial set that has already been discovered. + if ( + numProps >= MAX_AUTOCOMPLETE_ATTEMPTS || + matches.size >= MAX_AUTOCOMPLETIONS + ) { + break; + } + + for (let i = 0; i < props.length; i++) { + const prop = props[i]; + if (!propertyMatches(prop)) { + continue; + } + + // If it is an array index, we can't take it. + // This uses a trick: converting a string to a number yields NaN if + // the operation failed, and NaN is not equal to itself. + // eslint-disable-next-line no-self-compare + if (+prop != +prop) { + matches.add(prop); + } + + if (matches.size >= MAX_AUTOCOMPLETIONS) { + break; + } + } + } + + return matches; +} + +/** + * Returns a property value based on its name from the given object, by + * recursively checking the object's prototype. + * + * @param object obj + * An object to look the property into. + * @param string name + * The property that is looked up. + * @returns object|undefined + * A Debugger.Object if the property exists in the object's prototype + * chain, undefined otherwise. + */ +function getExactMatchImpl(obj, name, { chainIterator, getProperty }) { + // We need to go up the prototype chain. + const iter = chainIterator(obj); + for (obj of iter) { + const prop = getProperty(obj, name, obj); + if (prop) { + return prop.value; + } + } + return undefined; +} + +var JSObjectSupport = { + *chainIterator(obj) { + while (obj) { + yield obj; + try { + obj = Object.getPrototypeOf(obj); + } catch (error) { + // The above can throw e.g. for some proxy objects. + return; + } + } + }, + + getProperties(obj) { + try { + return Object.getOwnPropertyNames(obj); + } catch (error) { + // The above can throw e.g. for some proxy objects. + return null; + } + }, + + getProperty() { + // getProperty is unsafe with raw JS objects. + throw new Error("Unimplemented!"); + }, +}; + +var DebuggerObjectSupport = { + *chainIterator(obj) { + while (obj) { + yield obj; + try { + // There could be transparent security wrappers, unwrap to check if it's a proxy. + const unwrapped = DevToolsUtils.unwrap(obj); + if (unwrapped === undefined) { + // Objects belonging to an invisible-to-debugger compartment can't be unwrapped. + return; + } + + if (unwrapped.isProxy) { + // Proxies might have a `getPrototypeOf` method, which is triggered by `obj.proto`, + // but this does not impact the actual prototype chain. + // In such case, we need to use the proxy target prototype. + // We retrieve proxyTarget from `obj` (and not `unwrapped`) to avoid exposing + // the unwrapped target. + obj = unwrapped.proxyTarget; + } + obj = obj.proto; + } catch (error) { + // The above can throw e.g. for some proxy objects. + return; + } + } + }, + + getProperties(obj) { + try { + return obj.getOwnPropertyNames(); + } catch (error) { + // The above can throw e.g. for some proxy objects. + return null; + } + }, + + getProperty(obj, name, rootObj) { + // This is left unimplemented in favor to DevToolsUtils.getProperty(). + throw new Error("Unimplemented!"); + }, +}; + +var DebuggerEnvironmentSupport = { + *chainIterator(obj) { + while (obj) { + yield obj; + obj = obj.parent; + } + }, + + getProperties(obj) { + const names = obj.names(); + + // Include 'this' in results (in sorted order) + for (let i = 0; i < names.length; i++) { + if (i === names.length - 1 || names[i + 1] > "this") { + names.splice(i + 1, 0, "this"); + break; + } + } + + return names; + }, + + getProperty(obj, name) { + let result; + // Try/catch since name can be anything, and getVariable throws if + // it's not a valid ECMAScript identifier name + try { + // TODO: we should use getVariableDescriptor() here - bug 725815. + result = obj.getVariable(name); + } catch (e) { + // Ignore. + } + + // FIXME: Need actual UI, bug 941287. + if ( + result == null || + (typeof result == "object" && + (result.optimizedOut || result.missingArguments)) + ) { + return null; + } + return { value: result }; + }, +}; + +exports.JSPropertyProvider = DevToolsUtils.makeInfallible(JSPropertyProvider); + +// Export a version that will throw (for tests) +exports.FallibleJSPropertyProvider = JSPropertyProvider; diff --git a/devtools/shared/webconsole/messages.js b/devtools/shared/webconsole/messages.js new file mode 100644 index 0000000000..a0ec73b39e --- /dev/null +++ b/devtools/shared/webconsole/messages.js @@ -0,0 +1,55 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +function getArrayTypeNames() { + return [ + "Array", + "Int8Array", + "Uint8Array", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "Uint8ClampedArray", + "BigInt64Array", + "BigUint64Array", + ]; +} + +/** + * Return true if the parameters passed to console.log is supported. + * The parameters can be either from server side (without getGrip) or client + * side (with getGrip). + * + * @param {Message} parameters + * @returns {Boolean} + */ +function isSupportedByConsoleTable(parameters) { + const supportedClasses = [ + "Object", + "Map", + "Set", + "WeakMap", + "WeakSet", + ].concat(getArrayTypeNames()); + + if (!Array.isArray(parameters) || parameters.length === 0 || !parameters[0]) { + return false; + } + + if (parameters[0].getGrip) { + return supportedClasses.includes(parameters[0].getGrip().class); + } + + return supportedClasses.includes(parameters[0].class); +} + +module.exports = { + getArrayTypeNames, + isSupportedByConsoleTable, +}; diff --git a/devtools/shared/webconsole/moz.build b/devtools/shared/webconsole/moz.build new file mode 100644 index 0000000000..447912436b --- /dev/null +++ b/devtools/shared/webconsole/moz.build @@ -0,0 +1,33 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +if CONFIG["OS_TARGET"] != "Android": + MOCHITEST_CHROME_MANIFESTS += ["test/chrome/chrome.ini"] + XPCSHELL_TESTS_MANIFESTS += ["test/xpcshell/xpcshell.ini"] + BROWSER_CHROME_MANIFESTS += ["test/browser/browser.ini"] + +# Compute where to put transpiled files into omni.ja package +# All DevTools modules are used via resource://devtools/ URI +# See devtools/shared/jar.mn for how this resource is mapped into jar package. +base = FINAL_TARGET_FILES.chrome.devtools.modules + +# Now, navigate to the right sub-directory into devtools root modules folder +for dir in RELATIVEDIR.split("/"): + base = base[dir] +base += ["!reserved-js-words.js"] + +GeneratedFile( + "reserved-js-words.js", + script="GenerateReservedWordsJS.py", + inputs=["/js/src/frontend/ReservedWords.h"], +) + +DevToolsModules( + "analyze-input-string.js", + "js-property-provider.js", + "messages.js", + "parser-helper.js", +) diff --git a/devtools/shared/webconsole/parser-helper.js b/devtools/shared/webconsole/parser-helper.js new file mode 100644 index 0000000000..69981781b5 --- /dev/null +++ b/devtools/shared/webconsole/parser-helper.js @@ -0,0 +1,66 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const DevToolsUtils = require("resource://devtools/shared/DevToolsUtils.js"); +const lazy = {}; +ChromeUtils.defineESModuleGetters(lazy, { + Reflect: "resource://gre/modules/reflect.sys.mjs", +}); + +/** + * Gets a collection of parser methods for a specified source. + * + * @param string source + * The source text content. + * @param boolean logExceptions + */ +function getSyntaxTrees(source, logExceptions) { + // The source may not necessarily be JS, in which case we need to extract + // all the scripts. Fastest/easiest way is with a regular expression. + // Don't worry, the rules of using a + + +

Web Console HTTP Logging Testpage

+

This page is used to test the HTTP logging.

+ +
+
+
+
+ + diff --git a/devtools/shared/webconsole/test/chrome/chrome.ini b/devtools/shared/webconsole/test/chrome/chrome.ini new file mode 100644 index 0000000000..ee903ac727 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/chrome.ini @@ -0,0 +1,34 @@ +[DEFAULT] +tags = devtools +support-files = + common.js + data.json + data.json^headers^ + helper_serviceworker.js + network_requests_iframe.html + sandboxed_iframe.html + console-test-worker.js + !/browser/base/content/test/general/browser_star_hsts.sjs + +[test_basics.html] +[test_cached_messages.html] +[test_consoleapi.html] +[test_consoleapi_innerID.html] +[test_console_assert.html] +[test_console_group_styling.html] +[test_console_serviceworker.html] +[test_console_serviceworker_cached.html] +[test_console_styling.html] +[test_console_timestamp.html] +[test_console_worker.html] +[test_file_uri.html] +[test_jsterm_autocomplete.html] +[test_network_get.html] +skip-if = verify +[test_network_post.html] +[test_network_security-hsts.html] +[test_nsiconsolemessage.html] +[test_object_actor.html] +[test_object_actor_native_getters.html] +[test_object_actor_native_getters_lenient_this.html] +[test_page_errors.html] diff --git a/devtools/shared/webconsole/test/chrome/common.js b/devtools/shared/webconsole/test/chrome/common.js new file mode 100644 index 0000000000..62878d7e60 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/common.js @@ -0,0 +1,274 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/* exported attachConsole, attachConsoleToTab, attachConsoleToWorker, + closeDebugger, checkConsoleAPICalls, checkRawHeaders, runTests, nextTest, Ci, Cc, + withActiveServiceWorker, Services, consoleAPICall, createCommandsForTab, FRACTIONAL_NUMBER_REGEX, DevToolsServer */ + +const { require } = ChromeUtils.importESModule( + "resource://devtools/shared/loader/Loader.sys.mjs" +); +const { + DevToolsServer, +} = require("resource://devtools/server/devtools-server.js"); +const { + CommandsFactory, +} = require("resource://devtools/shared/commands/commands-factory.js"); + +// timeStamp are the result of a number in microsecond divided by 1000. +// so we can't expect a precise number of decimals, or even if there would +// be decimals at all. +const FRACTIONAL_NUMBER_REGEX = /^\d+(\.\d{1,3})?$/; + +function attachConsole(listeners) { + return _attachConsole(listeners); +} +function attachConsoleToTab(listeners) { + return _attachConsole(listeners, true); +} +function attachConsoleToWorker(listeners) { + return _attachConsole(listeners, true, true); +} + +var _attachConsole = async function (listeners, attachToTab, attachToWorker) { + try { + function waitForMessage(target) { + return new Promise(resolve => { + target.addEventListener("message", resolve, { once: true }); + }); + } + + // Fetch the console actor out of the expected target + // ParentProcessTarget / WorkerTarget / FrameTarget + let commands, target, worker; + if (!attachToTab) { + commands = await CommandsFactory.forMainProcess(); + target = await commands.descriptorFront.getTarget(); + } else { + commands = await CommandsFactory.forCurrentTabInChromeMochitest(); + // Descriptor's getTarget will only work if the TargetCommand watches for the first top target + await commands.targetCommand.startListening(); + target = await commands.descriptorFront.getTarget(); + if (attachToWorker) { + const workerName = "console-test-worker.js#" + new Date().getTime(); + worker = new Worker(workerName); + await waitForMessage(worker); + + const { workers } = await target.listWorkers(); + target = workers.filter(w => w.url == workerName)[0]; + if (!target) { + console.error( + "listWorkers failed. Unable to find the worker actor\n" + ); + return null; + } + // This is still important to attach workers as target is still a descriptor front + // which "becomes" a target when calling this method: + await target.morphWorkerDescriptorIntoWorkerTarget(); + } + } + + // Attach the Target and the target thread in order to instantiate the console client. + await target.attachThread(); + + const webConsoleFront = await target.getFront("console"); + + // By default the console isn't listening for anything, + // request listeners from here + const response = await webConsoleFront.startListeners(listeners); + return { + state: { + dbgClient: commands.client, + webConsoleFront, + actor: webConsoleFront.actor, + // Keep a strong reference to the Worker to avoid it being + // GCd during the test (bug 1237492). + // eslint-disable-next-line camelcase + _worker_ref: worker, + }, + response, + }; + } catch (error) { + console.error( + `attachConsole failed: ${error.error} ${error.message} - ` + error.stack + ); + } + return null; +}; + +async function createCommandsForTab() { + const commands = await CommandsFactory.forMainProcess(); + await commands.targetCommand.startListening(); + return commands; +} + +function closeDebugger(state, callback) { + const onClose = state.dbgClient.close(); + + state.dbgClient = null; + state.client = null; + + if (typeof callback === "function") { + onClose.then(callback); + } + return onClose; +} + +function checkConsoleAPICalls(consoleCalls, expectedConsoleCalls) { + is( + consoleCalls.length, + expectedConsoleCalls.length, + "received correct number of console calls" + ); + expectedConsoleCalls.forEach(function (message, index) { + info("checking received console call #" + index); + checkConsoleAPICall(consoleCalls[index], expectedConsoleCalls[index]); + }); +} + +function checkConsoleAPICall(call, expected) { + is( + call.arguments?.length || 0, + expected.arguments?.length || 0, + "number of arguments" + ); + + checkObject(call, expected); +} + +function checkObject(object, expected) { + if (object && object.getGrip) { + object = object.getGrip(); + } + + for (const name of Object.keys(expected)) { + const expectedValue = expected[name]; + const value = object[name]; + checkValue(name, value, expectedValue); + } +} + +function checkValue(name, value, expected) { + if (expected === null) { + ok(!value, "'" + name + "' is null"); + } else if (value === undefined) { + ok(false, "'" + name + "' is undefined"); + } else if (value === null) { + ok(false, "'" + name + "' is null"); + } else if ( + typeof expected == "string" || + typeof expected == "number" || + typeof expected == "boolean" + ) { + is(value, expected, "property '" + name + "'"); + } else if (expected instanceof RegExp) { + ok(expected.test(value), name + ": " + expected + " matched " + value); + } else if (Array.isArray(expected)) { + info("checking array for property '" + name + "'"); + checkObject(value, expected); + } else if (typeof expected == "object") { + info("checking object for property '" + name + "'"); + checkObject(value, expected); + } +} + +function checkHeadersOrCookies(array, expected) { + const foundHeaders = {}; + + for (const elem of array) { + if (!(elem.name in expected)) { + continue; + } + foundHeaders[elem.name] = true; + info("checking value of header " + elem.name); + checkValue(elem.name, elem.value, expected[elem.name]); + } + + for (const header in expected) { + if (!(header in foundHeaders)) { + ok(false, header + " was not found"); + } + } +} + +function checkRawHeaders(text, expected) { + const headers = text.split(/\r\n|\n|\r/); + const arr = []; + for (const header of headers) { + const index = header.indexOf(": "); + if (index < 0) { + continue; + } + arr.push({ + name: header.substr(0, index), + value: header.substr(index + 2), + }); + } + + checkHeadersOrCookies(arr, expected); +} + +var gTestState = {}; + +function runTests(tests, endCallback) { + function* driver() { + let lastResult, sendToNext; + for (let i = 0; i < tests.length; i++) { + gTestState.index = i; + const fn = tests[i]; + info("will run test #" + i + ": " + fn.name); + lastResult = fn(sendToNext, lastResult); + sendToNext = yield lastResult; + } + yield endCallback(sendToNext, lastResult); + } + gTestState.driver = driver(); + return gTestState.driver.next(); +} + +function nextTest(message) { + return gTestState.driver.next(message); +} + +function withActiveServiceWorker(win, url, scope) { + const opts = {}; + if (scope) { + opts.scope = scope; + } + return win.navigator.serviceWorker.register(url, opts).then(swr => { + if (swr.active) { + return swr; + } + + // Unfortunately we can't just use navigator.serviceWorker.ready promise + // here. If the service worker is for a scope that does not cover the window + // then the ready promise will never resolve. Instead monitor the service + // workers state change events to determine when its activated. + return new Promise(resolve => { + const sw = swr.waiting || swr.installing; + sw.addEventListener("statechange", function stateHandler(evt) { + if (sw.state === "activated") { + sw.removeEventListener("statechange", stateHandler); + resolve(swr); + } + }); + }); + }); +} + +/** + * + * @param {Front} consoleFront + * @param {Function} consoleCall: A function which calls the consoleAPI, e.g. : + * `() => top.console.log("test")`. + * @returns {Promise} A promise that will be resolved with the packet sent by the server + * in response to the consoleAPI call. + */ +function consoleAPICall(consoleFront, consoleCall) { + const onConsoleAPICall = consoleFront.once("consoleAPICall"); + consoleCall(); + return onConsoleAPICall; +} diff --git a/devtools/shared/webconsole/test/chrome/console-test-worker.js b/devtools/shared/webconsole/test/chrome/console-test-worker.js new file mode 100644 index 0000000000..9e92f6af65 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/console-test-worker.js @@ -0,0 +1,21 @@ +"use strict"; + +console.log("Log from worker init"); + +function f() { + const a = 1; + const b = 2; + const c = 3; + return { a, b, c }; +} + +self.onmessage = function (event) { + if (event.data == "ping") { + f(); + postMessage("pong"); + } else if (event.data?.type == "log") { + console.log(event.data.message); + } +}; + +postMessage("load"); diff --git a/devtools/shared/webconsole/test/chrome/data.json b/devtools/shared/webconsole/test/chrome/data.json new file mode 100644 index 0000000000..eca9d0e796 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/data.json @@ -0,0 +1,5 @@ +{ + "id": "test JSON data", + "myArray": ["foo", "bar", "baz", "biff"], + "veryLong": "foo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo barfoo bar" +} diff --git a/devtools/shared/webconsole/test/chrome/data.json^headers^ b/devtools/shared/webconsole/test/chrome/data.json^headers^ new file mode 100644 index 0000000000..bb6b45500f --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/data.json^headers^ @@ -0,0 +1,3 @@ +Content-Type: application/json +x-very-long: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse a ipsum massa. Phasellus at elit dictum libero laoreet sagittis. Phasellus condimentum ultricies imperdiet. Nam eu ligula justo, ut tincidunt quam. Etiam sollicitudin, tortor sed egestas blandit, sapien sem tincidunt nulla, eu luctus libero odio quis leo. Nam elit massa, mattis quis blandit ac, facilisis vitae arcu. Donec vitae dictum neque. Proin ornare nisl at lectus commodo iaculis eget eget est. Quisque scelerisque vestibulum quam sed interdum. +x-very-short: hello world diff --git a/devtools/shared/webconsole/test/chrome/helper_serviceworker.js b/devtools/shared/webconsole/test/chrome/helper_serviceworker.js new file mode 100644 index 0000000000..74092183e2 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/helper_serviceworker.js @@ -0,0 +1,21 @@ +"use strict"; + +console.log("script evaluation"); + +addEventListener("install", function (evt) { + console.log("install event"); +}); + +addEventListener("activate", function (evt) { + console.log("activate event"); +}); + +addEventListener("fetch", function (evt) { + console.log("fetch event: " + evt.request.url); + evt.respondWith(new Response("Hello world")); +}); + +addEventListener("message", function (evt) { + console.log("message event: " + evt.data.message); + evt.source.postMessage({ type: "PONG" }); +}); diff --git a/devtools/shared/webconsole/test/chrome/network_requests_iframe.html b/devtools/shared/webconsole/test/chrome/network_requests_iframe.html new file mode 100644 index 0000000000..6bb806b904 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/network_requests_iframe.html @@ -0,0 +1,66 @@ + + + + + Console HTTP test page + + + + +

Web Console HTTP Logging Testpage

+

This page is used to test the HTTP logging.

+ +
+
+
+
+ + diff --git a/devtools/shared/webconsole/test/chrome/sandboxed_iframe.html b/devtools/shared/webconsole/test/chrome/sandboxed_iframe.html new file mode 100644 index 0000000000..55a6224b50 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/sandboxed_iframe.html @@ -0,0 +1,8 @@ + +Sandboxed iframe + + + + diff --git a/devtools/shared/webconsole/test/chrome/test_basics.html b/devtools/shared/webconsole/test/chrome/test_basics.html new file mode 100644 index 0000000000..761a97bc8d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_basics.html @@ -0,0 +1,61 @@ + + + + + Basic Web Console Actor tests + + + + + +

Basic Web Console Actor tests

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_cached_messages.html b/devtools/shared/webconsole/test/chrome/test_cached_messages.html new file mode 100644 index 0000000000..12d5069c7d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_cached_messages.html @@ -0,0 +1,217 @@ + + + + + Test for cached messages + + + + + +

Test for cached messages

+ + + + + + diff --git a/devtools/shared/webconsole/test/chrome/test_console_assert.html b/devtools/shared/webconsole/test/chrome/test_console_assert.html new file mode 100644 index 0000000000..f847d5f5d8 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_assert.html @@ -0,0 +1,106 @@ + + + + + Test for console.group styling with %c + + + + + + +

+ +
+  
+ + diff --git a/devtools/shared/webconsole/test/chrome/test_console_group_styling.html b/devtools/shared/webconsole/test/chrome/test_console_group_styling.html new file mode 100644 index 0000000000..23a93f8b8d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_group_styling.html @@ -0,0 +1,121 @@ + + + + + Test for console.group styling with %c + + + + + + +

+ +
+  
+ + diff --git a/devtools/shared/webconsole/test/chrome/test_console_serviceworker.html b/devtools/shared/webconsole/test/chrome/test_console_serviceworker.html new file mode 100644 index 0000000000..33b6ba1457 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_serviceworker.html @@ -0,0 +1,202 @@ + + + + + Test for the Console API and Service Workers + + + + + +

Test for the Console API and Service Workers

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html b/devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html new file mode 100644 index 0000000000..9f94f82f93 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_serviceworker_cached.html @@ -0,0 +1,119 @@ + + + + + Test for getCachedMessages and Service Workers + + + + + +

Test for getCachedMessages and Service Workers

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_console_styling.html b/devtools/shared/webconsole/test/chrome/test_console_styling.html new file mode 100644 index 0000000000..841e19076f --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_styling.html @@ -0,0 +1,134 @@ + + + + + Test for console.log styling with %c + + + + + +

Test for console.log styling with %c

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_console_timestamp.html b/devtools/shared/webconsole/test/chrome/test_console_timestamp.html new file mode 100644 index 0000000000..a64de0d7b2 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_timestamp.html @@ -0,0 +1,48 @@ + + + + + Test for console.group styling with %c + + + + + + +

+ +
+  
+ + diff --git a/devtools/shared/webconsole/test/chrome/test_console_worker.html b/devtools/shared/webconsole/test/chrome/test_console_worker.html new file mode 100644 index 0000000000..330c083f6b --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_console_worker.html @@ -0,0 +1,73 @@ + + + + + Test for the Console API and Workers + + + + + +

Test for the Console API and Workers

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_consoleapi.html b/devtools/shared/webconsole/test/chrome/test_consoleapi.html new file mode 100644 index 0000000000..b5d8edf23e --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_consoleapi.html @@ -0,0 +1,225 @@ + + + + + Test for the Console API + + + + + +

Test for the Console API

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html b/devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html new file mode 100644 index 0000000000..98fc783a84 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_consoleapi_innerID.html @@ -0,0 +1,157 @@ + + + + + Test for the innerID property of the Console API + + + + + +

Test for the Console API

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_file_uri.html b/devtools/shared/webconsole/test/chrome/test_file_uri.html new file mode 100644 index 0000000000..76c3b8193e --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_file_uri.html @@ -0,0 +1,110 @@ + + + + + Test for file activity tracking + + + + + +

Test for file activity tracking

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html b/devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html new file mode 100644 index 0000000000..bbc9aeb6fc --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_jsterm_autocomplete.html @@ -0,0 +1,635 @@ + + + + + Test for JavaScript terminal functionality + + + + + +

Test for JavaScript terminal autocomplete functionality

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_network_get.html b/devtools/shared/webconsole/test/chrome/test_network_get.html new file mode 100644 index 0000000000..71bb6c388c --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_network_get.html @@ -0,0 +1,132 @@ + + + + + Test for the network actor (GET request) + + + + + +

Test for the network actor (GET request)

+ + + + + + diff --git a/devtools/shared/webconsole/test/chrome/test_network_post.html b/devtools/shared/webconsole/test/chrome/test_network_post.html new file mode 100644 index 0000000000..237494c323 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_network_post.html @@ -0,0 +1,143 @@ + + + + + Test for the network actor (POST request) + + + + + +

Test for the network actor (POST request)

+ + + + + + diff --git a/devtools/shared/webconsole/test/chrome/test_network_security-hsts.html b/devtools/shared/webconsole/test/chrome/test_network_security-hsts.html new file mode 100644 index 0000000000..6139aa4e05 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_network_security-hsts.html @@ -0,0 +1,89 @@ + + + + + Test for the network actor (HSTS detection) + + + + + +

Test for the network actor (HSTS detection)

+ + + + + + diff --git a/devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html b/devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html new file mode 100644 index 0000000000..4e460225df --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_nsiconsolemessage.html @@ -0,0 +1,74 @@ + + + + + Test for nsIConsoleMessages + + + + + +

Make sure that nsIConsoleMessages are logged. See bug 859756.

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_object_actor.html b/devtools/shared/webconsole/test/chrome/test_object_actor.html new file mode 100644 index 0000000000..f42035e2ce --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_object_actor.html @@ -0,0 +1,158 @@ + + + + + Test for the object actor + + + + + +

Test for the object actor

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html new file mode 100644 index 0000000000..6ac292fb9a --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters.html @@ -0,0 +1,75 @@ + + + + + Test for the native getters in object actors + + + + + +

Test for the native getters in object actors

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html new file mode 100644 index 0000000000..473dfb3b03 --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_object_actor_native_getters_lenient_this.html @@ -0,0 +1,54 @@ + + + + + Test that WebIDL attributes with the LenientThis extended attribute + do not appear in the wrong objects + + + + + +

Test for the native getters in object actors

+ + + + diff --git a/devtools/shared/webconsole/test/chrome/test_page_errors.html b/devtools/shared/webconsole/test/chrome/test_page_errors.html new file mode 100644 index 0000000000..0976eed92d --- /dev/null +++ b/devtools/shared/webconsole/test/chrome/test_page_errors.html @@ -0,0 +1,224 @@ + + + + + Test for page errors + + + + + +

Test for page errors

+ + + + diff --git a/devtools/shared/webconsole/test/xpcshell/.eslintrc.js b/devtools/shared/webconsole/test/xpcshell/.eslintrc.js new file mode 100644 index 0000000000..8611c174f5 --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the common devtools xpcshell eslintrc config. + extends: "../../../../.eslintrc.xpcshell.js", +}; diff --git a/devtools/shared/webconsole/test/xpcshell/head.js b/devtools/shared/webconsole/test/xpcshell/head.js new file mode 100644 index 0000000000..e65552771e --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/head.js @@ -0,0 +1,10 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +/* exported require */ + +"use strict"; + +var { require } = ChromeUtils.importESModule( + "resource://devtools/shared/loader/Loader.sys.mjs" +); diff --git a/devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js b/devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js new file mode 100644 index 0000000000..3df015056f --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/test_analyze_input_string.js @@ -0,0 +1,225 @@ +// Any copyright is dedicated to the Public Domain. +// http://creativecommons.org/publicdomain/zero/1.0/ + +"use strict"; +const { + analyzeInputString, +} = require("resource://devtools/shared/webconsole/analyze-input-string.js"); + +add_task(() => { + const tests = [ + { + desc: "simple property access", + input: `var a = {b: 1};a.b`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `var a = {b: 1};a`, + lastStatement: "a.b", + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "deep property access", + input: `a.b.c`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a.b`, + lastStatement: "a.b.c", + mainExpression: `a.b`, + matchProp: `c`, + }, + }, + { + desc: "element access", + input: `a["b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a["b`, + mainExpression: `a`, + matchProp: `"b`, + }, + }, + { + desc: "element access without quotes", + input: `a[b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a[b`, + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "simple optional chaining access", + input: `a?.b`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a?.b`, + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "deep optional chaining access", + input: `a?.b?.c`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a?.b`, + lastStatement: `a?.b?.c`, + mainExpression: `a?.b`, + matchProp: `c`, + }, + }, + { + desc: "optional chaining element access", + input: `a?.["b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a?.["b`, + mainExpression: `a`, + matchProp: `"b`, + }, + }, + { + desc: "optional chaining element access without quotes", + input: `a?.[b`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `a`, + lastStatement: `a?.[b`, + mainExpression: `a`, + matchProp: `b`, + }, + }, + { + desc: "deep optional chaining element access with quotes", + input: `var a = {b: 1, c: ["."]}; a?.["b"]?.c?.["d[.`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `var a = {b: 1, c: ["."]}; a?.["b"]?.c`, + lastStatement: `a?.["b"]?.c?.["d[.`, + mainExpression: `a?.["b"]?.c`, + matchProp: `"d[.`, + }, + }, + { + desc: "literal arrays with newline", + input: `[1,2,3,\n4\n].`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `[1,2,3,\n4\n]`, + lastStatement: `[1,2,3,4].`, + mainExpression: `[1,2,3,4]`, + matchProp: ``, + }, + }, + { + desc: "number literal with newline", + input: `1\n.`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `1\n`, + lastStatement: `1\n.`, + mainExpression: `1`, + matchProp: ``, + }, + }, + { + desc: "string literal", + input: `"abc".`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `"abc"`, + lastStatement: `"abc".`, + mainExpression: `"abc"`, + matchProp: ``, + }, + }, + { + desc: "string literal containing backslash", + input: `"\\n".`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `"\\n"`, + lastStatement: `"\\n".`, + mainExpression: `"\\n"`, + matchProp: ``, + }, + }, + { + desc: "single quote string literal containing backslash", + input: `'\\r'.`, + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: `'\\r'`, + lastStatement: `'\\r'.`, + mainExpression: `'\\r'`, + matchProp: ``, + }, + }, + { + desc: "template string literal containing backslash", + input: "`\\\\`.", + expected: { + isElementAccess: false, + isPropertyAccess: true, + expressionBeforePropertyAccess: "`\\\\`", + lastStatement: "`\\\\`.", + mainExpression: "`\\\\`", + matchProp: ``, + }, + }, + { + desc: "unterminated double quote string literal", + input: `"\n`, + expected: { + err: "unterminated string literal", + }, + }, + { + desc: "unterminated single quote string literal", + input: `'\n`, + expected: { + err: "unterminated string literal", + }, + }, + { + desc: "optional chaining operator with spaces", + input: `test ?. ["propA"] ?. [0] ?. ["propB"] ?. ['to`, + expected: { + isElementAccess: true, + isPropertyAccess: true, + expressionBeforePropertyAccess: `test ?. ["propA"] ?. [0] ?. ["propB"] `, + lastStatement: `test ?. ["propA"] ?. [0] ?. ["propB"] ?. ['to`, + mainExpression: `test ?. ["propA"] ?. [0] ?. ["propB"]`, + matchProp: `'to`, + }, + }, + ]; + + for (const { input, desc, expected } of tests) { + const result = analyzeInputString(input); + for (const [key, value] of Object.entries(expected)) { + Assert.equal(value, result[key], `${desc} | ${key} has expected value`); + } + } +}); diff --git a/devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js b/devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js new file mode 100644 index 0000000000..a6f2daee4b --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/test_js_property_provider.js @@ -0,0 +1,746 @@ +// Any copyright is dedicated to the Public Domain. +// http://creativecommons.org/publicdomain/zero/1.0/ + +"use strict"; +const { + FallibleJSPropertyProvider: JSPropertyProvider, +} = require("resource://devtools/shared/webconsole/js-property-provider.js"); + +const { addDebuggerToGlobal } = ChromeUtils.importESModule( + "resource://gre/modules/jsdebugger.sys.mjs" +); +addDebuggerToGlobal(globalThis); + +function run_test() { + Services.prefs.setBoolPref( + "security.allow_parent_unrestricted_js_loads", + true + ); + registerCleanupFunction(() => { + Services.prefs.clearUserPref("security.allow_parent_unrestricted_js_loads"); + }); + + const testArray = `var testArray = [ + {propA: "A"}, + { + propB: "B", + propC: [ + "D" + ] + }, + [ + {propE: "E"} + ] + ]`; + + const testObject = 'var testObject = {"propA": [{"propB": "B"}]}'; + const testHyphenated = 'var testHyphenated = {"prop-A": "res-A"}'; + const testLet = "let foobar = {a: ''}; const blargh = {a: 1};"; + + const testGenerators = ` + // Test with generator using a named function. + function* genFunc() { + for (let i = 0; i < 10; i++) { + yield i; + } + } + let gen1 = genFunc(); + gen1.next(); + + // Test with generator using an anonymous function. + let gen2 = (function* () { + for (let i = 0; i < 10; i++) { + yield i; + } + })();`; + + const testGetters = ` + var testGetters = { + get x() { + return Object.create(null, Object.getOwnPropertyDescriptors({ + hello: "", + world: "", + })); + }, + get y() { + return Object.create(null, Object.getOwnPropertyDescriptors({ + get y() { + return "plop"; + }, + })); + } + }; + `; + + const testProxies = ` + var testSelfPrototypeProxy = new Proxy({ + hello: 1 + }, { + getPrototypeOf: () => testProxy + }); + var testArrayPrototypeProxy = new Proxy({ + world: 2 + }, { + getPrototypeOf: () => Array.prototype + }) + `; + + const sandbox = Cu.Sandbox("http://example.com"); + const dbg = new Debugger(); + const dbgObject = dbg.addDebuggee(sandbox); + const dbgEnv = dbgObject.asEnvironment(); + Cu.evalInSandbox( + ` + const hello = Object.create(null, Object.getOwnPropertyDescriptors({world: 1})); + String.prototype.hello = hello; + Number.prototype.hello = hello; + Array.prototype.hello = hello; + `, + sandbox + ); + Cu.evalInSandbox(testArray, sandbox); + Cu.evalInSandbox(testObject, sandbox); + Cu.evalInSandbox(testHyphenated, sandbox); + Cu.evalInSandbox(testLet, sandbox); + Cu.evalInSandbox(testGenerators, sandbox); + Cu.evalInSandbox(testGetters, sandbox); + Cu.evalInSandbox(testProxies, sandbox); + + info("Running tests with dbgObject"); + runChecks(dbgObject, null, sandbox); + + info("Running tests with dbgEnv"); + runChecks(null, dbgEnv, sandbox); +} + +function runChecks(dbgObject, environment, sandbox) { + const propertyProvider = (inputValue, options) => + JSPropertyProvider({ + dbgObject, + environment, + inputValue, + ...options, + }); + + info("Test that suggestions are given for 'this'"); + let results = propertyProvider("t"); + test_has_result(results, "this"); + + if (dbgObject != null) { + info("Test that suggestions are given for 'this.'"); + results = propertyProvider("this."); + test_has_result(results, "testObject"); + + info("Test that suggestions are given for '(this).'"); + results = propertyProvider("(this)."); + test_has_result(results, "testObject"); + + info("Test that suggestions are given for deep 'this' properties access"); + results = propertyProvider("(this).testObject.propA."); + test_has_result(results, "shift"); + + results = propertyProvider("(this).testObject.propA["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(this)['testObject']['propA']["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(this).testObject['propA']."); + test_has_result(results, "shift"); + + info("Test that no suggestions are given for 'this.this'"); + results = propertyProvider("this.this"); + test_has_no_results(results); + } + + info("Test that suggestions are given for 'globalThis'"); + results = propertyProvider("g"); + test_has_result(results, "globalThis"); + + info("Test that suggestions are given for 'globalThis.'"); + results = propertyProvider("globalThis."); + test_has_result(results, "testObject"); + + info("Test that suggestions are given for '(globalThis).'"); + results = propertyProvider("(globalThis)."); + test_has_result(results, "testObject"); + + info( + "Test that suggestions are given for deep 'globalThis' properties access" + ); + results = propertyProvider("(globalThis).testObject.propA."); + test_has_result(results, "shift"); + + results = propertyProvider("(globalThis).testObject.propA["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(globalThis)['testObject']['propA']["); + test_has_result(results, `"shift"`); + + results = propertyProvider("(globalThis).testObject['propA']."); + test_has_result(results, "shift"); + + info("Testing lexical scope issues (Bug 1207868)"); + results = propertyProvider("foobar"); + test_has_result(results, "foobar"); + + results = propertyProvider("foobar."); + test_has_result(results, "a"); + + results = propertyProvider("blargh"); + test_has_result(results, "blargh"); + + results = propertyProvider("blargh."); + test_has_result(results, "a"); + + info("Test that suggestions are given for 'foo[n]' where n is an integer."); + results = propertyProvider("testArray[0]."); + test_has_result(results, "propA"); + + info("Test that suggestions are given for multidimensional arrays."); + results = propertyProvider("testArray[2][0]."); + test_has_result(results, "propE"); + + info("Test that suggestions are given for nested arrays."); + results = propertyProvider("testArray[1].propC[0]."); + test_has_result(results, "indexOf"); + + info("Test that suggestions are given for literal arrays."); + results = propertyProvider("[1,2,3]."); + test_has_result(results, "indexOf"); + + results = propertyProvider("[1,2,3].h"); + test_has_result(results, "hello"); + + results = propertyProvider("[1,2,3].hello.w"); + test_has_result(results, "world"); + + info("Test that suggestions are given for literal arrays with newlines."); + results = propertyProvider("[1,2,3,\n4\n]."); + test_has_result(results, "indexOf"); + + info("Test that suggestions are given for literal strings."); + results = propertyProvider("'foo'."); + test_has_result(results, "charAt"); + results = propertyProvider('"foo".'); + test_has_result(results, "charAt"); + results = propertyProvider("`foo`."); + test_has_result(results, "charAt"); + results = propertyProvider("`foo doc`."); + test_has_result(results, "charAt"); + results = propertyProvider('`foo " doc`.'); + test_has_result(results, "charAt"); + results = propertyProvider("`foo ' doc`."); + test_has_result(results, "charAt"); + results = propertyProvider("'[1,2,3]'."); + test_has_result(results, "charAt"); + results = propertyProvider("'foo'.h"); + test_has_result(results, "hello"); + results = propertyProvider("'foo'.hello.w"); + test_has_result(results, "world"); + results = propertyProvider(`"\\n".`); + test_has_result(results, "charAt"); + results = propertyProvider(`'\\r'.`); + test_has_result(results, "charAt"); + results = propertyProvider("`\\\\`."); + test_has_result(results, "charAt"); + + info("Test that suggestions are not given for syntax errors."); + results = propertyProvider("'foo\""); + Assert.equal(null, results); + results = propertyProvider("'foo d"); + Assert.equal(null, results); + results = propertyProvider(`"foo d`); + Assert.equal(null, results); + results = propertyProvider("`foo d"); + Assert.equal(null, results); + results = propertyProvider("[1,',2]"); + Assert.equal(null, results); + results = propertyProvider("'[1,2]."); + Assert.equal(null, results); + results = propertyProvider("'foo'.."); + Assert.equal(null, results); + + info("Test that suggestions are not given without a dot."); + results = propertyProvider("'foo'"); + test_has_no_results(results); + results = propertyProvider("`foo`"); + test_has_no_results(results); + results = propertyProvider("[1,2,3]"); + test_has_no_results(results); + results = propertyProvider("[1,2,3].\n'foo'"); + test_has_no_results(results); + + info("Test that suggestions are not given for index that's out of bounds."); + results = propertyProvider("testArray[10]."); + Assert.equal(null, results); + + info("Test that invalid element access syntax does not return anything"); + results = propertyProvider("testArray[][1]."); + Assert.equal(null, results); + + info("Test that deep element access works."); + results = propertyProvider("testObject['propA'][0]."); + test_has_result(results, "propB"); + + results = propertyProvider("testArray[1]['propC']."); + test_has_result(results, "shift"); + + results = propertyProvider("testArray[1].propC[0]["); + test_has_result(results, `"trim"`); + + results = propertyProvider("testArray[1].propC[0]."); + test_has_result(results, "trim"); + + info( + "Test that suggestions are displayed when variable is wrapped in parens" + ); + results = propertyProvider("(testObject)['propA'][0]."); + test_has_result(results, "propB"); + + results = propertyProvider("(testArray)[1]['propC']."); + test_has_result(results, "shift"); + + results = propertyProvider("(testArray)[1].propC[0]["); + test_has_result(results, `"trim"`); + + results = propertyProvider("(testArray)[1].propC[0]."); + test_has_result(results, "trim"); + + info("Test that suggestions are given if there is an hyphen in the chain."); + results = propertyProvider("testHyphenated['prop-A']."); + test_has_result(results, "trim"); + + info("Test that we have suggestions for generators."); + const gen1Result = Cu.evalInSandbox("gen1.next().value", sandbox); + results = propertyProvider("gen1."); + test_has_result(results, "next"); + info("Test that the generator next() was not executed"); + const gen1NextResult = Cu.evalInSandbox("gen1.next().value", sandbox); + Assert.equal(gen1Result + 1, gen1NextResult); + + info("Test with an anonymous generator."); + const gen2Result = Cu.evalInSandbox("gen2.next().value", sandbox); + results = propertyProvider("gen2."); + test_has_result(results, "next"); + const gen2NextResult = Cu.evalInSandbox("gen2.next().value", sandbox); + Assert.equal(gen2Result + 1, gen2NextResult); + + info( + "Test that getters are not executed if authorizedEvaluations is undefined" + ); + results = propertyProvider("testGetters.x."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x["); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.hell"); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x['hell"); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + info( + "Test that getters are not executed if authorizedEvaluations does not match" + ); + results = propertyProvider("testGetters.x.", { authorizedEvaluations: [] }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGetters"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGtrs", "x"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["x"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "x"], + }); + + info("Test that deep getter property access returns intermediate getters"); + results = propertyProvider("testGetters.y.y."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + results = propertyProvider("testGetters['y'].y."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + results = propertyProvider("testGetters['y']['y']."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + results = propertyProvider("testGetters.y['y']."); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + info("Test that deep getter property access invoke intermediate getters"); + results = propertyProvider("testGetters.y.y.", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + results = propertyProvider("testGetters['y'].y.", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + results = propertyProvider("testGetters['y']['y'].", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + results = propertyProvider("testGetters.y['y'].", { + authorizedEvaluations: [["testGetters", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y", "y"], + }); + + info( + "Test that getters are executed if matching an authorizedEvaluation element" + ); + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGetters", "x"]], + }); + test_has_exact_results(results, ["hello", "world"]); + Assert.ok(Object.keys(results).includes("isUnsafeGetter") === false); + Assert.ok(Object.keys(results).includes("getterPath") === false); + + results = propertyProvider("testGetters.x.", { + authorizedEvaluations: [["testGetters", "x"], ["y"]], + }); + test_has_exact_results(results, ["hello", "world"]); + Assert.ok(Object.keys(results).includes("isUnsafeGetter") === false); + Assert.ok(Object.keys(results).includes("getterPath") === false); + + info("Test that executing getters filters with provided string"); + results = propertyProvider("testGetters.x.hell", { + authorizedEvaluations: [["testGetters", "x"]], + }); + test_has_exact_results(results, ["hello"]); + + results = propertyProvider("testGetters.x['hell", { + authorizedEvaluations: [["testGetters", "x"]], + }); + test_has_exact_results(results, ["'hello'"]); + + info( + "Test children getters are not executed if not included in authorizedEvaluation" + ); + results = propertyProvider("testGetters.y.y.", { + authorizedEvaluations: [["testGetters", "y", "y"]], + }); + Assert.deepEqual(results, { + isUnsafeGetter: true, + getterPath: ["testGetters", "y"], + }); + + info( + "Test children getters are executed if matching an authorizedEvaluation element" + ); + results = propertyProvider("testGetters.y.y.", { + authorizedEvaluations: [ + ["testGetters", "y"], + ["testGetters", "y", "y"], + ], + }); + test_has_result(results, "trim"); + + info("Test with number literals"); + results = propertyProvider("1."); + Assert.ok(results === null, "Does not complete on possible floating number"); + + results = propertyProvider("(1).."); + Assert.ok(results === null, "Does not complete on invalid syntax"); + + results = propertyProvider("(1.1.)."); + Assert.ok(results === null, "Does not complete on invalid syntax"); + + results = propertyProvider("1.."); + test_has_result(results, "toFixed"); + + results = propertyProvider("1 ."); + test_has_result(results, "toFixed"); + + results = propertyProvider("1\n."); + test_has_result(results, "toFixed"); + + results = propertyProvider(".1."); + test_has_result(results, "toFixed"); + + results = propertyProvider("1["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("1[toFixed"); + test_has_exact_results(results, [`"toFixed"`]); + + results = propertyProvider("1['toFixed"); + test_has_exact_results(results, ["'toFixed'"]); + + results = propertyProvider("1.1["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("(1)."); + test_has_result(results, "toFixed"); + + results = propertyProvider("(.1)."); + test_has_result(results, "toFixed"); + + results = propertyProvider("(1.1)."); + test_has_result(results, "toFixed"); + + results = propertyProvider("(1).toFixed"); + test_has_exact_results(results, ["toFixed"]); + + results = propertyProvider("(1)["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("(1.1)["); + test_has_result(results, `"toFixed"`); + + results = propertyProvider("(1)[toFixed"); + test_has_exact_results(results, [`"toFixed"`]); + + results = propertyProvider("(1)['toFixed"); + test_has_exact_results(results, ["'toFixed'"]); + + results = propertyProvider("(1).h"); + test_has_result(results, "hello"); + + results = propertyProvider("(1).hello.w"); + test_has_result(results, "world"); + + info("Test access on dot-notation invalid property name"); + results = propertyProvider("testHyphenated.prop"); + Assert.ok( + !results.matches.has("prop-A"), + "Does not return invalid property name on dot access" + ); + + results = propertyProvider("testHyphenated['prop"); + test_has_result(results, `'prop-A'`); + + results = propertyProvider(`//t`); + Assert.ok(results === null, "Does not complete in inline comment"); + + results = propertyProvider(`// t`); + Assert.ok( + results === null, + "Does not complete in inline comment after space" + ); + + results = propertyProvider(`//I'm a comment\nt`); + test_has_result(results, "testObject"); + + results = propertyProvider(`1/t`); + test_has_result(results, "testObject"); + + results = propertyProvider(`/* t`); + Assert.ok(results === null, "Does not complete in multiline comment"); + + results = propertyProvider(`/*I'm\nt`); + Assert.ok( + results === null, + "Does not complete in multiline comment after line break" + ); + + results = propertyProvider(`/*I'm a comment\n \t * /t`); + Assert.ok( + results === null, + "Does not complete in multiline comment after line break and invalid comment end" + ); + + results = propertyProvider(`/*I'm a comment\n \t */t`); + test_has_result(results, "testObject"); + + results = propertyProvider(`/*I'm a comment\n \t */\n\nt`); + test_has_result(results, "testObject"); + + info("Test local expression variables"); + results = propertyProvider("b", { expressionVars: ["a", "b", "c"] }); + test_has_result(results, "b"); + Assert.equal(results.matches.has("a"), false); + Assert.equal(results.matches.has("c"), false); + + info( + "Test that local expression variables are not included when accessing an object properties" + ); + results = propertyProvider("testObject.prop", { + expressionVars: ["propLocal"], + }); + Assert.equal(results.matches.has("propLocal"), false); + test_has_result(results, "propA"); + + results = propertyProvider("testObject['prop", { + expressionVars: ["propLocal"], + }); + test_has_result(results, "'propA'"); + Assert.equal(results.matches.has("propLocal"), false); + + info("Test that expression with optional chaining operator are completed"); + results = propertyProvider("testObject?.prop"); + test_has_result(results, "propA"); + + results = propertyProvider("testObject?.propA[0]?.propB?.to"); + test_has_result(results, "toString"); + + results = propertyProvider("testObject?.propA?.[0]?.propB?.to"); + test_has_result(results, "toString"); + + results = propertyProvider( + "testObject ?. propA[0] ?. propB ?. to" + ); + test_has_result(results, "toString"); + + results = propertyProvider("testObject?.[prop"); + test_has_result(results, '"propA"'); + + results = propertyProvider(`testObject?.["prop`); + test_has_result(results, '"propA"'); + + results = propertyProvider(`testObject?.['prop`); + test_has_result(results, `'propA'`); + + results = propertyProvider(`testObject?.["propA"]?.[0]?.["propB"]?.["to`); + test_has_result(results, `"toString"`); + + results = propertyProvider( + `testObject ?. ["propA"] ?. [0] ?. ["propB"] ?. ['to` + ); + test_has_result(results, "'toString'"); + + results = propertyProvider("[1,2,3]?."); + test_has_result(results, "indexOf"); + + results = propertyProvider("'foo'?."); + test_has_result(results, "charAt"); + + results = propertyProvider("1?."); + test_has_result(results, "toFixed"); + + // check this doesn't throw since `propC` is not defined. + results = propertyProvider("testObject?.propC?.this?.does?.not?.exist?.d"); + + // check that ternary operator isn't mistaken for optional chaining + results = propertyProvider(`true?.3.to`); + test_has_result(results, `toExponential`); + + results = propertyProvider(`true?.3?.to`); + test_has_result(results, `toExponential`); + + // Test more ternary + results = propertyProvider(`true?t`); + test_has_result(results, `testObject`); + + results = propertyProvider(`true??t`); + test_has_result(results, `testObject`); + + results = propertyProvider(`true?/* comment */t`); + test_has_result(results, `testObject`); + + results = propertyProvider(`true? 0); + Assert.ok( + results.matches.has(requiredSuggestion), + `<${requiredSuggestion}> found in ${[...results.matches.values()].join( + " - " + )}` + ); +} + +/** + * A helper that ensures results are the expected ones. + * @param Object results + * The results returned by JSPropertyProvider. + * @param Array expectedMatches + * An array of the properties that should be returned by JsPropertyProvider. + */ +function test_has_exact_results(results, expectedMatches) { + Assert.deepEqual([...results.matches], expectedMatches); +} diff --git a/devtools/shared/webconsole/test/xpcshell/xpcshell.ini b/devtools/shared/webconsole/test/xpcshell/xpcshell.ini new file mode 100644 index 0000000000..a0d7e75ad1 --- /dev/null +++ b/devtools/shared/webconsole/test/xpcshell/xpcshell.ini @@ -0,0 +1,9 @@ +[DEFAULT] +tags = devtools +head = head.js +firefox-appdir = browser +skip-if = toolkit == 'android' +support-files = + +[test_analyze_input_string.js] +[test_js_property_provider.js] -- cgit v1.2.3