-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathcreate.ts
More file actions
850 lines (771 loc) · 26.6 KB
/
create.ts
File metadata and controls
850 lines (771 loc) · 26.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
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { confirm, input, password, select } from '@inquirer/prompts';
import { SupportedPHPVersions } from '@php-wasm/universal';
import {
DEFAULT_PHP_VERSION,
DEFAULT_WORDPRESS_VERSION,
MINIMUM_WORDPRESS_VERSION,
} from '@studio/common/constants';
import { installAiInstructionsToSite } from '@studio/common/lib/agent-skills';
import { extractFormValuesFromBlueprint } from '@studio/common/lib/blueprint-settings';
import { validateBlueprintData } from '@studio/common/lib/blueprint-validation';
import { SITE_EVENTS } from '@studio/common/lib/cli-events';
import { getDomainNameValidationError } from '@studio/common/lib/domains';
import {
arePathsEqual,
isEmptyDir,
isWordPressDirectory,
pathExists,
recursiveCopyDirectory,
} from '@studio/common/lib/fs-utils';
import { normalizeLandingPage } from '@studio/common/lib/landing-page';
import { DEFAULT_LOCALE } from '@studio/common/lib/locale';
import { isOnline } from '@studio/common/lib/network-utils';
import {
createPassword,
encodePassword,
validateAdminEmail,
validateAdminUsername,
} from '@studio/common/lib/passwords';
import { portFinder } from '@studio/common/lib/port-finder';
import {
hasDefaultDbBlock,
removeDbConstants,
} from '@studio/common/lib/remove-default-db-constants';
import { readSharedConfig } from '@studio/common/lib/shared-config';
import { sortSites } from '@studio/common/lib/sort-sites';
import { getServerFilesPath } from '@studio/common/lib/well-known-paths';
import {
isValidWordPressVersion,
isWordPressVersionAtLeast,
} from '@studio/common/lib/wordpress-version-utils';
import { fetchWordPressVersions } from '@studio/common/lib/wordpress-versions';
import { SiteCommandLoggerAction as LoggerAction } from '@studio/common/logger-actions';
import { __, sprintf } from '@wordpress/i18n';
import {
isStepDefinition,
type BlueprintV1Declaration,
type StepDefinition,
} from '@wp-playground/blueprints';
import { bumpStat, getPlatformMetric } from 'cli/lib/bump-stat';
import {
lockCliConfig,
readCliConfig,
saveCliConfig,
SiteData,
SiteRuntime,
siteRuntimeSchema,
unlockCliConfig,
} from 'cli/lib/cli-config/core';
import {
removeSiteFromConfig,
updateSiteAutoStart,
updateSiteLatestCliPid,
} from 'cli/lib/cli-config/sites';
import { connectToDaemon, disconnectFromDaemon, emitCliEvent } from 'cli/lib/daemon-client';
import { getAiInstructionsPath } from 'cli/lib/dependency-management/paths';
import { updateServerFiles } from 'cli/lib/dependency-management/setup';
import { copyLanguagePackToSite } from 'cli/lib/language-packs';
import { getPreferredSiteLanguage } from 'cli/lib/site-language';
import { generateSiteName } from 'cli/lib/site-name';
import { getDefaultSitePath } from 'cli/lib/site-paths';
import { logSiteDetails, openSiteInBrowser, setupCustomDomain } from 'cli/lib/site-utils';
import { keepSqliteIntegrationUpdated } from 'cli/lib/sqlite-integration';
import { StatsGroup } from 'cli/lib/types/bump-stats';
import { untildify } from 'cli/lib/utils';
import { ValidationError } from 'cli/lib/validation-error';
import { runBlueprint, startWordPressServer } from 'cli/lib/wordpress-server-manager';
import { Logger, LoggerError } from 'cli/logger';
import { StudioArgv } from 'cli/types';
const ALLOWED_PHP_VERSIONS = [ ...SupportedPHPVersions ];
const logger = new Logger< LoggerAction >();
type CreateCommandOptions = {
name?: string;
siteId?: string;
wpVersion: string;
phpVersion: ( typeof ALLOWED_PHP_VERSIONS )[ number ];
customDomain?: string;
enableHttps: boolean;
blueprint?: {
contents: unknown;
uri: string;
};
adminUsername?: string;
adminPassword?: string;
adminEmail?: string;
noStart: boolean;
skipBrowser: boolean;
skipLogDetails: boolean;
};
function resolveRuntimeFromEnv(): SiteRuntime {
return siteRuntimeSchema.catch( 'playground' ).parse( process.env.STUDIO_RUNTIME );
}
export async function runCommand(
sitePath: string,
options: CreateCommandOptions
): Promise< void > {
const isOnlineStatus = await isOnline();
try {
if ( isOnlineStatus ) {
const updated = await updateServerFiles();
if ( updated ) {
logger.reportSuccess( __( 'Dependencies updated' ) );
}
}
} catch ( error ) {
// Errors here aren't critical and likely relate to things outside the user's control,
// like network issues or bad API responses. Report them only in development.
if ( process.env.NODE_ENV !== 'production' ) {
const loggerError = new LoggerError( 'Failed to update dependencies', error );
logger.reportError( loggerError, false );
}
}
try {
logger.reportStart( LoggerAction.VALIDATE, __( 'Validating site configuration…' ) );
const pathExistsResult = await pathExists( sitePath );
const isEmptyDirResult = pathExistsResult && ( await isEmptyDir( sitePath ) );
const isWordPressDirResult = pathExistsResult && isWordPressDirectory( sitePath );
if ( pathExistsResult && ! isEmptyDirResult && ! isWordPressDirResult ) {
throw new LoggerError(
__( 'The selected directory is not empty nor an existing WordPress site.' )
);
}
let blueprintUri: string | undefined;
let blueprint: BlueprintV1Declaration | undefined;
let blueprintCredentials: { adminUsername?: string; adminPassword?: string } | null = null;
if ( options.blueprint ) {
const validation = await validateBlueprintData( options.blueprint.contents );
if ( ! validation.valid ) {
throw new LoggerError( validation.error );
}
// `validateBlueprintData()` does not give us a proper type guard, but in reality, it ensures
// `options.blueprint.contents` conforms to the `BlueprintV1Declaration` schema.
const formValues = extractFormValuesFromBlueprint(
options.blueprint.contents as BlueprintV1Declaration
);
if ( formValues.adminUsername || formValues.adminPassword ) {
blueprintCredentials = {
adminUsername: formValues.adminUsername,
adminPassword: formValues.adminPassword,
};
}
blueprintUri = options.blueprint.uri;
blueprint = options.blueprint.contents as BlueprintV1Declaration;
const blueprintHasMultisite = blueprint?.steps
?.filter( isStepDefinition )
.some( ( step ) => step.step === 'enableMultisite' );
if ( blueprintHasMultisite && ! options.customDomain ) {
throw new LoggerError(
__(
'The enableMultisite Blueprint step requires a custom domain. WordPress multisite does not support custom ports. Use --domain <name>.local to set a custom domain.'
)
);
}
}
const cliConfig = await readCliConfig();
if ( cliConfig.sites.some( ( site ) => arePathsEqual( site.path, sitePath ) ) ) {
throw new LoggerError( __( 'The selected directory is already in use.' ) );
}
for ( const site of cliConfig.sites ) {
portFinder.addUnavailablePort( site.port );
}
if ( options.customDomain ) {
const existingDomains = cliConfig.sites
.map( ( site ) => site.customDomain )
.filter( ( domain ): domain is string => Boolean( domain ) );
const domainError = getDomainNameValidationError(
true,
options.customDomain,
existingDomains
);
if ( domainError ) {
throw new LoggerError( domainError );
}
}
logger.reportSuccess( __( 'Site configuration validated' ) );
if ( ! pathExistsResult ) {
logger.reportStart( LoggerAction.CREATE_DIRECTORY, __( 'Creating site directory…' ) );
fs.mkdirSync( sitePath, { recursive: true } );
logger.reportSuccess( __( 'Site directory created' ) );
}
if ( options.wpVersion === 'latest' ) {
const bundledWPPath = path.join( getServerFilesPath(), 'wordpress-versions', 'latest' );
if ( ! ( await pathExists( bundledWPPath ) ) ) {
throw new LoggerError(
__(
'Cannot set up WordPress. Bundled WordPress files not found. Please connect to the internet or reinstall Studio.'
)
);
}
logger.reportStart( LoggerAction.SETUP_WORDPRESS, __( 'Copying bundled WordPress…' ) );
await recursiveCopyDirectory( bundledWPPath, sitePath );
logger.reportSuccess( __( 'WordPress files copied' ) );
} else if ( ! isOnlineStatus ) {
throw new LoggerError(
__(
'Cannot set up WordPress while offline. Specific WordPress versions require an internet connection. Try using "latest" version or ensure internet connectivity.'
)
);
}
logger.reportStart( LoggerAction.INSTALL_SQLITE, __( 'Setting up SQLite integration…' ) );
const isSqliteUpdated = await keepSqliteIntegrationUpdated( sitePath );
logger.reportSuccess(
isSqliteUpdated ? __( 'SQLite integration configured' ) : __( 'SQLite integration skipped' )
);
try {
const sharedConfig = await readSharedConfig();
const selectedSkills = sharedConfig.selectedSkills ?? [];
await installAiInstructionsToSite( sitePath, getAiInstructionsPath(), selectedSkills );
} catch ( error ) {
logger.reportError(
new LoggerError( __( 'Failed to install AI instructions. Proceeding anyway…' ), error ),
false
);
}
logger.reportStart( LoggerAction.ASSIGN_PORT, __( 'Assigning port…' ) );
const port = await portFinder.getOpenPort();
// translators: %d is the port number
logger.reportSuccess( sprintf( __( 'Port assigned: %d' ), port ) );
const siteName = options.name || path.basename( sitePath );
const siteId = options.siteId || crypto.randomUUID();
// Determine admin credentials: CLI args > Blueprint > defaults
// External passwords need to be encoded; createPassword() already returns encoded
const adminUsername = options.adminUsername || blueprintCredentials?.adminUsername || undefined;
if ( adminUsername ) {
const usernameError = validateAdminUsername( adminUsername );
if ( usernameError ) {
throw new LoggerError( usernameError );
}
}
const adminEmail = options.adminEmail?.trim() || undefined;
if ( adminEmail ) {
const emailError = validateAdminEmail( adminEmail );
if ( emailError ) {
throw new LoggerError( emailError );
}
}
const externalPassword = options.adminPassword || blueprintCredentials?.adminPassword;
const adminPassword = externalPassword ? encodePassword( externalPassword ) : createPassword();
const setupSteps: StepDefinition[] = [];
const siteLanguage = await getPreferredSiteLanguage( options.wpVersion );
if ( siteLanguage && siteLanguage !== DEFAULT_LOCALE ) {
// For the 'latest' WP version, try using bundled language packs first to avoid
// a network round-trip. Fall back to the Playground setSiteLanguage step for
// non-latest versions or when bundled packs aren't available.
let isUsingBundledLanguagePacks = false;
if ( options.wpVersion === DEFAULT_WORDPRESS_VERSION ) {
isUsingBundledLanguagePacks = await copyLanguagePackToSite( sitePath, siteLanguage );
}
if ( isUsingBundledLanguagePacks ) {
setupSteps.push(
{
step: 'defineWpConfigConsts',
consts: {
WPLANG: siteLanguage,
},
},
{
step: 'setSiteOptions',
options: {
WPLANG: siteLanguage,
},
}
);
} else if ( isOnlineStatus ) {
setupSteps.push(
{
step: 'setSiteLanguage',
language: siteLanguage,
},
{
step: 'setSiteOptions',
options: {
WPLANG: siteLanguage,
},
}
);
}
}
const hasWpConfig = await pathExists( path.join( sitePath, 'wp-config.php' ) );
const isWordPressDirectoryInitialized = isWordPressDirResult && hasWpConfig;
if ( options.name && ! isWordPressDirectoryInitialized ) {
setupSteps.push( {
step: 'setSiteOptions',
options: {
blogname: options.name,
},
} );
}
if ( setupSteps.length > 0 ) {
if ( ! blueprint ) {
blueprint = {};
// Since we know the user didn't supply a blueprint, we create an empty directory to use as a
// fake location for the `blueprintUri`
const blueprintDir = fs.mkdtempSync( path.join( os.tmpdir(), 'studio-empty-blueprint-' ) );
blueprintUri = path.join( blueprintDir, 'blueprint.json' );
}
const existingSteps = Array.isArray( blueprint.steps ) ? blueprint.steps : [];
blueprint = { ...blueprint, steps: [ ...setupSteps, ...existingSteps ] };
}
const siteDetails: SiteData = {
id: siteId,
name: siteName,
path: sitePath,
adminUsername,
adminPassword,
adminEmail,
port,
phpVersion: options.phpVersion,
running: false,
isWpAutoUpdating: options.wpVersion === DEFAULT_WORDPRESS_VERSION,
customDomain: options.customDomain,
enableHttps: options.enableHttps,
landingPage: normalizeLandingPage( blueprint?.landingPage ),
runtime: resolveRuntimeFromEnv(),
};
logger.reportStart( LoggerAction.SAVE_SITE, __( 'Saving site…' ) );
try {
await lockCliConfig();
const userData = await readCliConfig();
userData.sites.push( siteDetails );
sortSites( userData.sites );
await saveCliConfig( userData );
logger.reportSuccess( __( 'Site created successfully' ) );
} finally {
await unlockCliConfig();
}
if ( ! options.noStart ) {
logger.reportStart( LoggerAction.START_DAEMON, __( 'Starting process daemon…' ) );
await connectToDaemon();
logger.reportSuccess( __( 'Process daemon started' ) );
await setupCustomDomain( siteDetails, logger );
const startMessage = blueprint
? __( 'Starting WordPress server and applying Blueprint…' )
: __( 'Starting WordPress server…' );
logger.reportStart( LoggerAction.START_SITE, startMessage );
try {
const processDesc = await startWordPressServer( siteDetails, logger, {
wpVersion: options.wpVersion,
blueprint,
blueprintUri,
} );
logger.reportSuccess( __( 'WordPress server started' ) );
stripWpConfigDbConstants( sitePath );
if ( processDesc.status === 'online' ) {
await updateSiteLatestCliPid( siteDetails.id, processDesc.pid );
}
await updateSiteAutoStart( siteDetails.id, true );
siteDetails.running = true;
siteDetails.url = siteDetails.customDomain
? `${ siteDetails.enableHttps ? 'https' : 'http' }://${ siteDetails.customDomain }`
: `http://localhost:${ siteDetails.port }`;
if ( ! options.skipLogDetails ) {
logSiteDetails( siteDetails );
}
if ( ! options.skipBrowser ) {
await openSiteInBrowser( siteDetails );
}
} catch ( error ) {
await removeSiteFromConfig( siteDetails.id );
if ( ! isWordPressDirResult ) {
await fs.promises.rm( sitePath, { recursive: true, force: true } );
}
throw new LoggerError( __( 'Failed to start WordPress server' ), error );
}
} else {
if ( blueprint ) {
logger.reportStart( LoggerAction.START_DAEMON, __( 'Starting process daemon…' ) );
await connectToDaemon();
logger.reportSuccess( __( 'Process daemon started' ) );
logger.reportStart( LoggerAction.START_SITE, __( 'Applying Blueprint…' ) );
try {
if ( ! blueprintUri ) {
throw new LoggerError( __( 'Blueprint source path is missing' ) );
}
await runBlueprint( siteDetails, logger, {
wpVersion: options.wpVersion,
blueprint,
blueprintUri,
} );
logger.reportSuccess( __( 'Blueprint applied successfully' ) );
stripWpConfigDbConstants( sitePath );
} catch ( error ) {
await removeSiteFromConfig( siteDetails.id );
if ( ! isWordPressDirResult ) {
await fs.promises.rm( sitePath, { recursive: true, force: true } );
}
throw new LoggerError( __( 'Failed to apply Blueprint' ), error );
}
}
console.log( '' );
console.log( __( 'Site created successfully' ) );
console.log( '' );
if ( ! options.skipLogDetails ) {
logSiteDetails( siteDetails );
}
console.log( __( 'Run "studio site start" to start the site.' ) );
}
logger.reportKeyValuePair( 'id', siteDetails.id );
logger.reportKeyValuePair( 'running', String( siteDetails.running ) );
await emitCliEvent( { event: SITE_EVENTS.CREATED, data: { siteId: siteDetails.id } } );
} finally {
await disconnectFromDaemon();
}
}
async function fetchBlueprint( url: string ) {
const res = await fetch( url );
if ( ! res.ok ) {
throw new LoggerError( __( 'Failed to fetch Blueprint' ) );
}
try {
return await res.json();
} catch ( error ) {
throw new LoggerError( __( 'Failed to parse Blueprint JSON' ), error );
}
}
function stripWpConfigDbConstants( sitePath: string ): void {
const wpConfigPath = path.join( sitePath, 'wp-config.php' );
if ( ! fs.existsSync( wpConfigPath ) ) {
return;
}
const content = fs.readFileSync( wpConfigPath, 'utf-8' );
if ( hasDefaultDbBlock( content ) ) {
fs.writeFileSync( wpConfigPath, removeDbConstants( content ), 'utf-8' );
}
}
function readBlueprint( blueprintPath: string ) {
if ( ! fs.existsSync( blueprintPath ) ) {
throw new LoggerError( sprintf( __( 'Blueprint file not found: %s' ), blueprintPath ) );
}
try {
const blueprintContent = fs.readFileSync( blueprintPath, 'utf-8' );
return JSON.parse( blueprintContent );
} catch ( error ) {
throw new LoggerError(
sprintf( __( 'Failed to parse Blueprint JSON file: %s' ), blueprintPath ),
error
);
}
}
function coerceSiteId( value: string ) {
// Validate UUID format (8-4-4-4-12 hex characters)
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if ( ! uuidRegex.test( value ) ) {
throw new ValidationError( 'id', value, __( 'Must be a valid UUID' ) );
}
return value;
}
function coerceWpVersion( value: string ) {
if ( ! isValidWordPressVersion( value ) ) {
throw new ValidationError(
'wp',
value,
__(
'Must be: "latest", "nightly", or a valid version number (e.g., "6.4", "6.4.1", "6.4-beta1")'
)
);
}
if ( ! isWordPressVersionAtLeast( value, MINIMUM_WORDPRESS_VERSION ) ) {
throw new ValidationError(
'wp',
value,
sprintf( __( 'Must be: at least %s' ), MINIMUM_WORDPRESS_VERSION )
);
}
return value;
}
export const registerCommand = ( yargs: StudioArgv ) => {
return yargs.command( {
command: 'create',
describe: __( 'Create a new site' ),
builder: ( yargs ) => {
return yargs
.option( 'id', {
type: 'string',
describe: __( 'Site ID (UUID format, used internally by Studio app)' ),
hidden: true,
coerce: coerceSiteId,
} )
.option( 'name', {
type: 'string',
describe: __( 'Site name' ),
} )
.option( 'wp', {
type: 'string',
describe: __( 'WordPress version (e.g., "latest", "6.4", "6.4.1")' ),
defaultDescription: DEFAULT_WORDPRESS_VERSION,
coerce: coerceWpVersion,
} )
.option( 'php', {
type: 'string',
describe: __( 'PHP version' ),
choices: ALLOWED_PHP_VERSIONS,
defaultDescription: DEFAULT_PHP_VERSION,
} )
.option( 'domain', {
type: 'string',
describe: __( 'Custom domain (e.g., "mysite.local")' ),
} )
.option( 'https', {
type: 'boolean',
describe: __( 'Enable HTTPS for custom domain' ),
implies: 'domain',
} )
.option( 'blueprint', {
type: 'string',
describe: __( 'Path or URL to Blueprint JSON file' ),
} )
.option( 'original-blueprint-path', {
type: 'string',
hidden: true,
} )
.option( 'admin-username', {
type: 'string',
describe: __( 'Admin username (defaults to "admin")' ),
} )
.option( 'admin-password', {
type: 'string',
describe: __(
'Admin password (auto-generated if not provided). Note: passwords in CLI arguments may be visible in process lists; consider using a Blueprint file for sensitive passwords.'
),
} )
.option( 'admin-email', {
type: 'string',
describe: __( 'Admin email (defaults to "admin@localhost.com")' ),
} )
.option( 'start', {
type: 'boolean',
describe: __( 'Start the site after creation' ),
default: true,
} )
.option( 'skip-browser', {
type: 'boolean',
describe: __( 'Skip opening the site in browser after starting' ),
default: false,
} )
.option( 'skip-log-details', {
type: 'boolean',
describe: __( 'Skip printing site URL and admin credentials after creating' ),
default: false,
} );
},
handler: async ( argv ) => {
let siteName = argv.name;
let sitePath = argv.path;
let wpVersion = argv.wp;
let phpVersion = argv.php;
let customDomain = argv.domain;
let enableHttps = !! argv.https;
let adminUsername = argv.adminUsername;
let adminPassword = argv.adminPassword;
let adminEmail = argv.adminEmail;
// Validate and resolve the WordPress version against available versions before prompting
if ( wpVersion && wpVersion !== 'latest' && wpVersion !== 'nightly' ) {
try {
logger.reportStart( LoggerAction.VALIDATE, __( 'Checking WordPress version…' ) );
const availableVersions = await fetchWordPressVersions();
const matchedVersion = availableVersions.find(
( v ) => v.value === wpVersion || v.value.startsWith( wpVersion + '.' )
);
if ( ! matchedVersion ) {
const versionLabels = availableVersions
.filter( ( v ) => v.value !== 'latest' )
.map( ( v ) => v.label );
logger.reportError(
new LoggerError(
sprintf(
/* translators: %1$s: requested version, %2$s: list of available versions */
__( 'WordPress version "%1$s" is not available. Available versions: %2$s' ),
wpVersion,
versionLabels.join( ', ' )
)
)
);
return;
}
// Resolve short versions to full versions (e.g. "6.7" → "6.7.2")
if ( matchedVersion.value !== wpVersion ) {
logger.reportSuccess(
sprintf(
/* translators: %1$s: requested version, %2$s: resolved version */
__( 'WordPress version: %1$s → %2$s' ),
wpVersion,
matchedVersion.value
)
);
} else {
logger.reportSuccess(
sprintf(
/* translators: %s: WordPress version */
__( 'WordPress version: %s' ),
wpVersion
)
);
}
wpVersion = matchedVersion.value;
} catch {
// If we can't fetch versions (network issue), let it proceed and fail later
}
}
try {
if ( process.stdin.isTTY ) {
if ( ! siteName ) {
const defaultName = await generateSiteName();
siteName = await input( {
message: __( 'Site name:' ),
default: defaultName,
} );
}
const pathWasExplicitlyProvided = sitePath !== process.cwd();
if ( ! pathWasExplicitlyProvided ) {
const suggestedPath = getDefaultSitePath( siteName || __( 'My WordPress Website' ) );
const promptedPath = await input( {
message: __( 'Site path:' ),
default: suggestedPath,
} );
sitePath = path.resolve( untildify( promptedPath ) );
}
if ( ! wpVersion ) {
let wpChoices: { name: string; value: string }[];
try {
const versions = await fetchWordPressVersions();
wpChoices = versions.map( ( v ) => ( {
name: v.value === 'latest' ? `latest (${ v.label })` : v.label,
value: v.value,
} ) );
} catch {
// Offline or API failure — offer only "latest"
wpChoices = [
{
name: sprintf( __( '%s (recommended)' ), __( 'Latest' ) ),
value: 'latest',
},
];
}
wpVersion = await select( {
message: __( 'WordPress version:' ),
choices: wpChoices,
default: DEFAULT_WORDPRESS_VERSION,
loop: false,
} );
}
if ( ! phpVersion ) {
phpVersion = await select( {
message: __( 'PHP version:' ),
choices: ALLOWED_PHP_VERSIONS.map( ( v ) => ( {
name: v === DEFAULT_PHP_VERSION ? sprintf( __( '%s (recommended)' ), v ) : v,
value: v,
} ) ),
default: DEFAULT_PHP_VERSION,
} );
}
if ( ! customDomain ) {
const cliConfig = await readCliConfig();
const existingDomains = cliConfig.sites
.map( ( site ) => site.customDomain )
.filter( ( domain ): domain is string => Boolean( domain ) );
customDomain = await input( {
message: __( 'Custom domain (leave empty to skip):' ),
validate: ( value ) =>
getDomainNameValidationError( !! value, value, existingDomains ) || true,
} );
}
if ( customDomain && ! argv.https ) {
enableHttps = await confirm( {
message: __( 'Enable HTTPS?' ),
default: false,
} );
}
if ( ! adminUsername ) {
adminUsername = await input( {
message: __( 'Admin username:' ),
default: 'admin',
validate: ( value ) => validateAdminUsername( value ) || true,
} );
}
if ( ! adminPassword ) {
adminPassword = await password( {
message: __( 'Admin password (leave empty to auto-generate):' ),
mask: true,
} );
if ( ! adminPassword ) {
adminPassword = undefined;
}
}
if ( ! adminEmail ) {
adminEmail = await input( {
message: __( 'Admin email:' ),
default: 'admin@localhost.com',
validate: ( value ) => validateAdminEmail( value ) || true,
} );
}
}
} catch {
// User cancelled the prompt (Ctrl+C)
return;
}
// Apply defaults for non-interactive mode when flags weren't provided
wpVersion = wpVersion ?? DEFAULT_WORDPRESS_VERSION;
phpVersion = phpVersion ?? DEFAULT_PHP_VERSION;
const config: CreateCommandOptions = {
name: siteName,
siteId: argv.id,
wpVersion,
phpVersion,
customDomain,
enableHttps,
adminUsername,
adminPassword,
adminEmail,
noStart: ! argv.start,
skipBrowser: !! argv.skipBrowser,
skipLogDetails: !! argv.skipLogDetails,
};
if ( argv.blueprint ) {
if ( argv.blueprint.startsWith( 'http://' ) || argv.blueprint.startsWith( 'https://' ) ) {
config.blueprint = {
uri: argv.blueprint,
contents: await fetchBlueprint( argv.blueprint ),
};
} else {
const uri = path.resolve( untildify( argv.blueprint ) );
config.blueprint = {
uri,
contents: readBlueprint( uri ),
};
// When invoked by the desktop app, the blueprint contents come from a temp file
// but resources should be resolved relative to the original file location.
// For gallery blueprints the path is a URL; use it directly.
if ( argv.originalBlueprintPath ) {
const originalPath = argv.originalBlueprintPath;
config.blueprint.uri =
originalPath.startsWith( 'http://' ) || originalPath.startsWith( 'https://' )
? originalPath
: path.resolve( originalPath );
}
}
}
try {
await runCommand( sitePath, config );
if ( __ENABLE_CLI_TELEMETRY__ && ! argv.avoidTelemetry ) {
bumpStat(
__IS_PACKAGED_FOR_NPM__
? StatsGroup.STUDIO_CLI_SITE_CREATE_NPM
: StatsGroup.STUDIO_CLI_SITE_CREATE_APP,
getPlatformMetric()
);
}
} catch ( error ) {
if ( error instanceof LoggerError ) {
logger.reportError( error );
} else {
const loggerError = new LoggerError( __( 'Failed to create site' ), error );
logger.reportError( loggerError );
}
}
},
} );
};