@h3ravel/console 10.0.0 → 11.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +13 -1
  2. package/dist/Commands/Command.cjs +104 -0
  3. package/dist/Commands/Command.js +7 -0
  4. package/dist/Commands/MakeCommand.cjs +433 -0
  5. package/dist/Commands/MakeCommand.js +9 -0
  6. package/dist/Commands/MigrateCommand.cjs +202 -0
  7. package/dist/Commands/MigrateCommand.js +8 -0
  8. package/dist/Commands/ServeCommand.cjs +159 -0
  9. package/dist/Commands/ServeCommand.js +8 -0
  10. package/dist/Contracts/ICommand.cjs +18 -0
  11. package/dist/Contracts/ICommand.js +1 -0
  12. package/dist/IO/app.cjs +934 -0
  13. package/dist/IO/app.js +17 -0
  14. package/dist/IO/providers.cjs +909 -0
  15. package/dist/IO/providers.js +16 -0
  16. package/dist/Kernel.cjs +892 -0
  17. package/dist/Kernel.js +14 -0
  18. package/dist/Musket.cjs +837 -0
  19. package/dist/Musket.js +13 -0
  20. package/dist/Providers/ConsoleServiceProvider.cjs +904 -0
  21. package/dist/Providers/ConsoleServiceProvider.js +15 -0
  22. package/dist/Signature.cjs +172 -0
  23. package/dist/Signature.js +7 -0
  24. package/dist/Utils.cjs +218 -0
  25. package/dist/Utils.js +9 -0
  26. package/dist/chunk-3FVPHQCH.js +151 -0
  27. package/dist/chunk-FOSDCKCR.js +106 -0
  28. package/dist/chunk-IGEFNODG.js +22 -0
  29. package/dist/chunk-KMIFCLXG.js +16 -0
  30. package/dist/chunk-NADN2PHB.js +0 -0
  31. package/dist/chunk-O45AB4MX.js +83 -0
  32. package/dist/chunk-PMV4TMFS.js +151 -0
  33. package/dist/chunk-POF4JGTX.js +186 -0
  34. package/dist/chunk-SHUYVCID.js +6 -0
  35. package/dist/chunk-SP4JKAUC.js +63 -0
  36. package/dist/chunk-TN5SV7LF.js +133 -0
  37. package/dist/chunk-UCOXL3OM.js +0 -0
  38. package/dist/chunk-URLTFJET.js +68 -0
  39. package/dist/chunk-XSL373TG.js +36 -0
  40. package/dist/index.cjs +892 -6
  41. package/dist/index.d.cts +306 -2
  42. package/dist/index.d.ts +306 -2
  43. package/dist/index.js +43 -15
  44. package/dist/run.cjs +1 -0
  45. package/dist/run.js +1 -0
  46. package/package.json +23 -6
  47. package/dist/index.cjs.map +0 -1
  48. package/dist/index.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
9
  var __export = (target, all) => {
@@ -16,14 +18,889 @@ var __copyProps = (to, from, except, desc) => {
16
18
  }
17
19
  return to;
18
20
  };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
19
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
30
 
21
31
  // src/index.ts
22
- var src_exports = {};
23
- __export(src_exports, {
24
- ConsoleServiceProvider: () => ConsoleServiceProvider
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ Command: () => Command,
35
+ ConsoleServiceProvider: () => ConsoleServiceProvider,
36
+ Kernel: () => Kernel,
37
+ MakeCommand: () => MakeCommand,
38
+ MigrateCommand: () => MigrateCommand,
39
+ Musket: () => Musket,
40
+ ServeCommand: () => ServeCommand,
41
+ Signature: () => Signature,
42
+ TableGuesser: () => TableGuesser,
43
+ Utils: () => Utils
25
44
  });
