This repository was archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 439
/
Copy pathinstaller.js
executable file
·1073 lines (944 loc) · 46.2 KB
/
installer.js
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
var fs = require('fs');
var path = require('path');
var prompt = require('prompt-lite');
// Default settings for a few prompts
var usingiOS = false, usingAndroid = false, externalPushClient = false;
// The directories where the Podfile and include.gradle are stored
var directories = {
ios: './platforms/ios',
android: './platforms/android'
};
console.log('NativeScript Firebase Plugin Installation');
var appRoot = "../../../";
var pluginConfigFile = "firebase.nativescript.json";
var pluginConfigPath = path.join(appRoot, pluginConfigFile);
var config = {};
function mergeConfig(result) {
for (var key in result) {
config[key] = isSelected(result[key]);
}
// note that the semantics of "external_push_client_only" changed to "external push client" with plugin version 10.1.0
externalPushClient = isSelected(config["external_push_client_only"]);
}
function saveConfig() {
fs.writeFileSync(pluginConfigPath, JSON.stringify(config, null, 4));
}
function readConfig() {
try {
config = JSON.parse(fs.readFileSync(pluginConfigPath));
externalPushClient = isSelected(config["external_push_client_only"]);
} catch (e) {
console.log("Failed reading " + pluginConfigFile);
console.log(e);
config = {};
}
}
function isInteractive() {
return process.stdin && process.stdin.isTTY && process.stdout && process.stdout.isTTY;
}
// note that for CI builds you want a pluginConfigFile, otherwise the build will fail
if (process.argv.indexOf("config") === -1 && fs.existsSync(pluginConfigPath)) {
readConfig();
console.log("Config file exists (" + pluginConfigFile + ")");
askiOSPromptResult(config);
askAndroidPromptResult(config);
promptQuestionsResult(config);
} else if (!isInteractive()) {
console.log("No existing " + pluginConfigFile + " config file found and terminal is not interactive! Default configuration will be used.");
} else {
console.log("No existing " + pluginConfigFile + " config file found, so let's configure the Firebase plugin!");
prompt.start();
askiOSPrompt();
}
/**
* Prompt the user if they are integrating Firebase with iOS
*/
function askiOSPrompt() {
prompt.get({
name: 'using_ios',
description: 'Are you using iOS (y/n)',
default: 'y'
}, function (err, result) {
if (err) {
return console.log(err);
}
mergeConfig(result);
askiOSPromptResult(result);
askAndroidPrompt();
});
}
function askiOSPromptResult(result) {
if (isSelected(result.using_ios)) {
usingiOS = true;
}
}
/**
* Prompt the user if they are integrating Firebase with Android
*/
function askAndroidPrompt() {
prompt.get({
name: 'using_android',
description: 'Are you using Android (y/n)',
default: 'y'
}, function (err, result) {
if (err) {
return console.log(err);
}
mergeConfig(result);
askAndroidPromptResult(result);
if (usingiOS || usingAndroid) {
promptQuestions();
} else {
askSaveConfigPrompt();
}
});
}
function askAndroidPromptResult(result) {
if (isSelected(result.using_android)) {
usingAndroid = true;
}
}
/**
* Prompt the user through the configurable Firebase add-on services
*/
function promptQuestions() {
prompt.get([{
name: 'analytics',
description: 'Do you want to enable Firebase Analytics? (y/n)',
default: 'y'
}, {
name: 'firestore',
description: 'Are you using Firestore? (y/n)',
default: 'n'
}, {
name: 'realtimedb',
description: 'Are you using Realtime DB? (y/n)',
default: 'n'
}, {
name: 'authentication',
description: 'Are you using Firebase Authentication (pretty likely if you use Firestore or Realtime DB)? (y/n)',
default: 'y'
}, {
name: 'remote_config',
description: 'Are you using Firebase RemoteConfig? (y/n)',
default: 'n'
}, {
name: 'performance_monitoring',
description: 'Are you using Performance Monitoring? (y/n)',
default: 'n'
}, {
name: 'external_push_client_only',
description: 'Are you using this plugin as a Push Notification client for an external (NOT Firebase Cloud Messaging) Push service? (y/n)',
default: 'n'
}, {
name: 'messaging',
description: 'Are you using Firebase Cloud Messaging? (y/n)',
default: 'n'
}, {
name: 'in_app_messaging',
description: 'Are you using In-App Messaging? (y/n)',
default: 'n'
}, {
name: 'crashlytics',
description: 'Are you using Firebase Crashlytics? (y/n)',
default: 'n'
}, {
name: 'storage',
description: 'Are you using Firebase Storage? (y/n)',
default: 'n'
}, {
name: 'functions',
description: 'Are you using Firebase Cloud Functions? (y/n)',
default: 'n'
}, {
name: 'facebook_auth',
description: 'Are you using Firebase Facebook Authentication? (y/n)',
default: 'n'
}, {
name: 'google_auth',
description: 'Are you using Firebase Google Authentication? (y/n)',
default: 'n'
}, {
name: 'admob',
description: 'Are you using AdMob? (y/n)',
default: 'n'
}, {
name: 'dynamic_links',
description: 'Are you using Firebase Dynamic Links? (y/n)',
default: 'n'
}, {
name: 'ml_kit',
description: 'Are you using ML Kit? (y/n)',
default: 'n'
}], function (err, result) {
if (err) {
return console.log(err);
}
if (!isSelected(result.ml_kit)) {
mergeConfig(result);
promptQuestionsResult(result);
askSaveConfigPrompt();
} else {
prompt.get([{
name: 'ml_kit_text_recognition',
description: 'With ML Kit, do you want to recognize text? (y/n)',
default: 'n'
}, {
name: 'ml_kit_barcode_scanning',
description: 'With ML Kit, do you want to scan barcodes? (y/n)',
default: 'n'
}, {
name: 'ml_kit_face_detection',
description: 'With ML Kit, do you want to detect faces? (y/n)',
default: 'n'
}, {
name: 'ml_kit_image_labeling',
description: 'With ML Kit, do you want to label images? (y/n)',
default: 'n'
}, {
name: 'ml_kit_object_detection',
description: 'With ML Kit, do you want to use Object Detection and Tracking? (y/n)',
default: 'n'
}, {
name: 'ml_kit_automl',
description: 'With ML Kit, do you want to use AutoML Vision Edge to label images with your own models? (y/n)',
default: 'n'
}, {
name: 'ml_kit_custom_model',
description: 'With ML Kit, do you want to use a custom TensorFlow Lite model? (y/n)',
default: 'n'
}, {
name: 'ml_kit_natural_language_identification',
description: 'With ML Kit, do you want to recognize natural languages? (y/n)',
default: 'n'
}, {
name: 'ml_kit_natural_language_translation',
description: 'With ML Kit, do you want to translate text? (y/n)',
default: 'n'
}, {
name: 'ml_kit_natural_language_smartreply',
description: 'With ML Kit, do you want to use smart reply? (y/n)',
default: 'n'
}], function (mlkitErr, mlkitResult) {
if (mlkitErr) {
return console.log(mlkitErr);
}
for (var attrname in mlkitResult) {
result[attrname] = mlkitResult[attrname];
}
mergeConfig(result);
promptQuestionsResult(result);
askSaveConfigPrompt();
});
}
});
}
function promptQuestionsResult(result) {
if (usingiOS) {
writePodFile(result);
writeGoogleServiceCopyHook();
writeBuildscriptHookForCrashlytics(isSelected(result.crashlytics));
activateIOSMLKitCameraFramework(isSelected(result.ml_kit));
}
if (usingAndroid) {
writeGradleFile(result);
writeGoogleServiceCopyHook();
writeGoogleServiceGradleHook(result);
echoAndroidManifestChanges(result);
activateAndroidPushNotificationsLib(isSelected(result.messaging) || isSelected(result.external_push_client_only));
activateAndroidMLKitCustomModelLib(isSelected(result.ml_kit) && isSelected(result.ml_kit_custom_model));
}
console.log('Firebase post install completed. To re-run this script, navigate to the root directory of `nativescript-plugin-firebase` in your `node_modules` folder and run: `npm run config`.');
}
function echoAndroidManifestChanges(result) {
if (isSelected(result.ml_kit)) {
var selectedFeatures = [];
if (isSelected(result.ml_kit_text_recognition)) {
selectedFeatures.push("ocr");
}
if (isSelected(result.ml_kit_barcode_scanning)) {
selectedFeatures.push("barcode");
}
if (isSelected(result.ml_kit_face_detection)) {
selectedFeatures.push("face");
}
if (isSelected(result.ml_kit_image_labeling)) {
selectedFeatures.push("label");
}
if (selectedFeatures.length > 0) {
console.log('\n######################################################################################################');
console.log('Open your app\'s resources/Android/AndroidManifest.xml file and add this (see the demo for an example):');
console.log('<meta-data\n' +
' android:name="com.google.firebase.ml.vision.DEPENDENCIES"\n' +
' android:value="' + selectedFeatures.join(',') + '" />');
console.log('######################################################################################################\n');
}
}
}
function activateAndroidPushNotificationsLib(enable) {
if (enable && fs.existsSync(path.join(directories.android, 'firebase-release.aar-disabled'))) {
fs.renameSync(path.join(directories.android, 'firebase-release.aar-disabled'), path.join(directories.android, 'firebase-release.aar'));
} else if (!enable && fs.existsSync(path.join(directories.android, 'firebase-release.aar'))) {
fs.renameSync(path.join(directories.android, 'firebase-release.aar'), path.join(directories.android, 'firebase-release.aar-disabled'));
}
}
function activateAndroidMLKitCustomModelLib(enable) {
if (enable && fs.existsSync(path.join(directories.android, 'nativescript-firebase-mlkit-helper.jar-disabled'))) {
fs.renameSync(path.join(directories.android, 'nativescript-firebase-mlkit-helper.jar-disabled'), path.join(directories.android, 'nativescript-firebase-mlkit-helper.jar'));
} else if (!enable && fs.existsSync(path.join(directories.android, 'nativescript-firebase-mlkit-helper.jar'))) {
fs.renameSync(path.join(directories.android, 'nativescript-firebase-mlkit-helper.jar'), path.join(directories.android, 'nativescript-firebase-mlkit-helper.jar-disabled'));
}
}
function activateIOSMLKitCameraFramework(enable) {
if (enable && fs.existsSync(path.join(directories.ios, 'TNSMLKitCamera.framework-disabled'))) {
fs.renameSync(path.join(directories.ios, 'TNSMLKitCamera.framework-disabled'), path.join(directories.ios, 'TNSMLKitCamera.framework'));
} else if (!enable && fs.existsSync(path.join(directories.ios, 'TNSMLKitCamera.framework'))) {
fs.renameSync(path.join(directories.ios, 'TNSMLKitCamera.framework'), path.join(directories.ios, 'TNSMLKitCamera.framework-disabled'));
}
}
function askSaveConfigPrompt() {
prompt.get({
name: 'save_config',
description: 'Do you want to save the selected configuration. Reinstalling the dependency will reuse the setup from: ' + pluginConfigFile + '. CI will be easier. (y/n)',
default: 'y'
}, function (err, result) {
if (err) {
return console.log(err);
}
if (isSelected(result.save_config)) {
saveConfig();
}
});
}
/**
* Create the iOS PodFile for installing the Firebase iOS dependencies and service dependencies
*
* @param {any} result The answers to the micro-service prompts
*/
function writePodFile(result) {
if (!fs.existsSync(directories.ios)) {
fs.mkdirSync(directories.ios);
}
try {
fs.writeFileSync(directories.ios + '/Podfile',
// The MLVision pod requires a minimum of iOS 9, otherwise the build will fail
(isPresent(result.ml_kit) ? `` : `#`) + `platform :ios, '9.0'
` + (!isSelected(result.external_push_client_only) ? `` : `#`) + `pod 'Firebase/Core', '~>6.34.0'
# Analytics
` + (isSelected(result.analytics) || isSelected(result.crashlytics) || (!isSelected(result.external_push_client_only) && !isPresent(result.analytics)) ? `` : `#`) + `pod 'Firebase/Analytics'
# Authentication
` + (isSelected(result.authentication) || (!isSelected(result.external_push_client_only) && !isPresent(result.external_push_client_only)) ? `` : `#`) + `pod 'Firebase/Auth'
# Realtime DB
` + (isSelected(result.realtimedb) || (!isSelected(result.external_push_client_only) && !isPresent(result.realtimedb)) ? `` : `#`) + `pod 'Firebase/Database'
# Cloud Firestore
` + (isSelected(result.firestore) ? `` : `#`) + `pod 'Firebase/Firestore'
# Remote Config
` + (isSelected(result.remote_config) ? `` : `#`) + `pod 'Firebase/RemoteConfig'
# Performance Monitoring
` + (isSelected(result.performance_monitoring) ? `` : `#`) + `pod 'Firebase/Performance'
# Crashlytics
` + (isSelected(result.crashlytics) ? `` : `#`) + `pod 'Firebase/Crashlytics'
` + (!isSelected(result.crashlytics) ? `` : `
# Crashlytics works best without bitcode
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = "NO"
config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = "YES"
end
end
end`) + `
# Firebase Cloud Messaging (FCM)
` + (isSelected(result.messaging) ? `` : `#`) + `pod 'Firebase/Messaging'
# Firebase In-App Messaging
` + (isSelected(result.in_app_messaging) ? `` : `#`) + `pod 'Firebase/InAppMessaging'
# Firebase Cloud Storage
` + (isSelected(result.storage) ? `` : `#`) + `pod 'Firebase/Storage'
# Firebase Cloud Functions
` + (isSelected(result.functions) ? `` : `#`) + `pod 'Firebase/Functions'
# AdMob
` + (isSelected(result.admob) ? `` : `#`) + `pod 'Firebase/AdMob'
# Dynamic Links
` + (isSelected(result.dynamic_links) ? `` : `#`) + `pod 'Firebase/DynamicLinks'
# ML Kit
` + (isSelected(result.ml_kit) ? `` : `#`) + `pod 'Firebase/MLVision'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_text_recognition) ? `` : `#`) + `pod 'Firebase/MLVisionTextModel'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_barcode_scanning) ? `` : `#`) + `pod 'Firebase/MLVisionBarcodeModel'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_face_detection) ? `` : `#`) + `pod 'Firebase/MLVisionFaceModel'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_image_labeling) ? `` : `#`) + `pod 'Firebase/MLVisionLabelModel'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_object_detection) ? `` : `#`) + `pod 'Firebase/MLVisionObjectDetection'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_custom_model) ? `` : `#`) + `pod 'Firebase/MLModelInterpreter'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_automl) ? `` : `#`) + `pod 'Firebase/MLVisionAutoML'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_natural_language_identification) ? `` : `#`) + `pod 'Firebase/MLNaturalLanguage'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_natural_language_identification) ? `` : `#`) + `pod 'Firebase/MLNLLanguageID'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_natural_language_translation) ? `` : `#`) + `pod 'Firebase/MLNLTranslate'
` + (isSelected(result.ml_kit) && (isSelected(result.ml_kit_natural_language_smartreply) || isSelected(result.ml_kit_natural_language_translation)) ? `` : `#`) + `pod 'Firebase/MLCommon'
` + (isSelected(result.ml_kit) && isSelected(result.ml_kit_natural_language_smartreply) ? `` : `#`) + `pod 'Firebase/MLNLSmartReply'
# Facebook Authentication
` + (isSelected(result.facebook_auth) ? `` : `#`) + `pod 'FBSDKCoreKit'
` + (isSelected(result.facebook_auth) ? `` : `#`) + `pod 'FBSDKLoginKit'
# Google Authentication
` + (isSelected(result.google_auth) ? `` : `#`) + `pod 'GoogleSignIn', '~> 5.0.2'`);
console.log('Successfully created iOS (Pod) file.');
} catch (e) {
console.log('Failed to create iOS (Pod) file.');
console.log(e);
}
}
/**
* Create the iOS build script for uploading dSYM files to Crashlytics
*
* @param {any} enable Is Crashlytics enabled
*/
function writeBuildscriptHookForCrashlytics(enable) {
var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-crashlytics-buildscript.js");
if (!enable) {
if (fs.existsSync(scriptPath)) {
fs.unlinkSync(scriptPath);
}
return
}
console.log("Install Crashlytics buildscript hook.");
try {
var scriptContent =
`const fs = require('fs-extra');
const path = require('path');
const xcode = require('xcode');
const pattern1 = /\\n\\s*\\/\\/Crashlytics 1 BEGIN[\\s\\S]*\\/\\/Crashlytics 1 END.*\\n/m;
const pattern2 = /\\n\\s*\\/\\/Crashlytics 2 BEGIN[\\s\\S]*\\/\\/Crashlytics 2 END.*\\n/m;
const pattern3 = /\\n\\s*\\/\\/Crashlytics 3 BEGIN[\\s\\S]*\\/\\/Crashlytics 3 END.*\\n/m;
const string1 = \`
//Crashlytics 1 BEGIN
#else
#import <FirebaseCrashlytics/FirebaseCrashlytics.h>
#endif
//Crashlytics 1 END
\`;
const string2 = \`
//Crashlytics 2 BEGIN
#if DEBUG
#else
static int redirect_cls(const char *prefix, const char *buffer, int size) {
[[FIRCrashlytics crashlytics] logWithFormat:@"%s: %.*s", prefix, size, buffer];
return size;
}
static int stderr_redirect(void *inFD, const char *buffer, int size) {
return redirect_cls("stderr", buffer, size);
}
static int stdout_redirect(void *inFD, const char *buffer, int size) {
return redirect_cls("stdout", buffer, size);
}
#endif
//Crashlytics 2 END
\`;
const string3 = \`
//Crashlytics 3 BEGIN
#if DEBUG
#else
// Per https://docs.fabric.io/apple/crashlytics/enhanced-reports.html#custom-logs :
// Crashlytics ensures that all log entries are recorded, even if the very next line of code crashes.
// This means that logging must incur some IO. Be careful when logging in performance-critical areas.
// As per the note above, enabling this can affect performance if too much logging is present.
// stdout->_write = stdout_redirect;
// stderr usually only occurs during critical failures;
// so it is usually essential to identifying crashes, especially in JS
stderr->_write = stderr_redirect;
#endif
//Crashlytics 3 END
\`;
module.exports = function($logger, $projectData, hookArgs) {
const platformFromHookArgs = hookArgs && (hookArgs.platform || (hookArgs.prepareData && hookArgs.prepareData.platform));
const platform = (platformFromHookArgs || '').toLowerCase();
return new Promise(function(resolve, reject) {
const isNativeProjectPrepared = hookArgs.prepareData ? (!hookArgs.prepareData.nativePrepare || !hookArgs.prepareData.nativePrepare.skipNativePrepare) : (!hookArgs.nativePrepare || !hookArgs.nativePrepare.skipNativePrepare);
if (isNativeProjectPrepared) {
try {
if (platform === 'ios') {
const sanitizedAppName = path.basename($projectData.projectDir).split('').filter((c) => /[a-zA-Z0-9]/.test(c)).join('');
// write buildscript for dSYM upload
const xcodeProjectPath = path.join($projectData.platformsDir, 'ios', sanitizedAppName + '.xcodeproj', 'project.pbxproj');
$logger.trace('Using Xcode project', xcodeProjectPath);
if (fs.existsSync(xcodeProjectPath)) {
var xcodeProject = xcode.project(xcodeProjectPath);
xcodeProject.parseSync();
// Xcode 10 requires 'inputPaths' set, see https://firebase.google.com/docs/crashlytics/get-started
var options = {
shellPath: '/bin/sh', shellScript: '\"\${PODS_ROOT}/FirebaseCrashlytics/run\"',
inputPaths: ['"\$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)\"']
};
xcodeProject.addBuildPhase(
[], 'PBXShellScriptBuildPhase', 'Configure Crashlytics', undefined, options
).buildPhase;
fs.writeFileSync(xcodeProjectPath, xcodeProject.writeSync());
$logger.trace('Xcode project written');
} else {
$logger.error(xcodeProjectPath + ' is missing.');
reject();
return;
}
// Logging from stdout/stderr
$logger.info('Add iOS crash logging');
const mainmPath = path.join($projectData.platformsDir, 'ios', 'internal', 'main.m');
if (fs.existsSync(mainmPath)) {
let mainmContent = fs.readFileSync(mainmPath).toString();
// string1
mainmContent = pattern1.test(mainmContent)
? mainmContent.replace(pattern1, string1)
: mainmContent.replace(/(\\n#endif\\n)/, string1);
// string2
mainmContent = pattern2.test(mainmContent)
? mainmContent.replace(pattern2, string2)
: mainmContent.replace(/(\\nint main.*)/, string2 + '$1');
// string3
mainmContent = pattern3.test(mainmContent)
? mainmContent.replace(pattern3, string3)
: mainmContent.replace(/(int main.*\\n)/, '$1' + string3 + '\\n');
fs.writeFileSync(mainmPath, mainmContent);
} else {
$logger.error(mainmPath + ' is missing.');
reject();
return;
}
resolve();
} else {
resolve();
}
} catch (e) {
$logger.error('Unknown error during prepare Crashlytics', e);
reject();
}
} else {
$logger.trace("Native project not prepared.");
resolve();
}
});
};
`;
var afterPrepareDirPath = path.dirname(scriptPath);
var hooksDirPath = path.dirname(afterPrepareDirPath);
if (!fs.existsSync(afterPrepareDirPath)) {
if (!fs.existsSync(hooksDirPath)) {
fs.mkdirSync(hooksDirPath);
}
fs.mkdirSync(afterPrepareDirPath);
}
fs.writeFileSync(scriptPath, scriptContent);
} catch (e) {
console.log("Failed to install Crashlytics buildscript hook.");
console.log(e);
}
}
/**
* Create the Android Gradle for installing the Firebase Android dependencies and service dependencies
*
* @param {any} result The answers to the micro-service prompts
*/
function writeGradleFile(result) {
if (!fs.existsSync(directories.android)) {
fs.mkdirSync(directories.android);
}
try {
fs.writeFileSync(directories.android + '/include.gradle',
`
android {
// (possibly-temporary) workaround for https://stackoverflow.com/questions/52518378/more-than-one-file-was-found-with-os-independent-path-meta-inf-proguard-android
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
}
}
repositories {
mavenCentral()
maven {
url "https://maven.google.com"
}
jcenter()
}
dependencies {
def supportVersion = project.hasProperty("supportVersion") ? project.supportVersion : "26.1.0"
def googlePlayServicesVersion = project.hasProperty('googlePlayServicesVersion') ? project.googlePlayServicesVersion : "16.0.1"
if (googlePlayServicesVersion != '+' && org.gradle.util.VersionNumber.parse(googlePlayServicesVersion) < org.gradle.util.VersionNumber.parse('15.0.+')) {
throw new GradleException(" googlePlayServicesVersion set too low, please update to at least 15.0.0 / 15.0.+ (currently set to $googlePlayServicesVersion)");
}
implementation "com.android.support:appcompat-v7:$supportVersion"
implementation "com.android.support:cardview-v7:$supportVersion"
implementation "com.android.support:customtabs:$supportVersion"
implementation "com.android.support:design:$supportVersion"
implementation "com.android.support:support-compat:$supportVersion"
// make sure you have these versions by updating your local Android SDK's (Android Support repo and Google repo)
` + (isSelected(result.analytics) || (!isSelected(result.external_push_client_only) && !isPresent(result.analytics)) ? `` : `//`) + ` implementation "com.google.firebase:firebase-analytics:17.2.2"
// for reading google-services.json and configuration
implementation "com.google.android.gms:play-services-base:$googlePlayServicesVersion"
// Authentication
` + (isSelected(result.authentication) || (!isSelected(result.external_push_client_only) && !isPresent(result.authentication)) ? `` : `//`) + ` implementation "com.google.firebase:firebase-auth:19.2.0"
// Realtime DB
` + (isSelected(result.realtimedb) || (!isSelected(result.external_push_client_only) && !isPresent(result.realtimedb)) ? `` : `//`) + ` implementation "com.google.firebase:firebase-database:19.2.1"
// Cloud Firestore
` + (isSelected(result.firestore) ? `` : `//`) + ` implementation "com.google.firebase:firebase-firestore:21.4.0"
// Remote Config
` + (isSelected(result.remote_config) ? `` : `//`) + ` implementation "com.google.firebase:firebase-config:19.1.1"
// Performance Monitoring
` + (isSelected(result.performance_monitoring) ? `` : `//`) + ` implementation "com.google.firebase:firebase-perf:19.0.5"
// Crashlytics
` + (isSelected(result.crashlytics) ? `` : `//`) + ` implementation "com.google.firebase:firebase-crashlytics:17.2.2"
// Cloud Messaging (FCM)
` + (isSelected(result.messaging) || isSelected(result.external_push_client_only) ? `` : `//`) + ` implementation "com.google.firebase:firebase-messaging:20.1.0"
// ` + (isSelected(result.messaging) || isSelected(result.external_push_client_only) ? `` : `//`) + ` implementation "me.leolin:ShortcutBadger:1.1.22@aar"
// In-App Messaging
` + (isSelected(result.in_app_messaging) ? `` : `//`) + ` implementation "com.google.firebase:firebase-inappmessaging-display:19.0.3"
// Analytics seems to be required for In-App Messaging
` + (isSelected(result.in_app_messaging) && !isSelected(result.analytics) ? `` : `//`) + ` implementation "com.google.firebase:firebase-analytics:17.2.2"
// Cloud Storage
` + (isSelected(result.storage) ? `` : `//`) + ` implementation "com.google.firebase:firebase-storage:19.1.1"
// Cloud Functions
` + (isSelected(result.functions) ? `` : `//`) + ` implementation "com.google.firebase:firebase-functions:19.0.2"
// AdMob / Ads
` + (isSelected(result.admob) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ads:18.3.0"
// ML Kit
` + (isSelected(result.ml_kit) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-vision:24.0.1"
` + (isSelected(result.ml_kit_image_labeling) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-vision-image-label-model:19.0.0"
` + (isSelected(result.ml_kit_object_detection) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-vision-object-detection-model:19.0.3"
` + (isSelected(result.ml_kit_custom_model) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-model-interpreter:22.0.1"
` + (isSelected(result.ml_kit_automl) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-vision-automl:18.0.3"
` + (isSelected(result.ml_kit_natural_language_identification) || isSelected(result.ml_kit_natural_language_smartreply) || isSelected(result.ml_kit_natural_language_translation) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-natural-language:22.0.0"
` + (isSelected(result.ml_kit_natural_language_identification) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-natural-language-language-id-model:20.0.7"
` + (isSelected(result.ml_kit_natural_language_translation) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-natural-language-translate-model:20.0.7"
` + (isSelected(result.ml_kit_natural_language_smartreply) ? `` : `//`) + ` implementation "com.google.firebase:firebase-ml-natural-language-smart-reply-model:20.0.7"
// Facebook Authentication
// IMPORTANT: facebook-login SDK release versions are synced with its dependency package
// "facebook-common", which in 12.0.0 introduces a dependency on androidx.fragment:fragment
// 1.3.0. This will OVERRIDE @nativescript/android's build.gradle dependency on
// androidx.fragment:fragment 1.2.5 (as of @nativescript/android 8.1.1), breaking navigation in
// nested frames. We can only bump this once the value of androidXFragmentVersion from
// https://github.com/NativeScript/android-runtime/blob/master/test-app/app/build.gradle is
// bumped to at least 1.3.0, or there are changes in @nativescript/core around
// frames/navigation/fragments that fix nested frame navigation with androidx.fragment 1.3.0+
` + (isSelected(result.facebook_auth) ? `` : `//`) + ` implementation "com.facebook.android:facebook-login:11.+"
// Google Sign-In Authentication
` + (isSelected(result.google_auth) ? `` : `//`) + ` implementation "com.google.android.gms:play-services-auth:$googlePlayServicesVersion"
// Dynamic Links
` + (isSelected(result.dynamic_links) ? `` : `//`) + ` implementation "com.google.firebase:firebase-dynamic-links:19.0.0"
}
apply plugin: "com.google.gms.google-services"
// Crashlytics
` + (isSelected(result.crashlytics) ? `` : `//`) + `apply plugin: "com.google.firebase.crashlytics"
`);
console.log('Successfully created Android (include.gradle) file.');
} catch (e) {
console.log('Failed to create Android (include.gradle) file.');
console.log(e);
}
}
/**
* Installs an after-prepare build hook to copy the app/App_Resources/Android/google-services.json to platform/android on build.
* Installs before-checkForChange build hook to detect changes in environment and copy GoogleServices.plist on build.
*/
function writeGoogleServiceCopyHook() {
// Install after-prepare hook
console.log("Install google-service.json after-prepare copy hook.");
try {
var afterPrepareScriptContent =
`
var path = require("path");
var fs = require("fs");
module.exports = function($logger, $projectData, hookArgs) {
return new Promise(function(resolve, reject) {
/* Decide whether to prepare for dev or prod environment */
var validStagingEnvs = ["dev", "development", "staging"];
var validProdEnvs = ['prod','production'];
var isProdEnv = false; // building with --env.prod or --env.production flag
var isStagingEnv = false;
var env = (hookArgs.platformSpecificData || hookArgs.prepareData).env;
if (env) {
Object.keys(env).forEach((key) => {
if (validProdEnvs.indexOf(key)>-1) {
isProdEnv = true;
}
if (validStagingEnvs.indexOf(key) > -1) {
isStagingEnv = true;
}
});
}
var buildType = isProdEnv && !isStagingEnv ? "production" : "development";
const platformFromHookArgs = hookArgs && (hookArgs.platform || (hookArgs.prepareData && hookArgs.prepareData.platform));
const platform = (platformFromHookArgs || '').toLowerCase();
/* Create info file in platforms dir so we can detect changes in environment and force prepare if needed */
var npfInfoPath = path.join($projectData.platformsDir, platform, ".pluginfirebaseinfo");
var npfInfo = {
buildType: buildType,
};
try { fs.writeFileSync(npfInfoPath, JSON.stringify(npfInfo)); }
catch (err) {
$logger.info('nativescript-plugin-firebase: unable to create '+npfInfoPath+', prepare will be forced next time!');
}
/* Handle preparing of Google Services files */
if (platform === 'android') {
var destinationGoogleJson = path.join($projectData.platformsDir, "android", "app", "google-services.json");
var destinationGoogleJsonAlt = path.join($projectData.platformsDir, "android", "google-services.json");
var sourceGoogleJson = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json");
var sourceGoogleJsonProd = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json.prod");
var sourceGoogleJsonDev = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json.dev");
// ensure we have both dev/prod versions so we never overwrite singlular google-services.json
if (fs.existsSync(sourceGoogleJsonProd) && fs.existsSync(sourceGoogleJsonDev)) {
if (buildType==='production') { sourceGoogleJson = sourceGoogleJsonProd; } // use prod version
else { sourceGoogleJson = sourceGoogleJsonDev; } // use dev version
}
// copy correct version to destination
if (fs.existsSync(sourceGoogleJson) && fs.existsSync(path.dirname(destinationGoogleJson))) {
$logger.info("Copy " + sourceGoogleJson + " to " + destinationGoogleJson + ".");
fs.writeFileSync(destinationGoogleJson, fs.readFileSync(sourceGoogleJson));
resolve();
} else if (fs.existsSync(sourceGoogleJson) && fs.existsSync(path.dirname(destinationGoogleJsonAlt))) {
// NativeScript < 4 doesn't have the 'app' folder
$logger.info("Copy " + sourceGoogleJson + " to " + destinationGoogleJsonAlt + ".");
fs.writeFileSync(destinationGoogleJsonAlt, fs.readFileSync(sourceGoogleJson));
resolve();
} else {
$logger.warn("Unable to copy google-services.json. You need this file, because the Google Services Plugin cannot function without it..");
reject();
}
} else if (platform === 'ios') {
// we have copied our GoogleService-Info.plist during before-checkForChanges hook, here we delete it to avoid changes in git
var destinationGooglePlist = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist");
var sourceGooglePlistProd = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.prod");
var sourceGooglePlistDev = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.dev");
// if we have both dev/prod versions, let's remove GoogleService-Info.plist in destination dir
if (fs.existsSync(sourceGooglePlistProd) && fs.existsSync(sourceGooglePlistDev)) {
if (fs.existsSync(destinationGooglePlist)) { fs.unlinkSync(destinationGooglePlist); }
resolve();
} else { // single GoogleService-Info.plist modus
resolve();
}
} else {
resolve();
}
});
};
`;
var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-copy-google-services.js");
var afterPrepareDirPath = path.dirname(scriptPath);
var hooksDirPath = path.dirname(afterPrepareDirPath);
if (!fs.existsSync(afterPrepareDirPath)) {
if (!fs.existsSync(hooksDirPath)) {
fs.mkdirSync(hooksDirPath);
}
fs.mkdirSync(afterPrepareDirPath);
}
fs.writeFileSync(scriptPath, afterPrepareScriptContent);
} catch (e) {
console.log("Failed to install google-service.json after-prepare copy hook.");
console.log(e);
}
/*
Install before-checkForChanges hook
*/
console.log("Install google-service.json before-checkForChanges copy hook.");
try {
var beforeCheckForChangesContent =
`
var path = require("path");
var fs = require("fs");
module.exports = function($logger, hookArgs) {
return new Promise(function(resolve, reject) {
/* Decide whether to prepare for dev or prod environment */
var isReleaseBuild = !!((hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.projectChangesOptions) || hookArgs.prepareData).release;
var validProdEnvs = ['prod','production'];
var validStagingEnvs = ["dev", "development", "staging"];
var isStagingEnv = false;
var isProdEnv = false; // building with --env.prod or --env.production flag
var env = ((hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.projectData && hookArgs.checkForChangesOpts.projectData.$options && hookArgs.checkForChangesOpts.projectData.$options.argv) || hookArgs.prepareData).env;
if (env) {
Object.keys(env).forEach((key) => {
if (validProdEnvs.indexOf(key)>-1) { isProdEnv=true; }
if (validStagingEnvs.indexOf(key) > -1) { isStagingEnv = true; }
});
}
var buildType = (isReleaseBuild && !isStagingEnv) || isProdEnv ? 'production' : 'development';
/*
Detect if we have nativescript-plugin-firebase temp file created during after-prepare hook, so we know
for which environment {development|prod} the project was prepared. If needed, we delete the NS .nsprepareinfo
file so we force a new prepare
*/
var platform = (hookArgs.checkForChangesOpts || hookArgs.prepareData).platform.toLowerCase();
var projectData = (hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.projectData) || hookArgs.projectData;
var platformsDir = projectData.platformsDir;
var appResourcesDirectoryPath = projectData.appResourcesDirectoryPath;
var forcePrepare = true; // whether to force NS to run prepare, defaults to true
var npfInfoPath = path.join(platformsDir, platform, ".pluginfirebaseinfo");
var nsPrepareInfoPath = path.join(platformsDir, platform, ".nsprepareinfo");
var copyPlistOpts = { platform, appResourcesDirectoryPath, buildType, $logger }
if (fs.existsSync(npfInfoPath)) {
var npfInfo = undefined;
try { npfInfo = JSON.parse(fs.readFileSync(npfInfoPath, 'utf8')); }
catch (e) { $logger.info('nativescript-plugin-firebase: error reading '+npfInfoPath); }
if (npfInfo && npfInfo.hasOwnProperty('buildType') && npfInfo.buildType===buildType) {
$logger.info('nativescript-plugin-firebase: building for same environment, not forcing prepare.');
forcePrepare=false;
}
} else { $logger.info('nativescript-plugin-firebase: '+npfInfoPath+' not found, forcing prepare!'); }
if (forcePrepare) {
$logger.info('nativescript-plugin-firebase: running release build or change in environment detected, forcing prepare!');
if (fs.existsSync(npfInfoPath)) { fs.unlinkSync(npfInfoPath); }
if (fs.existsSync(nsPrepareInfoPath)) { fs.unlinkSync(nsPrepareInfoPath); }
if (copyPlist(copyPlistOpts)) { resolve(); } else { reject(); }
} else { resolve(); }
});
};
/*
Handle preparing of Google Services files for iOS
*/
var copyPlist = function(copyPlistOpts) {
if (copyPlistOpts.platform === 'android') { return true; }
else if (copyPlistOpts.platform === 'ios') {
var sourceGooglePlistProd = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.prod");
var sourceGooglePlistDev = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.dev");
var destinationGooglePlist = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist");
// if we have both dev/prod versions, we copy (or overwrite) GoogleService-Info.plist in destination dir
if (fs.existsSync(sourceGooglePlistProd) && fs.existsSync(sourceGooglePlistDev)) {
if (copyPlistOpts.buildType==='production') { // use prod version
copyPlistOpts.$logger.info("nativescript-plugin-firebase: copy " + sourceGooglePlistProd + " to " + destinationGooglePlist + ".");
fs.writeFileSync(destinationGooglePlist, fs.readFileSync(sourceGooglePlistProd));
return true;
} else { // use dev version
copyPlistOpts.$logger.info("nativescript-plugin-firebase: copy " + sourceGooglePlistDev + " to " + destinationGooglePlist + ".");
fs.writeFileSync(destinationGooglePlist, fs.readFileSync(sourceGooglePlistDev));
return true;
}
} else if (!fs.existsSync(destinationGooglePlist)) { // single GoogleService-Info.plist modus but missing`;
if (externalPushClient) {
beforeCheckForChangesContent += `
return true; // this may be a push-only project, so this is allowed`;
} else {
beforeCheckForChangesContent += `
copyPlistOpts.$logger.warn("nativescript-plugin-firebase: " + destinationGooglePlist + " does not exist. Please follow the installation instructions from the documentation");
return false;`;
}
beforeCheckForChangesContent += `
} else {
return true; // single GoogleService-Info.plist modus
}
} else { return true; }
}
`;
var scriptPath = path.join(appRoot, "hooks", "before-checkForChanges", "firebase-copy-google-services.js");
var afterPrepareDirPath = path.dirname(scriptPath);
var hooksDirPath = path.dirname(afterPrepareDirPath);
if (!fs.existsSync(afterPrepareDirPath)) {
if (!fs.existsSync(hooksDirPath)) {
fs.mkdirSync(hooksDirPath);
}
fs.mkdirSync(afterPrepareDirPath);
}
fs.writeFileSync(scriptPath, beforeCheckForChangesContent);
} catch (e) {
console.log("Failed to install google-service.json before-checkForChanges copy hook.");
console.log(e);
}
}
function writeGoogleServiceGradleHook(result) {
try {
var scriptContent =
`var path = require("path");
var fs = require("fs");
module.exports = function($logger, $projectData) {
return new Promise(function(resolve, reject) {
$logger.info("Configure firebase");
let projectBuildGradlePath = path.join($projectData.platformsDir, "android", "build.gradle");
if (fs.existsSync(projectBuildGradlePath)) {
let buildGradleContent = fs.readFileSync(projectBuildGradlePath).toString();
if (buildGradleContent.indexOf(" google()\\n") === -1) {
let repositoriesNode = buildGradleContent.indexOf("repositories", 0);
if (repositoriesNode > -1) {
repositoriesNode = buildGradleContent.indexOf("}", repositoriesNode);
buildGradleContent = buildGradleContent.substr(0, repositoriesNode - 1) + '\\t\\tgoogle()\\n' + buildGradleContent.substr(repositoriesNode - 1);
}
}
if (buildGradleContent.indexOf("https://dl.bintray.com/android/android-tools") === -1) {
let repositoriesNode = buildGradleContent.indexOf("repositories", 0);
if (repositoriesNode > -1) {
repositoriesNode = buildGradleContent.indexOf("}", repositoriesNode);
buildGradleContent = buildGradleContent.substr(0, repositoriesNode - 1) + '\\t\\tmaven { url "https://dl.bintray.com/android/android-tools" }\\n' + buildGradleContent.substr(repositoriesNode - 1);
}
}
if (buildGradleContent.indexOf("com.google.firebase:firebase-crashlytics-gradle") === -1) {
let dependenciesNode = buildGradleContent.indexOf("dependencies", 0);
if (dependenciesNode > -1) {
dependenciesNode = buildGradleContent.indexOf("}", dependenciesNode);
buildGradleContent = buildGradleContent.substr(0, dependenciesNode - 1) + ' classpath "com.google.firebase:firebase-crashlytics-gradle:2.3.0"\\n' + buildGradleContent.substr(dependenciesNode - 1);
}
}
let gradlePattern = /classpath ('|")com\\.android\\.tools\\.build:gradle:\\d+\\.\\d+\\.\\d+('|")/;
let googleServicesPattern = /classpath ('|")com\\.google\\.gms:google-services:\\d+\\.\\d+\\.\\d+('|")/;
let latestGoogleServicesPlugin = 'classpath "com.google.gms:google-services:4.3.4"';
if (googleServicesPattern.test(buildGradleContent)) {
buildGradleContent = buildGradleContent.replace(googleServicesPattern, latestGoogleServicesPlugin);
} else {
buildGradleContent = buildGradleContent.replace(gradlePattern, function (match) {
return match + '\\n ' + latestGoogleServicesPlugin;