-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathModule.cfc
More file actions
6029 lines (5421 loc) · 211 KB
/
Module.cfc
File metadata and controls
6029 lines (5421 loc) · 211 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
/**
* Wheels CLI Module for LuCLI
*
* Provides code generation, migrations, testing, and server management
* for Wheels applications. Each public function is a subcommand:
*
* wheels new myapp
* wheels create app myapp --port=3000
* wheels generate model User name email
* wheels migrate latest
* wheels test --filter=models
* wheels start
*
* hint: Wheels framework CLI - create, generate, migrate, test, and manage your app
*/
component extends="modules.BaseModule" {
function init(
boolean verboseEnabled = false,
boolean timingEnabled = false,
string cwd = "",
any timer = nullValue(),
struct moduleConfig = {}
) {
super.init(argumentCollection = arguments);
// Resolve project root (where lucee.json / vendor/wheels lives)
variables.projectRoot = resolveProjectRoot(arguments.cwd);
// Module root for template resolution
variables.moduleRoot = getDirectoryFromPath(getCurrentTemplatePath());
// Lazy-init service instances
variables.services = {};
return this;
}
/**
* Extract positional arguments from LuCLI's argCollection or __arguments.
*
* LuCLI dispatches module subcommands as:
* module.subcommand(argumentCollection={arg1:"val1", arg2:"val2", ...})
* where argCollection contains positional args as arg1..argN keys.
*
* Falls back to __arguments (minus the subcommand at index 1) for
* direct CFC invocation in tests.
*/
private array function getArgs(struct callerArgs = {}) {
// Prefer caller's arguments (LuCLI passes argCollection which spreads
// positional args as arg1, arg2, ... into the function's arguments scope)
if (structKeyExists(callerArgs, "arg1")) {
return argsFromCollection(callerArgs);
}
// Fallback: __arguments (direct invocation / tests)
var raw = __arguments ?: [];
if (isArray(raw) && arrayLen(raw) > 0) {
return raw;
}
return [];
}
/**
* Reconstruct args array from LuCLI's argCollection.
* Positional args are stored as arg1, arg2, ... (order matters).
* Named args (--key=value) are stored as key=value and must be
* re-prefixed with -- so parseGeneratorArgs() can parse them.
*/
private array function argsFromCollection(required struct coll) {
var result = [];
// Extract positional args in order
var i = 1;
while (structKeyExists(coll, "arg#i#")) {
arrayAppend(result, coll["arg#i#"]);
i++;
}
// Re-add named args as --key=value flags
for (var key in coll) {
if (reFindNoCase("^arg\d+$", key)) continue; // skip positional
var value = coll[key];
if (isSimpleValue(value) && value == "true") {
// Boolean flag: --key
arrayAppend(result, "--" & key);
} else if (isSimpleValue(value) && value == "false") {
// Negated flag: skip (--no-key was already converted)
} else if (isSimpleValue(value)) {
arrayAppend(result, "--" & key & "=" & value);
}
}
return result;
}
// ─────────────────────────────────────────────────
// MCP framework convention — hide CLI-only commands
// ─────────────────────────────────────────────────
/**
* hint: Declare public functions to hide from MCP tools/list.
*
* These remain reachable as CLI subcommands. Hidden because they are
* stateful (start/stop), destructive (new scaffolds a whole project),
* interactive (console), meta (mcp), alias (d), or don't translate to
* single-call MCP semantics (browser). Read by LuCLI >= 0.3.4 per the
* mcpHiddenTools() convention.
*/
public array function mcpHiddenTools() {
return [
"mcp", // meta command — prints MCP setup instructions
"d", // alias for destroy
"new", // scaffolds a whole new Wheels project
"console", // interactive CFML REPL — not usable over stdio
"start", // dev server lifecycle (stateful)
"stop", // dev server lifecycle (stateful)
"browser" // multi-step browser testing flow
];
}
// ─────────────────────────────────────────────────
// version / help — banner + command listing
// ─────────────────────────────────────────────────
// Emits the three-line `wheels --version` format the installation guide
// documents (Wheels Module + LuCLI runtime + JVM). See
// web/sites/guides/.../command-line-tools/installation.mdx for the
// canonical output shape; issue #2431 tracked the prior banner output
// drifting from the doc.
/**
* hint: Show Wheels Module, LuCLI runtime, and JVM versions
*/
public string function version() {
var nl = chr(10);
var moduleVersion = super.version();
var channel = new services.ReleaseChannel().classify(moduleVersion);
var channelTag = len(channel) ? " (" & channel & ")" : "";
var lines = ["Wheels " & moduleVersion & channelTag];
var lucliVersion = $detectLucliVersion();
if (len(lucliVersion)) {
arrayAppend(lines, "LuCLI " & lucliVersion);
}
var javaVersion = $detectJavaVersion();
if (len(javaVersion)) {
arrayAppend(lines, "Java " & javaVersion);
}
return arrayToList(lines, nl);
}
private string function $detectLucliVersion() {
try {
var sys = createObject("java", "java.lang.System");
var v = sys.getProperty("lucli.version");
if (!isNull(v) && len(v)) {
return v;
}
v = sys.getenv("LUCLI_VERSION");
if (!isNull(v) && len(v)) {
return v;
}
} catch (any e) {
// fall through
}
return "";
}
private string function $detectJavaVersion() {
try {
var sys = createObject("java", "java.lang.System");
var v = sys.getProperty("java.version");
if (!isNull(v) && len(v)) {
return v;
}
} catch (any e) {
// fall through
}
return "";
}
// Hand-written replacement for BaseModule's auto-discovered help. Grouped by
// task instead of alphabetical, mirrors what `wheels --help` emits from the
// wrapper. `wheels help` and `wheels --help` (rewritten by LuCLI's
// preprocessModuleHelp) both reach this.
/**
* hint: Show this help
*/
public string function showHelp() {
var v = super.version();
var nl = chr(10);
var help = "Wheels CLI " & v & nl;
help &= " CFML MVC framework — code generation, migrations, testing, server management" & nl & nl;
help &= "Usage:" & nl;
help &= " wheels <command> [options]" & nl & nl;
help &= "Getting Started:" & nl;
help &= " new <name> Scaffold a new Wheels application" & nl;
help &= " start Start the dev server" & nl;
help &= " stop Stop the dev server" & nl;
help &= " reload Reload the running app" & nl & nl;
help &= "Code Generation:" & nl;
help &= " generate Generate model, controller, scaffold, migration, etc." & nl;
help &= " destroy (or d) Remove generated files" & nl & nl;
help &= "Database:" & nl;
help &= " migrate Run database migrations (latest, up, down, info, rename-system-tables)" & nl;
help &= " seed Run database seeds" & nl;
help &= " db Database management (reset, status, version)" & nl & nl;
help &= "Testing & Inspection:" & nl;
help &= " test Run the test suite" & nl;
help &= " browser Browser-based tests (Playwright)" & nl;
help &= " console Open an interactive CFML REPL connected to your app" & nl;
help &= " routes Print the route table" & nl;
help &= " info Show framework version, environment, configuration" & nl;
help &= " doctor Diagnose project setup issues" & nl;
help &= " validate Validate project structure and configuration" & nl;
help &= " analyze Static analysis of project code" & nl;
help &= " stats Project statistics (lines of code, model counts, etc.)" & nl;
help &= " notes Find TODO / FIXME / HACK / OPTIMIZE comments" & nl & nl;
help &= "Packages & Deployment:" & nl;
help &= " packages Add, update, search Wheels packages (verb is `add`, not `install`)" & nl;
help &= " upgrade Scan for breaking changes before upgrading Wheels (read-only)" & nl;
help &= " deploy Deploy your app (Kamal-compatible)" & nl & nl;
help &= "Other:" & nl;
help &= " mcp Configure Wheels MCP server for AI assistants" & nl;
help &= " version Show Wheels CLI version" & nl;
help &= " help Show this help" & nl & nl;
help &= "For command-specific help: wheels <command> --help" & nl & nl;
help &= "More info: https://guides.wheels.dev";
return help;
}
// ─────────────────────────────────────────────────
// generate — Code generation
// ─────────────────────────────────────────────────
/**
* hint: Generate Wheels components (model, controller, view, migration, scaffold, route, test, property, api-resource, helper, snippets)
*/
public string function generate() {
var args = getArgs(arguments);
if (!arrayLen(args)) {
out("Usage: wheels generate <type> <name> [attributes...]", "yellow");
out("");
out("Types:", "bold");
out(" app Create a new Wheels application (alias for 'wheels new')");
out(" model Generate a model CFC");
out(" controller Generate a controller CFC");
out(" view Generate a view template");
out(" migration Generate a database migration");
out(" scaffold Generate model + controller + views + migration + tests + routes");
out(" api-resource Generate API-only model + controller + migration + tests + routes (no views)");
out(" route Add a resource route to config/routes.cfm");
out(" test Generate a test spec file");
out(" property Generate an add-column migration for a model property");
out(" helper Generate a helper file in app/helpers/");
out(" snippets Generate common code pattern snippets (auth, soft-delete, api, etc.)");
out(" admin Generate admin CRUD interface for an existing model");
out("");
out("Examples:", "bold");
out(" wheels generate app myapp");
out(" wheels generate model User name email:string active:boolean");
out(" wheels generate controller Users index show create");
out(" wheels generate migration CreateUsers");
out(" wheels generate scaffold Post title body:text publishedAt:datetime");
out(" wheels generate api-resource Product name price:decimal sku:string");
out(" wheels generate route posts");
out(" wheels generate test model User");
out(" wheels generate property User email:string");
out(" wheels generate helper formatting");
out(" wheels generate snippets auth");
out(" wheels generate admin User");
return "";
}
var type = args[1];
var remaining = args.len() > 1 ? args.slice(2) : [];
switch (lCase(type)) {
case "app":
case "a":
// Delegate to wheels new — pass remaining args as __arguments
__arguments = remaining;
return new();
case "model":
case "m":
return generateModel(remaining);
case "controller":
case "c":
return generateController(remaining);
case "view":
case "v":
return generateView(remaining);
case "migration":
case "migrate":
return generateMigration(remaining);
case "scaffold":
case "s":
return generateScaffold(remaining);
case "api-resource":
case "api":
return generateApiResource(remaining);
case "route":
case "r":
return generateRoute(remaining);
case "test":
return generateTest(remaining);
case "property":
case "prop":
return generateProperty(remaining);
case "helper":
case "h":
return generateHelper(remaining);
case "snippets":
return generateSnippets(remaining);
case "admin":
return generateAdmin(remaining);
default:
out("Unknown generator type: #type#", "red");
out("Run 'wheels generate' for available types.");
return "";
}
}
// ─────────────────────────────────────────────────
// migrate — Database migration management
// ─────────────────────────────────────────────────
/**
* hint: Run database migrations (latest, up, down, info)
*/
public string function migrate() {
var args = getArgs(arguments);
var action = arrayLen(args) ? lCase(args[1]) : "latest";
switch (action) {
case "latest":
case "up":
case "down":
case "info":
try {
return runMigration(action);
} catch (MigrationError e) {
out("Migration failed: #e.message#", "red");
return "";
}
case "rename-system-tables":
// F15 Phase 2: opt-in one-shot rename of legacy c_o_r_e_*
// system tables to wheels_*. Idempotent (no-op when nothing
// to rename); refuses to run on a partial-rename state.
var dryRun = false;
for (var i = 2; i <= arrayLen(args); i++) {
if (args[i] == "--dry-run") dryRun = true;
}
try {
return runRenameSystemTables(dryRun);
} catch (MigrationError e) {
out("Rename failed: #e.message#", "red");
return "";
}
default:
out("Unknown migration action: #action#", "red");
out("Usage: wheels migrate [latest|up|down|info|rename-system-tables]");
return "";
}
}
// ─────────────────────────────────────────────────
// seed — Database seeding
// ─────────────────────────────────────────────────
/**
* hint: Run database seeds (convention-based or generated)
*/
public string function seed() {
var args = getArgs(arguments);
var environment = "";
var mode = "auto";
for (var i = 1; i <= arrayLen(args); i++) {
var arg = args[i];
if (reFindNoCase("^--environment=", arg)) {
environment = valueAfterEquals(arg);
} else if (reFindNoCase("^--mode=", arg)) {
mode = valueAfterEquals(arg);
} else if (arg == "--generate") {
mode = "generate";
}
}
return runSeed(mode, environment);
}
// ─────────────────────────────────────────────────
// test — Run test suite
// ─────────────────────────────────────────────────
/**
* hint: Run test suite with optional filter and reporter
*/
public string function test() {
var args = getArgs(arguments);
var filter = "";
var reporter = "simple";
var format = "json";
var verboseOutput = false;
var ciMode = false;
var coreTests = false;
var db = "sqlite";
var dbExplicit = false;
var useTestDB = true;
// Parse named arguments from --key=value or --key value
for (var i = 1; i <= arrayLen(args); i++) {
var arg = args[i];
if (arg == "--filter" && i < arrayLen(args)) {
filter = args[++i];
} else if (reFindNoCase("^--filter=", arg)) {
filter = valueAfterEquals(arg);
} else if (arg == "--directory" && i < arrayLen(args)) {
// `--directory` is an alias for `--filter`. Documented in
// chapter 7 of the tutorial and historically referenced in
// `wheels test --help`; without this branch it would fall
// through to the positional fallback below and be silently
// dropped (it starts with `--` so the positional check
// excludes it). Onboarding finding #2.
filter = args[++i];
} else if (reFindNoCase("^--directory=", arg)) {
filter = valueAfterEquals(arg);
} else if (arg == "--reporter" && i < arrayLen(args)) {
reporter = args[++i];
} else if (reFindNoCase("^--reporter=", arg)) {
reporter = valueAfterEquals(arg);
} else if (arg == "--db" && i < arrayLen(args)) {
db = args[++i];
dbExplicit = true;
} else if (reFindNoCase("^--db=", arg)) {
db = valueAfterEquals(arg);
dbExplicit = true;
} else if (arg == "--verbose" || arg == "-v") {
verboseOutput = true;
} else if (arg == "--ci") {
ciMode = true;
} else if (arg == "--core") {
coreTests = true;
} else if (arg == "--no-test-db") {
useTestDB = false;
} else if (!arg.startsWith("--")) {
// Positional arg is the filter directory
filter = arg;
}
}
// Default to APP mode unless --core is set explicitly. The previous
// auto-detection ("if vendor/wheels/tests/ exists, default to core")
// always picked core mode for user apps because every Wheels app has
// the framework's tests vendored at vendor/wheels/tests/. That meant
// `wheels test` from a user's app pointed at framework specs instead
// of the user's own tests/specs/, producing "0 passed" silently with
// no spec discovery.
// Normalize short filter names to dotted paths the test runner
// accepts. The app-runner regex (`^tests(\.[a-zA-Z0-9_]+)*$`) and
// core-runner regex (`^(wheels\.tests|vendor\.<pkg>\.tests)...$`)
// both reject bare names like "browser" or "models" and silently
// fall back to the default scope, running the entire suite. The
// CLI normalizes here so `--filter=browser` does what the user
// expects. Onboarding finding #2.
filter = $normalizeTestFilter(filter, coreTests);
return runTests(filter, reporter, format, verboseOutput, coreTests, db, ciMode, useTestDB, dbExplicit);
}
/**
* Normalize a short filter name to a path the test runner's directory
* regex will accept. App mode prepends `tests.specs.`; core mode
* prepends `wheels.tests.specs.`. Already-qualified inputs pass through
* unchanged. Empty input stays empty (server applies its default).
*
* Examples:
* "" → "" (default scope)
* "browser" → "tests.specs.browser" (app mode)
* "browser" → "wheels.tests.specs.browser" (core mode)
* "tests.specs.browser" → "tests.specs.browser"
* "wheels.tests.specs.model" → "wheels.tests.specs.model"
* "vendor.wheels-sentry.tests" → "vendor.wheels-sentry.tests"
*/
public string function $normalizeTestFilter(
required string filter,
boolean coreTests = false
) {
var f = trim(arguments.filter);
if (!len(f)) return "";
if (arguments.coreTests) {
// Core runner accepts wheels.tests.* or vendor.<pkg>.tests.*
if (reFindNoCase("^(wheels\.tests|vendor\.[a-z0-9][a-z0-9\-]*\.tests)(\.[a-zA-Z0-9_]+)*$", f)) {
return f;
}
return "wheels.tests.specs." & f;
}
// App runner accepts tests.* (and treats `tests` alone as a valid root)
if (reFindNoCase("^tests(\.[a-zA-Z0-9_]+)*$", f)) {
return f;
}
return "tests.specs." & f;
}
// ─────────────────────────────────────────────────
// reload — Reload application
// ─────────────────────────────────────────────────
/**
* hint: Reload the running Wheels application. The reload password
* gates the HTTP `?reload=true` endpoint against remote attackers;
* the CLI reads it from `.env` or `config/settings.cfm` and forwards
* it because it runs locally with filesystem access. This matches
* how Rails, Laravel, Symfony, etc. treat CLI-vs-HTTP — the CLI is
* already trusted at the same level as the project on disk. See
* issue #2477 and `deployment/security-hardening.mdx`.
*/
public string function reload() {
var serverPort = $requireRunningServer();
var password = detectReloadPassword();
// F5 fix: physically wipe the Lucee compiled-class cache before
// triggering the framework reload. Lucee Express's default
// `inspectTemplate=once` means Lucee compiles each CFC once, caches
// the .class on disk, and never re-checks the source timestamp.
// `?reload=true` resets Wheels application state via applicationStop()
// but does not invalidate Lucee's template cache, so edits to models,
// controllers, and config silently miss until cfclasses is wiped.
// See onboarding finding F5.
$purgeServerCfclasses();
try {
var reloadUrl = "http://localhost:#serverPort#/?reload=true&password=#password#";
var httpResult = makeHttpRequest(reloadUrl);
out("Application reloaded successfully.", "green");
// Surface the hot-vs-cold reload contract — Wheels does NOT
// re-fire onApplicationStart on `?reload=true`. Users editing
// app/events/onapplicationstart.cfm or config/services.cfm need
// a full restart. See finding #8 in the 2026-04-29 fresh-VM
// triage.
out("Note: onApplicationStart does NOT re-fire. For init-code edits, run `wheels stop && wheels start`.", "cyan");
verbose("URL: http://localhost:#serverPort#/?reload=true&password=***");
} catch (any e) {
out("Failed to reload: #e.message#", "red");
if (!len(password)) {
out("Hint: Set RELOAD_PASSWORD in .env or config/settings.cfm", "yellow");
}
}
return "";
}
// ─────────────────────────────────────────────────
// start / stop — Dev server management
// ─────────────────────────────────────────────────
/**
* hint: Start the Wheels development server via LuCLI
*/
public string function start() {
var args = getArgs(arguments);
// Refuse to start from a non-Wheels-project directory. LuCLI's
// `server start` derives the server name from the cwd basename and
// silently registers a new context — running `wheels start` in the
// wrong directory leaves orphan registrations like `ws` or
// `Downloads`. Onboarding finding F6.
if (!$isWheelsProjectDir(variables.projectRoot)) {
out("This directory does not look like a Wheels project.", "yellow");
out(" Expected: config/settings.cfm under the current directory.", "yellow");
out("");
out("Tip: cd into your project directory, or run `wheels new <appname>`", "cyan");
out(" to scaffold one.", "cyan");
return "";
}
// Detect a stale `<lucliHome>/servers/<basename>/` registration before
// delegating to LuCLI. Without this intercept, LuCLI emits a numbered
// recovery prompt referencing `lucli server start --force`, but `lucli`
// isn't on PATH after `brew install wheels` — the user gets an
// unactionable error from a fresh `wheels start`. Onboarding F1/F2.
var force = false;
var passThrough = [];
for (var a in args) {
if (a == "--force") { force = true; }
else { arrayAppend(passThrough, a); }
}
var registry = getService("serverRegistry");
var serverName = registry.serverNameFor(variables.projectRoot);
var reg = registry.inspect(serverName, variables.projectRoot);
if (reg.alive) {
out("Server '" & serverName & "' is already running.", "yellow");
out("To restart: wheels stop && wheels start", "cyan");
return "";
}
if (reg.exists && !reg.ours && !force) {
out("");
out("Server name '" & serverName & "' is registered to a different project:", "yellow");
out(" registered: " & (len(reg.registeredPath) ? reg.registeredPath : "<unknown>"), "yellow");
out(" this dir: " & variables.projectRoot, "yellow");
out("");
out("Options:", "bold");
out(" - Pass --force to replace the registration:");
out(" wheels start --force", "cyan");
out(" - Or rename your project directory so it gets a unique server name.");
return "";
}
// Stale-but-ours, or --force was passed: wipe the dead registration so
// LuCLI's `server start` doesn't trip its "already exists" prompt.
if (reg.exists) {
registry.clean(serverName);
}
out("Starting Wheels server...", "cyan");
// Stage required JDBC drivers into the Lucee Express lib/ext/ before
// LuCLI provisions/boots Lucee. Without this, fresh `wheels new` apps
// with the SQLite-by-default datasource hit a class-load failure on
// the first request because the Lucee Express distribution doesn't
// ship the SQLite driver and not every install path (chocolatey,
// dev checkout, manual) drops the JAR via a wrapper script. See
// GH #2326 (F8). Pre-stage (this call) covers the first-start case
// where the express dir already exists; post-stage (after server
// start, below) covers the case where express was extracted by this
// very LuCLI invocation.
$ensureWheelsBundles();
// Drop a working rewrite.config at the project root if the project
// doesn't already ship one. LuCLI's bundled default uses a narrow
// allow-list and negated RewriteCond chains that 404 static assets
// for 3.x-conventional dirs (/miscellaneous/, /javascripts/, etc.);
// providing a project override sidesteps it. New apps get this file
// via `wheels new`; this catches 3.x → 4.0 upgrade paths. See GH #2626.
$ensureProjectRewriteConfig();
// Delegate to LuCLI's server start command. Forward only args we
// haven't consumed ourselves (--force is wheels-side, not LuCLI-side).
var cmdArgs = ["start"];
cmdArgs.append(passThrough, true);
executeCommand("server", cmdArgs, variables.projectRoot);
// Post-stage. If the express dir didn't exist at pre-stage time
// (very first LuCLI run on a fresh VM), the start command above just
// extracted it. Seed the JAR now so the *next* `wheels start` works
// zero-config without the user knowing the difference.
$ensureWheelsBundles();
return "";
}
/**
* hint: Stop the running Wheels development server
*/
public string function stop() {
out("Stopping Wheels server...", "cyan");
// If LuCLI's stop won't find a registered server for this directory
// (cwd doesn't match any `.project-path`), enumerate the user's
// running servers and offer specific stop commands. Without this,
// `wheels stop` is silently a no-op when run from a parent dir, an
// unrelated dir, or after the project was moved/deleted — leaving
// orphan Java processes the user has to chase with `lsof`+`kill`.
// See GH #2316.
var match = $findServerForProject(variables.projectRoot);
if (!len(match)) {
var orphans = $listRunningWheelsServers();
if (arrayLen(orphans)) {
out("");
out("No registered server matches this directory.", "yellow");
out("Running Wheels servers:", "yellow");
for (var s in orphans) {
out(" - " & s.name & " (port " & s.port & ", project " & s.projectPath & ")");
}
out("");
out("To stop a specific server: wheels server stop --name <name>", "cyan");
out("To list all servers: wheels server list", "cyan");
return "";
}
// Final fallback: scan live JVMs for processes whose catalina.base
// points into this user's LuCLI servers tree but whose registration
// was wiped (`rm -rf ~/.wheels/servers/<name>` is the user's only
// recovery from the F1/F2 stale-server prompt; it leaves the
// process orphaned). Without this scan, `wheels stop` falsely
// claims "no server is running" while the port is still held.
// Onboarding F3.
var stranded = $findStrandedLuceeProcesses();
if (arrayLen(stranded)) {
out("");
out("Found Lucee processes from prior sessions (LuCLI registration is gone):", "yellow");
var pids = [];
for (var p in stranded) {
out(" - PID " & p.pid & " (was server '" & p.serverName & "')");
arrayAppend(pids, p.pid);
}
out("");
out("To stop them: kill " & arrayToList(pids, " "), "cyan");
return "";
}
// No registered server AND no others running. Don't fall through
// to LuCLI's `server stop` — it would create a phantom server
// registration named after the cwd basename. Onboarding finding F6.
out("");
out("No Wheels server is registered for this directory, and none are running elsewhere.", "yellow");
if (!$isWheelsProjectDir(variables.projectRoot)) {
out("Tip: run this from inside your Wheels project directory.", "cyan");
}
return "";
}
executeCommand("server", ["stop"], variables.projectRoot);
return "";
}
// ─────────────────────────────────────────────────
// new — Scaffold a new Wheels project
// ─────────────────────────────────────────────────
/**
* hint: Scaffold a new Wheels project directory
*/
public string function new() {
var args = getArgs(arguments);
if (!arrayLen(args)) {
out("Usage: wheels new <appname> [options]", "yellow");
out("");
out("Creates a new Wheels application in the specified directory.");
out("By default, SQLite is configured as the zero-config database.");
out("");
out("Options:", "bold");
out(" --port=<number> Server port (default: 8080)");
out(" --datasource=<name> Datasource name (default: app name)");
out(" --reload-password=<pw> Reload password (default: app name)");
out(" --no-sqlite Skip default SQLite database setup");
out(" --setup-h2 Use H2 embedded database instead of SQLite");
out(" --no-open-browser Don't open browser on server start");
out("");
out("Examples:", "bold");
out(" wheels new myapp");
out(" wheels new myapp --port=3000 --setup-h2");
out(" wheels new myapp --datasource=mydb --no-sqlite");
return "";
}
var appName = "";
var options = {
port: 8080,
datasource: "",
reloadPassword: "",
setupH2: false,
noSQLite: false,
openBrowser: true
};
// Parse arguments: first non-flag arg is app name, flags are options
for (var i = 1; i <= arrayLen(args); i++) {
var arg = args[i];
if (reFindNoCase("^--port=", arg)) {
options.port = val(valueAfterEquals(arg));
} else if (reFindNoCase("^--datasource=", arg)) {
options.datasource = valueAfterEquals(arg);
} else if (reFindNoCase("^--reload-password=", arg)) {
options.reloadPassword = valueAfterEquals(arg);
} else if (arg == "--setup-h2") {
options.setupH2 = true;
} else if (arg == "--no-sqlite") {
options.noSQLite = true;
} else if (arg == "--no-open-browser") {
options.openBrowser = false;
} else if (!arg.startsWith("--") && !len(appName)) {
appName = arg;
}
}
if (!len(appName)) {
out("Error: app name is required.", "red");
out("Usage: wheels new <appname>");
// Args were supplied (the zero-args branch above already returned
// usage help) but none parsed as an app name — e.g. `wheels new
// --port=3000`. Throw so LuCLI surfaces a non-zero exit (GH #2214).
throw(
type="Wheels.InvalidArguments",
message="wheels new: app name argument is required"
);
}
// Default datasource to app name, generate random reload password
if (!len(options.datasource)) options.datasource = lCase(appName);
if (!len(options.reloadPassword)) options.reloadPassword = generateRandomPassword();
return scaffoldNewApp(appName, options);
}
// ─────────────────────────────────────────────────
// create — Create application components
// ─────────────────────────────────────────────────
/**
* hint: Create application components (wheels create app <name> [options])
*/
public string function create() {
var args = getArgs(arguments);
if (!arrayLen(args)) {
out("Usage: wheels create <type> <name> [options]", "yellow");
out("");
out("Types:", "bold");
out(" app Create a new Wheels application");
out("");
out("Examples:", "bold");
out(" wheels create app myapp");
out(" wheels create app myapp --port=3000 --setup-h2");
return "";
}
var type = lCase(args[1]);
var remaining = args.len() > 1 ? args.slice(2) : [];
switch (type) {
case "app":
__arguments = remaining;
return new();
default:
out("Unknown create type: #type#", "red");
out("Run 'wheels create' for available types.");
return "";
}
}
// ─────────────────────────────────────────────────
// routes — List application routes
// ─────────────────────────────────────────────────
/**
* hint: List all configured routes with method, path, and controller action
*/
public string function routes() {
var serverPort = $requireRunningServer();
try {
// /wheels/cli?command=routes returns the actual application route
// table as JSON. (The previous endpoint, /wheels/ai?context=routing,
// returns AI-documentation about routing patterns — not what users
// asking "what routes does my app have?" expect to see.)
var routesUrl = "http://localhost:#serverPort#/wheels/cli?command=routes&format=json";
var httpResult = makeHttpRequest(routesUrl);
var result = "";
try {
result = deserializeJSON(httpResult);
} catch (any jsonErr) {
out("Failed to parse routes response", "red");
verbose(httpResult);
return "";
}
if (!structKeyExists(result, "success") || !result.success) {
out("Failed to fetch routes: #result.message ?: 'unknown error'#", "red");
return "";
}
if (!structKeyExists(result, "routes") || !arrayLen(result.routes)) {
out("No routes configured.", "yellow");
return "";
}
// Normalise patterns so the leading "/" is shown exactly once. The
// framework stores routes with the leading slash already present,
// but defensively handle the case where it isn't.
var formatPattern = function(p) {
p = p ?: "";
return left(p, 1) == "/" ? p : "/" & p;
};
// Compute column widths from the data so the table aligns cleanly.
var maxMethod = len("METHOD");
var maxPattern = len("PATTERN");
var maxAction = len("CONTROLLER##ACTION");
for (var route in result.routes) {
var methodWidth = len(uCase(route.methods ?: ""));
var patternWidth = len(formatPattern(route.pattern));
var actionWidth = len((route.controller ?: "") & "##" & (route.action ?: ""));
if (methodWidth > maxMethod) maxMethod = methodWidth;
if (patternWidth > maxPattern) maxPattern = patternWidth;
if (actionWidth > maxAction) maxAction = actionWidth;
}
out(lJustify("METHOD", maxMethod) & " " & lJustify("PATTERN", maxPattern) & " " & "CONTROLLER##ACTION", "bold");
out(repeatString("-", maxMethod + maxPattern + maxAction + 4));
for (var route in result.routes) {
var line = lJustify(uCase(route.methods ?: ""), maxMethod)
& " " & lJustify(formatPattern(route.pattern), maxPattern)
& " " & (route.controller ?: "") & "##" & (route.action ?: "");
if (structKeyExists(route, "name") && len(route.name)) {
line &= " (" & route.name & ")";
}
out(line);
}
out("");
out("#arrayLen(result.routes)# route(s)", "cyan");
} catch (any e) {
out("Failed to fetch routes: #e.message#", "red");
}
return "";
}
// ─────────────────────────────────────────────────
// info — Show environment info
// ─────────────────────────────────────────────────
/**
* hint: Show framework version, environment, and configuration
*/
public string function info() {
out("Wheels CLI v#super.version()#", "bold");
out("");
if (len(variables.projectRoot) && directoryExists(variables.projectRoot & "/vendor/wheels")) {
out("Project: #variables.projectRoot#");
// Detect Wheels version from vendor
var versionFile = variables.projectRoot & "/vendor/wheels/events/onapplicationstart/settings.cfm";
if (fileExists(versionFile)) {
try {
var vContent = fileRead(versionFile);
var vMatch = reFindNoCase('version[^"]*"([^"]+)"', vContent, 1, true);
if (arrayLen(vMatch.match) > 1) {
out("Wheels: v#vMatch.match[2]#");
}
} catch (any e) { /* skip */ }
}
// CFML engine
out("Engine: Lucee (LuCLI module)");
// Datasource. Strip CFML/cfscript comments first so commented-out
// `set(...)` calls don't get parsed as live config, and use a
// word-boundary on the property name so `coreTestDataSourceName`
// is not picked up as if it were `dataSourceName`.
var settingsFile = variables.projectRoot & "/config/settings.cfm";
if (fileExists(settingsFile)) {
try {
var sContent = stripCfmlComments(fileRead(settingsFile));
var dsMatch = reFindNoCase('\bdataSourceName\s*=\s*"([^"]+)"', sContent, 1, true);
if (arrayLen(dsMatch.match) > 1) {
out("Database: #dsMatch.match[2]#");
}
} catch (any e) { /* skip */ }
}
// Environment file
var envFile = variables.projectRoot & "/.env";
if (fileExists(envFile)) {
out("Env file: .env found", "green");
}
// lucee.json
var luceeJson = variables.projectRoot & "/lucee.json";
if (fileExists(luceeJson)) {
out("Config: lucee.json found", "green");
}
// Count routes
var routesFile = variables.projectRoot & "/config/routes.cfm";
if (fileExists(routesFile)) {
var routeContent = fileRead(routesFile);
var resourceCount = 0;
var pos = 1;
while (pos > 0) {
pos = findNoCase(".resources(", routeContent, pos);
if (pos > 0) { resourceCount++; pos++; }
}
if (resourceCount > 0) {
out("Routes: #resourceCount# resource route(s)");
}
}
// Count models. Exclude the framework's parent `Model.cfc` — it
// extends `wheels.Model` and is not an application/domain model.
var modelsDir = variables.projectRoot & "/app/models";
if (directoryExists(modelsDir)) {
var modelFiles = directoryList(modelsDir, false, "name", "*.cfc");
var modelCount = 0;
for (var modelFile in modelFiles) {