26
- module.exports = __toCommonJS(src_exports);
45
+ module.exports = __toCommonJS(index_exports);
46
+
47
+ // src/Commands/Command.ts
48
+ var Command = class {
49
+ static {
50
+ __name(this, "Command");
51
+ }
52
+ app;
53
+ kernel;
54
+ constructor(app, kernel) {
55
+ this.app = app;
56
+ this.kernel = kernel;
57
+ }
58
+ /**
59
+ * The name and signature of the console command.
60
+ *
61
+ * @var string
62
+ */
63
+ signature;
64
+ /**
65
+ * A dictionary of signatures or what not.
66
+ *
67
+ * @var object
68
+ */
69
+ dictionary = {};
70
+ /**
71
+ * The console command description.
72
+ *
73
+ * @var string
74
+ */
75
+ description;
76
+ /**
77
+ * The console command input.
78
+ *
79
+ * @var object
80
+ */
81
+ input = {
82
+ options: {},
83
+ arguments: {}
84
+ };
85
+ /**
86
+ * Execute the console command.
87
+ */
88
+ async handle(..._args) {
89
+ }
90
+ setApplication(app) {
91
+ this.app = app;
92
+ }
93
+ setInput(options, args, regArgs, dictionary) {
94
+ this.dictionary = dictionary;
95
+ this.input.options = options;
96
+ this.input.arguments = regArgs.map((e, i) => ({
97
+ [e.name()]: args[i]
98
+ })).reduce((e, x) => Object.assign(e, x), {});
99
+ }
100
+ getSignature() {
101
+ return this.signature;
102
+ }
103
+ getDescription() {
104
+ return this.description;
105
+ }
106
+ option(key, def) {
107
+ return this.input.options[key] ?? def;
108
+ }
109
+ options(key) {
110
+ if (key) {
111
+ return this.input.options[key];
112
+ }
113
+ return this.input.options;
114
+ }
115
+ argument(key, def) {
116
+ return this.input.arguments[key] ?? def;
117
+ }
118
+ arguments() {
119
+ return this.input.arguments;
120
+ }
121
+ };
122
+
123
+ // src/Utils.ts
124
+ var import_promises = require("fs/promises");
125
+ var import_chalk = __toESM(require("chalk"), 1);
126
+
127
+ // ../../node_modules/.pnpm/escalade@3.2.0/node_modules/escalade/sync/index.mjs
128
+ var import_path = require("path");
129
+ var import_fs = require("fs");
130
+ function sync_default(start, callback) {
131
+ let dir = (0, import_path.resolve)(".", start);
132
+ let tmp, stats = (0, import_fs.statSync)(dir);
133
+ if (!stats.isDirectory()) {
134
+ dir = (0, import_path.dirname)(dir);
135
+ }
136
+ while (true) {
137
+ tmp = callback(dir, (0, import_fs.readdirSync)(dir));
138
+ if (tmp) return (0, import_path.resolve)(dir, tmp);
139
+ dir = (0, import_path.dirname)(tmp = dir);
140
+ if (tmp === dir) break;
141
+ }
142
+ }
143
+ __name(sync_default, "default");
144
+
145
+ // src/Utils.ts
146
+ var import_path2 = __toESM(require("path"), 1);
147
+ var join = import_path2.default.join;
148
+ var Utils = class {
149
+ static {
150
+ __name(this, "Utils");
151
+ }
152
+ /**
153
+ * Wraps text with chalk
154
+ *
155
+ * @param txt
156
+ * @param color
157
+ * @returns
158
+ */
159
+ static textFormat(txt, color) {
160
+ return String(txt).split(":").map((e, i, a) => i == 0 && a.length > 1 ? color(" " + e + ": ") : e).join("");
161
+ }
162
+ /**
163
+ * Ouput formater object
164
+ *
165
+ * @returns
166
+ */
167
+ static output() {
168
+ return {
169
+ success: /* @__PURE__ */ __name((msg, exit = false) => {
170
+ console.log(import_chalk.default.green("\u2713"), this.textFormat(msg, import_chalk.default.bgGreen), "\n");
171
+ if (exit) process.exit(0);
172
+ }, "success"),
173
+ info: /* @__PURE__ */ __name((msg, exit = false) => {
174
+ console.log(import_chalk.default.blue("\u2139"), this.textFormat(msg, import_chalk.default.bgBlue), "\n");
175
+ if (exit) process.exit(0);
176
+ }, "info"),
177
+ error: /* @__PURE__ */ __name((msg, exit = true) => {
178
+ if (msg instanceof Error) {
179
+ if (msg.message) {
180
+ console.error(import_chalk.default.red("\u2716"), this.textFormat("ERROR:" + msg.message, import_chalk.default.bgRed));
181
+ }
182
+ console.error(import_chalk.default.red(`${msg.detail ? `${msg.detail}
183
+ ` : ""}${msg.stack}`), "\n");
184
+ } else {
185
+ console.error(import_chalk.default.red("\u2716"), this.textFormat(msg, import_chalk.default.bgRed), "\n");
186
+ }
187
+ if (exit) process.exit(1);
188
+ }, "error"),
189
+ split: /* @__PURE__ */ __name((name, value, status, exit = false) => {
190
+ status ??= "info";
191
+ const color = {
192
+ success: import_chalk.default.bgGreen,
193
+ info: import_chalk.default.bgBlue,
194
+ error: import_chalk.default.bgRed
195
+ };
196
+ const regex = /\x1b\[\d+m/g;
197
+ const width = Math.min(process.stdout.columns, 100);
198
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
199
+ console.log(this.textFormat(name, color[status]), import_chalk.default.gray(".".repeat(dots)), value);
200
+ if (exit) process.exit(0);
201
+ }, "split"),
202
+ quiet: /* @__PURE__ */ __name(() => {
203
+ process.exit(0);
204
+ }, "quiet")
205
+ };
206
+ }
207
+ static findModulePkg(moduleId, cwd) {
208
+ const parts = moduleId.replace(/\\/g, "/").split("/");
209
+ let packageName = "";
210
+ if (parts.length > 0 && parts[0][0] === "@") {
211
+ packageName += parts.shift() + "/";
212
+ }
213
+ packageName += parts.shift();
214
+ const packageJson = import_path2.default.join(cwd ?? process.cwd(), "node_modules", packageName);
215
+ const resolved = this.findUpConfig(packageJson, "package", [
216
+ "json"
217
+ ]);
218
+ if (!resolved) {
219
+ return;
220
+ }
221
+ return import_path2.default.join(import_path2.default.dirname(resolved), parts.join("/"));
222
+ }
223
+ static async getMigrationPaths(cwd, migrator, defaultPath, path3) {
224
+ if (path3) {
225
+ return [
226
+ join(cwd, path3)
227
+ ];
228
+ }
229
+ return [
230
+ ...migrator.getPaths(),
231
+ join(cwd, defaultPath)
232
+ ];
233
+ }
234
+ static twoColumnDetail(name, value) {
235
+ const regex = /\x1b\[\d+m/g;
236
+ const width = Math.min(process.stdout.columns, 100);
237
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
238
+ return console.log(name, import_chalk.default.gray(".".repeat(dots)), value);
239
+ }
240
+ /**
241
+ * Check if file exists
242
+ *
243
+ * @param path
244
+ * @returns
245
+ */
246
+ static async fileExists(path3) {
247
+ try {
248
+ await (0, import_promises.access)(path3);
249
+ return true;
250
+ } catch {
251
+ return false;
252
+ }
253
+ }
254
+ static findUpConfig(cwd, name, extensions) {
255
+ return sync_default(cwd, (_dir, names) => {
256
+ for (const ext of extensions) {
257
+ const filename = `${name}.${ext}`;
258
+ if (names.includes(filename)) {
259
+ return filename;
260
+ }
261
+ }
262
+ return false;
263
+ });
264
+ }
265
+ };
266
+ var TableGuesser = class TableGuesser2 {
267
+ static {
268
+ __name(this, "TableGuesser");
269
+ }
270
+ static CREATE_PATTERNS = [
271
+ /^create_(\w+)_table$/,
272
+ /^create_(\w+)$/
273
+ ];
274
+ static CHANGE_PATTERNS = [
275
+ /.+_(to|from|in)_(\w+)_table$/,
276
+ /.+_(to|from|in)_(\w+)$/
277
+ ];
278
+ static guess(migration) {
279
+ for (const pattern of TableGuesser2.CREATE_PATTERNS) {
280
+ const matches = migration.match(pattern);
281
+ if (matches) {
282
+ return [
283
+ matches[1],
284
+ true
285
+ ];
286
+ }
287
+ }
288
+ for (const pattern of TableGuesser2.CHANGE_PATTERNS) {
289
+ const matches = migration.match(pattern);
290
+ if (matches) {
291
+ return [
292
+ matches[2],
293
+ false
294
+ ];
295
+ }
296
+ }
297
+ return [];
298
+ }
299
+ };
300
+
301
+ // src/Commands/MakeCommand.ts
302
+ var import_promises2 = require("fs/promises");
303
+ var import_chalk2 = __toESM(require("chalk"), 1);
304
+ var import_dayjs = __toESM(require("dayjs"), 1);
305
+ var import_node_fs = require("fs");
306
+ var import_node_path = __toESM(require("path"), 1);
307
+ var MakeCommand = class extends Command {
308
+ static {
309
+ __name(this, "MakeCommand");
310
+ }
311
+ /**
312
+ * The name and signature of the console command.
313
+ *
314
+ * @var string
315
+ */
316
+ signature = `#make:
317
+ {controller : Generates a new controller class. | {--a|api : Generate an API resource controller} | {--force : Overide existing controller.} }
318
+ {resource : Generates a new API resource class.}
319
+ {migration : Generates a new database migration class. | {--l|type=ts : The file type to generate} | {--t|table : The table to migrate} | {--c|create : The table to be created} }
320
+ {factory : Generates a new database factory class.}
321
+ {seeder : Generates a new database seeder class.}
322
+ {model : Generates a new Arquebus model class. | {--t|type=ts : The file type to generate}}
323
+ {^name : The name of the [name] to generate}
324
+ `;
325
+ /**
326
+ * The console command description.
327
+ *
328
+ * @var string
329
+ */
330
+ description = "Generate component classes";
331
+ async handle() {
332
+ const command = this.dictionary.baseCommand;
333
+ const methods = {
334
+ controller: "makeController",
335
+ resource: "makeResource",
336
+ migration: "makeMigration",
337
+ factory: "makeFactory",
338
+ seeder: "makeSeeder",
339
+ model: "makeModel"
340
+ };
341
+ try {
342
+ await this?.[methods[command]]();
343
+ } catch (e) {
344
+ this.kernel.output.error(e);
345
+ }
346
+ }
347
+ /**
348
+ * Generate a new controller class.
349
+ */
350
+ async makeController() {
351
+ const type = this.option("api") ? "-resource" : "";
352
+ const name = this.argument("name");
353
+ const force = this.option("force");
354
+ const path3 = import_node_path.default.join(app_path("Http/Controllers"), name + ".ts");
355
+ const dbPath = Utils.findModulePkg("@h3ravel/http", this.kernel.cwd) ?? "";
356
+ const stubPath = import_node_path.default.join(dbPath, `dist/stubs/controller${type}.stub`);
357
+ if (!force && (0, import_node_fs.existsSync)(path3)) {
358
+ this.kernel.output.error(`ERORR: ${name} controller already exists`);
359
+ }
360
+ let stub = await (0, import_promises2.readFile)(stubPath, "utf-8");
361
+ stub = stub.replace(/{{ name }}/g, name);
362
+ await (0, import_promises2.writeFile)(path3, stub);
363
+ this.kernel.output.split(`INFO: Controller Created`, import_chalk2.default.gray(import_node_path.default.basename(path3)));
364
+ }
365
+ makeResource() {
366
+ this.kernel.output.success(`Resource support is not yet available`);
367
+ }
368
+ /**
369
+ * Generate a new database migration class
370
+ */
371
+ async makeMigration() {
372
+ const name = this.argument("name");
373
+ const datePrefix = (0, import_dayjs.default)().format("YYYY_MM_DD_HHmmss");
374
+ const path3 = import_node_path.default.join(database_path("migrations"), `${datePrefix}_${name}.ts`);
375
+ const dbPath = Utils.findModulePkg("@h3ravel/database", this.kernel.cwd) ?? "";
376
+ let create = this.option("create", false);
377
+ let table = this.option("table");
378
+ if (!table && typeof create === "string") {
379
+ table = create;
380
+ create = true;
381
+ }
382
+ if (!table) {
383
+ const guessed = TableGuesser.guess(name);
384
+ table = guessed[0];
385
+ create = !!guessed[1];
386
+ }
387
+ const stubPath = import_node_path.default.join(dbPath, this.getMigrationStubName(table, create));
388
+ let stub = await (0, import_promises2.readFile)(stubPath, "utf-8");
389
+ if (table !== null) {
390
+ stub = stub.replace(/DummyTable|{{\s*table\s*}}/g, table);
391
+ }
392
+ this.kernel.output.info("INFO: Creating Migration");
393
+ await this.kernel.ensureDirectoryExists(import_node_path.default.dirname(path3));
394
+ await (0, import_promises2.writeFile)(path3, stub);
395
+ this.kernel.output.split(`INFO: Migration Created`, import_chalk2.default.gray(import_node_path.default.basename(path3)));
396
+ }
397
+ makeFactory() {
398
+ this.kernel.output.success(`Factory support is not yet available`);
399
+ }
400
+ makeSeeder() {
401
+ this.kernel.output.success(`Seeder support is not yet available`);
402
+ }
403
+ /**
404
+ * Generate a new Arquebus model class
405
+ */
406
+ async makeModel() {
407
+ const type = this.option("type", "ts");
408
+ const name = this.argument("name");
409
+ const path3 = import_node_path.default.join(app_path("Models"), name.toLowerCase() + "." + type);
410
+ const dbPath = Utils.findModulePkg("@h3ravel/database", this.kernel.cwd) ?? "";
411
+ const stubPath = import_node_path.default.join(dbPath, `dist/stubs/model-${type}.stub`);
412
+ let stub = await (0, import_promises2.readFile)(stubPath, "utf-8");
413
+ stub = stub.replace(/{{ name }}/g, name);
414
+ await (0, import_promises2.writeFile)(path3, stub);
415
+ this.kernel.output.split(`INFO: Model Created`, import_chalk2.default.gray(import_node_path.default.basename(path3)));
416
+ }
417
+ /**
418
+ * Ge the database migration file name
419
+ *
420
+ * @param table
421
+ * @param create
422
+ * @param type
423
+ * @returns
424
+ */
425
+ getMigrationStubName(table, create = false, type = "ts") {
426
+ let stub;
427
+ if (!table) {
428
+ stub = `migration-${type}.stub`;
429
+ } else if (create) {
430
+ stub = `migration.create-${type}.stub`;
431
+ } else {
432
+ stub = `migration.update-${type}.stub`;
433
+ }
434
+ return "dist/stubs/" + stub;
435
+ }
436
+ };
437
+
438
+ // src/Commands/MigrateCommand.ts
439
+ var import_arquebus = require("@h3ravel/arquebus");
440
+ var MigrateCommand = class extends Command {
441
+ static {
442
+ __name(this, "MigrateCommand");
443
+ }
444
+ /**
445
+ * The name and signature of the console command.
446
+ *
447
+ * @var string
448
+ */
449
+ signature = `migrate:
450
+ {fresh : Drop all tables and re-run all migrations.}
451
+ {install : Create the migration repository.}
452
+ {refresh : Reset and re-run all migrations.}
453
+ {reset : Rollback all database migrations.}
454
+ {rollback : Rollback the last database migration.}
455
+ {status : Show the status of each migration.}
456
+ {publish : Publish any migration files from installed packages.}
457
+ {^--s|seed : Seed the database}
458
+ `;
459
+ /**
460
+ * The console command description.
461
+ *
462
+ * @var string
463
+ */
464
+ description = "Run all pending migrations.";
465
+ /**
466
+ * Execute the console command.
467
+ */
468
+ async handle() {
469
+ const command = this.dictionary.name ?? this.dictionary.baseCommand;
470
+ const methods = {
471
+ migrate: "migrateRun",
472
+ fresh: "migrateFresh",
473
+ install: "migrateInstall",
474
+ refresh: "migrateRefresh",
475
+ reset: "migrateReset",
476
+ rollback: "migrateRollback",
477
+ status: "migrateStatus",
478
+ publish: "migratePublish"
479
+ };
480
+ await this?.[methods[command]]();
481
+ }
482
+ /**
483
+ * Run all pending migrations.
484
+ */
485
+ async migrateRun() {
486
+ this.kernel.output.success(`Running migrations are not yet supported.`);
487
+ }
488
+ /**
489
+ * Drop all tables and re-run all migrations.
490
+ */
491
+ async migrateFresh() {
492
+ this.kernel.output.success(`Drop all tables and re-run all migrations.`);
493
+ }
494
+ /**
495
+ * Create the migration repository.
496
+ */
497
+ async migrateInstall() {
498
+ this.kernel.output.success(`Create the migration repository.`);
499
+ }
500
+ /**
501
+ * Reset and re-run all migrations.
502
+ */
503
+ async migrateRefresh() {
504
+ this.kernel.output.success(`Resetting and re-running migrations is not yet supported.`);
505
+ }
506
+ /**
507
+ * Rollback all database migrations.
508
+ */
509
+ async migrateReset() {
510
+ this.kernel.output.success(`Rolling back all migration is not yet supported.`);
511
+ }
512
+ /**
513
+ * Rollback the last database migration.
514
+ */
515
+ async migrateRollback() {
516
+ this.kernel.output.success(`Rolling back the last migration is not yet supported.`);
517
+ }
518
+ /**
519
+ * Show the status of each migration.
520
+ */
521
+ async migrateStatus() {
522
+ const path3 = app_path();
523
+ console.log(import_arquebus.arquebus.connection());
524
+ this.kernel.output.success(`Show the status of each migration.`);
525
+ }
526
+ /**
527
+ * Publish any migration files from installed packages.
528
+ */
529
+ async migratePublish() {
530
+ this.kernel.output.success(`Publish any migration files from installed packages.`);
531
+ }
532
+ };
533
+
534
+ // src/Commands/ServeCommand.ts
535
+ var import_node_child_process = require("child_process");
536
+ var ServeCommand = class extends Command {
537
+ static {
538
+ __name(this, "ServeCommand");
539
+ }
540
+ /**
541
+ * The name and signature of the console command.
542
+ *
543
+ * @var string
544
+ */
545
+ signature = "serve";
546
+ /**
547
+ * The console command description.
548
+ *
549
+ * @var string
550
+ */
551
+ description = "Start the Developement Server";
552
+ async handle() {
553
+ try {
554
+ await this.serve();
555
+ } catch (e) {
556
+ this.kernel.output.error(e);
557
+ }
558
+ }
559
+ async serve() {
560
+ const child = (0, import_node_child_process.spawn)("tsup-node", {
561
+ stdio: "inherit",
562
+ shell: true,
563
+ env: Object.assign({}, process.env, {
564
+ NODE_ENV: "development"
565
+ }),
566
+ detached: true
567
+ });
568
+ const cleanup = /* @__PURE__ */ __name(() => {
569
+ console.log(111);
570
+ if (child.pid) {
571
+ process.kill(child.pid, "SIGTERM");
572
+ }
573
+ }, "cleanup");
574
+ process.on("SIGINT", () => child.kill("SIGINT"));
575
+ process.on("SIGTERM", () => child.kill("SIGTERM"));
576
+ process.on("SIGINT", () => {
577
+ cleanup();
578
+ process.exit(0);
579
+ });
580
+ process.on("SIGTERM", () => {
581
+ cleanup();
582
+ process.exit(0);
583
+ });
584
+ }
585
+ };
586
+
587
+ // src/IO/app.ts
588
+ var import_core2 = require("@h3ravel/core");
589
+ var import_node_events = require("events");
590
+
591
+ // src/Signature.ts
592
+ var Signature = class _Signature {
593
+ static {
594
+ __name(this, "Signature");
595
+ }
596
+ /**
597
+ * Helper to parse options inside a block of text
598
+ *
599
+ * @param block
600
+ * @returns
601
+ */
602
+ static parseOptions(block) {
603
+ const options = [];
604
+ const regex = /\{([^{}]+(?:\{[^{}]*\}[^{}]*)*)\}/g;
605
+ let match;
606
+ while ((match = regex.exec(block)) !== null) {
607
+ const shared = "^" === match[1][0] || /:[#^]/.test(match[1]);
608
+ const isHidden = ([
609
+ "#",
610
+ "^"
611
+ ].includes(match[1][0]) || /:[#^]/.test(match[1])) && !shared;
612
+ const content = match[1].trim().replace(/[#^]/, "");
613
+ const colonIndex = content.indexOf(":");
614
+ if (colonIndex === -1) {
615
+ options.push({
616
+ name: content
617
+ });
618
+ continue;
619
+ }
620
+ const namePart = content.substring(0, colonIndex).trim();
621
+ let rest = content.substring(colonIndex + 1).trim();
622
+ let description = rest;
623
+ let nestedOptions;
624
+ const pipeIndex = rest.indexOf("|");
625
+ if (pipeIndex !== -1) {
626
+ description = rest.substring(0, pipeIndex).trim();
627
+ const nestedText = rest.substring(pipeIndex + 1).trim();
628
+ const cleanedNestedText = nestedText.replace(/^\{/, "").trim();
629
+ nestedOptions = _Signature.parseOptions("{" + cleanedNestedText + "}");
630
+ } else {
631
+ description = description.trim();
632
+ }
633
+ let name = namePart;
634
+ let required = /[^a-zA-Z0-9_|-]/.test(name);
635
+ let multiple = false;
636
+ if (name.endsWith("?*")) {
637
+ required = false;
638
+ multiple = true;
639
+ name = name.slice(0, -2);
640
+ } else if (name.endsWith("*")) {
641
+ multiple = true;
642
+ name = name.slice(0, -1);
643
+ } else if (name.endsWith("?")) {
644
+ required = false;
645
+ name = name.slice(0, -1);
646
+ }
647
+ const isFlag = name.startsWith("--");
648
+ let flags;
649
+ let defaultValue;
650
+ if (isFlag) {
651
+ const flagParts = name.split("|").map((s) => s.trim());
652
+ flags = [];
653
+ for (let part of flagParts) {
654
+ if (part.startsWith("--") && part.slice(2).length === 1) {
655
+ part = "-" + part.slice(2);
656
+ } else if (part.startsWith("-") && !part.startsWith("--") && part.slice(1).length > 1) {
657
+ part = "--" + part.slice(1);
658
+ } else if (!part.startsWith("-") && part.slice(1).length > 1) {
659
+ part = "--" + part;
660
+ }
661
+ const eqIndex = part.indexOf("=");
662
+ if (eqIndex !== -1) {
663
+ flags.push(part.substring(0, eqIndex));
664
+ const val = part.substring(eqIndex + 1);
665
+ if (val === "*") {
666
+ defaultValue = [];
667
+ } else if (val === "true" || val === "false" || !val && !required) {
668
+ defaultValue = val === "true";
669
+ } else if (!isNaN(Number(val))) {
670
+ defaultValue = Number(val);
671
+ } else {
672
+ defaultValue = val;
673
+ }
674
+ } else {
675
+ flags.push(part);
676
+ }
677
+ }
678
+ }
679
+ options.push({
680
+ name: isFlag ? flags[flags.length - 1] : name,
681
+ required,
682
+ multiple,
683
+ description,
684
+ flags,
685
+ shared,
686
+ isFlag,
687
+ isHidden,
688
+ defaultValue,
689
+ nestedOptions
690
+ });
691
+ }
692
+ return options;
693
+ }
694
+ /**
695
+ * Helper to parse a command's signature
696
+ *
697
+ * @param signature
698
+ * @param commandClass
699
+ * @returns
700
+ */
701
+ static parseSignature(signature, commandClass) {
702
+ const lines = signature.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
703
+ const isHidden = [
704
+ "#",
705
+ "^"
706
+ ].includes(lines[0][0]) || /:[#^]/.test(lines[0]);
707
+ const baseCommand = lines[0].replace(/[^\w=:-]/g, "");
708
+ const description = commandClass.getDescription();
709
+ const isNamespaceCommand = baseCommand.endsWith(":");
710
+ const rest = lines.slice(1).join(" ");
711
+ const allOptions = _Signature.parseOptions(rest);
712
+ if (isNamespaceCommand) {
713
+ return {
714
+ baseCommand: baseCommand.slice(0, -1),
715
+ isNamespaceCommand,
716
+ subCommands: allOptions.filter((e) => !e.flags && !e.isHidden),
717
+ description,
718
+ commandClass,
719
+ options: allOptions.filter((e) => !!e.flags),
720
+ isHidden
721
+ };
722
+ } else {
723
+ return {
724
+ baseCommand,
725
+ isNamespaceCommand,
726
+ options: allOptions,
727
+ description,
728
+ commandClass,
729
+ isHidden
730
+ };
731
+ }
732
+ }
733
+ };
734
+
735
+ // src/Musket.ts
736
+ var import_chalk3 = __toESM(require("chalk"), 1);
737
+ var import_commander = require("commander");
738
+ var Musket = class _Musket {
739
+ static {
740
+ __name(this, "Musket");
741
+ }
742
+ app;
743
+ kernel;
744
+ output = Utils.output();
745
+ commands = [];
746
+ constructor(app, kernel) {
747
+ this.app = app;
748
+ this.kernel = kernel;
749
+ }
750
+ async build() {
751
+ this.loadBaseCommands();
752
+ await this.loadDiscoveredCommands();
753
+ return this.initialize();
754
+ }
755
+ loadBaseCommands() {
756
+ const commands = [
757
+ new ServeCommand(this.app, this.kernel),
758
+ new MakeCommand(this.app, this.kernel),
759
+ new MigrateCommand(this.app, this.kernel)
760
+ ];
761
+ commands.forEach((e) => this.addCommand(e));
762
+ }
763
+ async loadDiscoveredCommands() {
764
+ const commands = [];
765
+ commands.forEach((e) => this.addCommand(e));
766
+ }
767
+ addCommand(command) {
768
+ this.commands.push(Signature.parseSignature(command.getSignature(), command));
769
+ }
770
+ initialize() {
771
+ const cliVersion = [
772
+ "H3ravel Version:",
773
+ import_chalk3.default.green(this.kernel.consolePackage.version)
774
+ ].join(" ");
775
+ const localVersion = [
776
+ "Musket Version:",
777
+ import_chalk3.default.green(this.kernel.modulePackage.version || "None")
778
+ ].join(" ");
779
+ import_commander.program.name("musket").version(`${cliVersion}
780
+ ${localVersion}`);
781
+ import_commander.program.command("init").description("Initialize H3ravel.").action(async () => {
782
+ this.output.success(`Initialized: H3ravel has been initialized!`);
783
+ });
784
+ for (let i = 0; i < this.commands.length; i++) {
785
+ const command = this.commands[i];
786
+ const instance = command.commandClass;
787
+ if (command.isNamespaceCommand && command.subCommands) {
788
+ const cmd = command.isHidden ? import_commander.program : import_commander.program.command(command.baseCommand).description(command.description ?? "").action(async () => {
789
+ instance.setInput(cmd.opts(), cmd.args, cmd.registeredArguments, command);
790
+ await instance.handle();
791
+ });
792
+ if ((command.options?.length ?? 0) > 0) {
793
+ command.options?.filter((v, i2, a) => a.findIndex((t) => t.name === v.name) === i2).forEach((opt) => {
794
+ this.makeOption(opt, cmd);
795
+ });
796
+ }
797
+ command.subCommands.filter((v, i2, a) => !v.shared && a.findIndex((t) => t.name === v.name) === i2).forEach((sub) => {
798
+ const cmd2 = import_commander.program.command(`${command.baseCommand}:${sub.name}`).description(sub.description || "").action(async () => {
799
+ instance.setInput(cmd2.opts(), cmd2.args, cmd2.registeredArguments, sub);
800
+ await instance.handle();
801
+ });
802
+ command.subCommands?.filter((e) => e.shared).forEach((opt) => {
803
+ this.makeOption(opt, cmd2, false, sub);
804
+ });
805
+ command.options?.filter((e) => e.shared).forEach((opt) => {
806
+ this.makeOption(opt, cmd2, false, sub);
807
+ });
808
+ if (sub.nestedOptions) {
809
+ sub.nestedOptions.filter((v, i2, a) => a.findIndex((t) => t.name === v.name) === i2).forEach((opt) => {
810
+ this.makeOption(opt, cmd2);
811
+ });
812
+ }
813
+ });
814
+ } else {
815
+ const cmd = import_commander.program.command(command.baseCommand).description(command.description ?? "");
816
+ command?.options?.filter((v, i2, a) => a.findIndex((t) => t.name === v.name) === i2).forEach((opt) => {
817
+ this.makeOption(opt, cmd, true);
818
+ });
819
+ cmd.action(async () => {
820
+ instance.setInput(cmd.opts(), cmd.args, cmd.registeredArguments, command);
821
+ await instance.handle();
822
+ });
823
+ }
824
+ }
825
+ return import_commander.program;
826
+ }
827
+ makeOption(opt, cmd, parse, parent) {
828
+ const description = opt.description?.replace(/\[(\w+)\]/g, (_, k) => parent?.[k] ?? `[${k}]`) ?? "";
829
+ const type = opt.name.replaceAll("-", "");
830
+ if (opt.isFlag) {
831
+ if (parse) {
832
+ const flags = opt.flags?.map((f) => f.length === 1 ? `-${f}` : `--${f}`).join(", ");
833
+ cmd.option(flags || "", description, String(opt.defaultValue) || void 0);
834
+ } else {
835
+ cmd.option(opt.flags?.join(", ") + (opt.required ? ` <${type}>` : ""), description, opt.defaultValue);
836
+ }
837
+ } else {
838
+ cmd.argument(opt.required ? `<${opt.name}>` : `[${opt.name}]`, description, opt.defaultValue);
839
+ }
840
+ }
841
+ static async parse(kernel) {
842
+ return (await new _Musket(kernel.app, kernel).build()).parseAsync();
843
+ }
844
+ };
845
+
846
+ // src/Kernel.ts
847
+ var import_promises3 = require("fs/promises");
848
+ var import_node_path2 = __toESM(require("path"), 1);
849
+ var Kernel = class _Kernel {
850
+ static {
851
+ __name(this, "Kernel");
852
+ }
853
+ app;
854
+ cwd;
855
+ output = Utils.output();
856
+ basePath = "";
857
+ modulePath;
858
+ consolePath;
859
+ modulePackage;
860
+ consolePackage;
861
+ constructor(app, basePath) {
862
+ this.app = app;
863
+ }
864
+ static init(app) {
865
+ const instance = new _Kernel(app);
866
+ Promise.all([
867
+ instance.loadRequirements()
868
+ ]).then(([e]) => e.run());
869
+ }
870
+ async run() {
871
+ await Musket.parse(this);
872
+ process.exit(0);
873
+ }
874
+ async ensureDirectoryExists(dir) {
875
+ await (0, import_promises3.mkdir)(dir, {
876
+ recursive: true
877
+ });
878
+ }
879
+ async loadRequirements() {
880
+ this.cwd = import_node_path2.default.join(process.cwd(), this.basePath);
881
+ this.modulePath = Utils.findModulePkg("@h3ravel/core", this.cwd) ?? "";
882
+ this.consolePath = Utils.findModulePkg("@h3ravel/console", this.cwd) ?? "";
883
+ try {
884
+ this.modulePackage = await import(import_node_path2.default.join(this.modulePath, "package.json"));
885
+ } catch {
886
+ this.modulePackage = {
887
+ version: "N/A"
888
+ };
889
+ }
890
+ try {
891
+ this.consolePackage = await import(import_node_path2.default.join(this.consolePath, "package.json"));
892
+ } catch {
893
+ this.consolePackage = {
894
+ version: "N/A"
895
+ };
896
+ }
897
+ return this;
898
+ }
899
+ };
900
+
901
+ // src/IO/providers.ts
902
+ var import_config = require("@h3ravel/config");
903
+ var import_database = require("@h3ravel/database");
27
904
 
28
905
  // src/Providers/ConsoleServiceProvider.ts
29
906
  var import_core = require("@h3ravel/core");
@@ -33,10 +910,19 @@ var ConsoleServiceProvider = class extends import_core.ServiceProvider {
33
910
  }
34
911
  static priority = 992;
35
912
  register() {
913
+ Kernel.init(this.app);
36
914
  }
37
915
  };
38
916
  // Annotate the CommonJS export names for ESM import in node:
39
917
  0 && (module.exports = {
40
- ConsoleServiceProvider
918
+ Command,
919
+ ConsoleServiceProvider,
920
+ Kernel,
921
+ MakeCommand,
922
+ MigrateCommand,
923
+ Musket,
924
+ ServeCommand,
925
+ Signature,
926
+ TableGuesser,
927
+ Utils
41
928
  });
42
- //# sourceMappingURL=index.cjs.map