-
Notifications
You must be signed in to change notification settings - Fork 417
Expand file tree
/
Copy pathrun-cli.ts
More file actions
1984 lines (1838 loc) · 58.2 KB
/
run-cli.ts
File metadata and controls
1984 lines (1838 loc) · 58.2 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 { errorLogPath, logger, LogSeverity } from '@php-wasm/logger';
import { ProcessIdAllocator } from '@php-wasm/universal';
import {
createObjectPoolProxy,
type Pooled,
type PHPRequest,
type PathAlias,
type RemoteAPI,
type SupportedPHPVersion,
} from '@php-wasm/universal';
import {
PHPResponse,
StreamedPHPResponse,
HttpCookieStore,
exposeAPI,
exposeSyncAPI,
printDebugDetails,
} from '@php-wasm/universal';
import type {
BlueprintBundle,
BlueprintV1Declaration,
BlueprintV2Declaration,
} from '@wp-playground/blueprints';
import {
compileBlueprintV1,
runBlueprintV1Steps,
} from '@wp-playground/blueprints';
import { RecommendedPHPVersion } from '@wp-playground/common';
import fs, { existsSync, mkdirSync, readdirSync, rmdirSync } from 'fs';
import type { Server } from 'http';
import { MessageChannel as NodeMessageChannel, Worker } from 'worker_threads';
// @ts-ignore
import {
expandAutoMounts,
parseMountDirArguments,
parseMountWithDelimiterArguments,
} from './mounts';
import {
parseDefineStringArguments,
parseDefineBoolArguments,
parseDefineNumberArguments,
} from './defines';
import { isPortInUse, startServer } from './start-server';
import type { PlaygroundCliBlueprintV1Worker } from './blueprints-v1/worker-thread-v1';
import type { PlaygroundCliBlueprintV2Worker } from './blueprints-v2/worker-thread-v2';
import type { XdebugOptions } from '@php-wasm/node';
/* eslint-disable no-console */
import {
SupportedPHPVersions,
FileLockManagerInMemory,
} from '@php-wasm/universal';
import type { MessagePort as NodeMessagePort } from 'worker_threads';
import yargs, { type Argv, type Options as YargsOptions } from 'yargs';
import { isValidWordPressSlug } from './is-valid-wordpress-slug';
import { resolveBlueprint } from './resolve-blueprint';
import { BlueprintsV2Handler } from './blueprints-v2/blueprints-v2-handler';
import { BlueprintsV1Handler } from './blueprints-v1/blueprints-v1-handler';
import { startBridge } from '@php-wasm/xdebug-bridge';
import path from 'path';
import os from 'os';
import { exec } from 'child_process';
import {
cleanupStalePlaygroundTempDirs,
createPlaygroundCliTempDir,
} from './temp-dir';
import { type WordPressInstallMode } from '@wp-playground/wordpress';
import {
type Mount,
addXdebugIDEConfig,
clearXdebugIDEConfig,
createTempDirSymlink,
removeTempDirSymlink,
makeXdebugConfig,
DEFAULT_PATH_SKIPPINGS,
} from '@php-wasm/cli-util';
import { createHash } from 'crypto';
import { CLIOutput } from './cli-output';
import {
getPhpMyAdminInstallSteps,
PHPMYADMIN_ENTRY_PATH,
PHPMYADMIN_INSTALL_PATH,
} from '@wp-playground/tools';
import { jspi } from 'wasm-feature-detect';
// Inlined worker URLs for static analysis by downstream bundlers
// These are replaced at build time by the Vite plugin in vite.config.ts
declare const __WORKER_V1_URL__: string;
declare const __WORKER_V2_URL__: string;
export const LogVerbosity = {
Quiet: { name: 'quiet', severity: LogSeverity.Fatal },
Normal: { name: 'normal', severity: LogSeverity.Info },
Debug: { name: 'debug', severity: LogSeverity.Debug },
} as const;
type LogVerbosity = (typeof LogVerbosity)[keyof typeof LogVerbosity]['name'];
export type WorkerType = 'v1' | 'v2';
/**
* Returned by parseOptionsAndRunCLI when the CLI should exit
* without starting a long-running server.
*/
export interface CLIExitResult {
exitCode: number;
}
/**
* Returned by parseOptionsAndRunCLI when a server was started
* and is still running.
*/
export interface CLIServerResult extends AsyncDisposable {
[internalsKeyForTesting]: { cliServer: RunCLIServer };
}
export type ParseCLIResult = CLIExitResult | CLIServerResult;
/**
* Internal sentinel thrown inside yargs callbacks (which can only
* signal failure by throwing) when validation has already been
* reported to the user. Caught within parseOptionsAndRunCLI and
* converted to a CLIExitResult — never exposed to callers.
*/
class CLIArgsValidationError extends Error {
exitCode: number;
constructor(exitCode: number) {
super();
this.exitCode = exitCode;
}
}
/**
* Parse the CLI args and run the appropriate command.
*
* Returns a structured result so the caller can decide how to
* exit. Only throws for truly unexpected errors.
*
* @param argsToParse string[] The CLI args to parse.
*/
export async function parseOptionsAndRunCLI(
argsToParse: string[]
): Promise<ParseCLIResult> {
try {
/**
* @TODO This looks similar to Query API args https://wordpress.github.io/wordpress-playground/developers/apis/query-api/
* Perhaps the two could be handled by the same code?
*/
const sharedOptions: Record<string, YargsOptions> = {
'site-url': {
describe:
'Site URL to use for WordPress. Defaults to http://127.0.0.1:{port}',
type: 'string',
},
php: {
describe: 'PHP version to use.',
type: 'string',
default: RecommendedPHPVersion,
choices: SupportedPHPVersions,
},
wp: {
describe: 'WordPress version to use.',
type: 'string',
default: 'latest',
},
define: {
describe:
'Define PHP string constants (can be used multiple times). ' +
'Format: NAME value. ' +
'These constants are set via php.defineConstant() and only exist for the current request. ' +
'Examples: --define API_KEY secret --define CON=ST "va=lu=e"',
type: 'string',
nargs: 2,
array: true,
coerce: parseDefineStringArguments,
},
'define-bool': {
describe:
'Define PHP boolean constants (can be used multiple times). ' +
'Format: NAME value. Value must be "true", "false", "1", or "0". ' +
'Examples: --define-bool WP_DEBUG true --define-bool MY_FEATURE false',
type: 'string',
nargs: 2,
array: true,
coerce: parseDefineBoolArguments,
},
'define-number': {
describe:
'Define PHP number constants (can be used multiple times). ' +
'Format: NAME value. ' +
'Examples: --define-number LIMIT 100 --define-number RATE 45.67',
type: 'string',
nargs: 2,
array: true,
coerce: parseDefineNumberArguments,
},
// @TODO: Support read-only mounts, e.g. via WORKERFS, a custom
// ReadOnlyNODEFS, or by copying the files into MEMFS
mount: {
describe:
'Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path',
type: 'array',
string: true,
nargs: 1,
coerce: parseMountWithDelimiterArguments,
},
'mount-before-install': {
describe:
'Mount a directory to the PHP runtime before WordPress installation (can be used multiple times). Format: /host/path:/vfs/path',
type: 'array',
string: true,
nargs: 1,
coerce: parseMountWithDelimiterArguments,
},
'mount-dir': {
describe:
'Mount a directory to the PHP runtime (can be used multiple times). Format: "/host/path" "/vfs/path"',
type: 'array',
nargs: 2,
array: true,
coerce: parseMountDirArguments,
},
'mount-dir-before-install': {
describe:
'Mount a directory before WordPress installation (can be used multiple times). Format: "/host/path" "/vfs/path"',
type: 'string',
nargs: 2,
array: true,
coerce: parseMountDirArguments,
},
login: {
describe: 'Should log the user in',
type: 'boolean',
default: false,
},
blueprint: {
describe: 'Blueprint to execute.',
type: 'string',
},
'blueprint-may-read-adjacent-files': {
describe:
'Consent flag: Allow "bundled" resources in a local blueprint to read files in the same directory as the blueprint file.',
type: 'boolean',
default: false,
},
'wordpress-install-mode': {
describe:
'Control how Playground prepares WordPress before booting.',
type: 'string',
default: 'download-and-install',
choices: [
'download-and-install',
'install-from-existing-files',
'install-from-existing-files-if-needed',
'do-not-attempt-installing',
] as const,
},
'skip-wordpress-install': {
describe: '[Deprecated] Use --wordpress-install-mode instead.',
type: 'boolean',
hidden: true,
},
'skip-sqlite-setup': {
describe:
'Skip the SQLite integration plugin setup to allow the WordPress site to use MySQL.',
type: 'boolean',
default: false,
},
// Hidden - Deprecated in favor of verbosity
quiet: {
describe: 'Do not output logs and progress messages.',
type: 'boolean',
default: false,
hidden: true,
},
verbosity: {
describe: 'Output logs and progress messages.',
type: 'string',
choices: Object.values(LogVerbosity).map(
(verbosity) => verbosity.name
),
default: 'normal',
},
debug: {
describe:
'Print PHP error log content if an error occurs during Playground boot.',
type: 'boolean',
default: false,
// Hide this deprecated option. Use verbosity=debug instead.
hidden: true,
},
'auto-mount': {
describe: `Automatically mount the specified directory. If no path is provided, mount the current working directory. You can mount a WordPress directory, a plugin directory, a theme directory, a wp-content directory, or any directory containing PHP and HTML files.`,
type: 'string',
},
'follow-symlinks': {
describe:
'Allow Playground to follow symlinks by automatically mounting symlinked directories and files encountered in mounted directories. \nWarning: Following symlinks will expose files outside mounted directories to Playground and could be a security risk.',
type: 'boolean',
default: false,
},
'experimental-trace': {
describe:
'Print detailed messages about system behavior to the console. Useful for troubleshooting.',
type: 'boolean',
default: false,
// Hide this option because we want to replace with a more general log-level flag.
hidden: true,
},
'internal-cookie-store': {
describe:
'Enable internal cookie handling. When enabled, Playground will manage cookies internally using ' +
'an HttpCookieStore that persists cookies across requests. When disabled, cookies are handled ' +
'externally (e.g., by a browser in Node.js environments).',
type: 'boolean',
default: false,
},
intl: {
describe: 'Enable Intl.',
type: 'boolean',
default: true,
},
redis: {
describe: 'Enable Redis (requires JSPI support).',
type: 'boolean',
// No default - will be determined at runtime based on JSPI availability
},
memcached: {
describe: 'Enable Memcached.',
type: 'boolean',
// No default - will be determined at runtime based on JSPI availability
},
xdebug: {
describe: 'Enable Xdebug.',
type: 'boolean',
default: false,
},
'experimental-unsafe-ide-integration': {
describe:
'Enable experimental IDE development tools. This option edits IDE config files ' +
'to set Xdebug path mappings and web server details. CAUTION: If there are bugs, ' +
'this feature may break your IDE config files. Please consider backing up your IDE configs ' +
'before using this feature.',
type: 'string',
// The empty value means the option is enabled for all
// supported IDEs and, if needed, will create the relevant
// config file for each.
choices: ['', 'vscode', 'phpstorm'],
coerce: (value?: string) =>
value === '' ? ['vscode', 'phpstorm'] : [value],
},
'experimental-blueprints-v2-runner': {
describe: 'Use the experimental Blueprint V2 runner.',
type: 'boolean',
default: false,
// Remove the "hidden" flag once Blueprint V2 is fully supported
hidden: true,
},
mode: {
describe:
'Blueprints v2 runner mode to use. This option is required when using the --experimental-blueprints-v2-runner flag with a blueprint.',
type: 'string',
choices: ['create-new-site', 'apply-to-existing-site'],
// Remove the "hidden" flag once Blueprint V2 is fully supported
hidden: true,
},
phpmyadmin: {
describe:
'Install phpMyAdmin for database management. The phpMyAdmin URL will be printed after boot. Optionally specify a custom URL path (default: /phpmyadmin).',
type: 'string',
coerce: (value?: string) =>
'' === value ? '/phpmyadmin' : value,
},
};
const serverOnlyOptions: Record<string, YargsOptions> = {
port: {
describe:
'Port to listen on when serving. Defaults to 9400 when available.',
type: 'number',
},
'experimental-multi-worker': {
deprecated:
'This option is not needed. Multiple workers are always used.',
describe:
'Enable experimental multi-worker support which requires ' +
'a /wordpress directory backed by a real filesystem. ' +
'Pass a positive number to specify the number of workers to use. ' +
'Otherwise, default to the number of CPUs minus 1.',
type: 'number',
},
'experimental-devtools': {
describe: 'Enable experimental browser development tools.',
type: 'boolean',
},
};
/**
* Options for the high-level `start` command.
* This command provides a simplified, opinionated interface for common use cases,
* similar to wp-now. It auto-detects project type and uses sensible defaults.
*/
const startCommandOptions: Record<string, YargsOptions> = {
path: {
describe:
'Path to the project directory. Playground will auto-detect if this is a plugin, theme, wp-content, or WordPress directory.',
type: 'string',
default: process.cwd(),
},
php: {
describe: 'PHP version to use.',
type: 'string',
default: RecommendedPHPVersion,
choices: SupportedPHPVersions,
},
wp: {
describe: 'WordPress version to use.',
type: 'string',
default: 'latest',
},
port: {
describe: 'Port to listen on. Defaults to 9400 when available.',
type: 'number',
},
blueprint: {
describe:
'Path to a Blueprint JSON file to execute on startup.',
type: 'string',
},
login: {
describe: 'Auto-login as the admin user.',
type: 'boolean',
default: true,
},
xdebug: {
describe: 'Enable Xdebug for debugging.',
type: 'boolean',
default: false,
},
'experimental-unsafe-ide-integration':
sharedOptions['experimental-unsafe-ide-integration'],
'skip-browser': {
describe:
'Do not open the site in your default browser on startup.',
type: 'boolean',
default: false,
},
quiet: {
describe: 'Suppress non-essential output.',
type: 'boolean',
default: false,
},
// Advanced options for power users who need more control
'site-url': {
describe:
'Override the site URL. By default, derived from the port (http://127.0.0.1:<port>).',
type: 'string',
},
mount: {
describe:
'Mount a directory to the PHP runtime (can be used multiple times). Format: /host/path:/vfs/path. Use this for additional mounts beyond auto-detection.',
type: 'array',
string: true,
coerce: parseMountWithDelimiterArguments,
},
reset: {
describe:
'Deletes the stored site directory and starts a new site from scratch.',
type: 'boolean',
default: false,
},
'no-auto-mount': {
describe:
'Disable automatic project type detection. Use --mount to manually specify mounts instead.',
type: 'boolean',
default: false,
},
// Define constants
define: sharedOptions['define'],
'define-bool': sharedOptions['define-bool'],
'define-number': sharedOptions['define-number'],
// Tools
phpmyadmin: sharedOptions['phpmyadmin'],
};
const buildSnapshotOnlyOptions: Record<string, YargsOptions> = {
outfile: {
describe: 'When building, write to this output file.',
type: 'string',
default: 'wordpress.zip',
},
};
const yargsObject = yargs(argsToParse)
.usage('Usage: wp-playground <command> [options]')
.command(
'start',
'Start a local WordPress server with automatic project detection (recommended)',
(yargsInstance: Argv) =>
yargsInstance
.usage(
'Usage: wp-playground start [options]\n\n' +
'The easiest way to run WordPress locally. Automatically detects\n' +
'if your directory contains a plugin, theme, wp-content, or\n' +
'WordPress installation and configures everything for you.\n\n' +
'Examples:\n' +
' wp-playground start # Start in current directory\n' +
' wp-playground start --path=./my-plugin # Start with a specific path\n' +
' wp-playground start --wp=6.7 --php=8.3 # Use specific versions\n' +
' wp-playground start --skip-browser # Skip opening browser\n' +
' wp-playground start --no-auto-mount # Disable auto-detection'
)
.options(startCommandOptions)
)
.command(
'server',
'Start a local WordPress server (advanced, low-level)',
(yargsInstance: Argv) =>
yargsInstance.options({
...sharedOptions,
...serverOnlyOptions,
})
)
.command(
'run-blueprint',
'Execute a Blueprint without starting a server',
(yargsInstance: Argv) =>
yargsInstance.options({ ...sharedOptions })
)
.command(
'build-snapshot',
'Build a ZIP snapshot of a WordPress site based on a Blueprint',
(yargsInstance: Argv) =>
yargsInstance.options({
...sharedOptions,
...buildSnapshotOnlyOptions,
})
)
.command('php', 'Run a PHP script', (yargsInstance: Argv) =>
yargsInstance.options({ ...sharedOptions })
)
.demandCommand(1, 'Please specify a command')
.strictCommands()
.conflicts(
'experimental-unsafe-ide-integration',
'experimental-devtools'
)
.showHelpOnFail(false)
.fail((msg, err, yargsInstance) => {
if (err) {
throw err;
}
if (msg && msg.includes('Please specify a command')) {
yargsInstance.showHelp();
console.error('\n' + msg);
} else {
console.error(msg);
}
throw new CLIArgsValidationError(1);
})
.strictOptions()
.check(async (args) => {
if (args['skip-wordpress-install'] === true) {
args['wordpress-install-mode'] =
'do-not-attempt-installing';
args['wordpressInstallMode'] = 'do-not-attempt-installing';
}
if (
args['wp'] !== undefined &&
typeof args['wp'] === 'string' &&
!isValidWordPressSlug(args['wp'])
) {
try {
// Check if is valid URL
new URL(args['wp']);
} catch {
throw new Error(
'Unrecognized WordPress version. Please use "latest", "beta", "trunk", "nightly", a URL, or a numeric version such as "6.2", "6.0.1", "6.2-beta1", or "6.2-RC1" (see --help for details).'
);
}
}
const siteUrlArg = args['site-url'];
if (
typeof siteUrlArg === 'string' &&
siteUrlArg.trim() !== ''
) {
try {
new URL(siteUrlArg);
} catch {
throw new Error(
`Invalid site-url "${siteUrlArg}". Please provide a valid URL (e.g., http://localhost:8080 or https://example.com)`
);
}
}
if (args['auto-mount']) {
let autoMountIsDir = false;
try {
const autoMountStats = fs.statSync(
args['auto-mount'] as string
);
autoMountIsDir = autoMountStats.isDirectory();
} catch {
autoMountIsDir = false;
}
if (!autoMountIsDir) {
throw new Error(
`The specified --auto-mount path is not a directory: '${args['auto-mount']}'.`
);
}
}
if (args['experimental-blueprints-v2-runner'] === true) {
// TODO: Remove this once we have reworked the Blueprints v2 runner.
throw new Error(
'Blueprints v2 are temporarily disabled while we rework their runtime implementation.'
);
if (args['mode'] !== undefined) {
if (args['wordpress-install-mode'] !== undefined) {
throw new Error(
'The --wordpress-install-mode option cannot be used with the --mode option. Use one or the other.'
);
}
if ('skip-sqlite-setup' in args) {
throw new Error(
'The --skipSqliteSetup option is not supported in Blueprint V2 mode.'
);
}
if (args['auto-mount'] !== undefined) {
throw new Error(
'The --mode option cannot be used with --auto-mount because --auto-mount automatically sets the mode.'
);
}
} else {
// Support the legacy v1 runner options
if (
args['wordpress-install-mode'] ===
'do-not-attempt-installing'
) {
args['mode'] = 'apply-to-existing-site';
} else {
args['mode'] = 'create-new-site';
}
}
// Support the legacy v1 runner options
const allow = (args['allow'] as string[]) || [];
if (args['followSymlinks'] === true) {
allow.push('follow-symlinks');
}
if (args['blueprint-may-read-adjacent-files'] === true) {
allow.push('read-local-fs');
}
args['allow'] = allow;
} else {
if (args['mode'] !== undefined) {
throw new Error(
'The --mode option requires the --experimentalBlueprintsV2Runner flag.'
);
}
}
return true;
});
yargsObject.wrap(yargsObject.terminalWidth());
const args = await yargsObject.argv;
const command = args._[0] as string;
if (
![
'start',
'run-blueprint',
'server',
'build-snapshot',
'php',
].includes(command)
) {
yargsObject.showHelp();
throw new CLIArgsValidationError(1);
}
const define = (args['define'] || {}) as Record<string, string>;
const defineBool = (args['define-bool'] || {}) as Record<
string,
boolean
>;
const defineNumber = (args['define-number'] || {}) as Record<
string,
number
>;
const hasDebugDefine = (name: string) => {
return name in define || name in defineBool || name in defineNumber;
};
if (!hasDebugDefine('WP_DEBUG')) {
define['WP_DEBUG'] = 'true';
}
if (!hasDebugDefine('WP_DEBUG_LOG')) {
define['WP_DEBUG_LOG'] = 'true';
}
if (!hasDebugDefine('WP_DEBUG_DISPLAY')) {
define['WP_DEBUG_DISPLAY'] = 'false';
}
const cliArgs = {
...args,
define,
command,
mount: [
...((args['mount'] as Mount[]) || []),
...((args['mount-dir'] as Mount[]) || []),
],
'mount-before-install': [
...((args['mount-before-install'] as Mount[]) || []),
...((args['mount-dir-before-install'] as Mount[]) || []),
],
} as RunCLIArgs;
const cliResult = await runCLI(cliArgs);
if (typeof cliResult === 'number') {
// A one-shot command (e.g. `php`) finished with an
// explicit exit code.
return { exitCode: cliResult };
}
if (cliResult === undefined) {
// No server was started, so we are done with our work.
return { exitCode: 0 };
}
return {
[Symbol.asyncDispose]: () => cliResult[Symbol.asyncDispose](),
[internalsKeyForTesting]: { cliServer: cliResult },
};
} catch (e) {
// Validation errors have already been reported to the
// user (e.g. by the yargs .fail() handler). Convert them
// to a structured result instead of re-throwing.
if (e instanceof CLIArgsValidationError) {
return { exitCode: e.exitCode };
}
// Unexpected error — log details and re-throw so the
// caller (cli.ts) can exit with a non-zero code.
console.error(e);
const debug = process.argv.includes('--debug');
if (e instanceof Error) {
if (debug) {
printDebugDetails(e);
} else {
const messageChain = [];
let currentError: Error | undefined = e;
do {
messageChain.push(currentError.message);
currentError = currentError.cause as Error;
} while (currentError instanceof Error);
console.error(
'\x1b[1m' + messageChain.join(' caused by: ') + '\x1b[0m'
);
}
} else {
console.error('\x1b[1m' + describeError(e) + '\x1b[0m');
}
throw e;
}
}
/**
* Describe an error for display. Handles Error instances, Comlink-serialized
* plain objects (which lose their Error prototype during worker thread
* transfer), and arbitrary values.
*/
function describeError(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (error && typeof error === 'object') {
// Comlink-serialized errors arrive as plain objects like
// { name: 'ErrnoError', errno: 20 } with no .message.
const parts = [];
const obj = error as Record<string, unknown>;
if (obj['name']) {
parts.push(String(obj['name']));
}
if (obj['message']) {
parts.push(String(obj['message']));
}
if (obj['errno'] !== undefined) {
parts.push(`errno: ${obj['errno']}`);
}
if (parts.length > 0) {
return parts.join(' — ');
}
// Last resort: JSON-serialize the object so we at least see
// what fields it has.
try {
return JSON.stringify(error);
} catch {
return String(error);
}
}
return String(error);
}
function getMountForVfsPath(
mounts: Mount[],
vfsPath: string
): Mount | undefined {
return mounts.find(
(mount) =>
mount.vfsPath.replace(/\/$/, '') === vfsPath.replace(/\/$/, '')
);
}
export interface RunCLIArgs {
/**
* `_` holds positional tokens in the order they appeared.
* `_[0]` will typically be the command name.
*/
_?: string[];
blueprint?:
| BlueprintV1Declaration
| BlueprintV2Declaration
| BlueprintBundle;
command: 'start' | 'server' | 'run-blueprint' | 'build-snapshot' | 'php';
debug?: boolean;
login?: boolean;
mount?: Mount[];
'mount-before-install'?: Mount[];
outfile?: string;
php?: SupportedPHPVersion;
port?: number;
'site-url'?: string;
quiet?: boolean;
verbosity?: LogVerbosity;
wp?: string;
autoMount?: string;
pathAliases?: PathAlias[];
experimentalTrace?: boolean;
internalCookieStore?: boolean;
'additional-blueprint-steps'?: any[];
intl?: boolean;
phpmyadmin?: boolean | string;
redis?: boolean;
memcached?: boolean;
xdebug?: boolean | XdebugOptions;
experimentalUnsafeIdeIntegration?: string[];
experimentalDevtools?: boolean;
'experimental-blueprints-v2-runner'?: boolean;
wordpressInstallMode?: WordPressInstallMode;
/**
* PHP string constants defined via --define flag.
* Set via php.defineConstant(), process-specific only.
*/
define?: Record<string, string>;
/**
* PHP boolean constants defined via --define-bool flag.
* Set via php.defineConstant(), process-specific only.
*/
'define-bool'?: Record<string, boolean>;
/**
* PHP number constants defined via --define-number flag.
* Set via php.defineConstant(), process-specific only.
*/
'define-number'?: Record<string, number>;
// --------- Blueprint V1 args -----------
skipSqliteSetup?: boolean;
followSymlinks?: boolean;
'blueprint-may-read-adjacent-files'?: boolean;
// --------- Blueprint V2 args -----------
mode?: 'mount-only' | 'create-new-site' | 'apply-to-existing-site';
// --------- Blueprint V2 args (not available via CLI yet) -----------
'db-engine'?: 'sqlite' | 'mysql';
'db-host'?: string;
'db-user'?: string;
'db-pass'?: string;
'db-name'?: string;
'db-path'?: string;
'truncate-new-site-directory'?: boolean;
allow?: string;
// --------- Start command args -----------
path?: string;
skipBrowser?: boolean;
noAutoMount?: boolean;
reset?: boolean;
}
// TODO: Maybe we should just be declaring an interface instead of a type union
export type PlaygroundCliWorker =
| PlaygroundCliBlueprintV1Worker
| PlaygroundCliBlueprintV2Worker;
export const internalsKeyForTesting = Symbol('playground-cli-testing');
export interface RunCLIServer extends AsyncDisposable {
playground: Pooled<PlaygroundCliWorker>;
server: Server;
serverUrl: string;
[Symbol.asyncDispose](): Promise<void>;
// Provide some details and helpers for automated testing.
[internalsKeyForTesting]: {
workerThreadCount: number;
};
}
const bold = (text: string) =>
process.stdout.isTTY ? '\x1b[1m' + text + '\x1b[0m' : text;
const red = (text: string) =>
process.stdout.isTTY ? '\x1b[31m' + text + '\x1b[0m' : text;
const dim = (text: string) =>
process.stdout.isTTY ? `\x1b[2m${text}\x1b[0m` : text;
const italic = (text: string) =>
process.stdout.isTTY ? `\x1b[3m${text}\x1b[0m` : text;
const highlight = (text: string) =>
process.stdout.isTTY ? `\x1b[33m${text}\x1b[0m` : text;
// These overloads are declared for convenience so runCLI() can return
// different things depending on the CLI command without forcing the
// callers (mostly automated tests) to check return values.
// Re-export merge functions from defines.ts
export { mergeDefinedConstants } from './defines';
export async function runCLI(
args: RunCLIArgs & { command: 'build-snapshot' | 'run-blueprint' }
): Promise<void>;
export async function runCLI(
args: RunCLIArgs & { command: 'php' }
): Promise<number>;
export async function runCLI(
args: RunCLIArgs & { command: 'start' }
): Promise<RunCLIServer>;
export async function runCLI(
args: RunCLIArgs & { command: 'server' }
): Promise<RunCLIServer>;
export async function runCLI(
args: RunCLIArgs
): Promise<RunCLIServer | number | void>;
export async function runCLI(
args: RunCLIArgs
): Promise<RunCLIServer | number | void> {
let playgroundPool: Pooled<PlaygroundCliWorker>;
const cookieStore = args.internalCookieStore
? new HttpCookieStore()
: undefined;
const spawnedWorkers: SpawnedWorker[] = [];
const workerToPlaygroundMap: Map<
// TODO: Can this just be the worker, not a data structure with a port?
SpawnedWorker,
RemoteAPI<PlaygroundCliWorker>
> = new Map();
if (args.command === 'start') {
args = expandStartCommandArgs(args);
}
if (args.autoMount !== undefined) {
if (args.autoMount === '') {
// No auto-mount path was provided, so use the current working directory.
// Note: We default here instead of in the yargs declaration because
// it allows us to test the default as part of the runCLI() unit tests.
args = { ...args, autoMount: process.cwd() };
}
args = expandAutoMounts(args);
}
if (args.wordpressInstallMode === undefined) {
args.wordpressInstallMode = 'download-and-install';
}
// Keeping the '--quiet' option to preserve backward compatibility
if (args.quiet) {
args.verbosity = 'quiet';
delete args['quiet'];
}
// Keeping the '--debug' option to preserve backward compatibility
if (args.debug) {
args.verbosity = 'debug';
delete args['debug'];
}
if (args.verbosity) {
const severity = Object.values(LogVerbosity).find(
(v) => v.name === args.verbosity