-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPatchright.cs
More file actions
1282 lines (1025 loc) · 54.7 KB
/
Patchright.cs
File metadata and controls
1282 lines (1025 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/dotnet run
#:package Microsoft.CodeAnalysis.CSharp@5.0.0
// =================================================================================================
// Patchright .NET Patcher
// =================================================================================================
//
// This patcher applies the following categories of modifications:
//
// 1. METADATA PATCHES: Update NuGet package info (project files, version props, README)
// 2. DRIVER PATCHES: Point to Patchright's modified Chromium driver instead of standard Playwright
// 3. SCRIPT INJECTION PATCHES: Remove sourceURL comments that reveal automation
// 4. ISOLATED CONTEXT PATCHES: Add parameter to control JavaScript context isolation
// 5. ROUTE INJECTION PATCHES: Install routes to intercept and modify document requests
// 6. FOCUS CONTROL PATCHES: Add browser launch options for focus behavior control
//
// =================================================================================================
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
Console.WriteLine();
Console.WriteLine($"--- Patching Playwright .NET to create Patchright ---");
Console.WriteLine();
const string playwrightPath = "playwright-dotnet";
var isolatedContextDefaultValue = args.Length > 0 ? bool.Parse(args[0]) : true;
var driverVersion = args.Length > 1 ? args[1] : null;
var packageVersion = args.Length > 2 ? args[2] : null;
if (!Directory.Exists(playwrightPath))
{
Console.WriteLine($"Path to Playwright source '{playwrightPath}' not found, provide the path or run `git clone https://github.com/microsoft/playwright-dotnet.git` in this directory first.");
return;
}
////////////////////////////////////////////////////////////////////////
try
{
DisablePackageValidation();
PatchProjectFile();
PatchTargetsFile();
PatchVersionPropsFile();
ReplaceReadmeFile();
PatchDriverDownloader();
PatchScriptsHelper();
PatchWorker();
PatchJSHandle();
PatchFrame();
PatchLocator();
PatchPage();
PatchBrowserContext();
PatchClock();
PatchTracing();
PatchOptionsClasses();
PatchBrowser();
PatchBrowserType();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex);
Console.ResetColor();
}
////////////////////////////////////////////////////////////////////////
// Update the project file details for the Patchright NuGet package.
// This changes the package identity so users install "Patchright" instead of "Microsoft.Playwright".
void PatchProjectFile()
{
var playwrightProjectPath = Path.Combine(playwrightPath, "src", "Playwright", "Playwright.csproj");
Console.WriteLine($"Patching project file: {playwrightProjectPath}");
var doc = XDocument.Load(playwrightProjectPath);
// Disable treating warnings as errors because our patched methods don't have XML documentation
// for the new parameters we add (like isolatedContext) including some minor layout changes.
// TODO: Consider adding proper XML documentation to patched methods to re-enable this.
doc.Descendants("TreatWarningsAsErrors").FirstOrDefault()?.Value = "false";
// Update package metadata.
doc.Descendants("Title").FirstOrDefault()?.Value = "Patchright";
doc.Descendants("PackageId").FirstOrDefault()?.Value = "Patchright";
doc.Descendants("Summary").FirstOrDefault()?.Value = "The .NET port of Playwright patched with Patchright, used to automate Chromium with a single API.";
doc.Descendants("Description").FirstOrDefault()?.Value = "Undetected .NET version of the Playwright testing and automation library.";
doc.Descendants("Authors").FirstOrDefault()?.Value = "Microsoft Corporation, patched by Werner van Deventer";
doc.Descendants("RepositoryUrl").FirstOrDefault()?.Value = "https://github.com/DevEnterpriseSoftware/patchright-dotnet.git";
if (!string.IsNullOrWhiteSpace(packageVersion))
{
doc.Descendants("ReleaseVersion").FirstOrDefault()?.Value = packageVersion;
}
// Use specific writer settings to avoid BOM and control new lines for better diffs.
using var writer = XmlWriter.Create(playwrightProjectPath, new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Indent = true,
NewLineChars = "\n",
NewLineHandling = NewLineHandling.Replace
});
doc.Save(writer);
}
// Update the targets file to replace Nuget package ID Microsoft.Playwright with Patchright.
void PatchTargetsFile()
{
var targetFilePath = Path.Combine(playwrightPath, "src", "Playwright", "build", "Microsoft.Playwright.targets");
Console.WriteLine($"Patching Targets file: {targetFilePath}");
var content = File.ReadAllText(targetFilePath)
.Replace("<NuGetPackageId>Microsoft.Playwright</NuGetPackageId>", "<NuGetPackageId>Patchright</NuGetPackageId>");
var newTargetFilePath = Path.Combine(playwrightPath, "src", "Playwright", "build", "Patchright.targets");
File.WriteAllText(newTargetFilePath, content);
}
// Update the version properties file details for the Patchright NuGet package.
void PatchVersionPropsFile()
{
var playwrightVersionPropsPath = Path.Combine(playwrightPath, "src", "Common", "Version.props");
Console.WriteLine($"Patching Version Props file: {playwrightVersionPropsPath}");
var doc = XDocument.Load(playwrightVersionPropsPath);
// Update package metadata.
doc.Descendants("Authors").FirstOrDefault()?.Value = "Microsoft Corporation, patched by Werner van Deventer";
doc.Descendants("Owners").FirstOrDefault()?.Value = "DevEnterprise Software";
doc.Descendants("PackageTags").FirstOrDefault()?.Value = "patchright,undetected,headless,chrome,playwright";
doc.Descendants("PackageProjectUrl").FirstOrDefault()?.Value = "https://github.com/DevEnterpriseSoftware/patchright-dotnet";
doc.Descendants("RepositoryUrl").FirstOrDefault()?.Value = "https://github.com/DevEnterpriseSoftware/patchright-dotnet.git";
doc.Descendants("PackageLicenseExpression").FirstOrDefault()?.Value = "Apache-2.0";
if (!string.IsNullOrWhiteSpace(driverVersion))
{
doc.Descendants("DriverVersion").FirstOrDefault()?.Value = driverVersion;
}
if (!string.IsNullOrWhiteSpace(packageVersion))
{
doc.Descendants("AssemblyVersion").FirstOrDefault()?.Value = packageVersion;
}
// Use specific writer settings to avoid BOM and control new lines for better diffs.
using var writer = XmlWriter.Create(playwrightVersionPropsPath, new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Indent = true,
NewLineChars = "\n",
NewLineHandling = NewLineHandling.Replace
});
doc.Save(writer);
}
void ReplaceReadmeFile()
{
var playwrightReadmeFilePath = Path.Combine(playwrightPath, "README.md");
Console.WriteLine($"Replacing README file: {playwrightReadmeFilePath}");
File.Copy("README.md", playwrightReadmeFilePath, overwrite: true);
var readmeContent = File.ReadAllText(playwrightReadmeFilePath);
// Extract H1 content and convert to markdown.
var h1Match = Regex.Match(readmeContent, @"<h1[^>]*>(.*?)</h1>", RegexOptions.Singleline);
if (h1Match.Success)
{
var h1Content = h1Match.Groups[1].Value.Trim();
readmeContent = Regex.Replace(readmeContent, @"<h1[^>]*>.*?</h1>", $"# {h1Content}", RegexOptions.Singleline);
}
// Remove P tags and their contents (badges, etc.)
readmeContent = Regex.Replace(readmeContent, @"<p[^>]*>.*?</p>", "", RegexOptions.Singleline);
File.WriteAllText(playwrightReadmeFilePath, readmeContent);
}
// Disable package validation in all project files so that builds work with the new PackageId value.
void DisablePackageValidation()
{
foreach (var projectFile in Directory.EnumerateFiles(playwrightPath, "*.csproj", SearchOption.AllDirectories))
{
var doc = XDocument.Load(projectFile);
var element = doc.Descendants("EnablePackageValidation").FirstOrDefault(e => e.Value == "true");
if (element is not null)
{
Console.WriteLine($"Disabling EnablePackageValidation in project file: {projectFile}");
element.Value = "false";
// Use specific writer settings to avoid BOM and control new lines for better diffs.
using var writer = XmlWriter.Create(projectFile, new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Indent = true,
NewLineChars = "\n",
NewLineHandling = NewLineHandling.Replace
});
doc.Save(writer);
}
}
}
// Change the driver download URL to point to Patchright releases.
void PatchDriverDownloader()
{
var driverDownloaderPath = Path.Combine(playwrightPath, "src", "tools", "Playwright.Tooling", "DriverDownloader.cs");
Console.WriteLine($"Patching DriverDownloader file: {driverDownloaderPath}");
const string OldUrl = "https://playwright.azureedge.net/builds/driver";
const string NewUrl = "https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/releases/download";
const string OldUrlConstruction = "{cdn}/playwright-{driverVersion}-{platform}.zip";
const string NewUrlConstruction = "{cdn}/v{driverVersion}/playwright-{driverVersion}-{platform}.zip";
var content = File.ReadAllText(driverDownloaderPath)
.Replace(OldUrl, NewUrl)
.Replace(OldUrlConstruction, NewUrlConstruction);
File.WriteAllText(driverDownloaderPath, content);
}
// Remove sourceURL from being appended to any scripts.
void PatchScriptsHelper()
{
var scriptsHelperPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "ScriptsHelper.cs");
var scriptsHelperCode = File.ReadAllText(scriptsHelperPath);
Console.WriteLine($"Patching ScriptsHelper file: {scriptsHelperPath}");
var tree = CSharpSyntaxTree.ParseText(scriptsHelperCode);
var root = tree.GetRoot();
var lineEndingStyle = DetectLineEndingStyle(root);
var addSourceUrlMethod = root.GetMethods("AddSourceUrlToScript").First();
var originalBody = addSourceUrlMethod.Body!;
var newReturnStatement = SyntaxFactory.ParseStatement("return source;")
.WithLeadingTrivia(originalBody.Statements[0].GetLeadingTrivia())
.WithTrailingTrivia(lineEndingStyle);
var newAddSourceUrlBody = SyntaxFactory.Block(
SyntaxFactory.SingletonList(newReturnStatement))
.WithOpenBraceToken(originalBody.OpenBraceToken)
.WithCloseBraceToken(originalBody.CloseBraceToken);
root = root.ReplaceNode(addSourceUrlMethod, addSourceUrlMethod.WithBody(newAddSourceUrlBody));
File.WriteAllText(scriptsHelperPath, root.ToFullString());
}
// Add isolatedContext parameter to Frame methods.
void PatchWorker()
{
var methodNamesToPatch = new[] { "EvaluateAsync", "EvaluateHandleAsync" };
var workerPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Worker.cs");
var workerCode = File.ReadAllText(workerPath);
Console.WriteLine($"Patching Worker file: {workerPath}");
File.WriteAllText(workerPath, AddIsolatedContextToMethods(workerCode, "Worker", isolatedContextDefaultValue, methodNamesToPatch));
var workerGeneratedInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Generated", "IWorker.cs");
var workerGeneratedInterfaceCode = File.ReadAllText(workerGeneratedInterfacePath);
Console.WriteLine($"Patching generated IWorker file: {workerGeneratedInterfacePath}");
File.WriteAllText(workerGeneratedInterfacePath, AddIsolatedContextToMethods(workerGeneratedInterfaceCode, "IWorker", isolatedContextDefaultValue, methodNamesToPatch));
}
// Add isolatedContext parameter to JSHandle methods.
void PatchJSHandle()
{
var methodNamesToPatch = new[] { "EvaluateAsync", "EvaluateHandleAsync" };
var jsHandlePath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "JSHandle.cs");
var jsHandleCode = File.ReadAllText(jsHandlePath);
Console.WriteLine($"Patching JSHandle file: {jsHandlePath}");
File.WriteAllText(jsHandlePath, AddIsolatedContextToMethods(jsHandleCode, "JSHandle", isolatedContextDefaultValue, methodNamesToPatch));
var jsHandleGeneratedInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Generated", "IJSHandle.cs");
var jsHandleGeneratedInterfaceCode = File.ReadAllText(jsHandleGeneratedInterfacePath);
Console.WriteLine($"Patching generated IJSHandle file: {jsHandleGeneratedInterfacePath}");
File.WriteAllText(jsHandleGeneratedInterfacePath, AddIsolatedContextToMethods(jsHandleGeneratedInterfaceCode, "IJSHandle", isolatedContextDefaultValue, methodNamesToPatch));
var jsHandleSupplementsInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Supplements", "IJSHandle.cs");
var jsHandleSupplementsInterfaceCode = File.ReadAllText(jsHandleSupplementsInterfacePath);
Console.WriteLine($"Patching supplements IJSHandle file: {jsHandleSupplementsInterfacePath}");
var newJsHandleSupplementsInterfaceCode = AddIsolatedContextToMethods(jsHandleSupplementsInterfaceCode, "IJSHandle", isolatedContextDefaultValue, methodNamesToPatch);
File.WriteAllText(jsHandleSupplementsInterfacePath, newJsHandleSupplementsInterfaceCode.Replace("EvaluateAsync{T}(string, object)", "EvaluateAsync{T}(string, object, bool)"));
}
// Add isolatedContext parameter to Frame methods.
void PatchFrame()
{
// Playwright has a weird private methods with underscores that also needs to be patched.
var methodNamesToPatch = new[] { "EvaluateAsync", "EvaluateHandleAsync", "EvalOnSelectorAsync", "EvalOnSelectorAllAsync", "_evalOnSelectorAsync", "_evalOnSelectorAllAsync" };
var framePath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Frame.cs");
var frameCode = File.ReadAllText(framePath);
Console.WriteLine($"Patching Frame file: {framePath}");
File.WriteAllText(framePath, AddIsolatedContextToMethods(frameCode, "Frame", isolatedContextDefaultValue, methodNamesToPatch));
var frameGeneratedInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Generated", "IFrame.cs");
var frameGeneratedInterfaceCode = File.ReadAllText(frameGeneratedInterfacePath);
Console.WriteLine($"Patching generated IFrame file: {frameGeneratedInterfacePath}");
File.WriteAllText(frameGeneratedInterfacePath, AddIsolatedContextToMethods(frameGeneratedInterfaceCode, "IFrame", isolatedContextDefaultValue, methodNamesToPatch));
var frameSupplementsInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Supplements", "IFrame.cs");
var frameSupplementsInterfaceCode = File.ReadAllText(frameSupplementsInterfacePath);
Console.WriteLine($"Patching supplements IFrame file: {frameSupplementsInterfacePath}");
File.WriteAllText(frameSupplementsInterfacePath, AddIsolatedContextToMethods(frameSupplementsInterfaceCode, "IFrame", isolatedContextDefaultValue, methodNamesToPatch));
}
// Add isolatedContext parameter to Locator methods.
void PatchLocator()
{
var methodNamesToPatch = new[] { "EvaluateAsync", "EvaluateHandleAsync", "EvaluateAllAsync" };
var locatorPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Locator.cs");
var locatorCode = File.ReadAllText(locatorPath);
Console.WriteLine($"Patching Locator file: {locatorPath}");
File.WriteAllText(locatorPath, AddIsolatedContextToMethods(locatorCode, "Locator", isolatedContextDefaultValue, methodNamesToPatch));
var locatorGeneratedInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Generated", "ILocator.cs");
var locatorGeneratedInterfaceCode = File.ReadAllText(locatorGeneratedInterfacePath);
Console.WriteLine($"Patching generated ILocator file: {locatorGeneratedInterfacePath}");
File.WriteAllText(locatorGeneratedInterfacePath, AddIsolatedContextToMethods(locatorGeneratedInterfaceCode, "ILocator", isolatedContextDefaultValue, methodNamesToPatch));
var locatorSupplementsInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Supplements", "ILocator.cs");
var locatorSupplementsInterfaceCode = File.ReadAllText(locatorSupplementsInterfacePath);
Console.WriteLine($"Patching supplements ILocator file: {locatorSupplementsInterfacePath}");
File.WriteAllText(locatorSupplementsInterfacePath, AddIsolatedContextToMethods(locatorSupplementsInterfaceCode, "ILocator", isolatedContextDefaultValue, methodNamesToPatch));
}
// Add isolatedContext parameter to Page methods.
void PatchPage()
{
var methodNamesToPatch = new[] { "EvaluateAsync", "EvaluateHandleAsync", "EvalOnSelectorAsync", "EvalOnSelectorAllAsync" };
var pagePath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Page.cs");
var pageCode = File.ReadAllText(pagePath);
Console.WriteLine($"Patching Page file: {pagePath}");
File.WriteAllText(pagePath, AddIsolatedContextToMethods(pageCode, "Page", isolatedContextDefaultValue, methodNamesToPatch));
// Read the code again after the isolated context changes have been applied.
pageCode = File.ReadAllText(pagePath);
var tree = CSharpSyntaxTree.ParseText(pageCode);
var root = tree.GetRoot();
var lineEndingStyle = DetectLineEndingStyle(root);
var pageClass = root.GetClass("Page");
var indentation = pageClass.Members.First().GetIndentation();
var routeInjectingPropertyExists = pageClass.Members
.OfType<PropertyDeclarationSyntax>()
.Any(p => p.Identifier.Text == "RouteInjecting");
if (!routeInjectingPropertyExists)
{
var routeInjectingProperty = SyntaxFactory.ParseMemberDeclaration("public bool RouteInjecting { get; private set; }");
var injectRouteMethod = SyntaxFactory.ParseMemberDeclaration("""
[MethodImpl(MethodImplOptions.NoInlining)]
public async Task InstallInjectRouteAsync()
{
if (RouteInjecting || Context.RouteInjecting)
{
return;
}
await RouteAsync("**/*", async route =>
{
try
{
var request = route.Request;
if (request.ResourceType.Equals("document", StringComparison.OrdinalIgnoreCase) &&
request.Url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
var protocol = request.Url.Split(':')[0];
await route.FallbackAsync(new RouteFallbackOptions { Url = protocol + "://patchright-init-script-inject.internal/" }).ConfigureAwait(false);
}
else
{
await route.FallbackAsync().ConfigureAwait(false);
}
}
catch
{
await route.FallbackAsync().ConfigureAwait(false);
}
}).ConfigureAwait(false);
RouteInjecting = true;
}
""");
root = root.ReplaceNode(pageClass, pageClass.AddMembers(
routeInjectingProperty!.WithLeadingTrivia(indentation.Insert(0, lineEndingStyle)).WithTrailingTrivia(lineEndingStyle, lineEndingStyle),
injectRouteMethod!.WithFullIndentation(indentation, lineEndingStyle).WithTrailingTrivia(lineEndingStyle)));
// Get the class again from the new root.
pageClass = root.GetClass("Page");
// Add InstallInjectRouteAsync method to ExposeBindingAsync.
var exposeBindingMethod = root.GetMethods("InnerExposeBindingAsync").First();
var newExposeBindingMethod = PatchMethodWithInjectedStatement(exposeBindingMethod, "await InstallInjectRouteAsync().ConfigureAwait(false);", indentation, lineEndingStyle);
root = root.ReplaceNode(pageClass, pageClass.ReplaceNode(exposeBindingMethod, newExposeBindingMethod));
// Get the class again from the new root.
pageClass = root.GetClass("Page");
// Add InstallInjectRouteAsync method to AddInitScriptAsync.
var addInitScriptMethod = root.GetMethods("AddInitScriptAsync").First();
var newAddInitScripMethod = PatchMethodWithInjectedStatement(addInitScriptMethod, "await InstallInjectRouteAsync().ConfigureAwait(false);", indentation, lineEndingStyle);
root = root.ReplaceNode(pageClass, pageClass.ReplaceNode(addInitScriptMethod, newAddInitScripMethod));
File.WriteAllText(pagePath, root.ToFullString());
}
var pageGeneratedInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Generated", "IPage.cs");
var pageGeneratedInterfaceCode = File.ReadAllText(pageGeneratedInterfacePath);
Console.WriteLine($"Patching generated IPage file: {pageGeneratedInterfacePath}");
File.WriteAllText(pageGeneratedInterfacePath, AddIsolatedContextToMethods(pageGeneratedInterfaceCode, "IPage", isolatedContextDefaultValue, methodNamesToPatch));
var pageSupplementsInterfacePath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Supplements", "IPage.cs");
var pageSupplementsInterfaceCode = File.ReadAllText(pageSupplementsInterfacePath);
Console.WriteLine($"Patching supplements IPage file: {pageSupplementsInterfacePath}");
File.WriteAllText(pageSupplementsInterfacePath, AddIsolatedContextToMethods(pageSupplementsInterfaceCode, "IPage", isolatedContextDefaultValue, methodNamesToPatch));
}
// Add route injection to BrowserContext class and call from relevant methods.
void PatchBrowserContext()
{
var browserContextPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "BrowserContext.cs");
var browserContextCode = File.ReadAllText(browserContextPath);
Console.WriteLine($"Patching BrowserContext file: {browserContextPath}");
var tree = CSharpSyntaxTree.ParseText(browserContextCode);
var root = tree.GetRoot();
var lineEndingStyle = DetectLineEndingStyle(root);
var browserContextClass = root.GetClass("BrowserContext");
var indentation = browserContextClass.Members.First().GetIndentation();
var routeInjectingPropertyExists = browserContextClass.Members
.OfType<PropertyDeclarationSyntax>()
.Any(p => p.Identifier.Text == "RouteInjecting");
if (!routeInjectingPropertyExists)
{
var routeInjectingProperty = SyntaxFactory.ParseMemberDeclaration("public bool RouteInjecting { get; private set; }");
var injectRouteMethod = SyntaxFactory.ParseMemberDeclaration("""
[MethodImpl(MethodImplOptions.NoInlining)]
public async Task InstallInjectRouteAsync()
{
if (RouteInjecting)
{
return;
}
await RouteAsync("**/*", async route =>
{
try
{
var request = route.Request;
if (request.ResourceType.Equals("document", StringComparison.OrdinalIgnoreCase) &&
request.Url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
var protocol = request.Url.Split(':')[0];
await route.FallbackAsync(new RouteFallbackOptions { Url = protocol + "://patchright-init-script-inject.internal/" }).ConfigureAwait(false);
}
else
{
await route.FallbackAsync().ConfigureAwait(false);
}
}
catch
{
await route.FallbackAsync().ConfigureAwait(false);
}
}).ConfigureAwait(false);
RouteInjecting = true;
}
""");
root = root.ReplaceNode(browserContextClass, browserContextClass.AddMembers(
routeInjectingProperty!.WithLeadingTrivia(indentation.Insert(0, lineEndingStyle)).WithTrailingTrivia(lineEndingStyle, lineEndingStyle),
injectRouteMethod!.WithFullIndentation(indentation, lineEndingStyle).WithTrailingTrivia(lineEndingStyle)));
// Get the class again from the new root.
browserContextClass = root.GetClass("BrowserContext");
// Add InstallInjectRouteAsync method to ExposeBindingAsync.
var exposeBindingMethod = root.GetMethods("ExposeBindingAsync")
.First(m => m.Modifiers.Any(mod => mod.IsKind(SyntaxKind.PrivateKeyword)));
var newExposeBindingMethod = PatchMethodWithInjectedStatement(exposeBindingMethod, "await InstallInjectRouteAsync().ConfigureAwait(false);", indentation, lineEndingStyle);
root = root.ReplaceNode(browserContextClass, browserContextClass.ReplaceNode(exposeBindingMethod, newExposeBindingMethod));
// Get the class again from the new root.
browserContextClass = root.GetClass("BrowserContext");
// Add InstallInjectRouteAsync method to AddInitScriptAsync.
var addInitScriptMethod = root.GetMethods("AddInitScriptAsync").First();
var newAddInitScripMethod = PatchMethodWithInjectedStatement(addInitScriptMethod, "await InstallInjectRouteAsync().ConfigureAwait(false);", indentation, lineEndingStyle);
root = root.ReplaceNode(browserContextClass, browserContextClass.ReplaceNode(addInitScriptMethod, newAddInitScripMethod));
File.WriteAllText(browserContextPath, root.ToFullString());
}
}
// Call the InstallInjectRouteAsync method when a clock is installed.
void PatchClock()
{
var clockPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Clock.cs");
var clockCode = File.ReadAllText(clockPath);
Console.WriteLine($"Patching Clock file: {clockPath}");
var tree = CSharpSyntaxTree.ParseText(clockCode);
var root = tree.GetRoot();
var lineEndingStyle = DetectLineEndingStyle(root);
var clockClass = root.GetClass("Clock");
var installMethod = clockClass.GetMethods("InstallAsync").First();
var originalBody = installMethod.Body!;
var installMethodStatements = originalBody.Statements.ToList();
if (!installMethodStatements[0].ToFullString().Contains("InstallInjectRouteAsync"))
{
installMethodStatements.Insert(0, SyntaxFactory.ParseStatement("await browserContext.InstallInjectRouteAsync().ConfigureAwait(false);")
.WithLeadingTrivia(installMethodStatements[0].GetLeadingTrivia())
.WithTrailingTrivia(lineEndingStyle, lineEndingStyle));
var newInstallMethodBody = SyntaxFactory.Block(installMethodStatements)
.WithOpenBraceToken(originalBody.OpenBraceToken)
.WithCloseBraceToken(originalBody.CloseBraceToken);
root = root.ReplaceNode(clockClass, clockClass.ReplaceNode(installMethod, installMethod.WithBody(newInstallMethodBody)));
File.WriteAllText(clockPath, root.ToFullString());
}
}
// Call the InstallInjectRouteAsync method when tracing is started.
void PatchTracing()
{
var tracingPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Tracing.cs");
var tracingCode = File.ReadAllText(tracingPath);
Console.WriteLine($"Patching Tracing file: {tracingPath}");
var tree = CSharpSyntaxTree.ParseText(tracingCode);
var root = tree.GetRoot();
var lineEndingStyle = DetectLineEndingStyle(root);
var clockClass = root.GetClass("Tracing");
var startMethod = clockClass.GetMethods("StartAsync").First();
var originalBody = startMethod.Body!;
var startMethodStatements = originalBody.Statements.ToList();
if (!startMethodStatements[0].ToFullString().Contains("InstallInjectRouteAsync"))
{
startMethodStatements.Insert(0, SyntaxFactory.ParseStatement("await ((BrowserContext)Parent!).InstallInjectRouteAsync().ConfigureAwait(false);")
.WithLeadingTrivia(startMethodStatements[0].GetLeadingTrivia())
.WithTrailingTrivia(lineEndingStyle, lineEndingStyle));
var newStartMethodBody = SyntaxFactory.Block(startMethodStatements)
.WithOpenBraceToken(originalBody.OpenBraceToken)
.WithCloseBraceToken(originalBody.CloseBraceToken);
root = root.ReplaceNode(clockClass, clockClass.ReplaceNode(startMethod, startMethod.WithBody(newStartMethodBody)));
File.WriteAllText(tracingPath, root.ToFullString());
}
}
// Add FocusControl property and clone statement to options classes.
void PatchOptionsClasses()
{
foreach (var optionsClass in new[] { "BrowserTypeLaunchPersistentContextOptions", "BrowserTypeLaunchOptions", "BrowserNewPageOptions", "BrowserNewContextOptions" })
{
var optionsClassPath = Path.Combine(playwrightPath, "src", "Playwright", "API", "Generated", "Options", $"{optionsClass}.cs");
var optionsClassCode = File.ReadAllText(optionsClassPath);
Console.WriteLine($"Patching {optionsClass} file: {optionsClassPath}");
File.WriteAllText(optionsClassPath, AddFocusControlToOptionsClass(optionsClassCode, optionsClass));
}
}
// Add focusControl parameter to browser methods.
void PatchBrowser()
{
var methodNamesToPatch = new[] { "NewContextAsync" };
var browserPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "Browser.cs");
var browserCode = File.ReadAllText(browserPath);
Console.WriteLine($"Patching Browser file: {browserPath}");
var updatedBrowserCode = AddDictionaryEntryToMethod(browserCode, "Browser", methodNamesToPatch, "focusControl", "options.FocusControl");
// Parse the updated code to add FocusControl property assignment to NewPageAsync.
var tree = CSharpSyntaxTree.ParseText(updatedBrowserCode);
var root = tree.GetRoot();
var browserClass = root.GetClass("Browser");
var newPageMethod = browserClass.GetMethods("NewPageAsync").FirstOrDefault();
if (newPageMethod is not null)
{
// Find the contextOptions object creation
var objectCreation = newPageMethod.DescendantNodes()
.OfType<ObjectCreationExpressionSyntax>()
.FirstOrDefault(oc =>
oc.Type is IdentifierNameSyntax ins &&
ins.Identifier.Text == "BrowserNewContextOptions" &&
oc.Initializer is not null);
if (objectCreation?.Initializer is not null)
{
var expressions = objectCreation.Initializer.Expressions;
// Check if FocusControl assignment already exists.
var focusControlExists = expressions.Any(expr =>
expr is AssignmentExpressionSyntax assignment &&
assignment.Left is IdentifierNameSyntax identifierName &&
identifierName.Identifier.Text == "FocusControl");
if (!focusControlExists)
{
// Create the new FocusControl assignment.
var newAssignment = SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.IdentifierName("FocusControl"),
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("options"),
SyntaxFactory.IdentifierName("FocusControl")))
.WithOperatorToken(
SyntaxFactory.Token(SyntaxKind.EqualsToken)
.WithLeadingTrivia(SyntaxFactory.Space)
.WithTrailingTrivia(SyntaxFactory.Space));
// Get the first expression to copy trivia from
var firstExpression = expressions.FirstOrDefault();
if (firstExpression is not null)
{
newAssignment = newAssignment.WithTriviaFrom(firstExpression);
}
// Insert at the beginning.
var newExpressions = expressions.Insert(0, newAssignment);
// Build new separators list.
var lineEndingStyle = DetectLineEndingStyle(root);
var oldSeparators = expressions.GetSeparators().ToList();
var newSeparators = new List<SyntaxToken> { SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(lineEndingStyle) };
newSeparators.AddRange(oldSeparators);
var newSeparatedList = SyntaxFactory.SeparatedList(newExpressions, newSeparators);
var newInitializer = objectCreation.Initializer.WithExpressions(newSeparatedList);
var newObjectCreation = objectCreation.WithInitializer(newInitializer);
root = root.ReplaceNode(browserClass, browserClass.ReplaceNode(objectCreation, newObjectCreation));
updatedBrowserCode = root.ToFullString();
}
}
}
File.WriteAllText(browserPath, updatedBrowserCode);
}
// Add focusControl parameter to browser type methods.
void PatchBrowserType()
{
var methodNamesToPatch = new[] { "LaunchAsync", "LaunchPersistentContextAsync" };
var browserPath = Path.Combine(playwrightPath, "src", "Playwright", "Core", "BrowserType.cs");
var browserCode = File.ReadAllText(browserPath);
Console.WriteLine($"Patching BrowserType file: {browserPath}");
File.WriteAllText(browserPath, AddDictionaryEntryToMethod(browserCode, "BrowserType", methodNamesToPatch, "focusControl", "options.FocusControl"));
}
// Generic method to patch methods by adding async, replacing return with await, and injecting a statement at the beginning.
static MethodDeclarationSyntax PatchMethodWithInjectedStatement(MethodDeclarationSyntax methodDeclaration, string statementToInject, SyntaxTriviaList indentation, SyntaxTrivia lineEndingStyle)
{
bool isArrowFunction = methodDeclaration.ExpressionBody is not null;
var originalBody = methodDeclaration.Body!;
// Handle arrow function syntax.
if (isArrowFunction)
{
var arrowExpression = methodDeclaration.ExpressionBody!.Expression;
if (arrowExpression is InvocationExpressionSyntax invocation &&
invocation.Expression is SimpleNameSyntax simpleName &&
simpleName.Identifier.Text == "SendMessageToServerAsync")
{
// Check if ConfigureAwait is already present.
var hasConfigureAwait = invocation.DescendantNodes()
.OfType<MemberAccessExpressionSyntax>()
.Any(m => m.Name.Identifier.Text == "ConfigureAwait");
if (!hasConfigureAwait)
{
// Add .ConfigureAwait(false)
var configureAwaitInvocation = SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
invocation,
SyntaxFactory.IdentifierName("ConfigureAwait")),
SyntaxFactory.ArgumentList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)))));
arrowExpression = configureAwaitInvocation;
}
}
// Convert arrow function to block body with await.
var awaitExpression = SyntaxFactory.AwaitExpression(arrowExpression)
.WithAwaitKeyword(
SyntaxFactory.Token(SyntaxKind.AwaitKeyword)
.WithTrailingTrivia(SyntaxFactory.Space));
// Can't really figure out how to get the correct indentation here for the new code block statements.
// Since there was only one statement in the original arrow function, we can just double indent all new statements to line them up.
var doubleIndentation = SyntaxFactory.TriviaList(indentation).AddRange(indentation);
// Create statements list with injected statement and await.
var statements = new List<StatementSyntax>
{
SyntaxFactory.ParseStatement(statementToInject)
.WithLeadingTrivia(doubleIndentation)
.WithTrailingTrivia(lineEndingStyle, lineEndingStyle),
SyntaxFactory.ExpressionStatement(awaitExpression)
.WithLeadingTrivia(doubleIndentation)
.WithTrailingTrivia(lineEndingStyle)
};
var newMethodBody = SyntaxFactory.Block(statements)
.WithOpenBraceToken(
SyntaxFactory.Token(SyntaxKind.OpenBraceToken)
.WithLeadingTrivia(indentation)
.WithTrailingTrivia(lineEndingStyle))
.WithCloseBraceToken(
SyntaxFactory.Token(SyntaxKind.CloseBraceToken)
.WithLeadingTrivia(indentation)
.WithTrailingTrivia(lineEndingStyle));
// Remove expression body and add block body.
methodDeclaration = methodDeclaration
.WithExpressionBody(null)
.WithSemicolonToken(default)
.WithBody(newMethodBody);
}
else
{
// Handle regular method body.
var methodStatements = methodDeclaration.Body!.Statements.ToList();
// Insert the injected statement at the beginning.
methodStatements.Insert(0, SyntaxFactory.ParseStatement(statementToInject)
.WithLeadingTrivia(methodStatements[0].GetLeadingTrivia())
.WithTrailingTrivia(lineEndingStyle, lineEndingStyle));
var newMethodBody = SyntaxFactory.Block(methodStatements);
// Find and replace any return statement with and await statement.
var returnStatement = newMethodBody.DescendantNodes()
.OfType<ReturnStatementSyntax>()
.FirstOrDefault(r => r.Expression is InvocationExpressionSyntax inv &&
inv.Expression is SimpleNameSyntax simpleName &&
simpleName.Identifier.Text == "SendMessageToServerAsync");
if (returnStatement is not null)
{
var invocation = (InvocationExpressionSyntax)returnStatement.Expression!;
// Check if ConfigureAwait is already present.
var hasConfigureAwait = invocation.DescendantNodes()
.OfType<MemberAccessExpressionSyntax>()
.Any(m => m.Name.Identifier.Text == "ConfigureAwait");
if (!hasConfigureAwait)
{
// Add .ConfigureAwait(false)
var configureAwaitInvocation = SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
invocation,
SyntaxFactory.IdentifierName("ConfigureAwait")),
SyntaxFactory.ArgumentList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)))));
// Create await expression statement.
var awaitStatement = SyntaxFactory.ExpressionStatement(
SyntaxFactory.AwaitExpression(configureAwaitInvocation)
.WithAwaitKeyword(
SyntaxFactory.Token(SyntaxKind.AwaitKeyword)
.WithTrailingTrivia(SyntaxFactory.Space)))
.WithTriviaFrom(returnStatement);
newMethodBody = newMethodBody.ReplaceNode(returnStatement, awaitStatement);
}
}
methodDeclaration = methodDeclaration.WithBody(newMethodBody
.WithOpenBraceToken(originalBody.OpenBraceToken)
.WithCloseBraceToken(originalBody.CloseBraceToken));
}
// Add async modifier if not present.
var newMethodModifiers = methodDeclaration.Modifiers;
if (!newMethodModifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
newMethodModifiers = newMethodModifiers.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword).WithTrailingTrivia(SyntaxFactory.Space));
methodDeclaration = methodDeclaration.WithModifiers(newMethodModifiers);
}
return methodDeclaration;
}
// Method to add isolatedContext parameter to specified methods provided.
// This will also patch pass-through calls to private methods as needed and add the dictionary entry to SendMessageToServerAsync calls.
static string AddIsolatedContextToMethods(string code, string typeName, bool defaultValue, IEnumerable<string> methodNames)
{
var tree = CSharpSyntaxTree.ParseText(code);
var root = tree.GetRoot();
var lineEndingStyle = DetectLineEndingStyle(root);
var methodMissingIsolatedContextParam = new Func<MethodDeclarationSyntax, bool>(method => !method.ParameterList.Parameters.Any(p => p.Identifier.Text == "isolatedContext"));
foreach (var methodName in methodNames)
{
// Find all overloads of the method in the current class.
var methods = root
.GetType(typeName)
.GetMethods(methodName)
.Where(methodMissingIsolatedContextParam);
foreach (var method in methods)
{
var currentMethod = root
.GetType(typeName)
.GetMethods(methodName)
.First(methodMissingIsolatedContextParam);
// Find the first invocation of SendMessageToServerAsync and patch the dictionary parameter.
var sendInvocationExpression = currentMethod.DescendantNodes()
.OfType<InvocationExpressionSyntax>()
.FirstOrDefault(inv => inv.Expression is SimpleNameSyntax simpleName && simpleName.Identifier.Text == "SendMessageToServerAsync");
if (sendInvocationExpression is not null)
{
var dictObjCreation = sendInvocationExpression.ArgumentList.Arguments.FirstOrDefault(a => a.Expression is ObjectCreationExpressionSyntax);
if (dictObjCreation is not null)
{
var objectCreation = dictObjCreation.Expression as ObjectCreationExpressionSyntax;
// Create the new assignment expression.
// New Code: ["isolatedContext"] = isolatedContext
var newEntry = SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.ImplicitElementAccess(
SyntaxFactory.BracketedArgumentList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal("isolatedContext")))))),
SyntaxFactory.IdentifierName("isolatedContext"))
.WithOperatorToken(
SyntaxFactory.Token(SyntaxKind.EqualsToken)
.WithLeadingTrivia(SyntaxFactory.Space)
.WithTrailingTrivia(SyntaxFactory.Space));
// Get existing expressions and determine the trivia to use.
var existingExpressions = objectCreation!.Initializer!.Expressions;
// Add proper leading trivia (newline and indentation) to match existing entries.
if (existingExpressions.Count > 0)
{
var lastExpression = existingExpressions.Last();
newEntry = newEntry.WithTriviaFrom(lastExpression);
}
// Create a new separated syntax list with the new entry.
var separator = SyntaxFactory.Token(SyntaxKind.CommaToken);
var newExpressions = existingExpressions.Add(newEntry);
var newSeparatedList = SyntaxFactory.SeparatedList(newExpressions, existingExpressions.GetSeparators().Append(separator.WithTrailingTrivia(lineEndingStyle)));
var newInitializer = objectCreation.Initializer.WithExpressions(newSeparatedList);
var newObjectCreation = objectCreation.WithInitializer(newInitializer);
root = root.ReplaceNode(currentMethod, currentMethod.ReplaceNode(objectCreation, newObjectCreation));
// Refresh the current method reference after root update.
currentMethod = root
.GetType(typeName)
.GetMethods(methodName)
.First(methodMissingIsolatedContextParam);
}
}
// The Playwright code has some passthrough calls to private methods or chain calls to frames which then call SendMessageToServerAsync (handled above).
// Need to detect these and pass-through the isolatedContext parameter.
var passthroughInvocationExpression = currentMethod.DescendantNodes()
.OfType<InvocationExpressionSyntax>()
.FirstOrDefault(inv =>
{
// Direct method call (e.g., EvaluateAsync(...))
if (inv.Expression is SimpleNameSyntax simpleName)
{
return simpleName.Identifier.Text.StartsWith("_eval") || simpleName.Identifier.Text.StartsWith("Eval");
}
// Member access calls (e.g., h.EvaluateAsync(...) or _frame.EvalOnSelectorAllAsync(...))
if (inv.Expression is MemberAccessExpressionSyntax memberAccess)
{
return memberAccess.Name.Identifier.Text.StartsWith("Eval");
}
return false;
});
if (passthroughInvocationExpression is not null)
{
// Create the new named argument.
// New Code: isolatedContext: isolatedContext
var newArgument = SyntaxFactory.Argument(
SyntaxFactory.IdentifierName("isolatedContext"))
.WithNameColon(
SyntaxFactory.NameColon(
SyntaxFactory.IdentifierName("isolatedContext"))
.WithLeadingTrivia(SyntaxFactory.Space)
.WithTrailingTrivia(SyntaxFactory.Space));
// Create new argument list with the additional argument.
var newArgumentList = passthroughInvocationExpression.ArgumentList.AddArguments(newArgument);
// Create the new invocation expression.
var newPassthroughInvocationExpression = passthroughInvocationExpression.WithArgumentList(newArgumentList);
// Replace in the syntax tree.
root = root.ReplaceNode(currentMethod, currentMethod.ReplaceNode(passthroughInvocationExpression, newPassthroughInvocationExpression));
// Refresh the current method reference after root update.
currentMethod = root
.GetType(typeName)
.GetMethods(methodName)
.First(methodMissingIsolatedContextParam);
}