From f01af994e35809d7cb72bccb0eb9d8bfc1ecb77f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Kondratiuk?= Date: Wed, 24 Feb 2021 09:39:02 -0300 Subject: [PATCH] fix: don't fail on possible invalid script (#1156) * Don't fail on possible invalid script * fix * Fix extension --- .../PageEvaluateTests.cs | 8 +++++++ .../Helpers/StringExtensions.cs | 21 ++++++++----------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/PlaywrightSharp.Tests/PageEvaluateTests.cs b/src/PlaywrightSharp.Tests/PageEvaluateTests.cs index af0457d1ae..6606aad6d7 100644 --- a/src/PlaywrightSharp.Tests/PageEvaluateTests.cs +++ b/src/PlaywrightSharp.Tests/PageEvaluateTests.cs @@ -666,6 +666,14 @@ public async Task ShouldRoundtripDate() Assert.Equal(date, result); } + [Fact(Skip = "The driver doesn't support this yet")] + public async Task ShouldTreatEcma2020AsFunctions() + => Assert.Equal("dario", await Page.EvaluateAsync( + @"() => { + const person = { name: 'dario' }; + return person?.name; + }")); + [PlaywrightTest("page-evaluate.spec.ts", "should roundtrip regex")] [Fact(Skip = "Regex is not native as in javascript")] public void ShouldRoundtripRegex() diff --git a/src/PlaywrightSharp/Helpers/StringExtensions.cs b/src/PlaywrightSharp/Helpers/StringExtensions.cs index 8704767756..85c992efc3 100644 --- a/src/PlaywrightSharp/Helpers/StringExtensions.cs +++ b/src/PlaywrightSharp/Helpers/StringExtensions.cs @@ -651,8 +651,10 @@ public static Dictionary ParseQueryString(this string query) /// Determine if the script is a javascript function and not an expression. /// /// Script to evaluate. + /// Whether it should retry by wrapping the code in parenthesis. + /// Checks whether the function could be a function expression. /// Whether the script is a function or not. - public static bool IsJavascriptFunction(this string script) + public static bool IsJavascriptFunction(this string script, bool retry = true, bool checkExpression = false) { try { @@ -662,7 +664,9 @@ public static bool IsJavascriptFunction(this string script) if (program.Body.Count > 0) { return - (program.Body[0] is ExpressionStatement expression && expression.Expression.Type == Nodes.ArrowFunctionExpression) || + (program.Body[0] is ExpressionStatement expression && ( + expression.Expression.Type == Nodes.ArrowFunctionExpression || + (checkExpression && expression.Expression.Type == Nodes.FunctionExpression))) || program.Body[0] is FunctionDeclaration; } @@ -670,19 +674,12 @@ public static bool IsJavascriptFunction(this string script) } catch (ParserException) { - // Retry using parenthesis - var parser = new JavaScriptParser($"({script})"); - var program = parser.ParseScript(); - - if (program.Body.Count > 0) + if (retry) { - return - program.Body.Count > 0 && - program.Body[0] is ExpressionStatement expression && - expression.Expression.Type == Nodes.FunctionExpression; + return IsJavascriptFunction($"({script})", false, true); } - return false; + return true; } }