-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcommand.ts
More file actions
2511 lines (2229 loc) · 92.6 KB
/
command.ts
File metadata and controls
2511 lines (2229 loc) · 92.6 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
import type { ExecSyncOptions } from 'node:child_process'
import type { Options, PendingOnboardingApp } from '../api/app'
import type { Organization } from '../utils'
import { execSync, spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import path, { dirname, join } from 'node:path'
import { cwd, env, exit, platform, stdin, stdout } from 'node:process'
import { canParse, format, increment, lessThan, parse } from '@std/semver'
import tmp from 'tmp'
import { checkAppIdsExist, completePendingOnboardingApp, listPendingOnboardingApps } from '../api/app'
import { checkVersionStatus } from '../api/update'
import { addAppInternal } from '../app/add'
import { markSnag, waitLog } from '../app/debug'
import { canUseFilePicker, openPackageJsonPicker } from '../build/onboarding/file-picker'
import { uploadBundleInternal } from '../bundle/upload'
import { addChannelInternal } from '../channel/add'
import { writeConfigUpdater } from '../config'
import { getRepoStarStatus, isRepoStarredInSession, starAllRepositories, starRepository } from '../github'
import { createKeyInternal } from '../key'
import { doLoginExists, loginInternal } from '../login'
import { showReplicationProgress } from '../replicationProgress'
import { createSupabaseClient, findBuildCommandForProjectType, findMainFile, findMainFileForProjectType, findProjectType, findRoot, findSavedKey, formatError, getAllPackagesDependencies, getAppId, getBundleVersion, getConfig, getInstalledVersion, getLocalConfig, getNativeProjectResetAdvice, getPackageScripts, getPMAndCommand, PACKNAME, projectIsMonorepo, updateConfigbyKey, updateConfigUpdater, validateIosUpdaterSync, verifyUser } from '../utils'
import { cancel as pCancel, confirm as pConfirm, intro as pIntro, isCancel as pIsCancel, log as pLog, outro as pOutro, select as pSelect, spinner as pSpinner, text as pText } from './prompts'
import { setInitVersionWarning, stopInitInkSession } from './runtime'
import { formatInitResumeMessage, initOnboardingSteps, renderInitOnboardingComplete, renderInitOnboardingFrame, renderInitOnboardingWelcome } from './ui'
interface SuperOptions extends Options {
local: boolean
}
const importInject = 'import { CapacitorUpdater } from \'@capgo/capacitor-updater\''
const codeInject = 'CapacitorUpdater.notifyAppReady()'
// create regex to find line who start by 'import ' and end by ' from '
const regexImport = /import.*from.*/g
const defaultChannel = 'production'
const channelNameRegex = /^[\w.-]+$/
const appIdRegex = /^[a-z0-9]+(?:\.[\w-]+)+$/i
const execOption = { stdio: 'pipe' }
const capacitorConfigFiles = ['capacitor.config.ts', 'capacitor.config.js', 'capacitor.config.json']
const capacitorGettingStartedUrl = 'https://capacitorjs.com/docs/getting-started'
const nextWebDirPattern = /["']?webDir["']?\s*:\s*["']out["']/
const nuxtWebDirPattern = /["']?webDir["']?\s*:\s*["']\.output\/public["']/
const frameworkSetupGuides = {
nextjs: 'https://capgo.app/blog/nextjs-mobile-app-capacitor-from-scratch/',
nuxtjs: 'https://capgo.app/blog/nuxt-mobile-app-capacitor-from-scratch/',
sveltekit: 'https://capgo.app/blog/creating-mobile-apps-with-sveltekit-and-capacitor/',
} as const
let tmpObject: tmp.FileResult['name'] | undefined
let globalPathToPackageJson: string | undefined
let globalChannelName = defaultChannel
let globalPlatform: 'ios' | 'android' = 'ios'
let globalDelta = false
let globalCurrentVersion: string | undefined
let globalAppId: string | undefined
function readTmpObj() {
tmpObject ??= readdirSync(tmp.tmpdir)
.map((name) => { return { name, full: `${tmp.tmpdir}/${name}` } })
.find(obj => obj.name.startsWith('capgocli'))
?.full
?? tmp.fileSync({ prefix: 'capgocli' }).name
}
function getTmpObjectPath() {
readTmpObj()
if (!tmpObject)
throw new Error('Unable to allocate onboarding state file')
return tmpObject
}
function findNearestNamedFile(startDir: string, fileNames: string[]) {
let currentDir = startDir
const rootDir = path.parse(currentDir).root
while (true) {
for (const fileName of fileNames) {
const candidate = join(currentDir, fileName)
if (existsSync(candidate))
return candidate
}
if (currentDir === rootDir)
break
const parent = dirname(currentDir)
if (parent === currentDir)
break
currentDir = parent
}
return undefined
}
function findNearestPackageJson(startDir: string) {
return findNearestNamedFile(startDir, [PACKNAME])
}
function readExistingFile(filePath: string | undefined) {
if (!filePath || !existsSync(filePath))
return undefined
return readFileSync(filePath, 'utf8')
}
function getFrameworkKind(projectType: string): keyof typeof frameworkSetupGuides | undefined {
if (projectType.startsWith('nextjs-'))
return 'nextjs'
if (projectType.startsWith('nuxtjs-'))
return 'nuxtjs'
if (projectType.startsWith('sveltekit-'))
return 'sveltekit'
return undefined
}
function getFrameworkDisplayName(projectType: string) {
const frameworkKind = getFrameworkKind(projectType)
if (frameworkKind === 'nextjs')
return 'Next.js'
if (frameworkKind === 'nuxtjs')
return 'Nuxt'
if (frameworkKind === 'sveltekit')
return 'SvelteKit'
return 'web'
}
function getSuggestedWebDir(projectType: string) {
const frameworkKind = getFrameworkKind(projectType)
if (frameworkKind === 'nextjs')
return 'out'
if (frameworkKind === 'nuxtjs')
return '.output/public'
if (frameworkKind === 'sveltekit')
return 'build'
return 'dist'
}
function getPackageJsonData(packageJsonPath: string | undefined) {
if (!packageJsonPath || !existsSync(packageJsonPath))
return undefined
try {
return JSON.parse(readFileSync(packageJsonPath, 'utf8')) as { name?: string }
}
catch {
return undefined
}
}
function getSuggestedAppName(projectDir: string) {
const packageJson = getPackageJsonData(findNearestPackageJson(projectDir))
const rawName = packageJson?.name?.split('/').pop() || path.basename(projectDir)
return rawName
.replaceAll(/[-_]+/g, ' ')
.replaceAll(/\b\w/g, char => char.toUpperCase())
}
function getFrameworkSetupIssues(projectType: string, projectDir: string, capacitorConfigPath?: string) {
const frameworkKind = getFrameworkKind(projectType)
if (!frameworkKind)
return []
const issues: string[] = []
if (frameworkKind === 'nextjs') {
const nextConfig = readExistingFile(findNearestNamedFile(projectDir, ['next.config.ts', 'next.config.js', 'next.config.mjs']))
if (!nextConfig?.includes('output') || !nextConfig.includes('export')) {
issues.push('Next.js must use static export (`output: \'export\'`).')
}
const capacitorConfig = readExistingFile(capacitorConfigPath)
if (capacitorConfig && !nextWebDirPattern.test(capacitorConfig)) {
issues.push('Capacitor `webDir` should point to `out` for Next.js.')
}
}
if (frameworkKind === 'nuxtjs') {
const nuxtConfig = readExistingFile(findNearestNamedFile(projectDir, ['nuxt.config.ts', 'nuxt.config.js']))
if (!nuxtConfig?.includes('preset') || !nuxtConfig.includes('static')) {
issues.push('Nuxt must use static Nitro output (`nitro.preset = "static"`).')
}
const capacitorConfig = readExistingFile(capacitorConfigPath)
if (capacitorConfig && !nuxtWebDirPattern.test(capacitorConfig)) {
issues.push('Capacitor `webDir` should point to `.output/public` for Nuxt.')
}
}
if (frameworkKind === 'sveltekit') {
const svelteConfig = readExistingFile(findNearestNamedFile(projectDir, ['svelte.config.js', 'svelte.config.ts']))
if (!svelteConfig?.includes('adapter-static')) {
issues.push('SvelteKit must use `@sveltejs/adapter-static` before Capacitor sync works reliably.')
}
}
return issues
}
function exitBeforeAuthenticatedOnboarding() {
pOutro(`Bye 👋\n💡 You can resume the onboarding anytime by running the same command again`)
exit(1)
}
function cancelBeforeAuthenticatedOnboarding(command: boolean | string | symbol) {
if (pIsCancel(command)) {
pCancel('Operation cancelled.')
exitBeforeAuthenticatedOnboarding()
}
}
async function waitUntilSetupIsDone(message = 'Type "ready" when the setup is done.') {
while (true) {
const ready = await pText({
message,
placeholder: 'ready',
validate: (value) => {
if (!value?.trim())
return 'Type "ready" when you are done.'
if (value.trim().toLowerCase() !== 'ready')
return 'Type "ready" when you are done.'
},
})
cancelBeforeAuthenticatedOnboarding(ready)
if ((ready as string).trim().toLowerCase() === 'ready')
return
}
}
async function askForAppName(message: string, initialValue: string) {
const appName = await pText({
message,
placeholder: initialValue,
validate: (value) => {
if (!value?.trim())
return 'App name is required'
},
})
cancelBeforeAuthenticatedOnboarding(appName)
return (appName as string).trim()
}
async function askForWebDir(projectType: string) {
const suggestedWebDir = getSuggestedWebDir(projectType)
const webDir = await pText({
message: 'Enter the web build directory to use for Capacitor:',
placeholder: suggestedWebDir,
validate: (value) => {
if (!value?.trim())
return 'Web directory is required'
},
})
cancelBeforeAuthenticatedOnboarding(webDir)
return (webDir as string).trim()
}
async function maybeRunCapacitorInit(projectDir: string, projectType: string, initialAppId?: string) {
const shouldInitCapacitor = await pConfirm({
message: 'Do you want me to install Capacitor here and run init now?',
initialValue: true,
})
cancelBeforeAuthenticatedOnboarding(shouldInitCapacitor)
if (!shouldInitCapacitor)
exitBeforeAuthenticatedOnboarding()
const appName = await askForAppName('App name for Capacitor:', getSuggestedAppName(projectDir))
const capacitorAppId = initialAppId || await askForAppId('Enter your appId for Capacitor:')
const webDir = await askForWebDir(projectType)
const spinner = pSpinner()
const pm = getPMAndCommand()
try {
spinner.start(`Installing Capacitor packages with ${pm.installCommand}`)
const installCoreResult = spawnSync(pm.pm, [pm.command, '@capacitor/core'], { stdio: 'pipe', cwd: projectDir })
if (installCoreResult.error)
throw installCoreResult.error
if (installCoreResult.status !== 0) {
const stderr = installCoreResult.stderr?.toString().trim()
const stdout = installCoreResult.stdout?.toString().trim()
throw new Error(stderr || stdout || `${pm.installCommand} @capacitor/core exited with code ${installCoreResult.status}`)
}
const installCliResult = spawnSync(pm.pm, [pm.command, '-D', '@capacitor/cli'], { stdio: 'pipe', cwd: projectDir })
if (installCliResult.error)
throw installCliResult.error
if (installCliResult.status !== 0) {
const stderr = installCliResult.stderr?.toString().trim()
const stdout = installCliResult.stdout?.toString().trim()
throw new Error(stderr || stdout || `${pm.installCommand} -D @capacitor/cli exited with code ${installCliResult.status}`)
}
spinner.message(`Running: ${pm.runner} cap init "${appName}" "${capacitorAppId}" --web-dir ${webDir}`)
const initResult = spawnSync(pm.runner, ['cap', 'init', appName, capacitorAppId, '--web-dir', webDir], { stdio: 'pipe', cwd: projectDir })
if (initResult.error)
throw initResult.error
if (initResult.status !== 0) {
const stderr = initResult.stderr?.toString().trim()
const stdout = initResult.stdout?.toString().trim()
throw new Error(stderr || stdout || `cap init exited with code ${initResult.status}`)
}
spinner.stop('Capacitor init done ✅')
pLog.info(`Capacitor was initialized with webDir ${webDir}.`)
return capacitorAppId
}
catch (error) {
spinner.stop('Capacitor init failed ❌')
pLog.error(formatError(error))
const retry = await pConfirm({
message: 'Capacitor init failed. Do you want to try again?',
initialValue: true,
})
cancelBeforeAuthenticatedOnboarding(retry)
if (retry)
return maybeRunCapacitorInit(projectDir, projectType, capacitorAppId)
exitBeforeAuthenticatedOnboarding()
}
}
function runCreateAppTemplate() {
stopInitInkSession({ text: 'Starting Capacitor app template creation...', tone: 'green' })
const result = spawnSync('npm', ['init', '@capacitor/app@latest'], { stdio: 'inherit' })
if (result.error || result.status !== 0) {
stdout.write('Capacitor app template creation failed. Run npm init @capacitor/app@latest manually and try again.\n')
exit(1)
}
stdout.write('Capacitor app template creation finished. Run init again from the new app folder.\n')
exit(0)
}
async function ensureWorkspaceReadyForInit(initialAppId?: string): Promise<string | undefined> {
while (true) {
const currentDir = cwd()
const nearestCapacitorConfig = findNearestCapacitorConfig(currentDir)
const nearestPackageJson = findNearestPackageJson(currentDir)
const projectDir = nearestCapacitorConfig?.dir || (nearestPackageJson ? dirname(nearestPackageJson) : currentDir)
const projectType = await findProjectType({ quiet: true })
const frameworkKind = getFrameworkKind(projectType)
if (nearestCapacitorConfig?.dir === currentDir) {
const frameworkIssues = getFrameworkSetupIssues(projectType, projectDir, nearestCapacitorConfig.file)
if (frameworkIssues.length === 0)
return
pLog.warn(`${getFrameworkDisplayName(projectType)} is detected, but the Capacitor setup is not ready yet.`)
for (const issue of frameworkIssues) {
pLog.warn(issue)
}
if (frameworkKind) {
pLog.info(`Follow this guide to finish the setup: ${frameworkSetupGuides[frameworkKind]}`)
}
await waitUntilSetupIsDone()
continue
}
if (nearestCapacitorConfig) {
return
}
if (frameworkKind) {
const frameworkIssues = getFrameworkSetupIssues(projectType, projectDir)
if (frameworkIssues.length > 0) {
pLog.warn(`${getFrameworkDisplayName(projectType)} project detected, but the setup is not ready yet.`)
for (const issue of frameworkIssues) {
pLog.warn(issue)
}
pLog.info(`Follow this guide: ${frameworkSetupGuides[frameworkKind]}`)
await waitUntilSetupIsDone()
continue
}
const initializedAppId = await maybeRunCapacitorInit(projectDir, projectType, initialAppId)
return initializedAppId
}
if (nearestPackageJson) {
pLog.warn('This looks like a web app, but Capacitor is not initialized yet.')
pLog.info(`Follow the Capacitor getting started guide: ${capacitorGettingStartedUrl}`)
const initializedAppId = await maybeRunCapacitorInit(projectDir, projectType, initialAppId)
return initializedAppId
}
const createAppNow = await pConfirm({
message: 'This folder is not a web app yet. Do you want to start npm init @capacitor/app@latest now?',
initialValue: true,
})
cancelBeforeAuthenticatedOnboarding(createAppNow)
if (createAppNow) {
runCreateAppTemplate()
}
else {
pLog.info('Create a new Capacitor app first with: npm init @capacitor/app@latest')
pLog.info('Then run this onboarding again from the new app folder.')
exitBeforeAuthenticatedOnboarding()
}
}
}
let globalOrgId: string | undefined
let globalOrgName: string | undefined
function markStepDone(step: number, pathToPackageJson?: string, channelName?: string) {
try {
writeFileSync(getTmpObjectPath(), JSON.stringify({
step_done: step,
orgId: globalOrgId,
orgName: globalOrgName,
appId: globalAppId,
pathToPackageJson: pathToPackageJson ?? globalPathToPackageJson,
channelName: channelName ?? globalChannelName,
platform: globalPlatform,
delta: globalDelta,
currentVersion: globalCurrentVersion,
}))
if (pathToPackageJson) {
globalPathToPackageJson = pathToPackageJson
}
if (channelName) {
globalChannelName = channelName
}
}
catch (err) {
pLog.error(`Cannot mark step as done in the CLI, error:\n${err}`)
pLog.warn('Onboarding will continue but please report it to the capgo team!')
}
}
interface ResumeResult {
stepDone: number
orgId: string
orgName: string
appId?: string
}
async function tryResumeOnboarding(apikey: string): Promise<ResumeResult | undefined> {
try {
const rawData = readFileSync(getTmpObjectPath(), 'utf-8')
if (!rawData || rawData.length === 0)
return undefined
const { step_done, orgId, orgName, appId: savedAppId, pathToPackageJson, channelName, platform, delta, currentVersion } = JSON.parse(rawData)
if (!orgId || !step_done) {
pLog.warn('⚠️ Found previous onboarding progress, but it was saved in an older format.')
pLog.info(' Starting fresh. Your previous progress cannot be resumed.')
return undefined
}
pLog.info(formatInitResumeMessage(step_done, initOnboardingSteps.length))
if (orgName) {
pLog.info(` Organization: ${orgName}`)
}
const resumeChoice = await pSelect({
message: 'Would you like to continue from where you left off?',
options: [
{ value: 'yes', label: '✅ Yes, continue' },
{ value: 'no', label: '❌ No, start over' },
],
})
await cancelCommand(resumeChoice, orgId, apikey)
if (resumeChoice === 'yes') {
if (pathToPackageJson) {
globalPathToPackageJson = pathToPackageJson
}
if (channelName) {
globalChannelName = channelName
}
if (platform === 'ios' || platform === 'android') {
globalPlatform = platform
}
if (typeof delta === 'boolean') {
globalDelta = delta
}
if (typeof currentVersion === 'string' && currentVersion.length > 0) {
globalCurrentVersion = currentVersion
}
if (savedAppId) {
globalAppId = savedAppId
}
return { stepDone: step_done, orgId, orgName, appId: savedAppId }
}
return undefined
}
catch (err) {
pLog.error(`Cannot read which steps have been completed, error:\n${err}`)
pLog.warn('Onboarding will continue but please report it to the capgo team!')
return undefined
}
}
function cleanupStepsDone() {
if (!tmpObject) {
return
}
try {
rmSync(tmpObject)
}
catch (err) {
pLog.error(`Cannot delete the tmp steps file.\nError: ${err}`)
}
}
async function cancelCommand(command: boolean | string | symbol, orgId: string, apikey: string) {
if (pIsCancel(command)) {
await markSnag('onboarding-v2', orgId, apikey, 'canceled', undefined, '🤷')
pOutro(`Bye 👋\n💡 You can resume the onboarding anytime by running the same command again`)
exit()
}
}
interface RecoveryOption<T extends string> {
value: T
label: string
hint?: string
}
async function selectRecoveryOption<T extends string>(
orgId: string,
apikey: string,
message: string,
options: RecoveryOption<T>[],
): Promise<T> {
type RecoveryChoice = T | '__cancel__'
const choice = await pSelect<RecoveryChoice>({
message,
options: [
...options,
{ value: '__cancel__', label: 'Exit onboarding' },
],
})
if (pIsCancel(choice) || choice === '__cancel__') {
await markSnag('onboarding-v2', orgId, apikey, 'canceled', undefined, '🤷')
pOutro(`Bye 👋\n💡 You can resume the onboarding anytime by running the same command again`)
exit(1)
}
return choice as T
}
async function askForExistingDirectoryPath(orgId: string, apikey: string, message: string, placeholder?: string): Promise<string> {
const selectedPath = await pText({
message,
placeholder,
validate: (value) => {
const trimmedValue = value?.trim()
if (!trimmedValue)
return 'Path is required.'
if (!existsSync(trimmedValue))
return `Path ${trimmedValue} does not exist`
if (!statSync(trimmedValue).isDirectory())
return 'Selected path is not a directory'
},
})
if (pIsCancel(selectedPath)) {
await cancelCommand(selectedPath, orgId, apikey)
}
return (selectedPath as string).trim()
}
/**
* Find the nearest Capacitor config file by walking up the directory tree.
*/
function findNearestCapacitorConfig(startDir: string) {
let currentDir = startDir
const rootDir = path.parse(currentDir).root
while (true) {
for (const file of capacitorConfigFiles) {
const candidate = join(currentDir, file)
if (existsSync(candidate))
return { dir: currentDir, file: candidate }
}
if (currentDir === rootDir)
break
const parent = dirname(currentDir)
if (parent === currentDir)
break
currentDir = parent
}
return undefined
}
/**
* Warn and optionally stop if onboarding is started outside the Capacitor project root.
*/
async function warnIfNotInCapacitorRoot() {
const currentDir = cwd()
const configHere = capacitorConfigFiles.some(file => existsSync(join(currentDir, file)))
if (configHere)
return
const nearest = findNearestCapacitorConfig(currentDir)
pLog.warn('Capacitor config not found in the current folder.')
if (nearest) {
pLog.info(`Found a capacitor config at: ${nearest.file}`)
pLog.info(`You are currently in: ${currentDir}`)
}
else {
pLog.info('No capacitor config was found in this folder or any parent directories.')
}
const currentFolder = path.basename(currentDir)
if (currentFolder === 'ios' || currentFolder === 'android') {
pLog.info('It looks like you are inside a platform folder (ios/android).')
pLog.info('Try running the onboarding from the project root (the folder with capacitor.config.*).')
}
const continueAnyway = await pConfirm({
message: 'Are you sure you want to continue? If you do, the auto-configuration will probably not work from here.',
initialValue: false,
})
if (pIsCancel(continueAnyway) || !continueAnyway) {
pCancel('Operation cancelled.')
exit(1)
}
}
async function markStep(orgId: string, apikey: string, step: string, appId: string) {
return markSnag('onboarding-v2', orgId, apikey, `onboarding-step-${step}`, appId)
}
/**
* Save the app ID to the CapacitorUpdater plugin config.
*/
async function saveAppIdToCapacitorConfig(appId: string) {
try {
await updateConfigUpdater({ appId })
pLog.info(`💾 Saved new app ID "${appId}" to CapacitorUpdater config`)
}
catch (err) {
pLog.warn(`⚠️ Could not save app ID to capacitor config: ${err}`)
pLog.info(` You may need to manually update your capacitor.config file with the new app ID: ${appId}`)
}
}
/**
* When reusing an app created by the web onboarding flow, the dashboard app ID becomes authoritative.
*/
async function syncPendingAppIdToCapacitorConfig(appId: string) {
try {
const extConfig = await getConfig()
extConfig.config.appId = appId
extConfig.config.plugins ||= {}
extConfig.config.plugins.CapacitorUpdater = {
...extConfig.config.plugins.CapacitorUpdater,
appId,
}
await writeConfigUpdater(extConfig, true)
pLog.info(`💾 Synced pending onboarding app ID "${appId}" to capacitor config`)
}
catch (err) {
pLog.warn(`⚠️ Could not save app ID to capacitor config: ${err}`)
pLog.info(` You may need to manually update your capacitor.config file with the new app ID: ${appId}`)
}
}
async function handleBrokenIosSync(platformRunner: string, details: string[], orgId: string, apikey: string, failureCount: number) {
const resetAdvice = getNativeProjectResetAdvice(platformRunner, 'ios')
pLog.error('Capgo iOS dependency sync verification failed.')
for (const detail of details) {
pLog.error(detail)
}
pLog.error('The native iOS project is still broken, so this build step cannot continue yet.')
pLog.warn(resetAdvice.summary)
pLog.info(resetAdvice.command)
if (failureCount % 3 === 0) {
const cancelInit = await pConfirm({
message: `iOS sync has failed ${failureCount} times. Do you want to cancel init?`,
initialValue: false,
})
await cancelCommand(cancelInit, orgId, apikey)
if (cancelInit) {
await markSnag('onboarding-v2', orgId, apikey, 'canceled', undefined, '🤷')
pOutro('Bye 👋\n💡 You can resume the onboarding anytime by running the same command again')
exit(1)
}
}
const runResetNow = await pConfirm({
message: 'Would you like me to run this reset command for you now?',
initialValue: true,
})
await cancelCommand(runResetNow, orgId, apikey)
if (runResetNow) {
const resetSpinner = pSpinner()
resetSpinner.start(`Running: ${resetAdvice.command}`)
try {
execSync(resetAdvice.command, execOption as ExecSyncOptions)
resetSpinner.stop('iOS folder recreated and synced ✅')
}
catch (err) {
resetSpinner.stop('iOS folder reset failed ❌')
pLog.error(formatError(err))
}
return
}
pLog.info('We will wait while you fix the iOS folder yourself.')
pLog.info('When you are ready, type "ready" and I will retry this step.')
while (true) {
const ready = await pText({
message: 'Type "ready" when the iOS folder is fixed.',
placeholder: 'ready',
validate: (value) => {
if (!value?.trim())
return 'Type "ready" to retry.'
if (value.trim().toLowerCase() !== 'ready')
return 'Type "ready" to retry.'
},
})
if (pIsCancel(ready)) {
await cancelCommand(ready, orgId, apikey)
}
if ((ready as string).trim().toLowerCase() === 'ready') {
return
}
}
}
function validateAppId(value: string | undefined): string | undefined {
if (!value)
return 'App ID is required'
if (value.includes('--'))
return 'App ID cannot contain "--"'
if (!appIdRegex.test(value))
return 'Invalid format. Use reverse domain notation (e.g., com.example.app)'
}
function validateChannelName(value: string | undefined): string | undefined {
const trimmedValue = value?.trim()
if (!trimmedValue)
return 'Channel name is required'
if (!channelNameRegex.test(trimmedValue))
return 'Use only letters, numbers, dot, dash, or underscore'
}
function normalizeConcreteVersion(version: string | undefined) {
if (!version)
return undefined
const trimmedVersion = version.trim()
if (!trimmedVersion || trimmedVersion === 'latest')
return undefined
if (canParse(trimmedVersion))
return format(parse(trimmedVersion))
const fallbackMatch = /\d+\.\d+\.\d+(?:-[0-9A-Z.-]+)?/i.exec(trimmedVersion)
if (!fallbackMatch?.[0])
return undefined
if (!canParse(fallbackMatch[0]))
return undefined
return format(parse(fallbackMatch[0]))
}
async function askForAppId(message = 'Enter your appId:'): Promise<string> {
const appId = await pText({
message,
validate: validateAppId,
})
if (pIsCancel(appId)) {
pCancel('Operation cancelled.')
pOutro(`Bye 👋\n💡 You can resume the onboarding anytime by running the same command again`)
exit()
}
return appId as string
}
async function ensureCapacitorProjectReady(
orgId: string,
apikey: string,
appId: string,
pendingApp?: PendingOnboardingApp,
) {
const nearestConfig = findNearestCapacitorConfig(cwd())
if (nearestConfig?.dir === cwd()) {
return
}
if (nearestConfig) {
await warnIfNotInCapacitorRoot()
return
}
if (pendingApp?.existing_app === false) {
const pm = getPMAndCommand()
const appName = pendingApp.name?.trim() || appId
pLog.info(`No Capacitor config was found for ${appId}.`)
pLog.info('This app was created from the web onboarding as a new app.')
const initCommand = `${pm.runner} cap init "${appName}" "${appId}"`
const shouldInitCapacitor = await pConfirm({
message: `Do you want me to run "${initCommand}" now?`,
initialValue: true,
})
await cancelCommand(shouldInitCapacitor, orgId, apikey)
if (shouldInitCapacitor) {
const spinner = pSpinner()
spinner.start(`Running: ${pm.runner} cap init "${appName}" "${appId}"`)
try {
const initResult = spawnSync(pm.runner, ['cap', 'init', appName, appId], { stdio: 'pipe' as const })
if (initResult.error)
throw initResult.error
if (initResult.status !== 0) {
const stderr = initResult.stderr?.toString().trim()
const stdout = initResult.stdout?.toString().trim()
throw new Error(stderr || stdout || `cap init exited with code ${initResult.status}`)
}
spinner.stop('Capacitor init done ✅')
await saveAppIdToCapacitorConfig(appId)
return
}
catch (error) {
spinner.stop('Capacitor init failed ❌')
throw error
}
}
}
await warnIfNotInCapacitorRoot()
}
async function selectPendingOnboardingApp(
orgId: string,
apikey: string,
requestedAppId: string | undefined,
pendingApps: PendingOnboardingApp[],
) {
const requestedApp = requestedAppId
? pendingApps.find(app => app.app_id === requestedAppId)
: undefined
if (requestedApp) {
const useRequestedApp = await pConfirm({
message: `Use the pending onboarding app "${requestedApp.name || requestedApp.app_id}" (${requestedApp.app_id}) from the web console?`,
initialValue: true,
})
await cancelCommand(useRequestedApp, orgId, apikey)
return useRequestedApp ? requestedApp : undefined
}
if (pendingApps.length === 0) {
return undefined
}
const selectedAppId = await pSelect({
message: 'A pending onboarding app already exists in Capgo. What do you want to do?',
options: [
...pendingApps.map(app => ({
value: app.app_id,
label: `${app.name || app.app_id} (${app.app_id})`,
hint: app.existing_app ? 'Existing app' : 'New app created from web onboarding',
})),
{ value: '__create_new__', label: 'Create a new app from the CLI' },
],
})
await cancelCommand(selectedAppId, orgId, apikey)
if (selectedAppId === '__create_new__') {
return undefined
}
return pendingApps.find(app => app.app_id === selectedAppId)
}
async function maybeReusePendingOnboardingApp(
organization: Organization,
apikey: string,
appId: string | undefined,
supabase: Awaited<ReturnType<typeof createSupabaseClient>>,
) {
const pendingApps = await listPendingOnboardingApps(supabase, organization.gid)
const selectedApp = await selectPendingOnboardingApp(organization.gid, apikey, appId, pendingApps)
if (!selectedApp) {
return {
appId,
pendingApp: undefined,
reusedPendingApp: false,
}
}
const selectedAppId = selectedApp.app_id
pLog.info(`Using pending onboarding app ${selectedAppId}`)
if (findNearestCapacitorConfig(cwd())) {
await syncPendingAppIdToCapacitorConfig(selectedAppId)
}
const cleanupSpinner = pSpinner()
cleanupSpinner.start(`Preparing ${selectedAppId} for real onboarding`)
try {
await completePendingOnboardingApp(supabase, organization.gid, selectedAppId)
cleanupSpinner.stop('Pending onboarding app prepared ✅')
}
catch (error) {
cleanupSpinner.stop('Could not prepare pending onboarding app ❌')
throw error
}
await markStep(organization.gid, apikey, 'add-app', selectedAppId)
return {
appId: selectedAppId,
pendingApp: selectedApp,
reusedPendingApp: true,
}
}
async function selectOrganizationForInit(
supabase: Awaited<ReturnType<typeof createSupabaseClient>>,
roles: string[],
): Promise<Organization> {
const { error: orgError, data: allOrganizations } = await supabase.rpc('get_orgs_v7')
if (orgError) {
pLog.error('Cannot get the list of organizations - exiting')
pLog.error(`Error ${JSON.stringify(orgError)}`)
throw new Error('Cannot get the list of organizations')
}
const normalizeRole = (role: string | null | undefined) => role?.replace(/^org_/, '') ?? ''
const normalizedRoles = new Set(roles.map(role => normalizeRole(role)))
const adminOrgs = allOrganizations.filter(org => normalizedRoles.has(normalizeRole(org.role)))
if (allOrganizations.length === 0) {
pLog.error('Could not get organization please create an organization first')
throw new Error('No organizations available')
}
if (adminOrgs.length === 0) {
pLog.error(`Could not find organization with roles: ${roles.join(' or ')} please create an organization or ask the admin to add you to the organization with this roles`)
throw new Error('Could not find organization with required roles')
}
const organizationUidRaw = adminOrgs.length > 1
? await pSelect({
message: 'Pick the organization that should own this app',
options: adminOrgs.map((org) => {
const twoFaWarning = (org.enforcing_2fa && !org['2fa_has_access']) ? '2FA required' : undefined
return {
value: org.gid,
label: org.name,
hint: twoFaWarning,
}
}),
})
: adminOrgs[0].gid
if (pIsCancel(organizationUidRaw)) {
pOutro('Bye 👋\n💡 You can resume the onboarding anytime by running the same command again')
exit()
}
const organizationUid = organizationUidRaw as string
const organization = allOrganizations.find(org => org.gid === organizationUid)
if (!organization) {
throw new Error('Selected organization not found')
}
if (organization.enforcing_2fa && !organization['2fa_has_access']) {
pLog.error(`The organization "${organization.name}" requires all members to have 2FA enabled.`)
pLog.error('Enable 2FA at https://web.capgo.app/settings/account and try again.')
throw new Error('2FA required for selected organization')
}
pLog.info(`Using organization "${organization.name}" as the app owner`)
return organization
}
async function checkPrerequisitesStep(orgId: string, apikey: string) {
pLog.info(`📋 Checking development environment prerequisites`)
pLog.info(` For mobile development, you need at least one platform setup`)
const hasXcode = platform === 'darwin' && existsSync('/Applications/Xcode.app')
// Check for Android SDK in common locations
const homeDir = env.HOME || env.USERPROFILE || '~'
const androidPaths = [
env.ANDROID_HOME,
env.ANDROID_SDK_ROOT,
join(homeDir, 'Library', 'Android', 'sdk'), // macOS
join(homeDir, 'Android', 'Sdk'), // Windows/Linux
join(homeDir, 'AppData', 'Local', 'Android', 'Sdk'), // Windows alternative
].filter(Boolean)
const hasAndroidStudio = androidPaths.some(path => path && existsSync(path))