larats 0.0.0-stage → 1.0.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1721 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import fs3 from "fs";
5
+ import path3 from "path";
6
+ import * as p from "@clack/prompts";
7
+ import pc from "picocolors";
8
+
9
+ // src/detector.ts
10
+ import fs from "fs";
11
+ import path from "path";
12
+ function readJsonSafe(filePath) {
13
+ try {
14
+ if (!fs.existsSync(filePath)) return null;
15
+ const content = fs.readFileSync(filePath, "utf-8");
16
+ return JSON.parse(content);
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+ async function detectProjectType(targetDir = process.cwd()) {
22
+ const resolvedDir = path.resolve(targetDir);
23
+ const dirName = path.basename(resolvedDir);
24
+ const hasArtisan = fs.existsSync(path.join(resolvedDir, "artisan"));
25
+ const composerPath = path.join(resolvedDir, "composer.json");
26
+ const hasComposer = fs.existsSync(composerPath);
27
+ const tsconfigPath = path.join(resolvedDir, "tsconfig.json");
28
+ const hasTsConfig = fs.existsSync(tsconfigPath);
29
+ const packageJsonPath = path.join(resolvedDir, "package.json");
30
+ const hasPackageJson = fs.existsSync(packageJsonPath);
31
+ if (hasArtisan && hasComposer) {
32
+ const composerData = readJsonSafe(composerPath);
33
+ const allDeps = {
34
+ ...composerData?.require || {},
35
+ ...composerData?.["require-dev"] || {}
36
+ };
37
+ const hasFilament = Object.keys(allDeps).some((dep) => dep.startsWith("filament/"));
38
+ const hasLivewire = "livewire/livewire" in allDeps;
39
+ const hasInertia = "inertiajs/inertia-laravel" in allDeps;
40
+ const hasSanctum = "laravel/sanctum" in allDeps;
41
+ const rawVersion = allDeps["laravel/framework"] || "";
42
+ const cleanVersion = rawVersion.replace(/[\^~><=]/g, "").trim();
43
+ const appModulesDir = path.join(resolvedDir, "app", "Modules");
44
+ const rootModulesDir = path.join(resolvedDir, "modules");
45
+ const isModular = fs.existsSync(appModulesDir) || fs.existsSync(rootModulesDir);
46
+ const modulesDir = fs.existsSync(appModulesDir) ? "app/Modules" : fs.existsSync(rootModulesDir) ? "modules" : void 0;
47
+ const extras = [];
48
+ if (hasFilament) extras.push("Filament");
49
+ if (hasLivewire) extras.push("Livewire");
50
+ if (hasInertia) extras.push("Inertia");
51
+ if (isModular) extras.push("Modular Architecture");
52
+ const summary = `Laravel ${cleanVersion || ""}${extras.length > 0 ? ` (${extras.join(", ")})` : ""}`.trim();
53
+ return {
54
+ type: "laravel",
55
+ name: composerData?.name?.split("/")[1] || dirName,
56
+ rootPath: resolvedDir,
57
+ laravel: {
58
+ version: cleanVersion || void 0,
59
+ hasFilament,
60
+ hasLivewire,
61
+ hasInertia,
62
+ hasSanctum,
63
+ isModular,
64
+ modulesDir
65
+ },
66
+ summary
67
+ };
68
+ }
69
+ if (hasTsConfig && hasPackageJson) {
70
+ const pkg = readJsonSafe(packageJsonPath);
71
+ const allDeps = {
72
+ ...pkg?.dependencies || {},
73
+ ...pkg?.devDependencies || {}
74
+ };
75
+ let framework = "unknown";
76
+ if ("@nestjs/core" in allDeps) framework = "nest";
77
+ else if ("next" in allDeps) framework = "next";
78
+ else if ("express" in allDeps) framework = "express";
79
+ else if ("fastify" in allDeps) framework = "fastify";
80
+ else if ("hono" in allDeps) framework = "hono";
81
+ else if ("react" in allDeps) framework = "react";
82
+ else if ("vue" in allDeps) framework = "vue";
83
+ else framework = "node-vanilla";
84
+ const hasPrisma = "prisma" in allDeps || "@prisma/client" in allDeps || fs.existsSync(path.join(resolvedDir, "prisma"));
85
+ const hasTypeORM = "typeorm" in allDeps;
86
+ const hasDrizzle = "drizzle-orm" in allDeps;
87
+ const isMonorepo = Boolean(pkg?.workspaces) || fs.existsSync(path.join(resolvedDir, "pnpm-workspace.yaml")) || fs.existsSync(path.join(resolvedDir, "turbo.json")) || fs.existsSync(path.join(resolvedDir, "lerna.json"));
88
+ const hasSrc = fs.existsSync(path.join(resolvedDir, "src"));
89
+ const srcDir = hasSrc ? "src" : ".";
90
+ const isModular = fs.existsSync(path.join(resolvedDir, srcDir, "modules")) || fs.existsSync(path.join(resolvedDir, "modules"));
91
+ const extras = [framework !== "node-vanilla" ? framework : "TypeScript"];
92
+ if (hasPrisma) extras.push("Prisma");
93
+ if (hasTypeORM) extras.push("TypeORM");
94
+ if (hasDrizzle) extras.push("Drizzle");
95
+ if (isMonorepo) extras.push("Monorepo");
96
+ if (isModular) extras.push("Modular");
97
+ const summary = `TypeScript (${extras.join(", ")})`;
98
+ return {
99
+ type: "typescript",
100
+ name: pkg?.name || dirName,
101
+ rootPath: resolvedDir,
102
+ typescript: {
103
+ framework,
104
+ hasPrisma,
105
+ hasTypeORM,
106
+ hasDrizzle,
107
+ isMonorepo,
108
+ isModular,
109
+ srcDir
110
+ },
111
+ summary
112
+ };
113
+ }
114
+ let fallbackName = dirName;
115
+ if (hasPackageJson) {
116
+ const pkg = readJsonSafe(packageJsonPath);
117
+ if (pkg?.name) fallbackName = pkg.name;
118
+ }
119
+ return {
120
+ type: "unknown",
121
+ name: fallbackName,
122
+ rootPath: resolvedDir,
123
+ summary: "Generic / Unknown Project"
124
+ };
125
+ }
126
+
127
+ // src/scanner.ts
128
+ import fg from "fast-glob";
129
+ var SAFE_IGNORE_LIST = [
130
+ // Dependencies & package management
131
+ "**/node_modules/**",
132
+ "**/vendor/**",
133
+ "**/.pnpm/**",
134
+ "**/.yarn/**",
135
+ // Version control
136
+ "**/.git/**",
137
+ "**/.svn/**",
138
+ "**/.hg/**",
139
+ // Storage, cache & build outputs
140
+ "**/storage/**",
141
+ "**/dist/**",
142
+ "**/build/**",
143
+ "**/out/**",
144
+ "**/.next/**",
145
+ "**/.nuxt/**",
146
+ "**/.turbo/**",
147
+ "**/.cache/**",
148
+ "**/coverage/**",
149
+ "**/.temp/**",
150
+ "**/tmp/**",
151
+ // IDEs & OS files
152
+ "**/.idea/**",
153
+ "**/.vscode/**",
154
+ "**/.DS_Store",
155
+ "**/Thumbs.db",
156
+ // Secrets & environment configurations
157
+ "**/.env*",
158
+ "**/*.pem",
159
+ "**/*.key",
160
+ "**/*.pfx",
161
+ "**/*.cert",
162
+ "**/*.crt",
163
+ "**/*.secret",
164
+ "**/*.id_rsa",
165
+ "**/*.pub",
166
+ // Logs & Lock files
167
+ "**/*.log",
168
+ "**/*.lock",
169
+ "**/package-lock.json",
170
+ "**/yarn.lock",
171
+ "**/pnpm-lock.yaml",
172
+ "**/composer.lock"
173
+ ];
174
+ function buildCleanDirectoryTree(files, maxDepth = 3) {
175
+ const root = { name: "", isDir: true, children: /* @__PURE__ */ new Map() };
176
+ for (const file of files) {
177
+ const parts = file.split(/[/\\]/);
178
+ let current = root;
179
+ for (let i = 0; i < parts.length; i++) {
180
+ const part = parts[i];
181
+ const isLast = i === parts.length - 1;
182
+ if (!current.children.has(part)) {
183
+ current.children.set(part, {
184
+ name: part,
185
+ isDir: !isLast,
186
+ children: /* @__PURE__ */ new Map()
187
+ });
188
+ }
189
+ current = current.children.get(part);
190
+ }
191
+ }
192
+ const lines = [];
193
+ function renderNode(node, prefix, currentDepth) {
194
+ if (currentDepth > maxDepth) return;
195
+ const entries = Array.from(node.children.values()).sort((a, b) => {
196
+ if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
197
+ return a.name.localeCompare(b.name);
198
+ });
199
+ if (currentDepth === maxDepth && entries.length > 0) {
200
+ lines.push(`${prefix}\u2514\u2500\u2500 ... (${entries.length} items hidden)`);
201
+ return;
202
+ }
203
+ const maxEntriesPerDir = 8;
204
+ const displayedEntries = entries.slice(0, maxEntriesPerDir);
205
+ const hiddenCount = entries.length - displayedEntries.length;
206
+ displayedEntries.forEach((child, index) => {
207
+ const isLast = index === displayedEntries.length - 1 && hiddenCount === 0;
208
+ const pointer = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
209
+ const displayName = child.isDir ? `${child.name}/` : child.name;
210
+ lines.push(`${prefix}${pointer}${displayName}`);
211
+ if (child.isDir) {
212
+ const nextPrefix = prefix + (isLast ? " " : "\u2502 ");
213
+ renderNode(child, nextPrefix, currentDepth + 1);
214
+ }
215
+ });
216
+ if (hiddenCount > 0) {
217
+ lines.push(`${prefix}\u2514\u2500\u2500 ... (${hiddenCount} more files/folders)`);
218
+ }
219
+ }
220
+ const topLevel = Array.from(root.children.values()).sort((a, b) => {
221
+ if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
222
+ return a.name.localeCompare(b.name);
223
+ });
224
+ topLevel.forEach((child, index) => {
225
+ const isLast = index === topLevel.length - 1;
226
+ const pointer = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
227
+ const displayName = child.isDir ? `${child.name}/` : child.name;
228
+ lines.push(`${pointer}${displayName}`);
229
+ if (child.isDir) {
230
+ const nextPrefix = isLast ? " " : "\u2502 ";
231
+ renderNode(child, nextPrefix, 1);
232
+ }
233
+ });
234
+ return lines.join("\n");
235
+ }
236
+ async function scanProject(projectInfo) {
237
+ const startTime = Date.now();
238
+ const root = projectInfo.rootPath;
239
+ const allFiles = await fg("**/*", {
240
+ cwd: root,
241
+ ignore: SAFE_IGNORE_LIST,
242
+ dot: false,
243
+ onlyFiles: true
244
+ });
245
+ const normalizedFiles = allFiles.map((f) => f.replace(/\\/g, "/"));
246
+ const components = {};
247
+ const modulesSet = /* @__PURE__ */ new Set();
248
+ if (projectInfo.type === "laravel") {
249
+ const models = normalizedFiles.filter((f) => /^app\/(Models\/.*|.*Model)\.php$/i.test(f));
250
+ components["Models"] = {
251
+ name: "Eloquent Models",
252
+ count: models.length,
253
+ files: models,
254
+ description: "Database entity mappings and business logic models"
255
+ };
256
+ const controllers = normalizedFiles.filter((f) => /^app\/Http\/Controllers\/.*\.php$/i.test(f));
257
+ components["Controllers"] = {
258
+ name: "HTTP Controllers",
259
+ count: controllers.length,
260
+ files: controllers,
261
+ description: "Request handling and response orchestration"
262
+ };
263
+ const services = normalizedFiles.filter((f) => /^app\/(Services|Domain\/.*\/Services)\/.*\.php$/i.test(f));
264
+ components["Services"] = {
265
+ name: "Service Classes",
266
+ count: services.length,
267
+ files: services,
268
+ description: "Encapsulated business logic and external integrations"
269
+ };
270
+ const actions = normalizedFiles.filter((f) => /^app\/(Actions|Domain\/.*\/Actions)\/.*\.php$/i.test(f));
271
+ components["Actions"] = {
272
+ name: "Action Classes",
273
+ count: actions.length,
274
+ files: actions,
275
+ description: "Single-responsibility invokable operations"
276
+ };
277
+ const requests = normalizedFiles.filter((f) => /^app\/Http\/Requests\/.*\.php$/i.test(f));
278
+ components["Form Requests"] = {
279
+ name: "Form Requests",
280
+ count: requests.length,
281
+ files: requests,
282
+ description: "Input validation and authorization rules"
283
+ };
284
+ const filament = normalizedFiles.filter((f) => /^app\/Filament\/.*\.php$/i.test(f));
285
+ if (filament.length > 0 || projectInfo.laravel?.hasFilament) {
286
+ components["Filament Resources"] = {
287
+ name: "Filament Admin Resources",
288
+ count: filament.length,
289
+ files: filament,
290
+ description: "Admin panel CRUD pages, widgets, and schemas"
291
+ };
292
+ }
293
+ const routes = normalizedFiles.filter((f) => /^routes\/.*\.php$/i.test(f));
294
+ components["Routes"] = {
295
+ name: "Routing Definitions",
296
+ count: routes.length,
297
+ files: routes,
298
+ description: "Web, API, and console endpoint routes"
299
+ };
300
+ const migrations = normalizedFiles.filter((f) => /^database\/migrations\/.*\.php$/i.test(f));
301
+ components["Migrations"] = {
302
+ name: "Database Migrations",
303
+ count: migrations.length,
304
+ files: migrations,
305
+ description: "Schema version control and table definitions"
306
+ };
307
+ const moduleFiles = normalizedFiles.filter((f) => /^app\/Modules\/([^/]+)/i.test(f) || /^modules\/([^/]+)/i.test(f));
308
+ for (const mf of moduleFiles) {
309
+ const match = mf.match(/^(?:app\/Modules|modules)\/([^/]+)/i);
310
+ if (match && match[1]) modulesSet.add(match[1]);
311
+ }
312
+ } else if (projectInfo.type === "typescript") {
313
+ const controllers = normalizedFiles.filter((f) => /(?:^src\/.*(?:\.|\/)controller\.(?:ts|js)$)/i.test(f));
314
+ components["Controllers"] = {
315
+ name: "Controllers",
316
+ count: controllers.length,
317
+ files: controllers,
318
+ description: "HTTP request handlers and response dispatchers"
319
+ };
320
+ const services = normalizedFiles.filter((f) => /(?:^src\/.*(?:\.|\/)service\.(?:ts|js)$)/i.test(f));
321
+ components["Services"] = {
322
+ name: "Services",
323
+ count: services.length,
324
+ files: services,
325
+ description: "Core domain logic and application workflows"
326
+ };
327
+ const repositories = normalizedFiles.filter((f) => /(?:^src\/.*(?:\.|\/)repository\.(?:ts|js)$)/i.test(f));
328
+ components["Repositories"] = {
329
+ name: "Repositories",
330
+ count: repositories.length,
331
+ files: repositories,
332
+ description: "Data access abstraction and database queries"
333
+ };
334
+ const routes = normalizedFiles.filter((f) => /(?:^src\/.*(?:\.|\/)routes?\.(?:ts|js)$)/i.test(f));
335
+ components["Routes"] = {
336
+ name: "Routes",
337
+ count: routes.length,
338
+ files: routes,
339
+ description: "API endpoint mappings and router handlers"
340
+ };
341
+ const dtos = normalizedFiles.filter((f) => /(?:^src\/.*(?:\.|\/)(?:dto|schema)\.(?:ts|js)$)/i.test(f));
342
+ components["DTOs & Schemas"] = {
343
+ name: "DTOs & Schemas",
344
+ count: dtos.length,
345
+ files: dtos,
346
+ description: "Data transfer objects and request validation schemas"
347
+ };
348
+ const models = normalizedFiles.filter(
349
+ (f) => /(?:^src\/.*(?:\.|\/)(?:model|entity)\.(?:ts|js)$|^prisma\/schema\.prisma$)/i.test(f)
350
+ );
351
+ components["Models & Entities"] = {
352
+ name: "Models & Entities",
353
+ count: models.length,
354
+ files: models,
355
+ description: "Database schema definitions and entity declarations"
356
+ };
357
+ const componentsFiles = normalizedFiles.filter((f) => /^src\/(?:components|ui)\/.*\.(?:tsx|jsx|vue|ts|js)$/i.test(f));
358
+ if (componentsFiles.length > 0) {
359
+ components["UI Components"] = {
360
+ name: "UI Components",
361
+ count: componentsFiles.length,
362
+ files: componentsFiles,
363
+ description: "Reusable user interface views and components"
364
+ };
365
+ }
366
+ const moduleFiles = normalizedFiles.filter((f) => /^src\/modules\/([^/]+)/i.test(f));
367
+ for (const mf of moduleFiles) {
368
+ const match = mf.match(/^src\/modules\/([^/]+)/i);
369
+ if (match && match[1]) modulesSet.add(match[1]);
370
+ }
371
+ } else {
372
+ const srcFiles = normalizedFiles.filter((f) => /^src\//i.test(f));
373
+ const testFiles = normalizedFiles.filter((f) => /(?:test|spec)\.[a-z]+$/i.test(f));
374
+ components["Source Files"] = {
375
+ name: "Source Files",
376
+ count: srcFiles.length,
377
+ files: srcFiles,
378
+ description: "Main application source code"
379
+ };
380
+ components["Test Files"] = {
381
+ name: "Test Files",
382
+ count: testFiles.length,
383
+ files: testFiles,
384
+ description: "Automated test suites and specifications"
385
+ };
386
+ }
387
+ const directoryTree = buildCleanDirectoryTree(normalizedFiles, 3);
388
+ const scanDurationMs = Date.now() - startTime;
389
+ return {
390
+ projectInfo,
391
+ totalFilesScanned: normalizedFiles.length,
392
+ components,
393
+ modules: Array.from(modulesSet).sort(),
394
+ directoryTree,
395
+ scanDurationMs
396
+ };
397
+ }
398
+
399
+ // src/generator/markdown.ts
400
+ function generateMermaidDiagram(scanResult) {
401
+ const { projectInfo, components, modules } = scanResult;
402
+ if (projectInfo.type === "laravel") {
403
+ const hasFilament = projectInfo.laravel?.hasFilament || (components["Filament Resources"]?.count ?? 0) > 0;
404
+ const hasActions = (components["Actions"]?.count ?? 0) > 0;
405
+ const hasServices = (components["Services"]?.count ?? 0) > 0;
406
+ let diagram = `flowchart TD
407
+ %% Styling Definitions
408
+ classDef client fill:#E0F2FE,stroke:#0284C7,stroke-width:2px,color:#0369A1;
409
+ classDef routing fill:#FEF3C7,stroke:#D97706,stroke-width:2px,color:#B45309;
410
+ classDef controller fill:#DCFCE7,stroke:#16A34A,stroke-width:2px,color:#15803D;
411
+ classDef service fill:#F3E8FF,stroke:#9333EA,stroke-width:2px,color:#7E22CE;
412
+ classDef data fill:#FEE2E2,stroke:#DC2626,stroke-width:2px,color:#B91C1C;
413
+ classDef db fill:#F1F5F9,stroke:#475569,stroke-width:2px,color:#334155;
414
+
415
+ subgraph Layer1 ["1. Client & Entrypoints"]
416
+ Client["Client / Browser / API Consumer"]:::client
417
+ Routes["HTTP Routes<br/>(routes/web.php, routes/api.php)"]:::routing
418
+ end
419
+
420
+ subgraph Layer2 ["2. Request Pipeline & Security"]
421
+ Middleware["Middleware Pipeline<br/>(Auth, CSRF, Rate Limiting)"]:::routing
422
+ FormRequests["Form Requests<br/>(Validation & Authorization)"]:::routing
423
+ end
424
+
425
+ subgraph Layer3 ["3. Controllers & Presentation"]
426
+ Controllers["HTTP Controllers<br/>(app/Http/Controllers)"]:::controller
427
+ `;
428
+ if (hasFilament) {
429
+ diagram += ` Filament["Filament Admin Panel<br/>(app/Filament/Resources)"]:::controller
430
+ `;
431
+ }
432
+ diagram += ` end
433
+
434
+ subgraph Layer4 ["4. Domain & Business Logic"]
435
+ `;
436
+ if (hasServices || !hasActions) {
437
+ diagram += ` Services["Service Layer<br/>(app/Services)"]:::service
438
+ `;
439
+ }
440
+ if (hasActions) {
441
+ diagram += ` Actions["Action Classes<br/>(app/Actions)"]:::service
442
+ `;
443
+ }
444
+ diagram += ` end
445
+
446
+ subgraph Layer5 ["5. Data Persistence & Storage"]
447
+ Models["Eloquent Models<br/>(app/Models)"]:::data
448
+ Database[("Database<br/>(MySQL / Postgres / SQLite)")]:::db
449
+ Migrations["Database Migrations<br/>(database/migrations)"]:::data
450
+ end
451
+
452
+ Client --> Routes
453
+ Routes --> Middleware
454
+ Middleware --> FormRequests
455
+ FormRequests --> Controllers
456
+ `;
457
+ if (hasServices && hasActions) {
458
+ diagram += ` Controllers --> Services
459
+ Controllers --> Actions
460
+ Services --> Models
461
+ Actions --> Models
462
+ `;
463
+ } else if (hasActions) {
464
+ diagram += ` Controllers --> Actions
465
+ Actions --> Models
466
+ `;
467
+ } else {
468
+ diagram += ` Controllers --> Services
469
+ Services --> Models
470
+ `;
471
+ }
472
+ if (hasFilament) {
473
+ diagram += ` Client --> Filament
474
+ Filament --> Models
475
+ `;
476
+ }
477
+ diagram += ` Models --> Database
478
+ Migrations -.-> Database
479
+ `;
480
+ if (modules.length > 0) {
481
+ diagram += `
482
+ subgraph ModulesLayer ["\u{1F4E6} Detected Modules (${modules.length})"]
483
+ `;
484
+ modules.slice(0, 6).forEach((mod, idx) => {
485
+ diagram += ` Mod_${idx}["${mod} Module"]:::service
486
+ `;
487
+ });
488
+ if (modules.length > 6) {
489
+ diagram += ` Mod_More["...and ${modules.length - 6} more modules"]:::service
490
+ `;
491
+ }
492
+ diagram += ` end
493
+ `;
494
+ }
495
+ return diagram;
496
+ }
497
+ if (projectInfo.type === "typescript") {
498
+ const fw = projectInfo.typescript?.framework || "Express";
499
+ const orm = projectInfo.typescript?.hasPrisma ? "Prisma" : projectInfo.typescript?.hasTypeORM ? "TypeORM" : "ORM";
500
+ let diagram = `flowchart TD
501
+ %% Styling Definitions
502
+ classDef client fill:#E0F2FE,stroke:#0284C7,stroke-width:2px,color:#0369A1;
503
+ classDef routing fill:#FEF3C7,stroke:#D97706,stroke-width:2px,color:#B45309;
504
+ classDef controller fill:#DCFCE7,stroke:#16A34A,stroke-width:2px,color:#15803D;
505
+ classDef service fill:#F3E8FF,stroke:#9333EA,stroke-width:2px,color:#7E22CE;
506
+ classDef data fill:#FEE2E2,stroke:#DC2626,stroke-width:2px,color:#B91C1C;
507
+ classDef db fill:#F1F5F9,stroke:#475569,stroke-width:2px,color:#334155;
508
+
509
+ subgraph Layer1 ["1. Client & API Gateway"]
510
+ Client["Frontend / API Client"]:::client
511
+ Router["Router & Endpoints<br/>(${fw} Routes)"]:::routing
512
+ end
513
+
514
+ subgraph Layer2 ["2. Validation & Guards"]
515
+ Middleware["Auth & Error Middleware"]:::routing
516
+ DTOs["DTOs & Schemas<br/>(Input Validation)"]:::routing
517
+ end
518
+
519
+ subgraph Layer3 ["3. Controllers"]
520
+ Controllers["Controllers<br/>(Request Handling)"]:::controller
521
+ end
522
+
523
+ subgraph Layer4 ["4. Application Services"]
524
+ Services["Domain Services<br/>(Business Logic)"]:::service
525
+ end
526
+
527
+ subgraph Layer5 ["5. Data Layer & Storage"]
528
+ Repositories["Repositories / ${orm}<br/>(Data Access Layer)"]:::data
529
+ Database[("Database<br/>(SQL / NoSQL)")]:::db
530
+ end
531
+
532
+ Client --> Router
533
+ Router --> Middleware
534
+ Middleware --> DTOs
535
+ DTOs --> Controllers
536
+ Controllers --> Services
537
+ Services --> Repositories
538
+ Repositories --> Database
539
+ `;
540
+ if (modules.length > 0) {
541
+ diagram += `
542
+ subgraph ModulesLayer ["\u{1F4E6} Detected Feature Modules (${modules.length})"]
543
+ `;
544
+ modules.slice(0, 6).forEach((mod, idx) => {
545
+ diagram += ` Mod_${idx}["${mod} Module"]:::service
546
+ `;
547
+ });
548
+ if (modules.length > 6) {
549
+ diagram += ` Mod_More["...and ${modules.length - 6} more modules"]:::service
550
+ `;
551
+ }
552
+ diagram += ` end
553
+ `;
554
+ }
555
+ return diagram;
556
+ }
557
+ return `flowchart TD
558
+ classDef client fill:#E0F2FE,stroke:#0284C7,stroke-width:2px,color:#0369A1;
559
+ classDef core fill:#DCFCE7,stroke:#16A34A,stroke-width:2px,color:#15803D;
560
+ classDef test fill:#FEF3C7,stroke:#D97706,stroke-width:2px,color:#B45309;
561
+
562
+ subgraph App ["Application Architecture"]
563
+ Entry["Entrypoint / CLI"]:::client
564
+ Source["Source Core Logic (src/)"]:::core
565
+ Tests["Test Suites"]:::test
566
+ end
567
+
568
+ Entry --> Source
569
+ Tests -.-> Source
570
+ `;
571
+ }
572
+ function generateArchitectureMarkdown(scanResult) {
573
+ const { projectInfo, totalFilesScanned, components, modules, directoryTree, scanDurationMs } = scanResult;
574
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19) + " UTC";
575
+ const mermaid = generateMermaidDiagram(scanResult);
576
+ const componentRows = Object.entries(components).map(([key, comp]) => {
577
+ const sampleFiles = comp.files.slice(0, 3).map((f) => `\`${f}\``).join(", ");
578
+ const moreSuffix = comp.files.length > 3 ? ` *(+${comp.files.length - 3} more)*` : "";
579
+ return `| **${comp.name}** | \`${comp.count}\` | ${comp.description} | ${sampleFiles || "-"} ${moreSuffix} |`;
580
+ }).join("\n");
581
+ let modulesSection = "";
582
+ if (modules.length > 0) {
583
+ modulesSection = `
584
+ ## \u{1F4E6} Detected Modules & Domains (${modules.length})
585
+
586
+ This project organizes features into modular domains:
587
+
588
+ ${modules.map((m) => `- **\`${m}\`**`).join("\n")}
589
+ `;
590
+ }
591
+ return `# \u{1F3DB}\uFE0F Architecture Overview: ${projectInfo.name}
592
+
593
+ > Auto-generated by **[LaraTS CLI](https://github.com/SidiqFatuh187/Larats)** on \`${timestamp}\`.
594
+ > **100% Local & Safe:** Generated entirely in offline mode via local filesystem metadata analysis. Zero data transmitted.
595
+
596
+ ---
597
+
598
+ ## \u{1F4CC} Project Summary
599
+
600
+ | Attribute | Details |
601
+ | :--- | :--- |
602
+ | **Project Name** | \`${projectInfo.name}\` |
603
+ | **Project Type** | **${projectInfo.type.toUpperCase()}** |
604
+ | **Detected Stack** | \`${projectInfo.summary}\` |
605
+ | **Scanned Files** | \`${totalFilesScanned}\` files indexed (safe ignore filter applied) |
606
+ | **Scan Duration** | \`${scanDurationMs} ms\` |
607
+
608
+ ---
609
+
610
+ ## \u{1F4CA} Architectural Components Statistics
611
+
612
+ | Component Layer | Count | Description | Sample Files |
613
+ | :--- | :---: | :--- | :--- |
614
+ ${componentRows || "| *No architectural components identified* | `0` | - | - |"}
615
+ ${modulesSection}
616
+ ---
617
+
618
+ ## \u{1F5FA}\uFE0F Visual Architecture Flowchart
619
+
620
+ Visual representation of the project layers and request lifecycle rendered with [Mermaid.js](https://mermaid.js.org/):
621
+
622
+ \`\`\`mermaid
623
+ ${mermaid}
624
+ \`\`\`
625
+
626
+ ---
627
+
628
+ ## \u{1F332} Directory Structure Tree
629
+
630
+ Clean, high-level directory tree showing key folders (ignoring build artifacts, vendor files, and sensitive keys):
631
+
632
+ \`\`\`text
633
+ ${directoryTree || "(Empty directory structure)"}
634
+ \`\`\`
635
+
636
+ ---
637
+
638
+ ## \u{1F512} Security & Privacy Notice
639
+
640
+ This architectural map was produced with strict privacy rules:
641
+ - **Zero Network Transmission:** Executed locally without telemetry or outbound communication.
642
+ - **Safe Exclusion Filter:** Ignored \`node_modules\`, \`vendor\`, \`.env*\`, key files, credentials, and cache folders.
643
+ - **Metadata Only:** Scanned file names and relative paths only; no secrets or private business contents were extracted.
644
+
645
+ *Generated with \u2764\uFE0F by LaraTS CLI.*
646
+ `;
647
+ }
648
+
649
+ // src/generator/scaffolder.ts
650
+ import fs2 from "fs";
651
+ import path2 from "path";
652
+
653
+ // src/templates/laravel.ts
654
+ function getNaming(input) {
655
+ const words = input.trim().replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^a-zA-Z0-9]/g, " ").split(/\s+/).filter(Boolean);
656
+ if (words.length === 0) {
657
+ words.push("SampleModule");
658
+ }
659
+ const pascal = words.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join("");
660
+ const camel = pascal.charAt(0).toLowerCase() + pascal.slice(1);
661
+ const snake = words.map((w) => w.toLowerCase()).join("_");
662
+ const kebab = words.map((w) => w.toLowerCase()).join("-");
663
+ const pluralSuffix = snake.endsWith("s") || snake.endsWith("ch") || snake.endsWith("sh") ? "es" : "s";
664
+ const pluralSnake = snake + pluralSuffix;
665
+ const pluralPascal = pascal + pluralSuffix;
666
+ return { pascal, camel, kebab, snake, pluralSnake, pluralPascal };
667
+ }
668
+ function laravelModelTemplate(names, namespace = "App\\Models") {
669
+ return `<?php
670
+
671
+ namespace ${namespace};
672
+
673
+ use IlluminateDatabaseEloquentFactoriesHasFactory;
674
+ use IlluminateDatabaseEloquentModel;
675
+
676
+ class ${names.pascal} extends Model
677
+ {
678
+ use HasFactory;
679
+
680
+ /**
681
+ * The table associated with the model.
682
+ *
683
+ * @var string
684
+ */
685
+ protected $table = '${names.pluralSnake}';
686
+
687
+ /**
688
+ * The attributes that are mass assignable.
689
+ *
690
+ * @var list<string>
691
+ */
692
+ protected $fillable = [
693
+ 'name',
694
+ 'status',
695
+ 'metadata',
696
+ ];
697
+
698
+ /**
699
+ * Get the attributes that should be cast.
700
+ *
701
+ * @return array<string, string>
702
+ */
703
+ protected function casts(): array
704
+ {
705
+ return [
706
+ 'metadata' => 'array',
707
+ 'created_at' => 'datetime',
708
+ 'updated_at' => 'datetime',
709
+ ];
710
+ }
711
+ }
712
+ `;
713
+ }
714
+ function laravelControllerTemplate(names, options = {}) {
715
+ const namespace = options.namespace || "App\\Http\\Controllers";
716
+ const modelNamespace = options.modelNamespace || "App\\Models";
717
+ const serviceNamespace = options.serviceNamespace || "App\\Services";
718
+ const requestNamespace = options.requestNamespace || "App\\Http\\Requests";
719
+ return `<?php
720
+
721
+ namespace ${namespace};
722
+
723
+ use ${modelNamespace}\\${names.pascal};
724
+ use ${serviceNamespace}\\${names.pascal}Service;
725
+ use ${requestNamespace}\\${names.pascal}Request;
726
+ use IlluminateHttpJsonResponse;
727
+ use IlluminateHttpRequest;
728
+
729
+ class ${names.pascal}Controller extends Controller
730
+ {
731
+ public function __construct(
732
+ protected ${names.pascal}Service $${names.camel}Service
733
+ ) {}
734
+
735
+ /**
736
+ * Display a listing of ${names.pascal} resources.
737
+ */
738
+ public function index(Request $request): JsonResponse
739
+ {
740
+ $items = $this->${names.camel}Service->getAll($request->all());
741
+
742
+ return response()->json([
743
+ 'status' => 'success',
744
+ 'data' => $items,
745
+ ]);
746
+ }
747
+
748
+ /**
749
+ * Display the specified ${names.pascal} resource.
750
+ */
751
+ public function show(int $id): JsonResponse
752
+ {
753
+ $item = $this->${names.camel}Service->getById($id);
754
+
755
+ return response()->json([
756
+ 'status' => 'success',
757
+ 'data' => $item,
758
+ ]);
759
+ }
760
+
761
+ /**
762
+ * Store a newly created ${names.pascal} in storage.
763
+ */
764
+ public function store(${names.pascal}Request $request): JsonResponse
765
+ {
766
+ $item = $this->${names.camel}Service->create($request->validated());
767
+
768
+ return response()->json([
769
+ 'status' => 'success',
770
+ 'message' => '${names.pascal} created successfully.',
771
+ 'data' => $item,
772
+ ], 201);
773
+ }
774
+
775
+ /**
776
+ * Update the specified ${names.pascal} in storage.
777
+ */
778
+ public function update(${names.pascal}Request $request, int $id): JsonResponse
779
+ {
780
+ $item = $this->${names.camel}Service->update($id, $request->validated());
781
+
782
+ return response()->json([
783
+ 'status' => 'success',
784
+ 'message' => '${names.pascal} updated successfully.',
785
+ 'data' => $item,
786
+ ]);
787
+ }
788
+
789
+ /**
790
+ * Remove the specified ${names.pascal} from storage.
791
+ */
792
+ public function destroy(int $id): JsonResponse
793
+ {
794
+ $this->${names.camel}Service->delete($id);
795
+
796
+ return response()->json([
797
+ 'status' => 'success',
798
+ 'message' => '${names.pascal} deleted successfully.',
799
+ ]);
800
+ }
801
+ }
802
+ `;
803
+ }
804
+ function laravelServiceTemplate(names, options = {}) {
805
+ const namespace = options.namespace || "App\\Services";
806
+ const modelNamespace = options.modelNamespace || "App\\Models";
807
+ return `<?php
808
+
809
+ namespace ${namespace};
810
+
811
+ use ${modelNamespace}\\${names.pascal};
812
+ use IlluminateDatabaseEloquentCollection;
813
+
814
+ class ${names.pascal}Service
815
+ {
816
+ /**
817
+ * Retrieve all ${names.pluralPascal}.
818
+ */
819
+ public function getAll(array $filters = []): Collection
820
+ {
821
+ return ${names.pascal}::query()
822
+ ->latest()
823
+ ->get();
824
+ }
825
+
826
+ /**
827
+ * Find ${names.pascal} by primary key.
828
+ */
829
+ public function getById(int $id): ${names.pascal}
830
+ {
831
+ return ${names.pascal}::findOrFail($id);
832
+ }
833
+
834
+ /**
835
+ * Create a new ${names.pascal}.
836
+ */
837
+ public function create(array $data): ${names.pascal}
838
+ {
839
+ return ${names.pascal}::create($data);
840
+ }
841
+
842
+ /**
843
+ * Update an existing ${names.pascal}.
844
+ */
845
+ public function update(int $id, array $data): ${names.pascal}
846
+ {
847
+ $item = $this->getById($id);
848
+ $item->update($data);
849
+
850
+ return $item;
851
+ }
852
+
853
+ /**
854
+ * Delete a ${names.pascal}.
855
+ */
856
+ public function delete(int $id): bool
857
+ {
858
+ $item = $this->getById($id);
859
+
860
+ return (bool) $item->delete();
861
+ }
862
+ }
863
+ `;
864
+ }
865
+ function laravelActionTemplate(names, options = {}) {
866
+ const namespace = options.namespace || "App\\Actions";
867
+ const modelNamespace = options.modelNamespace || "App\\Models";
868
+ return `<?php
869
+
870
+ namespace ${namespace};
871
+
872
+ use ${modelNamespace}\\${names.pascal};
873
+
874
+ class Create${names.pascal}Action
875
+ {
876
+ /**
877
+ * Execute the ${names.pascal} creation workflow.
878
+ */
879
+ public function execute(array $data): ${names.pascal}
880
+ {
881
+ return ${names.pascal}::create($data);
882
+ }
883
+ }
884
+ `;
885
+ }
886
+ function laravelRequestTemplate(names, namespace = "App\\Http\\Requests") {
887
+ return `<?php
888
+
889
+ namespace ${namespace};
890
+
891
+ use IlluminateFoundationHttpFormRequest;
892
+
893
+ class ${names.pascal}Request extends FormRequest
894
+ {
895
+ /**
896
+ * Determine if the user is authorized to make this request.
897
+ */
898
+ public function authorize(): bool
899
+ {
900
+ return true;
901
+ }
902
+
903
+ /**
904
+ * Get the validation rules that apply to the request.
905
+ *
906
+ * @return array<string, list<string>>
907
+ */
908
+ public function rules(): array
909
+ {
910
+ return [
911
+ 'name' => ['required', 'string', 'max:255'],
912
+ 'status' => ['nullable', 'string', 'in:draft,active,archived'],
913
+ 'metadata' => ['nullable', 'array'],
914
+ ];
915
+ }
916
+
917
+ /**
918
+ * Get custom error messages for validation rules.
919
+ *
920
+ * @return array<string, string>
921
+ */
922
+ public function messages(): array
923
+ {
924
+ return [
925
+ 'name.required' => 'The ${names.camel} name field is required.',
926
+ ];
927
+ }
928
+ }
929
+ `;
930
+ }
931
+ function laravelMigrationTemplate(names) {
932
+ return `<?php
933
+
934
+ use IlluminateDatabaseMigrationsMigration;
935
+ use IlluminateDatabaseSchemaBlueprint;
936
+ use IlluminateSupportFacadesSchema;
937
+
938
+ return new class extends Migration
939
+ {
940
+ /**
941
+ * Run the migrations.
942
+ */
943
+ public function up(): void
944
+ {
945
+ Schema::create('${names.pluralSnake}', function (Blueprint $table) {
946
+ $table->id();
947
+ $table->string('name');
948
+ $table->string('status')->default('draft');
949
+ $table->json('metadata')->nullable();
950
+ $table->timestamps();
951
+ });
952
+ }
953
+
954
+ /**
955
+ * Reverse the migrations.
956
+ */
957
+ public function down(): void
958
+ {
959
+ Schema::dropIfExists('${names.pluralSnake}');
960
+ }
961
+ };
962
+ `;
963
+ }
964
+
965
+ // src/templates/typescript.ts
966
+ function tsControllerTemplate(names, isModular = true) {
967
+ const serviceImport = isModular ? `./${names.kebab}.service.js` : `../services/${names.kebab}.service.js`;
968
+ const dtoImport = isModular ? `./${names.kebab}.dto.js` : `../dtos/${names.kebab}.dto.js`;
969
+ return `import type { Request, Response, NextFunction } from 'express';
970
+ import { ${names.pascal}Service } from '${serviceImport}';
971
+ import type { Create${names.pascal}Dto, Update${names.pascal}Dto } from '${dtoImport}';
972
+
973
+ export class ${names.pascal}Controller {
974
+ constructor(private readonly ${names.camel}Service: ${names.pascal}Service = new ${names.pascal}Service()) {}
975
+
976
+ /**
977
+ * GET /api/${names.kebab}
978
+ */
979
+ getAll = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
980
+ try {
981
+ const items = await this.${names.camel}Service.findAll(req.query);
982
+ res.status(200).json({ status: 'success', data: items });
983
+ } catch (error) {
984
+ next(error);
985
+ }
986
+ };
987
+
988
+ /**
989
+ * GET /api/${names.kebab}/:id
990
+ */
991
+ getById = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
992
+ try {
993
+ const { id } = req.params;
994
+ const item = await this.${names.camel}Service.findById(id);
995
+ if (!item) {
996
+ res.status(404).json({ status: 'fail', message: '${names.pascal} not found' });
997
+ return;
998
+ }
999
+ res.status(200).json({ status: 'success', data: item });
1000
+ } catch (error) {
1001
+ next(error);
1002
+ }
1003
+ };
1004
+
1005
+ /**
1006
+ * POST /api/${names.kebab}
1007
+ */
1008
+ create = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
1009
+ try {
1010
+ const payload: Create${names.pascal}Dto = req.body;
1011
+ const created = await this.${names.camel}Service.create(payload);
1012
+ res.status(201).json({ status: 'success', data: created });
1013
+ } catch (error) {
1014
+ next(error);
1015
+ }
1016
+ };
1017
+
1018
+ /**
1019
+ * PUT /api/${names.kebab}/:id
1020
+ */
1021
+ update = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
1022
+ try {
1023
+ const { id } = req.params;
1024
+ const payload: Update${names.pascal}Dto = req.body;
1025
+ const updated = await this.${names.camel}Service.update(id, payload);
1026
+ res.status(200).json({ status: 'success', data: updated });
1027
+ } catch (error) {
1028
+ next(error);
1029
+ }
1030
+ };
1031
+
1032
+ /**
1033
+ * DELETE /api/${names.kebab}/:id
1034
+ */
1035
+ delete = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
1036
+ try {
1037
+ const { id } = req.params;
1038
+ await this.${names.camel}Service.delete(id);
1039
+ res.status(200).json({ status: 'success', message: '${names.pascal} deleted successfully' });
1040
+ } catch (error) {
1041
+ next(error);
1042
+ }
1043
+ };
1044
+ }
1045
+ `;
1046
+ }
1047
+ function tsServiceTemplate(names, isModular = true) {
1048
+ const repoImport = isModular ? `./${names.kebab}.repository.js` : `../repositories/${names.kebab}.repository.js`;
1049
+ const dtoImport = isModular ? `./${names.kebab}.dto.js` : `../dtos/${names.kebab}.dto.js`;
1050
+ return `import { ${names.pascal}Repository } from '${repoImport}';
1051
+ import type { ${names.pascal}Entity, Create${names.pascal}Dto, Update${names.pascal}Dto } from '${dtoImport}';
1052
+
1053
+ export class ${names.pascal}Service {
1054
+ constructor(private readonly ${names.camel}Repository: ${names.pascal}Repository = new ${names.pascal}Repository()) {}
1055
+
1056
+ async findAll(query: Record<string, any> = {}): Promise<${names.pascal}Entity[]> {
1057
+ return this.${names.camel}Repository.findAll(query);
1058
+ }
1059
+
1060
+ async findById(id: string): Promise<${names.pascal}Entity | null> {
1061
+ return this.${names.camel}Repository.findById(id);
1062
+ }
1063
+
1064
+ async create(data: Create${names.pascal}Dto): Promise<${names.pascal}Entity> {
1065
+ return this.${names.camel}Repository.create(data);
1066
+ }
1067
+
1068
+ async update(id: string, data: Update${names.pascal}Dto): Promise<${names.pascal}Entity> {
1069
+ return this.${names.camel}Repository.update(id, data);
1070
+ }
1071
+
1072
+ async delete(id: string): Promise<boolean> {
1073
+ return this.${names.camel}Repository.delete(id);
1074
+ }
1075
+ }
1076
+ `;
1077
+ }
1078
+ function tsRepositoryTemplate(names, isModular = true) {
1079
+ const dtoImport = isModular ? `./${names.kebab}.dto.js` : `../dtos/${names.kebab}.dto.js`;
1080
+ return `import type { ${names.pascal}Entity, Create${names.pascal}Dto, Update${names.pascal}Dto } from '${dtoImport}';
1081
+
1082
+ export interface I${names.pascal}Repository {
1083
+ findAll(query?: Record<string, any>): Promise<${names.pascal}Entity[]>;
1084
+ findById(id: string): Promise<${names.pascal}Entity | null>;
1085
+ create(data: Create${names.pascal}Dto): Promise<${names.pascal}Entity>;
1086
+ update(id: string, data: Update${names.pascal}Dto): Promise<${names.pascal}Entity>;
1087
+ delete(id: string): Promise<boolean>;
1088
+ }
1089
+
1090
+ export class ${names.pascal}Repository implements I${names.pascal}Repository {
1091
+ // In-memory store fallback. Replace with Prisma / TypeORM / Drizzle client calls.
1092
+ private storage: Map<string, ${names.pascal}Entity> = new Map();
1093
+
1094
+ async findAll(_query?: Record<string, any>): Promise<${names.pascal}Entity[]> {
1095
+ return Array.from(this.storage.values());
1096
+ }
1097
+
1098
+ async findById(id: string): Promise<${names.pascal}Entity | null> {
1099
+ return this.storage.get(id) || null;
1100
+ }
1101
+
1102
+ async create(data: Create${names.pascal}Dto): Promise<${names.pascal}Entity> {
1103
+ const id = (Math.random() * 100000).toFixed(0);
1104
+ const newRecord: ${names.pascal}Entity = {
1105
+ id,
1106
+ ...data,
1107
+ status: data.status || 'draft',
1108
+ createdAt: new Date(),
1109
+ updatedAt: new Date(),
1110
+ };
1111
+ this.storage.set(id, newRecord);
1112
+ return newRecord;
1113
+ }
1114
+
1115
+ async update(id: string, data: Update${names.pascal}Dto): Promise<${names.pascal}Entity> {
1116
+ const existing = await this.findById(id);
1117
+ if (!existing) {
1118
+ throw new Error(\`${names.pascal} with id \${id} not found\`);
1119
+ }
1120
+ const updated: ${names.pascal}Entity = {
1121
+ ...existing,
1122
+ ...data,
1123
+ updatedAt: new Date(),
1124
+ };
1125
+ this.storage.set(id, updated);
1126
+ return updated;
1127
+ }
1128
+
1129
+ async delete(id: string): Promise<boolean> {
1130
+ return this.storage.delete(id);
1131
+ }
1132
+ }
1133
+ `;
1134
+ }
1135
+ function tsRoutesTemplate(names, isModular = true) {
1136
+ const controllerImport = isModular ? `./${names.kebab}.controller.js` : `../controllers/${names.kebab}.controller.js`;
1137
+ return `import { Router } from 'express';
1138
+ import { ${names.pascal}Controller } from '${controllerImport}';
1139
+
1140
+ const router = Router();
1141
+ const controller = new ${names.pascal}Controller();
1142
+
1143
+ /**
1144
+ * Route declarations for ${names.pascal}
1145
+ */
1146
+ router.get('/', controller.getAll);
1147
+ router.get('/:id', controller.getById);
1148
+ router.post('/', controller.create);
1149
+ router.put('/:id', controller.update);
1150
+ router.delete('/:id', controller.delete);
1151
+
1152
+ export const ${names.camel}Routes = router;
1153
+ export default router;
1154
+ `;
1155
+ }
1156
+ function tsDtoTemplate(names) {
1157
+ return `export interface ${names.pascal}Entity {
1158
+ id: string;
1159
+ name: string;
1160
+ status: 'draft' | 'active' | 'archived';
1161
+ description?: string;
1162
+ metadata?: Record<string, unknown>;
1163
+ createdAt: Date;
1164
+ updatedAt: Date;
1165
+ }
1166
+
1167
+ export interface Create${names.pascal}Dto {
1168
+ name: string;
1169
+ status?: 'draft' | 'active' | 'archived';
1170
+ description?: string;
1171
+ metadata?: Record<string, unknown>;
1172
+ }
1173
+
1174
+ export interface Update${names.pascal}Dto {
1175
+ name?: string;
1176
+ status?: 'draft' | 'active' | 'archived';
1177
+ description?: string;
1178
+ metadata?: Record<string, unknown>;
1179
+ }
1180
+ `;
1181
+ }
1182
+
1183
+ // src/generator/scaffolder.ts
1184
+ function getMigrationTimestamp() {
1185
+ const now = /* @__PURE__ */ new Date();
1186
+ const YYYY = now.getFullYear();
1187
+ const MM = String(now.getMonth() + 1).padStart(2, "0");
1188
+ const DD = String(now.getDate()).padStart(2, "0");
1189
+ const hh = String(now.getHours()).padStart(2, "0");
1190
+ const mm = String(now.getMinutes()).padStart(2, "0");
1191
+ const ss = String(now.getSeconds()).padStart(2, "0");
1192
+ return `${YYYY}_${MM}_${DD}_${hh}${mm}${ss}`;
1193
+ }
1194
+ async function scaffoldModule(projectInfo, options) {
1195
+ const root = projectInfo.rootPath;
1196
+ const names = getNaming(options.moduleName);
1197
+ const filesToGenerate = [];
1198
+ const isModular = options.isModular ?? (projectInfo.type === "laravel" ? Boolean(projectInfo.laravel?.isModular) : projectInfo.type === "typescript" ? Boolean(projectInfo.typescript?.isModular) : true);
1199
+ if (projectInfo.type === "laravel") {
1200
+ const selected = new Set(options.components);
1201
+ if (isModular) {
1202
+ const baseDir = `app/Modules/${names.pascal}`;
1203
+ const baseNamespace = `App\\Modules\\${names.pascal}`;
1204
+ if (selected.has("model")) {
1205
+ filesToGenerate.push({
1206
+ relativePath: `${baseDir}/Models/${names.pascal}.php`,
1207
+ content: laravelModelTemplate(names, `${baseNamespace}\\Models`)
1208
+ });
1209
+ }
1210
+ if (selected.has("controller")) {
1211
+ filesToGenerate.push({
1212
+ relativePath: `${baseDir}/Controllers/${names.pascal}Controller.php`,
1213
+ content: laravelControllerTemplate(names, {
1214
+ namespace: `${baseNamespace}\\Controllers`,
1215
+ modelNamespace: `${baseNamespace}\\Models`,
1216
+ serviceNamespace: `${baseNamespace}\\Services`,
1217
+ requestNamespace: `${baseNamespace}\\Requests`
1218
+ })
1219
+ });
1220
+ }
1221
+ if (selected.has("service")) {
1222
+ filesToGenerate.push({
1223
+ relativePath: `${baseDir}/Services/${names.pascal}Service.php`,
1224
+ content: laravelServiceTemplate(names, {
1225
+ namespace: `${baseNamespace}\\Services`,
1226
+ modelNamespace: `${baseNamespace}\\Models`
1227
+ })
1228
+ });
1229
+ }
1230
+ if (selected.has("action")) {
1231
+ filesToGenerate.push({
1232
+ relativePath: `${baseDir}/Actions/Create${names.pascal}Action.php`,
1233
+ content: laravelActionTemplate(names, {
1234
+ namespace: `${baseNamespace}\\Actions`,
1235
+ modelNamespace: `${baseNamespace}\\Models`
1236
+ })
1237
+ });
1238
+ }
1239
+ if (selected.has("request")) {
1240
+ filesToGenerate.push({
1241
+ relativePath: `${baseDir}/Requests/${names.pascal}Request.php`,
1242
+ content: laravelRequestTemplate(names, `${baseNamespace}\\Requests`)
1243
+ });
1244
+ }
1245
+ if (selected.has("migration")) {
1246
+ const timestamp = getMigrationTimestamp();
1247
+ filesToGenerate.push({
1248
+ relativePath: `database/migrations/${timestamp}_create_${names.pluralSnake}_table.php`,
1249
+ content: laravelMigrationTemplate(names)
1250
+ });
1251
+ }
1252
+ } else {
1253
+ if (selected.has("model")) {
1254
+ filesToGenerate.push({
1255
+ relativePath: `app/Models/${names.pascal}.php`,
1256
+ content: laravelModelTemplate(names, "App\\Models")
1257
+ });
1258
+ }
1259
+ if (selected.has("controller")) {
1260
+ filesToGenerate.push({
1261
+ relativePath: `app/Http/Controllers/${names.pascal}Controller.php`,
1262
+ content: laravelControllerTemplate(names)
1263
+ });
1264
+ }
1265
+ if (selected.has("service")) {
1266
+ filesToGenerate.push({
1267
+ relativePath: `app/Services/${names.pascal}Service.php`,
1268
+ content: laravelServiceTemplate(names)
1269
+ });
1270
+ }
1271
+ if (selected.has("action")) {
1272
+ filesToGenerate.push({
1273
+ relativePath: `app/Actions/Create${names.pascal}Action.php`,
1274
+ content: laravelActionTemplate(names)
1275
+ });
1276
+ }
1277
+ if (selected.has("request")) {
1278
+ filesToGenerate.push({
1279
+ relativePath: `app/Http/Requests/${names.pascal}Request.php`,
1280
+ content: laravelRequestTemplate(names)
1281
+ });
1282
+ }
1283
+ if (selected.has("migration")) {
1284
+ const timestamp = getMigrationTimestamp();
1285
+ filesToGenerate.push({
1286
+ relativePath: `database/migrations/${timestamp}_create_${names.pluralSnake}_table.php`,
1287
+ content: laravelMigrationTemplate(names)
1288
+ });
1289
+ }
1290
+ }
1291
+ } else {
1292
+ const selected = new Set(options.components);
1293
+ const srcDir = projectInfo.typescript?.srcDir || "src";
1294
+ if (isModular) {
1295
+ const moduleFolder = `${srcDir}/modules/${names.kebab}`;
1296
+ if (selected.has("controller")) {
1297
+ filesToGenerate.push({
1298
+ relativePath: `${moduleFolder}/${names.kebab}.controller.ts`,
1299
+ content: tsControllerTemplate(names, true)
1300
+ });
1301
+ }
1302
+ if (selected.has("service")) {
1303
+ filesToGenerate.push({
1304
+ relativePath: `${moduleFolder}/${names.kebab}.service.ts`,
1305
+ content: tsServiceTemplate(names, true)
1306
+ });
1307
+ }
1308
+ if (selected.has("repository")) {
1309
+ filesToGenerate.push({
1310
+ relativePath: `${moduleFolder}/${names.kebab}.repository.ts`,
1311
+ content: tsRepositoryTemplate(names, true)
1312
+ });
1313
+ }
1314
+ if (selected.has("route")) {
1315
+ filesToGenerate.push({
1316
+ relativePath: `${moduleFolder}/${names.kebab}.routes.ts`,
1317
+ content: tsRoutesTemplate(names, true)
1318
+ });
1319
+ }
1320
+ if (selected.has("dto")) {
1321
+ filesToGenerate.push({
1322
+ relativePath: `${moduleFolder}/${names.kebab}.dto.ts`,
1323
+ content: tsDtoTemplate(names)
1324
+ });
1325
+ }
1326
+ if (filesToGenerate.length > 1) {
1327
+ const exports = [];
1328
+ if (selected.has("controller")) exports.push(`export * from './${names.kebab}.controller.js';`);
1329
+ if (selected.has("service")) exports.push(`export * from './${names.kebab}.service.js';`);
1330
+ if (selected.has("repository")) exports.push(`export * from './${names.kebab}.repository.js';`);
1331
+ if (selected.has("route")) exports.push(`export * from './${names.kebab}.routes.js';`);
1332
+ if (selected.has("dto")) exports.push(`export * from './${names.kebab}.dto.js';`);
1333
+ filesToGenerate.push({
1334
+ relativePath: `${moduleFolder}/index.ts`,
1335
+ content: `${exports.join("\n")}
1336
+ `
1337
+ });
1338
+ }
1339
+ } else {
1340
+ if (selected.has("controller")) {
1341
+ filesToGenerate.push({
1342
+ relativePath: `${srcDir}/controllers/${names.kebab}.controller.ts`,
1343
+ content: tsControllerTemplate(names, false)
1344
+ });
1345
+ }
1346
+ if (selected.has("service")) {
1347
+ filesToGenerate.push({
1348
+ relativePath: `${srcDir}/services/${names.kebab}.service.ts`,
1349
+ content: tsServiceTemplate(names, false)
1350
+ });
1351
+ }
1352
+ if (selected.has("repository")) {
1353
+ filesToGenerate.push({
1354
+ relativePath: `${srcDir}/repositories/${names.kebab}.repository.ts`,
1355
+ content: tsRepositoryTemplate(names, false)
1356
+ });
1357
+ }
1358
+ if (selected.has("route")) {
1359
+ filesToGenerate.push({
1360
+ relativePath: `${srcDir}/routes/${names.kebab}.routes.ts`,
1361
+ content: tsRoutesTemplate(names, false)
1362
+ });
1363
+ }
1364
+ if (selected.has("dto")) {
1365
+ filesToGenerate.push({
1366
+ relativePath: `${srcDir}/dtos/${names.kebab}.dto.ts`,
1367
+ content: tsDtoTemplate(names)
1368
+ });
1369
+ }
1370
+ }
1371
+ }
1372
+ const results = [];
1373
+ let createdCount = 0;
1374
+ let skippedCount = 0;
1375
+ let errorCount = 0;
1376
+ for (const item of filesToGenerate) {
1377
+ const fullPath = path2.resolve(root, item.relativePath);
1378
+ if (fs2.existsSync(fullPath) && !options.forceOverwrite) {
1379
+ results.push({
1380
+ filePath: fullPath,
1381
+ relativeFilePath: item.relativePath,
1382
+ status: "skipped",
1383
+ reason: "File already exists (overwrite protected)"
1384
+ });
1385
+ skippedCount++;
1386
+ continue;
1387
+ }
1388
+ if (options.dryRun) {
1389
+ results.push({
1390
+ filePath: fullPath,
1391
+ relativeFilePath: item.relativePath,
1392
+ status: "created",
1393
+ reason: "Dry run simulated"
1394
+ });
1395
+ createdCount++;
1396
+ continue;
1397
+ }
1398
+ try {
1399
+ const parentDir = path2.dirname(fullPath);
1400
+ if (!fs2.existsSync(parentDir)) {
1401
+ fs2.mkdirSync(parentDir, { recursive: true });
1402
+ }
1403
+ fs2.writeFileSync(fullPath, item.content, "utf-8");
1404
+ results.push({
1405
+ filePath: fullPath,
1406
+ relativeFilePath: item.relativePath,
1407
+ status: "created"
1408
+ });
1409
+ createdCount++;
1410
+ } catch (err) {
1411
+ results.push({
1412
+ filePath: fullPath,
1413
+ relativeFilePath: item.relativePath,
1414
+ status: "error",
1415
+ reason: err.message || String(err)
1416
+ });
1417
+ errorCount++;
1418
+ }
1419
+ }
1420
+ return {
1421
+ moduleName: names.pascal,
1422
+ targetDir: root,
1423
+ files: results,
1424
+ createdCount,
1425
+ skippedCount,
1426
+ errorCount
1427
+ };
1428
+ }
1429
+
1430
+ // src/index.ts
1431
+ var VERSION = "1.0.0";
1432
+ function showHelp() {
1433
+ console.log(`
1434
+ ${pc.bold(pc.cyan("LaraTS CLI"))} ${pc.gray(`v${VERSION}`)}
1435
+ ${pc.gray("Smart Architecture Visualizer & Contextual Module Scaffolder")}
1436
+
1437
+ ${pc.bold("USAGE:")}
1438
+ ${pc.cyan("$")} npx larats [command] [options]
1439
+ ${pc.cyan("$")} larats [command] [options]
1440
+
1441
+ ${pc.bold("COMMANDS:")}
1442
+ ${pc.green("scan")} Scan repository & generate ARCHITECTURE.md
1443
+ ${pc.green("scaffold")}, ${pc.green("make")} [name] Scaffold a new module or feature with clean boilerplate
1444
+ ${pc.green("info")} Show detected project type & architectural flavor
1445
+ ${pc.green("help")} Display this help message
1446
+
1447
+ ${pc.bold("OPTIONS:")}
1448
+ ${pc.yellow("-o, --output")} <file> Output markdown path for scan (default: ARCHITECTURE.md)
1449
+ ${pc.yellow("-m, --modular")} Enforce modular directory structure
1450
+ ${pc.yellow("-s, --standard")} Enforce standard/layered directory structure
1451
+ ${pc.yellow("--dry-run")} Simulate generation without writing files
1452
+ ${pc.yellow("-f, --force")} Overwrite files if they already exist
1453
+ ${pc.yellow("-v, --version")} Display CLI version
1454
+ ${pc.yellow("-h, --help")} Display this help message
1455
+
1456
+ ${pc.bold("EXAMPLES:")}
1457
+ ${pc.cyan("$")} larats
1458
+ ${pc.cyan("$")} larats scan
1459
+ ${pc.cyan("$")} larats scan --output docs/ARCHITECTURE.md
1460
+ ${pc.cyan("$")} larats scaffold Payment
1461
+ ${pc.cyan("$")} larats make Order --modular
1462
+ `);
1463
+ }
1464
+ function handleCancel() {
1465
+ p.cancel(pc.yellow("Operation cancelled. See you next time! \u{1F44B}"));
1466
+ process.exit(0);
1467
+ }
1468
+ async function runScan(projectInfo, outputPath = "ARCHITECTURE.md") {
1469
+ const spinner2 = p.spinner();
1470
+ spinner2.start("Scanning codebase structure & components (strict ignore list active)...");
1471
+ try {
1472
+ const scanResult = await scanProject(projectInfo);
1473
+ spinner2.stop(pc.green(`Scan completed in ${scanResult.scanDurationMs}ms`));
1474
+ const markdown = generateArchitectureMarkdown(scanResult);
1475
+ const destination = path3.resolve(projectInfo.rootPath, outputPath);
1476
+ const parentDir = path3.dirname(destination);
1477
+ if (!fs3.existsSync(parentDir)) {
1478
+ fs3.mkdirSync(parentDir, { recursive: true });
1479
+ }
1480
+ fs3.writeFileSync(destination, markdown, "utf-8");
1481
+ p.note(
1482
+ `${pc.bold("Scanned Files:")} ${scanResult.totalFilesScanned}
1483
+ ${pc.bold("Components Identified:")} ${Object.keys(scanResult.components).length}
1484
+ ${pc.bold("Modules Detected:")} ${scanResult.modules.length > 0 ? scanResult.modules.join(", ") : "None (monolithic structure)"}
1485
+ ${pc.bold("Documentation:")} Saved to ${pc.cyan(path3.relative(projectInfo.rootPath, destination) || outputPath)}`,
1486
+ pc.green("Architecture Map Generated! \u{1F5FA}\uFE0F")
1487
+ );
1488
+ p.outro(pc.cyan(`Open ${outputPath} to view your project structure & Mermaid diagram!`));
1489
+ } catch (err) {
1490
+ spinner2.stop(pc.red("Scan failed"));
1491
+ p.log.error(err.message || String(err));
1492
+ }
1493
+ }
1494
+ async function runScaffold(projectInfo, moduleNameArg, cliOptions = {}) {
1495
+ let moduleName = moduleNameArg;
1496
+ if (!moduleName) {
1497
+ const input = await p.text({
1498
+ message: "What is the name of the new module or feature?",
1499
+ placeholder: "e.g. Payment, Order, UserProfile",
1500
+ validate(val) {
1501
+ if (!val || !val.trim()) return "Module name cannot be empty.";
1502
+ if (!/^[a-zA-Z0-9_-]+$/.test(val.trim())) return "Use only alphanumeric characters, dashes, or underscores.";
1503
+ }
1504
+ });
1505
+ if (p.isCancel(input)) handleCancel();
1506
+ moduleName = input.trim();
1507
+ }
1508
+ let selectedComponents = [];
1509
+ if (projectInfo.type === "laravel") {
1510
+ const componentsPrompt = await p.multiselect({
1511
+ message: `Select components to scaffold for ${pc.cyan(moduleName)}:`,
1512
+ options: [
1513
+ { value: "model", label: "Eloquent Model", hint: "Includes table name, fillables, and casts" },
1514
+ { value: "controller", label: "Resourceful Controller", hint: "Includes standard CRUD methods & DI service" },
1515
+ { value: "service", label: "Service Class", hint: "Encapsulated business logic operations" },
1516
+ { value: "action", label: "Single Action Class", hint: "Invokable single-responsibility class" },
1517
+ { value: "request", label: "Form Request", hint: "Request validation rules & authorization" },
1518
+ { value: "migration", label: "Database Migration", hint: "Schema definition with timestamps" }
1519
+ ],
1520
+ initialValues: ["model", "controller", "service", "request", "migration"],
1521
+ required: true
1522
+ });
1523
+ if (p.isCancel(componentsPrompt)) handleCancel();
1524
+ selectedComponents = componentsPrompt;
1525
+ } else {
1526
+ const componentsPrompt = await p.multiselect({
1527
+ message: `Select components to scaffold for ${pc.cyan(moduleName)}:`,
1528
+ options: [
1529
+ { value: "controller", label: "Controller", hint: "Express request handlers & response orchestration" },
1530
+ { value: "service", label: "Service", hint: "Application logic & repository coordination" },
1531
+ { value: "repository", label: "Repository", hint: "Data persistence abstraction & queries" },
1532
+ { value: "route", label: "Router & Routes", hint: "Express router mapping endpoints to controller" },
1533
+ { value: "dto", label: "DTOs & Interfaces", hint: "Typed interfaces for entities and payloads" }
1534
+ ],
1535
+ initialValues: ["controller", "service", "repository", "route", "dto"],
1536
+ required: true
1537
+ });
1538
+ if (p.isCancel(componentsPrompt)) handleCancel();
1539
+ selectedComponents = componentsPrompt;
1540
+ }
1541
+ let isModular = true;
1542
+ if (cliOptions.modular) {
1543
+ isModular = true;
1544
+ } else if (cliOptions.standard) {
1545
+ isModular = false;
1546
+ } else {
1547
+ const defaultModular = projectInfo.type === "laravel" ? Boolean(projectInfo.laravel?.isModular) : projectInfo.type === "typescript" ? Boolean(projectInfo.typescript?.isModular) : true;
1548
+ const structurePrompt = await p.select({
1549
+ message: "Choose folder architecture structure:",
1550
+ options: projectInfo.type === "laravel" ? [
1551
+ {
1552
+ value: "modular",
1553
+ label: "Modular Domain Structure",
1554
+ hint: `app/Modules/${moduleName}/[Models, Controllers, Services]`
1555
+ },
1556
+ {
1557
+ value: "standard",
1558
+ label: "Standard Laravel Structure",
1559
+ hint: `app/Models, app/Http/Controllers, app/Services`
1560
+ }
1561
+ ] : [
1562
+ {
1563
+ value: "modular",
1564
+ label: "Modular Feature Structure",
1565
+ hint: `src/modules/${moduleName.toLowerCase()}/...`
1566
+ },
1567
+ {
1568
+ value: "standard",
1569
+ label: "Layered Folder Structure",
1570
+ hint: `src/controllers, src/services, src/routes...`
1571
+ }
1572
+ ],
1573
+ initialValue: defaultModular ? "modular" : "standard"
1574
+ });
1575
+ if (p.isCancel(structurePrompt)) handleCancel();
1576
+ isModular = structurePrompt === "modular";
1577
+ }
1578
+ const spinner2 = p.spinner();
1579
+ spinner2.start(`Generating boilerplate files for ${pc.cyan(moduleName)}...`);
1580
+ const result = await scaffoldModule(projectInfo, {
1581
+ moduleName,
1582
+ components: selectedComponents,
1583
+ isModular,
1584
+ dryRun: cliOptions.dryRun,
1585
+ forceOverwrite: cliOptions.force
1586
+ });
1587
+ spinner2.stop("Generation finished!");
1588
+ const fileLines = result.files.map((f) => {
1589
+ if (f.status === "created") {
1590
+ return ` ${pc.green("\u2714")} ${f.relativeFilePath} ${pc.gray("(created)")}`;
1591
+ } else if (f.status === "skipped") {
1592
+ return ` ${pc.yellow("\u26A0")} ${f.relativeFilePath} ${pc.yellow(`(skipped - ${f.reason})`)}`;
1593
+ } else {
1594
+ return ` ${pc.red("\u2716")} ${f.relativeFilePath} ${pc.red(`(error - ${f.reason})`)}`;
1595
+ }
1596
+ });
1597
+ p.note(
1598
+ fileLines.join("\n") + `
1599
+
1600
+ ${pc.bold("Summary:")} ${pc.green(`${result.createdCount} created`)}, ${pc.yellow(`${result.skippedCount} skipped`)}, ${pc.red(`${result.errorCount} errors`)}`,
1601
+ pc.cyan(`Module Scaffolding: ${moduleName}`)
1602
+ );
1603
+ if (result.skippedCount > 0 && !cliOptions.force) {
1604
+ p.log.warn(pc.yellow("Anti-Overwrite Protection prevented modifying existing files. Use --force to overwrite if intended."));
1605
+ }
1606
+ p.outro(pc.green(`\u2728 Successfully scaffolded ${moduleName} module!`));
1607
+ }
1608
+ function showProjectInfo(projectInfo) {
1609
+ let details = `${pc.bold("Project Name:")} ${projectInfo.name}
1610
+ ${pc.bold("Project Type:")} ${projectInfo.type.toUpperCase()}
1611
+ ${pc.bold("Flavor / Stack:")} ${projectInfo.summary}
1612
+ ${pc.bold("Working Path:")} ${projectInfo.rootPath}`;
1613
+ if (projectInfo.type === "laravel" && projectInfo.laravel) {
1614
+ details += `
1615
+ ${pc.bold("Filament Admin:")} ${projectInfo.laravel.hasFilament ? pc.green("Yes") : "No"}
1616
+ ${pc.bold("Livewire:")} ${projectInfo.laravel.hasLivewire ? pc.green("Yes") : "No"}
1617
+ ${pc.bold("Inertia.js:")} ${projectInfo.laravel.hasInertia ? pc.green("Yes") : "No"}
1618
+ ${pc.bold("Modular App:")} ${projectInfo.laravel.isModular ? pc.green("Yes") : "No"}`;
1619
+ } else if (projectInfo.type === "typescript" && projectInfo.typescript) {
1620
+ details += `
1621
+ ${pc.bold("Framework:")} ${projectInfo.typescript.framework}
1622
+ ${pc.bold("Prisma ORM:")} ${projectInfo.typescript.hasPrisma ? pc.green("Yes") : "No"}
1623
+ ${pc.bold("Monorepo:")} ${projectInfo.typescript.isMonorepo ? pc.green("Yes") : "No"}
1624
+ ${pc.bold("Modular Src:")} ${projectInfo.typescript.isModular ? pc.green("Yes") : "No"}`;
1625
+ }
1626
+ p.note(details, pc.cyan("Detected Project Architecture"));
1627
+ }
1628
+ async function main() {
1629
+ const args = process.argv.slice(2);
1630
+ if (args.includes("--help") || args.includes("-h") || args[0] === "help") {
1631
+ showHelp();
1632
+ return;
1633
+ }
1634
+ if (args.includes("--version") || args.includes("-v")) {
1635
+ console.log(`larats v${VERSION}`);
1636
+ return;
1637
+ }
1638
+ let outputPath = "ARCHITECTURE.md";
1639
+ const outputIdx = args.findIndex((a) => a === "--output" || a === "-o");
1640
+ if (outputIdx !== -1 && args[outputIdx + 1]) {
1641
+ outputPath = args[outputIdx + 1];
1642
+ }
1643
+ const isModularFlag = args.includes("--modular") || args.includes("-m");
1644
+ const isStandardFlag = args.includes("--standard") || args.includes("-s");
1645
+ const isForceFlag = args.includes("--force") || args.includes("-f");
1646
+ const isDryRunFlag = args.includes("--dry-run");
1647
+ const command = args[0] && !args[0].startsWith("-") ? args[0] : null;
1648
+ const projectInfo = await detectProjectType(process.cwd());
1649
+ if (command === "scan") {
1650
+ p.intro(`${pc.bgCyan(pc.black(" LaraTS "))} ${pc.gray(`v${VERSION}`)} - Scanning Architecture`);
1651
+ p.log.info(`Detected: ${pc.green(projectInfo.summary)}`);
1652
+ await runScan(projectInfo, outputPath);
1653
+ return;
1654
+ }
1655
+ if (command === "scaffold" || command === "make") {
1656
+ const moduleName = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
1657
+ p.intro(`${pc.bgCyan(pc.black(" LaraTS "))} ${pc.gray(`v${VERSION}`)} - Module Scaffolder`);
1658
+ p.log.info(`Target Project: ${pc.green(projectInfo.summary)}`);
1659
+ await runScaffold(projectInfo, moduleName, {
1660
+ modular: isModularFlag,
1661
+ standard: isStandardFlag,
1662
+ force: isForceFlag,
1663
+ dryRun: isDryRunFlag
1664
+ });
1665
+ return;
1666
+ }
1667
+ if (command === "info") {
1668
+ p.intro(`${pc.bgCyan(pc.black(" LaraTS "))} ${pc.gray(`v${VERSION}`)}`);
1669
+ showProjectInfo(projectInfo);
1670
+ p.outro(pc.cyan("Done."));
1671
+ return;
1672
+ }
1673
+ p.intro(`${pc.bgCyan(pc.black(" LaraTS "))} ${pc.bold("Smart Architecture Visualizer & Scaffolder")} ${pc.gray(`v${VERSION}`)}`);
1674
+ p.log.info(`Working Directory: ${pc.gray(process.cwd())}`);
1675
+ p.log.info(`Detected Architecture: ${pc.bold(pc.green(projectInfo.summary))}`);
1676
+ const action = await p.select({
1677
+ message: "What would you like to do?",
1678
+ options: [
1679
+ {
1680
+ value: "scan",
1681
+ label: "\u{1F50D} Scan Architecture & Generate ARCHITECTURE.md",
1682
+ hint: "Creates component stats, directory tree & Mermaid flowchart"
1683
+ },
1684
+ {
1685
+ value: "scaffold",
1686
+ label: "\u{1F3D7}\uFE0F Scaffold New Feature / Module",
1687
+ hint: "Interactively generate boilerplate components with safety checks"
1688
+ },
1689
+ {
1690
+ value: "info",
1691
+ label: "\u{1F4CA} Inspect Detected Architecture Details",
1692
+ hint: "View detected frameworks, ORMs, and configurations"
1693
+ },
1694
+ {
1695
+ value: "exit",
1696
+ label: "\u{1F6AA} Exit"
1697
+ }
1698
+ ]
1699
+ });
1700
+ if (p.isCancel(action) || action === "exit") {
1701
+ handleCancel();
1702
+ }
1703
+ if (action === "scan") {
1704
+ await runScan(projectInfo, outputPath);
1705
+ } else if (action === "scaffold") {
1706
+ await runScaffold(projectInfo, void 0, {
1707
+ modular: isModularFlag,
1708
+ standard: isStandardFlag,
1709
+ force: isForceFlag,
1710
+ dryRun: isDryRunFlag
1711
+ });
1712
+ } else if (action === "info") {
1713
+ showProjectInfo(projectInfo);
1714
+ p.outro(pc.cyan("Done!"));
1715
+ }
1716
+ }
1717
+ main().catch((err) => {
1718
+ p.log.error(pc.red(`Fatal error: ${err.message || String(err)}`));
1719
+ process.exit(1);
1720
+ });
1721
+ //# sourceMappingURL=index.js.map