-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildPlugin.ps1
More file actions
1311 lines (1118 loc) · 55.4 KB
/
Copy pathbuildPlugin.ps1
File metadata and controls
1311 lines (1118 loc) · 55.4 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
# PowerShell Script: Analyze Android Dependencies and Generate PluginConfig.json
# Set color output function
function Write-ColorOutput {
param(
[string]$Message,
[string]$Color = 'White'
)
switch ($Color) {
'Red' { Write-Host $Message -ForegroundColor Red }
'Green' { Write-Host $Message -ForegroundColor Green }
'Yellow' { Write-Host $Message -ForegroundColor Yellow }
'Blue' { Write-Host $Message -ForegroundColor Blue }
default { Write-Host $Message }
}
}
# Detect operating system type
function Test-OperatingSystem {
Write-ColorOutput 'Running on Windows' 'Blue'
}
<#
Function: Self-CheckScriptIntegrity
Purpose: Detect problematic quotes/encoding and parse errors in this script
Input: ScriptPath - full path of the script
Output: [bool] true if self-check passes; false otherwise
#>
function Self-CheckScriptIntegrity {
param([string]$ScriptPath)
Write-ColorOutput '=== Self-check: Script integrity ===' 'Blue'
if ([string]::IsNullOrWhiteSpace($ScriptPath) -or -not (Test-Path $ScriptPath)) {
Write-ColorOutput 'Cannot locate script path; skipping self-check' 'Yellow'
return $true
}
try {
$bytes = [IO.File]::ReadAllBytes($ScriptPath)
}
catch {
Write-ColorOutput "Failed to read script; skipping self-check: $_" 'Yellow'
return $true
}
$hasUtf16Le = $bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE
$hasUtf16Be = $bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF
if ($hasUtf16Le -or $hasUtf16Be) {
Write-ColorOutput 'UTF-16 detected; please save as UTF-8 without BOM' 'Yellow'
}
$text = [Text.Encoding]::UTF8.GetString($bytes)
if ($text -match '[\u201C\u201D\u2018\u2019]') {
Write-ColorOutput 'Smart quotes detected (curly quotes); PowerShell may fail to parse' 'Yellow'
}
if ($text -match '\x00') {
Write-ColorOutput 'NUL character detected; possible encoding or copy/paste issue' 'Yellow'
}
$errors = $null
[System.Management.Automation.PSParser]::Tokenize($text, [ref]$errors) | Out-Null
if ($errors -and $errors.Count -gt 0) {
Write-ColorOutput 'Self-check found PowerShell parse errors' 'Red'
foreach ($e in $errors) {
Write-ColorOutput "$($e.Message) at line $($e.Token.StartLine), column $($e.Token.StartColumn)" 'Red'
}
return $false
}
Write-ColorOutput 'Self-check passed' 'Green'
return $true
}
<#
Function: Test-HasAndroidNativeCode
Purpose: Detect Android native sources (.java/.kt) or compiled classes in the project and node_modules
Input: ProjectRoot - project root path
Output: [bool] whether native code/classes exist
#>
function Test-HasAndroidNativeCode {
param([string]$ProjectRoot)
$hasNative = $false
$androidDirs = @()
$androidDirs += Join-Path $ProjectRoot 'android'
$androidDirs += Join-Path $ProjectRoot 'app\android'
foreach ($dir in $androidDirs) {
if (Test-Path $dir) {
$javaFiles = Get-ChildItem -Path $dir -Recurse -Filter '*.java' -File -ErrorAction SilentlyContinue
$ktFiles = Get-ChildItem -Path $dir -Recurse -Filter '*.kt' -File -ErrorAction SilentlyContinue
if (($javaFiles -and $javaFiles.Count -gt 0) -or ($ktFiles -and $ktFiles.Count -gt 0)) { $hasNative = $true }
}
if ($hasNative) { break }
}
if (-not $hasNative) {
$nodeModulesDir = Join-Path $ProjectRoot 'node_modules'
if (Test-Path $nodeModulesDir) {
$candidateModules = Get-ChildItem -Path $nodeModulesDir -Directory
foreach ($moduleDir in $candidateModules) {
if ($moduleDir.Name -eq 'sn-plugin-lib') { continue }
$dirsToScan = @()
$dirsToScan += (Join-Path $moduleDir.FullName 'android')
$dirsToScan += (Join-Path $moduleDir.FullName 'platforms\android')
$dirsToScan += (Join-Path $moduleDir.FullName 'platforms\android-native')
foreach ($scanDir in $dirsToScan) {
if (Test-Path $scanDir) {
$javaFiles = Get-ChildItem -Path $scanDir -Recurse -Filter '*.java' -File -ErrorAction SilentlyContinue
$ktFiles = Get-ChildItem -Path $scanDir -Recurse -Filter '*.kt' -File -ErrorAction SilentlyContinue
if (($javaFiles -and $javaFiles.Count -gt 0) -or ($ktFiles -and $ktFiles.Count -gt 0)) { $hasNative = $true; break }
}
}
if ($hasNative) { break }
}
}
}
if (-not $hasNative) {
$javacDir = Join-Path $ProjectRoot 'android\app\build\intermediates\javac'
if (Test-Path $javacDir) {
$classesCandidates = Get-ChildItem -Path $javacDir -Directory -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -match 'compile.*JavaWithJavac\\classes$' }
foreach ($c in $classesCandidates) {
$classFiles = Get-ChildItem -Path $c.FullName -Recurse -Filter '*.class' -File -ErrorAction SilentlyContinue
if ($classFiles -and $classFiles.Count -gt 0) { $hasNative = $true; break }
}
}
}
return $hasNative
}
# Generate 16-character random string (numbers and lowercase letters)
function New-RandomString {
param([int]$Length = 16)
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
$randomString = ''
for ($i = 0; $i -lt $Length; $i++) {
$randomIndex = Get-Random -Maximum $chars.Length
$randomString += $chars[$randomIndex]
}
return $randomString
}
# Get project information from package.json
function Get-PackageInfo {
param([string]$ProjectRoot)
$packageJsonPath = Join-Path $ProjectRoot 'package.json'
if (Test-Path $packageJsonPath) {
try {
$packageJson = Get-Content $packageJsonPath -Raw | ConvertFrom-Json
$name = $packageJson.name
$description = if ($packageJson.description) { $packageJson.description } else { '' }
$version = if ($packageJson.version) { $packageJson.version } else { '0.0.1' }
return @{
Name = $name
Description = $description
Version = $version
}
}
catch {
Write-ColorOutput "Failed to parse package.json file: $_" 'Red'
exit 1
}
}
else {
Write-ColorOutput 'package.json file not found' 'Red'
exit 1
}
}
# Create PluginConfig.json file
function New-PluginConfig {
param(
[string]$PluginId,
[hashtable]$PackageInfo,
[string]$ProjectRoot
)
$configFile = Join-Path $ProjectRoot 'PluginConfig.json'
Write-ColorOutput 'Creating PluginConfig.json file...' 'Blue'
$config = @{
name = $PackageInfo.Name
desc = $PackageInfo.Description
iconPath = ''
versionName = $PackageInfo.Version
versionCode = '1'
pluginID = $PluginId
pluginKey = $PackageInfo.Name
jsMainPath = 'index'
}
try {
$config | ConvertTo-Json -Depth 10 | Set-Content $configFile -Encoding UTF8
Write-ColorOutput "PluginConfig.json file created: $configFile" 'Green'
}
catch {
Write-ColorOutput "Failed to create PluginConfig.json file: $_" 'Red'
exit 1
}
}
# Update reactPackages field in PluginConfig.json
function Update-PluginConfigPackages {
param(
[string]$ProjectRoot,
[array]$FoundPackages,
[string]$BuildGeneratedDir
)
# PluginConfig.json file in build/generated folder
$configFile = Join-Path $BuildGeneratedDir 'PluginConfig.json'
if ($FoundPackages.Count -eq 0) {
Write-ColorOutput 'No ReactPackage implementations found, skipping PluginConfig.json update' 'Yellow'
return
}
Write-ColorOutput 'Updating reactPackages field in build/generated folder''s PluginConfig.json...' 'Blue'
try {
# Check if PluginConfig.json exists in build/generated folder
if (-not (Test-Path $configFile)) {
# If not exists, copy from project root
$rootConfigFile = Join-Path $ProjectRoot 'PluginConfig.json'
if (Test-Path $rootConfigFile) {
Copy-Item $rootConfigFile $configFile -Force
Write-ColorOutput 'Copied PluginConfig.json from project root to build/generated folder' 'Blue'
}
else {
Write-ColorOutput 'PluginConfig.json file not found in both project root and build/generated folder' 'Red'
return
}
}
$config = Get-Content $configFile -Raw | ConvertFrom-Json
# Convert PSCustomObject to Hashtable for modification
$configHash = @{}
$config.PSObject.Properties | ForEach-Object { $configHash[$_.Name] = $_.Value }
# Add or update reactPackages field - ensure always in array format
if ($FoundPackages.Count -eq 1) {
# Force convert to array when only one element to avoid PowerShell converting to string
$configHash.reactPackages = @($FoundPackages)
} else {
$configHash.reactPackages = $FoundPackages
}
# Convert back to JSON and save
$configHash | ConvertTo-Json -Depth 10 | Set-Content $configFile -Encoding UTF8
Write-ColorOutput 'PluginConfig.json in build/generated folder updated with reactPackages field' 'Green'
}
catch {
Write-ColorOutput "Failed to update PluginConfig.json in build/generated folder: $_" 'Red'
}
}
# Find ReactPackage implementations in specified directory
function Find-PackagesInDirectory {
param(
[string]$SearchDir,
[string]$ResultFile,
[ref]$FoundPackages
)
if (-not (Test-Path $SearchDir)) {
return
}
# Find ReactPackage implementations in Java and Kotlin files
$javaFiles = Get-ChildItem -Path $SearchDir -Recurse -Filter '*.java' -File -ErrorAction SilentlyContinue
$ktFiles = Get-ChildItem -Path $SearchDir -Recurse -Filter '*.kt' -File -ErrorAction SilentlyContinue
$sourceFiles = @()
if ($javaFiles) { $sourceFiles += $javaFiles }
if ($ktFiles) { $sourceFiles += $ktFiles }
foreach ($file in $sourceFiles) {
try {
$content = Get-Content $file.FullName -Raw -ErrorAction SilentlyContinue
$isKotlin = ([System.IO.Path]::GetExtension($file.FullName)).ToLower() -eq '.kt'
$matchesClass = $false
$className = $null
$packageName = $null
if ($isKotlin) {
if ($content -match 'class\s+([A-Za-z0-9_]+)\s*:\s*[^\{\n]*\b(ReactPackage|TurboReactPackage|BaseReactPackage|ViewManagerOnDemandReactPackage)\b') {
$matchesClass = $true
$className = $matches[1].Trim()
}
if ($content -match 'package\s+([^\s;]+)') {
$packageName = $matches[1].Trim()
}
} else {
if ($content -match '(implements\s+(ReactPackage|ViewManagerOnDemandReactPackage)|extends\s+(ReactPackage|TurboReactPackage|BaseReactPackage))') {
$matchesClass = $true
}
if ($content -match 'class\s+([A-Za-z0-9_]+)') {
$className = $matches[1].Trim()
}
if ($content -match 'package\s+([^;]+);') {
$packageName = $matches[1].Trim()
}
}
if ($matchesClass -and $packageName -and $className) {
$fullClassName = "$packageName.$className"
Write-ColorOutput " - Found ReactPackage implementation: $fullClassName" 'Green'
Add-Content $ResultFile " - $fullClassName"
$FoundPackages.Value += $fullClassName
Write-Host "Added to file: $fullClassName"
}
}
catch {
continue
}
}
}
<#
Function: Is-IgnoredModuleName
Purpose: Determine whether a node_modules module should be ignored (RN official libraries and specified modules)
Input: moduleName - module name, either '@scope/name' or 'name'
Output: [bool] ignore flag
#>
function Is-IgnoredModuleName {
param([string]$moduleName)
if (-not $moduleName) { return $false }
$lower = $moduleName.ToLower()
if ($lower -eq 'react-native') { return $true }
if ($lower -eq 'react') { return $true }
if ($lower -eq 'sn-plugin-lib') { return $true }
if ($lower -like '@react-native*') { return $true }
if ($lower -like '@react-navigation*') { return $true }
return $false
}
<#
Function: Find-ProjectReactPackages
Purpose: Scan project sources (android and app\android) to collect ReactPackage/TurboReactPackage implementation classes
Input: ProjectRoot - project root path
Output: [string[]] fully-qualified ReactPackage class names
#>
function Find-ProjectReactPackages {
param([string]$ProjectRoot)
$resultFile = Join-Path $ProjectRoot 'android_project_react_packages.txt'
'ReactPackage implementations in project:' | Set-Content $resultFile -Encoding UTF8
$foundPackages = @()
$androidDir = Join-Path $ProjectRoot 'android'
if (Test-Path $androidDir) {
Find-PackagesInDirectory -SearchDir $androidDir -ResultFile $resultFile -FoundPackages ([ref]$foundPackages)
}
$appAndroidDir = Join-Path $ProjectRoot 'app\android'
if (Test-Path $appAndroidDir) {
Find-PackagesInDirectory -SearchDir $appAndroidDir -ResultFile $resultFile -FoundPackages ([ref]$foundPackages)
}
$foundPackages = $foundPackages | Sort-Object -Unique
Write-ColorOutput "Detected ReactPackage/TurboReactPackage classes in project: $($foundPackages.Count)" 'Blue'
foreach ($pkg in $foundPackages) { Write-ColorOutput " - $pkg" 'Green' }
return $foundPackages
}
<#
Function: Scan-NodeModulesNativeCode
Purpose: Scan node_modules for third-party dependencies containing Java/Kotlin sources (ignore RN official libraries and sn-plugin-lib)
Input: ProjectRoot - project root path
Output: [string[]] third-party module names that include native sources
#>
function Scan-NodeModulesNativeCode {
param([string]$ProjectRoot)
$nodeModulesDir = Join-Path $ProjectRoot 'node_modules'
$modsWithNative = @()
if (-not (Test-Path $nodeModulesDir)) { return $modsWithNative }
$topDirs = Get-ChildItem -Path $nodeModulesDir -Directory -ErrorAction SilentlyContinue
foreach ($dir in $topDirs) {
if ($dir.Name -like '@*') {
$scoped = Get-ChildItem -Path $dir.FullName -Directory -ErrorAction SilentlyContinue
foreach ($sub in $scoped) {
$moduleName = "$($dir.Name)/$($sub.Name)"
if (Is-IgnoredModuleName -moduleName $moduleName) { continue }
$moduleRoot = $sub.FullName
$dirsToScan = @()
$dirsToScan += (Join-Path $moduleRoot 'android')
$dirsToScan += (Join-Path $moduleRoot 'platforms\android')
$dirsToScan += (Join-Path $moduleRoot 'platforms\android-native')
$hasNative = $false
foreach ($scanDir in $dirsToScan) {
if (Test-Path $scanDir) {
$javaFiles = Get-ChildItem -Path $scanDir -Recurse -Filter '*.java' -File -ErrorAction SilentlyContinue
$ktFiles = Get-ChildItem -Path $scanDir -Recurse -Filter '*.kt' -File -ErrorAction SilentlyContinue
if (($javaFiles -and $javaFiles.Count -gt 0) -or ($ktFiles -and $ktFiles.Count -gt 0)) { $hasNative = $true; break }
}
}
if ($hasNative) {
$modsWithNative += $moduleName
Write-ColorOutput "Third-party module contains Android sources: $moduleName" 'Yellow'
}
}
} else {
$moduleName = $dir.Name
if (Is-IgnoredModuleName -moduleName $moduleName) { continue }
$moduleRoot = $dir.FullName
$dirsToScan = @()
$dirsToScan += (Join-Path $moduleRoot 'android')
$dirsToScan += (Join-Path $moduleRoot 'platforms\android')
$dirsToScan += (Join-Path $moduleRoot 'platforms\android-native')
$hasNative = $false
foreach ($scanDir in $dirsToScan) {
if (Test-Path $scanDir) {
$javaFiles = Get-ChildItem -Path $scanDir -Recurse -Filter '*.java' -File -ErrorAction SilentlyContinue
$ktFiles = Get-ChildItem -Path $scanDir -Recurse -Filter '*.kt' -File -ErrorAction SilentlyContinue
if (($javaFiles -and $javaFiles.Count -gt 0) -or ($ktFiles -and $ktFiles.Count -gt 0)) { $hasNative = $true; break }
}
}
if ($hasNative) {
$modsWithNative += $moduleName
Write-ColorOutput "Third-party module contains Android sources: $moduleName" 'Yellow'
}
}
}
$modsWithNative = $modsWithNative | Sort-Object -Unique
Write-ColorOutput "Third-party dependencies with Android sources: $($modsWithNative.Count)" 'Blue'
return $modsWithNative
}
<#
Function: Find-ManualReactPackagesFromApplication
Purpose: Parse Application classes to extract ReactPackage/TurboReactPackage added via getPackages/add
Input: ProjectRoot - project root path
Output: [string[]] fully-qualified class names manually added
#>
function Find-ManualReactPackagesFromApplication {
param([string]$ProjectRoot)
$dirsToScan = @()
$dirsToScan += (Join-Path $ProjectRoot 'android\app\src\main\java')
$dirsToScan += (Join-Path $ProjectRoot 'android\src\main\java')
$dirsToScan += (Join-Path $ProjectRoot 'app\android\src\main\java')
$found = @()
foreach ($dir in $dirsToScan) {
if (-not (Test-Path $dir)) { continue }
$files = @()
$files += (Get-ChildItem -Path $dir -Recurse -Filter '*.kt' -File -ErrorAction SilentlyContinue)
$files += (Get-ChildItem -Path $dir -Recurse -Filter '*.java' -File -ErrorAction SilentlyContinue)
foreach ($f in $files) {
try {
$text = Get-Content $f.FullName -Raw -ErrorAction SilentlyContinue
# 去除注释,避免匹配示例代码
$text = ($text -replace '(?m)^\s*//.*$', '')
$text = ($text -replace '(?s)/\*.*?\*/', '')
$packageName = $null
if ($text -match '(?m)^\s*package\s+([^\s;]+)') {
$packageName = $matches[1].Trim()
}
$imports = @{}
foreach ($imp in ($text -split "`r?`n")) {
if ($imp -match '^\s*import\s+([^\s;]+)') {
$fq = $matches[1].Trim()
$short = $fq.Split('.')[-1]
$imports[$short] = $fq
}
}
$resolveFqcn = {
param([string]$name)
if ($name -like '*.*') { return $name }
if ($imports.ContainsKey($name)) { return $imports[$name] }
if ($packageName) { return "$packageName.$name" }
return $name
}
$varToClass = @{}
$matchesKotlinAssign = [System.Text.RegularExpressions.Regex]::Matches($text, '(?m)\b(?:val|var)\s+([A-Za-z0-9_]+)\s*=\s*([A-Za-z0-9_\.]+)\s*\(')
foreach ($m in $matchesKotlinAssign) {
$varName = $m.Groups[1].Value
$className = $m.Groups[2].Value
if (-not [string]::IsNullOrWhiteSpace($varName) -and -not [string]::IsNullOrWhiteSpace($className)) {
$varToClass[$varName] = (& $resolveFqcn $className)
}
}
$matchesJavaTypedAssign = [System.Text.RegularExpressions.Regex]::Matches($text, '(?m)\b([A-Za-z0-9_\.]+)\s+([A-Za-z0-9_]+)\s*=\s*new\s+([A-Za-z0-9_\.]+)\s*\(')
foreach ($m in $matchesJavaTypedAssign) {
$varName = $m.Groups[2].Value
$className = $m.Groups[3].Value
if (-not [string]::IsNullOrWhiteSpace($varName) -and -not [string]::IsNullOrWhiteSpace($className)) {
$varToClass[$varName] = (& $resolveFqcn $className)
}
}
$matchesJavaAssign = [System.Text.RegularExpressions.Regex]::Matches($text, '(?m)\b([A-Za-z0-9_]+)\s*=\s*new\s+([A-Za-z0-9_\.]+)\s*\(')
foreach ($m in $matchesJavaAssign) {
$varName = $m.Groups[1].Value
$className = $m.Groups[2].Value
if (-not [string]::IsNullOrWhiteSpace($varName) -and -not [string]::IsNullOrWhiteSpace($className)) {
$varToClass[$varName] = (& $resolveFqcn $className)
}
}
# Kotlin add(ClassName()) 或 packages.add(ClassName())
$matchesKotlin = [System.Text.RegularExpressions.Regex]::Matches($text, '\badd\(\s*([A-Za-z0-9_\.]+)\s*\(')
foreach ($m in $matchesKotlin) {
$name = $m.Groups[1].Value
$fqcn = (& $resolveFqcn $name)
if ($fqcn -match 'Package$') { $found += $fqcn }
}
$matchesKotlinVar = [System.Text.RegularExpressions.Regex]::Matches($text, '\badd\(\s*([A-Za-z0-9_]+)\s*\)')
foreach ($m in $matchesKotlinVar) {
$varName = $m.Groups[1].Value
if ($varToClass.ContainsKey($varName)) {
$fqcn = $varToClass[$varName]
if ($fqcn -match 'Package$') { $found += $fqcn }
}
}
# Java packages.add(new ClassName()) 或 add(new ClassName())
$matchesJava = [System.Text.RegularExpressions.Regex]::Matches($text, '\b(?:packages\.)?add\(\s*new\s+([A-Za-z0-9_\.]+)\s*\(')
foreach ($m in $matchesJava) {
$name = $m.Groups[1].Value
$fqcn = (& $resolveFqcn $name)
if ($fqcn -match 'Package$') { $found += $fqcn }
}
$matchesJavaVar = [System.Text.RegularExpressions.Regex]::Matches($text, '\b(?:packages\.)?add\(\s*(?!new\b)([A-Za-z0-9_]+)\s*\)')
foreach ($m in $matchesJavaVar) {
$varName = $m.Groups[1].Value
if ($varToClass.ContainsKey($varName)) {
$fqcn = $varToClass[$varName]
if ($fqcn -match 'Package$') { $found += $fqcn }
}
}
} catch { continue }
}
}
$found = $found | Sort-Object -Unique
Write-ColorOutput "Manually added packages in Application: $($found.Count)" 'Blue'
foreach ($pkg in $found) { Write-ColorOutput " - $pkg" 'Green' }
return $found
}
<#
Function: Get-ReactPackagesFromAutolinkingSource
Purpose: Parse autolinking-generated PackageList.java to extract getPackages entries and filter specified package names
Input: ProjectRoot - project root path; Exclude - array of package names to exclude
Output: [string[]] filtered fully-qualified package names
#>
function Get-ReactPackagesFromAutolinkingSource {
param([string]$ProjectRoot, [string[]]$Exclude)
$srcFile = Join-Path $ProjectRoot 'android\app\build\generated\autolinking\src\main\java\com\facebook\react\PackageList.java'
if (-not (Test-Path $srcFile)) {
Write-ColorOutput "Autolinking PackageList.java not found: $srcFile" 'Yellow'
return @()
}
try {
$text = Get-Content $srcFile -Raw
# Build import map
$imports = @{}
foreach ($line in ($text -split "`r?`n")) {
if ($line -match '^\s*import\s+([^\s;]+)') {
$fq = $matches[1].Trim()
$short = $fq.Split('.')[-1]
$imports[$short] = $fq
}
}
# Extract new ClassName() occurrences
$matchesNew = [System.Text.RegularExpressions.Regex]::Matches($text, 'new\s+([A-Za-z0-9_\.]+)\s*\(')
$pkgs = @()
foreach ($m in $matchesNew) {
$name = $m.Groups[1].Value
$fqcn = if ($name -like '*.*') { $name } elseif ($imports.ContainsKey($name)) { $imports[$name] } else { $name }
if ($fqcn -match 'Package$') { $pkgs += $fqcn }
}
$pkgs = $pkgs | Sort-Object -Unique
Write-ColorOutput "Packages extracted from autolinking source: $($pkgs.Count)" 'Blue'
foreach ($p in $pkgs) { Write-ColorOutput " - $p" 'Yellow' }
if ($Exclude -and $Exclude.Count -gt 0) {
$pkgs = $pkgs | Where-Object { $Exclude -notcontains $_ }
}
Write-ColorOutput "Filtered package count: $($pkgs.Count)" 'Blue'
foreach ($p in $pkgs) { Write-ColorOutput " - kept: $p" 'Green' }
return $pkgs
} catch {
Write-ColorOutput "Failed to parse Autolinking PackageList.java: $_" 'Red'
return @()
}
}
# Find ReactPackage implementations
function Find-ReactPackages {
param([string]$ProjectRoot)
Write-ColorOutput 'Starting to find and process dependencies with Android native code...' 'Green'
$resultFile = Join-Path $ProjectRoot 'android_native_deps.txt'
'List of dependencies with Android native code:' | Set-Content $resultFile -Encoding UTF8
# Store found ReactPackage implementation classes
$foundPackages = @()
# Find ReactPackage implementations in current project
$androidDir = Join-Path $ProjectRoot 'android'
if (Test-Path $androidDir) {
Write-ColorOutput 'Finding ReactPackage implementations in current project...' 'Blue'
'' | Add-Content $resultFile
'ReactPackage implementations in current project:' | Add-Content $resultFile
Find-PackagesInDirectory -SearchDir $androidDir -ResultFile $resultFile -FoundPackages ([ref]$foundPackages)
# If app directory exists, search there too
$appAndroidDir = Join-Path $ProjectRoot 'app\android'
if (Test-Path $appAndroidDir) {
Find-PackagesInDirectory -SearchDir $appAndroidDir -ResultFile $resultFile -FoundPackages ([ref]$foundPackages)
}
}
# Find and process dependencies in node_modules directory
$nodeModulesDir = Join-Path $ProjectRoot 'node_modules'
if (Test-Path $nodeModulesDir) {
Write-ColorOutput 'Finding ReactPackage implementations in node_modules...' 'Blue'
'' | Add-Content $resultFile
'ReactPackage implementations in node_modules:' | Add-Content $resultFile
$candidateModules = Get-ChildItem -Path $nodeModulesDir -Directory
foreach ($moduleDir in $candidateModules) {
$moduleName = $moduleDir.Name
if ($moduleName -eq 'sn-plugin-lib') { continue }
$depName = "node_modules/$moduleName"
$dirsToScan = @()
$moduleAndroidDir = Join-Path $moduleDir.FullName 'android'
$platformsAndroidDir = Join-Path $moduleDir.FullName 'platforms\android'
$platformsAndroidNativeDir = Join-Path $moduleDir.FullName 'platforms\android-native'
$moduleAndroidGradle = Join-Path $moduleAndroidDir 'build.gradle'
$platformsAndroidGradle = Join-Path $platformsAndroidDir 'build.gradle'
$platformsAndroidNativeGradle = Join-Path $platformsAndroidNativeDir 'build.gradle'
if (Test-Path $moduleAndroidGradle) { $dirsToScan += $moduleAndroidDir }
if (Test-Path $platformsAndroidGradle) { $dirsToScan += $platformsAndroidDir }
if (Test-Path $platformsAndroidNativeGradle) { $dirsToScan += $platformsAndroidNativeDir }
if ($dirsToScan.Count -gt 0) {
Write-ColorOutput "Processing dependency: $depName" 'Yellow'
'' | Add-Content $resultFile
"$depName`:" | Add-Content $resultFile
foreach ($scanDir in $dirsToScan) {
Find-PackagesInDirectory -SearchDir $scanDir -ResultFile $resultFile -FoundPackages ([ref]$foundPackages)
}
}
}
}
Write-ColorOutput 'All dependencies processed!' 'Blue'
Write-ColorOutput "Results saved to: $resultFile" 'Blue'
Write-ColorOutput 'Final results:' 'Yellow'
Get-Content $resultFile | Write-Host
return $foundPackages
}
# Execute Gradle build to generate APK (optionally enforcing reactPackages check)
function Build-AndroidApk {
param(
[string]$ProjectRoot,
[string]$BuildGeneratedConfigFile,
[bool]$RequireReactPackagesCheck = $false
)
if ($RequireReactPackagesCheck) {
try {
$config = Get-Content $BuildGeneratedConfigFile -Raw | ConvertFrom-Json
if (-not $config.reactPackages) {
Write-ColorOutput 'No reactPackages field in build/generated folder''s PluginConfig.json, skipping APK build' 'Yellow'
return $false
}
}
catch {
Write-ColorOutput 'No reactPackages field in build/generated folder''s PluginConfig.json, skipping APK build' 'Yellow'
return $false
}
}
Write-ColorOutput 'Starting gradle build script to generate APK...' 'Blue'
# Switch to android directory
$androidDir = Join-Path $ProjectRoot 'android'
if (-not (Test-Path $androidDir)) {
Write-ColorOutput 'Cannot find android directory' 'Red'
return $false
}
$currentDir = Get-Location
try {
Set-Location $androidDir
# Execute gradle build - use custom buildCustomApkDebug task
$gradlewPath = Join-Path $androidDir 'gradlew.bat'
if (Test-Path $gradlewPath) {
Write-ColorOutput 'Using gradlew.bat to execute buildCustomApkDebug task...' 'Green'
# Ensure JAVA_HOME environment variable is set
if (-not $env:JAVA_HOME) {
Write-ColorOutput 'JAVA_HOME environment variable not set, trying to find Java installation...' 'Yellow'
# Try to find Java from registry or common paths
$javaPath = Get-ChildItem 'C:\Program Files\Java' -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like 'jdk*' } |
Sort-Object Name -Descending |
Select-Object -First 1
if ($javaPath) {
$env:JAVA_HOME = $javaPath.FullName
Write-ColorOutput "Set JAVA_HOME to: $($env:JAVA_HOME)" 'Green'
}
else {
Write-ColorOutput 'Java installation not found, please ensure JAVA_HOME environment variable is set' 'Red'
return $false
}
}
# Execute gradle build
$process = Start-Process -FilePath 'cmd.exe' -ArgumentList '/c', 'gradlew.bat', 'buildCustomApkDebug' -Wait -PassThru -NoNewWindow
$buildResult = $process.ExitCode
}
elseif (Get-Command 'gradle' -ErrorAction SilentlyContinue) {
Write-ColorOutput 'Using gradle to execute buildCustomApkDebug task...' 'Green'
$process = Start-Process -FilePath 'gradle' -ArgumentList 'buildCustomApkDebug' -Wait -PassThru -NoNewWindow
$buildResult = $process.ExitCode
}
else {
Write-ColorOutput 'Neither gradle nor gradlew.bat found, cannot build APK' 'Red'
return $false
}
if ($buildResult -eq 0) {
Write-ColorOutput 'APK build successful' 'Green'
return $true
}
else {
Write-ColorOutput 'APK build failed' 'Red'
return $false
}
}
finally {
Set-Location $currentDir
}
}
# Copy APK file and update nativeCodePackage field
function Copy-ApkAndUpdateConfig {
param([string]$ProjectRoot, [string]$BuildGeneratedDir, [string]$BuildGeneratedConfigFile)
# Find generated APK file - prioritize custom APK
$apkSearchPath = Join-Path $ProjectRoot 'android\app\build\outputs\apk'
# First look for custom APK files
$customApkFiles = Get-ChildItem -Path $apkSearchPath -Recurse -Filter '*custom*.apk' -ErrorAction SilentlyContinue
$apkPath = $null
if ($customApkFiles) {
$apkPath = $customApkFiles[0].FullName
Write-ColorOutput "Found custom APK file: $apkPath" 'Green'
}
else {
# If no custom APK found, look for other APK files
$apkFiles = Get-ChildItem -Path $apkSearchPath -Recurse -Filter '*.apk' -ErrorAction SilentlyContinue
if ($apkFiles) {
$apkPath = $apkFiles[0].FullName
Write-ColorOutput "Found APK file: $apkPath" 'Green'
}
}
if (-not $apkPath -or -not (Test-Path $apkPath)) {
Write-ColorOutput 'Generated APK file not found' 'Red'
return $false
}
# Copy APK file to build/generated folder and rename to app.npk
$newApkFileName = 'app.npk'
$targetApkPath = Join-Path $BuildGeneratedDir $newApkFileName
try {
Copy-Item $apkPath $targetApkPath -Force
Write-ColorOutput "APK file copied and renamed to build/generated folder: $targetApkPath" 'Green'
# Check if PluginConfig.json exists in build/generated folder
if (-not (Test-Path $BuildGeneratedConfigFile)) {
# If not exists, copy from project root
$rootConfigFile = Join-Path $ProjectRoot 'PluginConfig.json'
if (Test-Path $rootConfigFile) {
Copy-Item $rootConfigFile $BuildGeneratedConfigFile -Force
Write-ColorOutput 'Copied PluginConfig.json from project root to build/generated folder' 'Blue'
}
else {
Write-ColorOutput 'PluginConfig.json file not found in both project root and build/generated folder' 'Red'
return $false
}
}
# Update nativeCodePackage field in build/generated folder's PluginConfig.json
$config = Get-Content $BuildGeneratedConfigFile -Raw | ConvertFrom-Json
# Convert PSCustomObject to Hashtable for modification
$configHash = @{}
$config.PSObject.Properties | ForEach-Object { $configHash[$_.Name] = $_.Value }
# Add or update nativeCodePackage field using relative path format
$configHash.nativeCodePackage = "/$newApkFileName"
# Convert back to JSON and save
$configHash | ConvertTo-Json -Depth 10 | Set-Content $BuildGeneratedConfigFile -Encoding UTF8
Write-ColorOutput "PluginConfig.json in build/generated folder updated with nativeCodePackage field: /$newApkFileName" 'Green'
return $true
}
catch {
Write-ColorOutput "Failed to copy APK file or update configuration: $_" 'Red'
return $false
}
}
# Execute React Native bundling command
function Build-ReactNativeBundle {
param([string]$ProjectRoot, [string]$ProjectName, [string]$OutputDir)
Write-ColorOutput 'Starting React Native bundling...' 'Blue'
# Build bundle output path and assets directory
$bundleOutput = Join-Path $OutputDir "$ProjectName.bundle"
$assetsDir = $OutputDir
# Build npx command
$bundleCommand = "npx react-native bundle --entry-file index.js --bundle-output `"$bundleOutput`" --platform android --assets-dest `"$assetsDir`" --dev false"
Write-ColorOutput "Executing command: $bundleCommand" 'Yellow'
try {
# Execute bundling command
$process = Start-Process -FilePath 'cmd.exe' -ArgumentList '/c', $bundleCommand -Wait -PassThru -NoNewWindow -WorkingDirectory $ProjectRoot
if ($process.ExitCode -eq 0) {
Write-ColorOutput 'React Native bundling successful' 'Green'
Write-ColorOutput "Bundle file generated: $bundleOutput" 'Green'
return $true
} else {
Write-ColorOutput "React Native bundling failed, exit code: $($process.ExitCode)" 'Red'
return $false
}
}
catch {
Write-ColorOutput "Error occurred while executing React Native bundle command: $_" 'Red'
return $false
}
}
# Parse PackageList.class and extract ReactPackage list from getPackages
# Parse PackageList.class and extract ReactPackage list from getPackages
<#
Function: Get-ReactPackagesFromPackageListClass
Purpose: Use javap to parse PackageList.class getPackages and extract ReactPackage class names
Input: ClassesDir - classes root directory
Output: [string[]] fully-qualified ReactPackage class names
#>
function Get-ReactPackagesFromPackageListClass {
param([string]$ClassesDir)
$classFile = Join-Path $ClassesDir 'com\facebook\react\PackageList.class'
if (-not (Test-Path $classFile)) {
Write-ColorOutput "PackageList.class not found: $classFile" 'Yellow'
return @()
}
try {
$output = & javap -classpath $ClassesDir -verbose com.facebook.react.PackageList 2>&1
$lines = $output -split "`r?`n"
$pkgs = @()
foreach ($line in $lines) {
if ($line -match 'new\s+#\d+\s+//\s+class\s+([\w/\.\-$]+)') {
$raw = $matches[1]
$normalized = $raw.Replace('/', '.')
if ($normalized -notmatch '^java\.' -and $normalized -notmatch '^android\.') {
if ($normalized -match 'Package$') { $pkgs += $normalized }
}
}
}
$pkgs = $pkgs | Sort-Object -Unique
return $pkgs
}
catch {
Write-ColorOutput "Failed to parse PackageList.class via javap: $_" 'Red'
return @()
}
}
<#
Function: Find-ReactPackagesInClassesDir
Purpose: Scan classes directory for classes implementing/extending ReactPackage/TurboReactPackage/BaseReactPackage/ViewManagerOnDemandReactPackage
Input: ClassesDir - classes root directory
Output: [string[]] fully-qualified ReactPackage-related class names
#>
function Find-ReactPackagesInClassesDir {
param([string]$ClassesDir)
if (-not (Test-Path $ClassesDir)) { return @() }
$classFiles = Get-ChildItem -Path $ClassesDir -Recurse -Filter '*.class' -ErrorAction SilentlyContinue
$found = @()
$hasJavap = Get-Command 'javap' -ErrorAction SilentlyContinue
foreach ($file in $classFiles) {
try {
$relative = $file.FullName.Substring($ClassesDir.Length).TrimStart('\\','/')
$fqcn = $relative.Replace('\\','.').Replace('/','.').Replace('.class','')
if ([string]::IsNullOrWhiteSpace($fqcn)) { continue }
if ($hasJavap) {
$out = & javap -classpath $ClassesDir $fqcn 2>&1
$text = ($out | Out-String)
if ($text -match 'implements\s+com\.facebook\.react\.ReactPackage' -or
$text -match 'extends\s+com\.facebook\.react\.TurboReactPackage' -or
$text -match 'extends\s+com\.facebook\.react\.BaseReactPackage' -or
$text -match 'implements\s+com\.facebook\.react\.uimanager\.ViewManagerOnDemandReactPackage') {
if ($fqcn -notmatch '^java\.' -and $fqcn -notmatch '^android\.') { $found += $fqcn }
}
} else {
$bytes = [System.IO.File]::ReadAllBytes($file.FullName)
$ascii = [System.Text.Encoding]::ASCII.GetString($bytes)
if ($ascii -match 'com/facebook/react/ReactPackage' -or
$ascii -match 'com/facebook/react/TurboReactPackage' -or
$ascii -match 'com/facebook/react/BaseReactPackage' -or
$ascii -match 'com/facebook/react/uimanager/ViewManagerOnDemandReactPackage') {
if ($fqcn -notmatch '^java\.' -and $fqcn -notmatch '^android\.') { $found += $fqcn }
}
}
} catch { continue }
}
$found = $found | Sort-Object -Unique
return $found
}
# Copy icon file and update iconPath field
function Copy-IconAndUpdatePath {
param([string]$ProjectRoot, [string]$BuildGeneratedDir, [string]$BuildGeneratedConfigFile)
Write-ColorOutput 'Checking and copying icon file...' 'Blue'
try {
# Read PluginConfig.json from project root
$rootConfigFile = Join-Path $ProjectRoot 'PluginConfig.json'
$rootConfig = Get-Content $rootConfigFile -Raw | ConvertFrom-Json
if ($rootConfig.iconPath -and $rootConfig.iconPath -ne '') {
$iconPath = $rootConfig.iconPath
Write-ColorOutput "Detected icon path: $iconPath" 'Yellow'
# Handle relative and absolute paths
if ([System.IO.Path]::IsPathRooted($iconPath)) {
# Absolute path
$sourceIconPath = $iconPath
} else {
# Relative path, relative to project root
$sourceIconPath = Join-Path $ProjectRoot $iconPath
}
if (Test-Path $sourceIconPath) {
# Get icon file name