create-mohit-next 0.0.0-stage → 2.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.
Files changed (202) hide show
  1. package/README.md +139 -2
  2. package/index.js +399 -0
  3. package/lib/features.js +358 -0
  4. package/lib/scaffold.js +471 -0
  5. package/package.json +40 -4
  6. package/templates/common/_editorconfig +12 -0
  7. package/templates/common/_gitattributes +5 -0
  8. package/templates/common/_github/dependabot.yml +14 -0
  9. package/templates/common/_github/workflows/ci.yml +66 -0
  10. package/templates/common/_husky/commit-msg +1 -0
  11. package/templates/common/_husky/pre-commit +1 -0
  12. package/templates/common/_nvmrc +1 -0
  13. package/templates/common/_prettierignore +15 -0
  14. package/templates/common/commitlint.config.mjs +10 -0
  15. package/templates/next/AGENTS.md +9 -0
  16. package/templates/next/Dockerfile +48 -0
  17. package/templates/next/README.md +328 -0
  18. package/templates/next/_dockerignore +13 -0
  19. package/templates/next/_env.example +20 -0
  20. package/templates/next/_gitignore +50 -0
  21. package/templates/next/docker-compose.yml +33 -0
  22. package/templates/next/e2e/rbac.spec.ts +69 -0
  23. package/templates/next/e2e/server.mjs +35 -0
  24. package/templates/next/eslint.config.mjs +33 -0
  25. package/templates/next/next.config.ts +47 -0
  26. package/templates/next/package.json +68 -0
  27. package/templates/next/playwright.config.ts +30 -0
  28. package/templates/next/public/robots.txt +6 -0
  29. package/templates/next/scripts/seed.ts +111 -0
  30. package/templates/next/src/app/(app)/admin/audit/page.tsx +99 -0
  31. package/templates/next/src/app/(app)/admin/page.tsx +92 -0
  32. package/templates/next/src/app/(app)/dashboard/page.tsx +120 -0
  33. package/templates/next/src/app/(app)/error.tsx +28 -0
  34. package/templates/next/src/app/(app)/layout.tsx +58 -0
  35. package/templates/next/src/app/(app)/loading.tsx +5 -0
  36. package/templates/next/src/app/(app)/reports/page.tsx +128 -0
  37. package/templates/next/src/app/(app)/settings/page.tsx +66 -0
  38. package/templates/next/src/app/(auth)/forgot-password/page.tsx +17 -0
  39. package/templates/next/src/app/(auth)/layout.tsx +18 -0
  40. package/templates/next/src/app/(auth)/login/page.tsx +18 -0
  41. package/templates/next/src/app/(auth)/register/page.tsx +18 -0
  42. package/templates/next/src/app/(auth)/reset-password/page.tsx +18 -0
  43. package/templates/next/src/app/api/account/password/route.ts +45 -0
  44. package/templates/next/src/app/api/account/route.ts +25 -0
  45. package/templates/next/src/app/api/account/sessions/route.ts +12 -0
  46. package/templates/next/src/app/api/admin/audit/route.ts +13 -0
  47. package/templates/next/src/app/api/admin/users/[id]/route.ts +61 -0
  48. package/templates/next/src/app/api/admin/users/route.ts +18 -0
  49. package/templates/next/src/app/api/auth/forgot-password/route.ts +47 -0
  50. package/templates/next/src/app/api/auth/login/route.ts +43 -0
  51. package/templates/next/src/app/api/auth/logout/route.ts +21 -0
  52. package/templates/next/src/app/api/auth/me/route.ts +21 -0
  53. package/templates/next/src/app/api/auth/register/route.ts +74 -0
  54. package/templates/next/src/app/api/auth/resend-verification/route.ts +25 -0
  55. package/templates/next/src/app/api/auth/reset-password/route.ts +43 -0
  56. package/templates/next/src/app/api/auth/verify-email/route.ts +29 -0
  57. package/templates/next/src/app/api/health/route.ts +27 -0
  58. package/templates/next/src/app/favicon.ico +0 -0
  59. package/templates/next/src/app/forbidden/page.tsx +47 -0
  60. package/templates/next/src/app/layout.tsx +55 -0
  61. package/templates/next/src/app/not-found.tsx +20 -0
  62. package/templates/next/src/app/opengraph-image.tsx +49 -0
  63. package/templates/next/src/app/page.tsx +165 -0
  64. package/templates/next/src/app/robots.ts +15 -0
  65. package/templates/next/src/app/sitemap.ts +13 -0
  66. package/templates/next/src/app/verify-email/page.tsx +23 -0
  67. package/templates/next/src/components/admin/user-actions.tsx +124 -0
  68. package/templates/next/src/components/admin/users-data-table.tsx +221 -0
  69. package/templates/next/src/components/admin/users-table.tsx +67 -0
  70. package/templates/next/src/components/auth/auth-card.tsx +41 -0
  71. package/templates/next/src/components/auth/can.tsx +34 -0
  72. package/templates/next/src/components/auth/forgot-password-form.tsx +76 -0
  73. package/templates/next/src/components/auth/form-field.tsx +40 -0
  74. package/templates/next/src/components/auth/login-form.tsx +87 -0
  75. package/templates/next/src/components/auth/password-input.tsx +43 -0
  76. package/templates/next/src/components/auth/register-form.tsx +117 -0
  77. package/templates/next/src/components/auth/reset-password-form.tsx +80 -0
  78. package/templates/next/src/components/auth/session-refresher.tsx +44 -0
  79. package/templates/next/src/components/auth/verify-email-banner.tsx +43 -0
  80. package/templates/next/src/components/auth/verify-email-status.tsx +44 -0
  81. package/templates/next/src/components/layout/nav-links.tsx +37 -0
  82. package/templates/next/src/components/layout/navbar.tsx +27 -0
  83. package/templates/next/src/components/layout/page-header.tsx +21 -0
  84. package/templates/next/src/components/layout/sidebar.tsx +83 -0
  85. package/templates/next/src/components/layout/skeletons.tsx +57 -0
  86. package/templates/next/src/components/layout/user-menu.tsx +118 -0
  87. package/templates/next/src/components/logo.tsx +16 -0
  88. package/templates/next/src/components/motion/fade-in.tsx +19 -0
  89. package/templates/next/src/components/providers/user-provider.tsx +60 -0
  90. package/templates/next/src/components/reports/animated-bar.tsx +24 -0
  91. package/templates/next/src/components/reports/role-chart.tsx +61 -0
  92. package/templates/next/src/components/reports/signups-chart.tsx +64 -0
  93. package/templates/next/src/components/role-badge.tsx +11 -0
  94. package/templates/next/src/components/settings/password-form.tsx +80 -0
  95. package/templates/next/src/components/settings/profile-form.tsx +63 -0
  96. package/templates/next/src/components/settings/sessions-card.tsx +70 -0
  97. package/templates/next/src/components/theme-toggle.tsx +61 -0
  98. package/templates/next/src/config/rbac.test.ts +89 -0
  99. package/templates/next/src/config/rbac.ts +170 -0
  100. package/templates/next/src/config/site.ts +4 -0
  101. package/templates/next/src/lib/api.ts +179 -0
  102. package/templates/next/src/lib/audit.ts +66 -0
  103. package/templates/next/src/lib/auth.ts +50 -0
  104. package/templates/next/src/lib/dal.ts +63 -0
  105. package/templates/next/src/lib/db.ts +35 -0
  106. package/templates/next/src/lib/email-templates.ts +55 -0
  107. package/templates/next/src/lib/email.ts +53 -0
  108. package/templates/next/src/lib/env.ts +90 -0
  109. package/templates/next/src/lib/http.ts +57 -0
  110. package/templates/next/src/lib/password-strength.test.ts +20 -0
  111. package/templates/next/src/lib/password-strength.ts +24 -0
  112. package/templates/next/src/lib/rate-limit.test.ts +47 -0
  113. package/templates/next/src/lib/rate-limit.ts +70 -0
  114. package/templates/next/src/lib/redirect.test.ts +23 -0
  115. package/templates/next/src/lib/redirect.ts +21 -0
  116. package/templates/next/src/lib/session.ts +71 -0
  117. package/templates/next/src/lib/theme.ts +32 -0
  118. package/templates/next/src/lib/tokens.ts +63 -0
  119. package/templates/next/src/lib/users.ts +196 -0
  120. package/templates/next/src/lib/validations/account.ts +20 -0
  121. package/templates/next/src/lib/validations/auth.test.ts +39 -0
  122. package/templates/next/src/lib/validations/auth.ts +66 -0
  123. package/templates/next/src/lib/validations/user.ts +13 -0
  124. package/templates/next/src/models/audit-log.ts +33 -0
  125. package/templates/next/src/models/auth-token.ts +26 -0
  126. package/templates/next/src/models/user.ts +35 -0
  127. package/templates/next/src/proxy.ts +57 -0
  128. package/templates/next/src/styles/app.css +1092 -0
  129. package/templates/next/src/types/user.ts +13 -0
  130. package/templates/next/tsconfig.json +34 -0
  131. package/templates/next/vitest.config.mts +13 -0
  132. package/templates/styles/css.css +580 -0
  133. package/templates/styles/shadcn.css +142 -0
  134. package/templates/styles/tailwind.css +140 -0
  135. package/templates/ui/css/components/alert-dialog.tsx +172 -0
  136. package/templates/ui/css/components/avatar.tsx +17 -0
  137. package/templates/ui/css/components/badge.tsx +18 -0
  138. package/templates/ui/css/components/button.tsx +41 -0
  139. package/templates/ui/css/components/card.tsx +33 -0
  140. package/templates/ui/css/components/dropdown-menu.tsx +230 -0
  141. package/templates/ui/css/components/input.tsx +7 -0
  142. package/templates/ui/css/components/label.tsx +7 -0
  143. package/templates/ui/css/components/native-select.tsx +23 -0
  144. package/templates/ui/css/components/skeleton.tsx +7 -0
  145. package/templates/ui/css/components/slot.tsx +30 -0
  146. package/templates/ui/css/components/table.tsx +31 -0
  147. package/templates/ui/css/utils.ts +16 -0
  148. package/templates/ui/shadcn/components/alert-dialog.tsx +199 -0
  149. package/templates/ui/shadcn/components/avatar.tsx +111 -0
  150. package/templates/ui/shadcn/components/badge.tsx +44 -0
  151. package/templates/ui/shadcn/components/button.tsx +66 -0
  152. package/templates/ui/shadcn/components/card.tsx +87 -0
  153. package/templates/ui/shadcn/components/dropdown-menu.tsx +268 -0
  154. package/templates/ui/shadcn/components/input.tsx +18 -0
  155. package/templates/ui/shadcn/components/label.tsx +20 -0
  156. package/templates/ui/shadcn/components/native-select.tsx +54 -0
  157. package/templates/ui/shadcn/components/skeleton.tsx +13 -0
  158. package/templates/ui/shadcn/components/table.tsx +115 -0
  159. package/templates/ui/shadcn/utils.ts +1 -0
  160. package/templates/ui/tailwind/components/alert-dialog.tsx +177 -0
  161. package/templates/ui/tailwind/components/avatar.tsx +36 -0
  162. package/templates/ui/tailwind/components/badge.tsx +29 -0
  163. package/templates/ui/tailwind/components/button.tsx +65 -0
  164. package/templates/ui/tailwind/components/card.tsx +70 -0
  165. package/templates/ui/tailwind/components/dropdown-menu.tsx +236 -0
  166. package/templates/ui/tailwind/components/input.tsx +17 -0
  167. package/templates/ui/tailwind/components/label.tsx +16 -0
  168. package/templates/ui/tailwind/components/native-select.tsx +32 -0
  169. package/templates/ui/tailwind/components/skeleton.tsx +13 -0
  170. package/templates/ui/tailwind/components/slot.tsx +34 -0
  171. package/templates/ui/tailwind/components/table.tsx +56 -0
  172. package/templates/ui/tailwind/utils.ts +1 -0
  173. package/templates/vite/Dockerfile +29 -0
  174. package/templates/vite/README.md +142 -0
  175. package/templates/vite/_dockerignore +14 -0
  176. package/templates/vite/_env.example +8 -0
  177. package/templates/vite/_gitignore +37 -0
  178. package/templates/vite/e2e/app.spec.ts +41 -0
  179. package/templates/vite/index.html +32 -0
  180. package/templates/vite/nginx.conf +26 -0
  181. package/templates/vite/package.json +61 -0
  182. package/templates/vite/playwright.config.ts +27 -0
  183. package/templates/vite/public/favicon.svg +1 -0
  184. package/templates/vite/src/App.test.tsx +28 -0
  185. package/templates/vite/src/App.tsx +26 -0
  186. package/templates/vite/src/components/home.tsx +121 -0
  187. package/templates/vite/src/components/layout/root-layout.tsx +18 -0
  188. package/templates/vite/src/components/layout/site-footer.tsx +10 -0
  189. package/templates/vite/src/components/layout/site-header.tsx +49 -0
  190. package/templates/vite/src/components/theme-toggle.tsx +90 -0
  191. package/templates/vite/src/env.ts +36 -0
  192. package/templates/vite/src/lib/theme.ts +26 -0
  193. package/templates/vite/src/main.tsx +13 -0
  194. package/templates/vite/src/pages/about.tsx +52 -0
  195. package/templates/vite/src/pages/not-found.tsx +33 -0
  196. package/templates/vite/src/router.ts +24 -0
  197. package/templates/vite/src/styles/app.css +281 -0
  198. package/templates/vite/src/test/setup.ts +21 -0
  199. package/templates/vite/tsconfig.app.json +31 -0
  200. package/templates/vite/tsconfig.json +7 -0
  201. package/templates/vite/tsconfig.node.json +23 -0
  202. package/templates/vite/vite.config.ts +30 -0
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # create-mohit-next
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Scaffold a production-ready React app in one command, choosing exactly what you need:
4
+
5
+ ```bash
6
+ npm create mohit-next@latest my-app
7
+ ```
8
+
9
+ The CLI asks, in order:
10
+
11
+ 1. **Project name**
12
+ 2. **Language**: TypeScript or JavaScript
13
+ 3. **Framework**:
14
+ - **Next.js** (full-stack): MongoDB + Mongoose, JWT auth (bcrypt + `jose`), role-based access
15
+ control (`user` < `manager` < `admin`, enforced in the proxy, the data layer and the API)
16
+ - **Vite + React** (single-page app)
17
+ 4. **Styling**: Tailwind CSS + shadcn/ui, Tailwind CSS only, or none (plain CSS)
18
+ 5. **Yes/no questions** for everything else:
19
+
20
+ | Group | Question | Next.js | Vite |
21
+ | ----- | -------- | :-----: | :--: |
22
+ | Core | React Router (pages + client-side routing) | (built in) | ✓ |
23
+ | Core | Basic UI components (Button, Input, Card, Badge, Table, Dialog...) | (always) | ✓ |
24
+ | Core | Environment variables with zod validation | ✓ | ✓ |
25
+ | Code quality | ESLint / Oxlint | ESLint | Oxlint |
26
+ | Code quality | Prettier | ✓ | ✓ |
27
+ | Code quality | Husky + lint-staged + commitlint | ✓ | ✓ |
28
+ | Frontend | Sidebar dashboard layout (or top navbar) | ✓ | |
29
+ | Frontend | Admin users table with search, sort & pagination | ✓ | |
30
+ | Frontend | Charts on the reports page (Recharts) | ✓ | |
31
+ | Frontend | SEO: sitemap, robots.txt, Open Graph image | ✓ | |
32
+ | Backend | Profile & settings (name, password, sign out other devices) | ✓ | |
33
+ | Backend | Forgot password + email verification (Resend) | ✓ | |
34
+ | Backend | Rate limiting on auth endpoints | ✓ | |
35
+ | Backend | Audit log of admin actions | ✓ | |
36
+ | Backend | Seed script with demo users | ✓ | |
37
+ | Testing | Vitest unit tests | ✓ | ✓ |
38
+ | Testing | Playwright end-to-end tests | ✓ | ✓ |
39
+ | DevOps | Docker | ✓ (app + MongoDB) | ✓ (nginx) |
40
+ | DevOps | GitHub Actions CI + Dependabot | ✓ | ✓ |
41
+ | DevOps | VS Code settings + EditorConfig | ✓ | ✓ |
42
+
43
+ Finally it asks **Install dependencies?** and **Initialize git?**, shows a summary, and creates the
44
+ project after you confirm.
45
+
46
+ Code for features you decline is left out entirely (files, imports, packages, scripts and README
47
+ sections), and the result is formatted with Prettier.
48
+
49
+ ## Options
50
+
51
+ ```bash
52
+ npm create mohit-next@latest [project-name] -- [options]
53
+ ```
54
+
55
+ | Option | Description |
56
+ | ------ | ----------- |
57
+ | `--ts`, `--js` | Language (default: TypeScript) |
58
+ | `--next`, `--vite` | Framework (default: Next.js) |
59
+ | `--shadcn`, `--tailwind`, `--css` | Styling (default: Tailwind + shadcn/ui) |
60
+ | `--<feature>`, `--no-<feature>` | Turn one feature on/off: `router`, `ui`, `env`, `eslint`, `oxlint`, `prettier`, `git-hooks`, `sidebar`, `data-table`, `charts`, `seo`, `profile`, `email`, `rate-limit`, `audit-log`, `seed`, `vitest`, `playwright`, `docker`, `ci`, `editor` |
61
+ | `-y`, `--yes` | No prompts: defaults with every feature on |
62
+ | `--minimal` | No prompts: every optional feature off |
63
+ | `--no-install` | Don't install dependencies |
64
+ | `--no-git` | Don't initialize a git repository |
65
+ | `-h`, `--help` | Show help |
66
+
67
+ With `npm create`, put `--` before the options so npm forwards them:
68
+
69
+ ```bash
70
+ npm create mohit-next@latest my-app -- --yes --vite --css --no-docker
71
+ pnpm create mohit-next my-app --js --minimal
72
+ ```
73
+
74
+ The package manager you run it with (npm, pnpm, yarn or bun) is detected and used for installing,
75
+ in the README and in the CI workflow. Without a TTY (CI) prompts are skipped and defaults are used.
76
+
77
+ ## Developing the CLI
78
+
79
+ ```text
80
+ create-mohit-next/
81
+ ├── index.js # prompts + flow (@clack/prompts, picocolors)
82
+ ├── lib/
83
+ │ ├── features.js # every question, and which files/packages/scripts depend on it
84
+ │ └── scaffold.js # copy, apply markers, TS->JS, package.json, format
85
+ └── templates/
86
+ ├── next/ # Next.js app (TypeScript source)
87
+ ├── vite/ # Vite app (TypeScript source)
88
+ ├── common/ # files shared by both (CI, hooks, editor config)
89
+ ├── ui/{shadcn,tailwind,css}/ # the UI kit for each styling option (same API)
90
+ └── styles/{shadcn,tailwind,css}.css # global CSS for each styling option
91
+ ```
92
+
93
+ How a project is generated:
94
+
95
+ 1. Copy `templates/<framework>` + `templates/common`, the UI kit and global CSS for the chosen style.
96
+ 2. Restore dotfiles: npm strips them on publish, so templates store `_gitignore`, `_github/`, etc.
97
+ 3. Delete files whose condition fails (`FILE_RULES` in `lib/features.js`).
98
+ 4. Apply code markers. Lines between `// @feature key` and `// @end key` are kept only when `key`
99
+ is on (`!key` = off, `a|b` = either). The same works with `#`, `{/* */}`, `/* */` and `<!-- -->`.
100
+ Markers must be on their own line.
101
+ 5. Prune `package.json` dependencies and scripts (`PACKAGE_RULES`, `SCRIPT_RULES`).
102
+ 6. For JavaScript, strip the types with `sucrase` (`.tsx` -> `.jsx`, `.ts` -> `.js`), keeping JSX.
103
+ 7. Format everything with Prettier, then create `.env.local`.
104
+
105
+ Built-in keys for markers: `ts`, `next`, `vite`, `shadcn`, `tailwind` (shadcn or Tailwind only),
106
+ `css`, `ui`, plus every question key.
107
+
108
+ ### Test locally with `npm link`
109
+
110
+ ```bash
111
+ cd create-mohit-next
112
+ npm install
113
+ npm link # puts `create-mohit-next` on your PATH
114
+
115
+ cd /some/empty/folder
116
+ create-mohit-next my-app # interactive
117
+ create-mohit-next my-app2 --yes --vite --js # no prompts
118
+ ```
119
+
120
+ `npm unlink -g create-mohit-next` removes the link. Check a generated app before publishing:
121
+
122
+ ```bash
123
+ cd my-app
124
+ npm run typecheck && npm run lint && npm test && npm run build
125
+ ```
126
+
127
+ ### Publish to npm
128
+
129
+ Requires Node.js 22.12+ and two-factor authentication on your npm account.
130
+
131
+ ```bash
132
+ npm login
133
+ npm pack --dry-run # check the tarball: index.js, lib/, templates/
134
+ npm version minor # or patch / major
135
+ npm publish
136
+ ```
137
+
138
+ ## License
139
+
140
+ MIT
package/index.js ADDED
@@ -0,0 +1,399 @@
1
+ #!/usr/bin/env node
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+
6
+ import * as p from "@clack/prompts";
7
+ import pc from "picocolors";
8
+
9
+ import { FRAMEWORKS, LANGUAGES, QUESTIONS, QUESTION_KEYS, STYLES } from "./lib/features.js";
10
+ import { scaffold } from "./lib/scaffold.js";
11
+
12
+ const DEFAULT_NAME = "my-app";
13
+
14
+ const HELP = `
15
+ ${pc.bold("create-mohit-next")} - scaffold a production-ready React app (Next.js or Vite)
16
+
17
+ ${pc.bold("Usage")}
18
+ npm create mohit-next@latest ${pc.cyan("[project-name]")} ${pc.dim("-- [options]")}
19
+
20
+ ${pc.bold("Choices")}
21
+ --ts | --js Language (default: TypeScript)
22
+ --next | --vite Framework (default: Next.js full-stack)
23
+ --shadcn | --tailwind | --css Styling (default: Tailwind + shadcn/ui)
24
+
25
+ ${pc.bold("Features")} ${pc.dim("(each can be turned on/off: --<name> / --no-<name>)")}
26
+ ${QUESTION_KEYS.join(", ")}
27
+
28
+ ${pc.bold("Other")}
29
+ -y, --yes Skip prompts: use the defaults above with every feature on
30
+ --minimal Skip prompts: every optional feature off
31
+ --no-install Don't install dependencies
32
+ --no-git Don't initialize a git repository
33
+ -h, --help Show this help
34
+
35
+ ${pc.bold("Examples")}
36
+ npm create mohit-next@latest my-app
37
+ npm create mohit-next@latest my-app -- --yes --vite --css --no-docker
38
+ `;
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Arguments
42
+ // ---------------------------------------------------------------------------
43
+
44
+ function parseArgs(argv) {
45
+ const opts = { name: undefined, yes: false, minimal: false, help: false, features: {} };
46
+ const set = (k, v) => (opts[k] = v);
47
+ const aliases = {
48
+ "--ts": () => set("lang", "ts"),
49
+ "--typescript": () => set("lang", "ts"),
50
+ "--js": () => set("lang", "js"),
51
+ "--javascript": () => set("lang", "js"),
52
+ "--next": () => set("framework", "next"),
53
+ "--vite": () => set("framework", "vite"),
54
+ "--shadcn": () => set("style", "shadcn"),
55
+ "--tailwind": () => set("style", "tailwind"),
56
+ "--css": () => set("style", "css"),
57
+ "--install": () => set("install", true),
58
+ "--no-install": () => set("install", false),
59
+ "--git": () => set("git", true),
60
+ "--no-git": () => set("git", false),
61
+ "-y": () => set("yes", true),
62
+ "--yes": () => set("yes", true),
63
+ "--minimal": () => set("minimal", true),
64
+ "-h": () => set("help", true),
65
+ "--help": () => set("help", true),
66
+ };
67
+ for (const arg of argv) {
68
+ if (aliases[arg]) {
69
+ aliases[arg]();
70
+ continue;
71
+ }
72
+ const feature = /^--(no-)?([a-z-]+)$/.exec(arg);
73
+ if (feature && QUESTION_KEYS.includes(feature[2])) {
74
+ opts.features[feature[2]] = !feature[1];
75
+ continue;
76
+ }
77
+ if (arg.startsWith("-")) {
78
+ console.error(pc.red(`Unknown option: ${arg}`));
79
+ console.log(HELP);
80
+ process.exit(1);
81
+ }
82
+ if (opts.name) {
83
+ console.error(pc.red(`Unexpected argument: ${arg}`));
84
+ process.exit(1);
85
+ }
86
+ opts.name = arg;
87
+ }
88
+ return opts;
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Helpers
93
+ // ---------------------------------------------------------------------------
94
+
95
+ // Same rules npm uses for new package names (validate-npm-package-name).
96
+ function validateProjectName(input) {
97
+ const value = (input ?? "").trim();
98
+ if (!value) return "Project name is required.";
99
+ // "." scaffolds into the current directory, whose name becomes the package name.
100
+ const name = value === "." ? path.basename(process.cwd()) : path.basename(value);
101
+ if (name.length > 214) return "Name must be 214 characters or fewer.";
102
+ if (name !== name.toLowerCase()) {
103
+ return value === "."
104
+ ? `The current directory name "${name}" is not a valid npm package name (must be lowercase).`
105
+ : "Name must be lowercase.";
106
+ }
107
+ if (/^[._]/.test(name)) return "Name cannot start with a dot or underscore.";
108
+ if (!/^[a-z0-9][a-z0-9._~-]*$/.test(name)) {
109
+ return "Use only lowercase letters, digits, '-', '.', '_' or '~' (npm package name rules).";
110
+ }
111
+ if (["node_modules", "favicon.ico"].includes(name)) return `"${name}" is a reserved name.`;
112
+ return undefined;
113
+ }
114
+
115
+ function isDirEmpty(dir) {
116
+ if (!fs.existsSync(dir)) return true;
117
+ if (!fs.statSync(dir).isDirectory()) return false;
118
+ const ignorable = new Set([".git", ".DS_Store", "Thumbs.db", ".idea", ".vscode"]);
119
+ return fs.readdirSync(dir).every((entry) => ignorable.has(entry));
120
+ }
121
+
122
+ function validateTarget(input) {
123
+ const nameError = validateProjectName(input);
124
+ if (nameError) return nameError;
125
+ const dir = path.resolve(process.cwd(), input.trim());
126
+ if (!isDirEmpty(dir)) return `Directory "${input.trim()}" already exists and is not empty.`;
127
+ return undefined;
128
+ }
129
+
130
+ function detectPackageManager() {
131
+ const ua = process.env.npm_config_user_agent ?? "";
132
+ const name = ua.split(" ")[0]?.split("/")[0];
133
+ if (name === "pnpm" || name === "yarn" || name === "bun") return name;
134
+ return "npm";
135
+ }
136
+
137
+ function runScriptCmd(pm, script) {
138
+ return pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`;
139
+ }
140
+
141
+ function toTitle(name) {
142
+ return name
143
+ .replace(/^@[^/]+\//, "")
144
+ .split(/[-_.~]+/)
145
+ .filter(Boolean)
146
+ .map((w) => w[0].toUpperCase() + w.slice(1))
147
+ .join(" ");
148
+ }
149
+
150
+ function run(cmd, args, cwd, { shell = false } = {}) {
151
+ return new Promise((resolve) => {
152
+ let output = "";
153
+ const child = spawn(cmd, args, { cwd, shell, env: process.env, stdio: ["ignore", "pipe", "pipe"] });
154
+ child.stdout?.on("data", (d) => (output += d));
155
+ child.stderr?.on("data", (d) => (output += d));
156
+ child.on("error", (err) => resolve({ ok: false, output: String(err) }));
157
+ child.on("close", (code) => resolve({ ok: code === 0, output }));
158
+ });
159
+ }
160
+
161
+ // Animated spinner in a terminal; plain log lines in CI / piped output.
162
+ function spinner() {
163
+ if (process.stdout.isTTY) return p.spinner();
164
+ return {
165
+ start: (msg) => p.log.step(msg),
166
+ stop: (msg) => p.log.success(msg),
167
+ error: (msg) => p.log.error(msg),
168
+ };
169
+ }
170
+
171
+ function bail(message) {
172
+ p.cancel(message);
173
+ process.exit(1);
174
+ }
175
+
176
+ function guard(value) {
177
+ if (p.isCancel(value)) bail("Operation cancelled.");
178
+ return value;
179
+ }
180
+
181
+ function questionMessage(q, framework) {
182
+ return typeof q.message === "function" ? q.message(framework) : q.message;
183
+ }
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // Post-scaffold steps
187
+ // ---------------------------------------------------------------------------
188
+
189
+ function hasGit() {
190
+ const git = spawnSync("git", ["--version"], { stdio: "ignore" });
191
+ return !git.error && git.status === 0;
192
+ }
193
+
194
+ function insideGitRepo(dir) {
195
+ const res = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: dir, stdio: "pipe" });
196
+ return res.status === 0 && String(res.stdout).trim() === "true";
197
+ }
198
+
199
+ async function gitInit(targetDir) {
200
+ let init = await run("git", ["init", "-b", "main"], targetDir);
201
+ if (!init.ok) init = await run("git", ["init"], targetDir); // git < 2.28
202
+ return init.ok;
203
+ }
204
+
205
+ async function gitCommit(targetDir) {
206
+ const s = spinner();
207
+ s.start("Creating the initial commit");
208
+ await run("git", ["add", "-A"], targetDir);
209
+ const commit = await run(
210
+ "git",
211
+ ["commit", "-m", "chore: initial commit from create-mohit-next"],
212
+ targetDir,
213
+ );
214
+ if (commit.ok) s.stop("Git repository initialized with an initial commit");
215
+ else s.stop("Git repository initialized (commit skipped - configure git user.name/user.email)");
216
+ }
217
+
218
+ async function installDependencies(targetDir, pm) {
219
+ const s = spinner();
220
+ s.start(`Installing dependencies with ${pm} (this can take a minute)`);
221
+ const { ok, output } = await run(pm, ["install"], targetDir, { shell: process.platform === "win32" });
222
+ if (ok) {
223
+ s.stop("Dependencies installed");
224
+ return true;
225
+ }
226
+ s.error(`Dependency installation failed. Run ${pc.cyan(`${pm} install`)} manually.`);
227
+ p.log.message(pc.dim(output.trim().split("\n").slice(-15).join("\n")));
228
+ return false;
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Main
233
+ // ---------------------------------------------------------------------------
234
+
235
+ async function main() {
236
+ const args = parseArgs(process.argv.slice(2));
237
+ if (args.help) {
238
+ console.log(HELP);
239
+ return;
240
+ }
241
+
242
+ const pm = detectPackageManager();
243
+ // Without a TTY (CI, piped input) prompts can't be answered, so use defaults.
244
+ const interactive =
245
+ !args.yes && !args.minimal && Boolean(process.stdin.isTTY && process.stdout.isTTY);
246
+
247
+ console.log();
248
+ p.intro(pc.bgCyan(pc.black(" create-mohit-next ")));
249
+
250
+ // 1. Project name ----------------------------------------------------------
251
+ let projectName = args.name;
252
+ if (projectName) {
253
+ const error = validateTarget(projectName);
254
+ if (error) bail(error);
255
+ } else if (interactive) {
256
+ projectName = guard(
257
+ await p.text({
258
+ message: "What is your project named?",
259
+ placeholder: DEFAULT_NAME,
260
+ defaultValue: DEFAULT_NAME,
261
+ validate: (value) => validateTarget(value || DEFAULT_NAME),
262
+ }),
263
+ );
264
+ } else {
265
+ projectName = DEFAULT_NAME;
266
+ const error = validateTarget(projectName);
267
+ if (error) bail(error);
268
+ }
269
+ projectName = projectName.trim();
270
+
271
+ const targetDir = path.resolve(process.cwd(), projectName);
272
+ const packageName = path.basename(targetDir).toLowerCase();
273
+ const projectTitle = toTitle(packageName) || "My App";
274
+
275
+ // 2-4. Language, framework, styling ---------------------------------------
276
+ const choose = async (value, message, options, fallback) => {
277
+ if (value) return value;
278
+ if (!interactive) return fallback;
279
+ return guard(await p.select({ message, options, initialValue: fallback }));
280
+ };
281
+ const lang = await choose(args.lang, "Which language?", LANGUAGES, "ts");
282
+ const framework = await choose(args.framework, "Which framework?", FRAMEWORKS, "next");
283
+ const style = await choose(args.style, "How do you want to style it?", STYLES, "shadcn");
284
+
285
+ const keys = new Set([framework, style]);
286
+ if (lang === "ts") keys.add("ts");
287
+ if (style !== "css") keys.add("tailwind");
288
+ if (framework === "next") keys.add("ui"); // the Next.js pages are built from the UI kit
289
+
290
+ // 5. Yes / no questions -----------------------------------------------------
291
+ const on = (key) => keys.has(key);
292
+ let lastGroup;
293
+ for (const q of QUESTIONS) {
294
+ if (!q.frameworks.includes(framework)) continue;
295
+ if (q.when && !q.when(on)) continue;
296
+ let answer = args.features[q.key];
297
+ if (answer === undefined) {
298
+ if (interactive) {
299
+ if (q.group !== lastGroup) {
300
+ p.log.step(pc.bold(q.group));
301
+ lastGroup = q.group;
302
+ }
303
+ answer = guard(
304
+ await p.confirm({ message: questionMessage(q, framework), initialValue: true }),
305
+ );
306
+ } else {
307
+ answer = !args.minimal;
308
+ }
309
+ }
310
+ if (answer) keys.add(q.key);
311
+ }
312
+
313
+ // 6. Install / git ------------------------------------------------------------
314
+ const ask = async (flag, message) => {
315
+ if (flag !== undefined) return flag;
316
+ if (!interactive) return true;
317
+ return guard(await p.confirm({ message, initialValue: true }));
318
+ };
319
+ if (interactive) p.log.step(pc.bold("Setup"));
320
+ const install = await ask(args.install, `Install dependencies with ${pm}?`);
321
+ const git = await ask(args.git, "Initialize a git repository?");
322
+
323
+ // Summary + confirmation ------------------------------------------------------
324
+ const label = (list, value) => list.find((o) => o.value === value)?.label ?? value;
325
+ const features = QUESTIONS.filter((q) => keys.has(q.key)).map((q) => q.key);
326
+ const summary = [
327
+ `${pc.dim("Name")} ${packageName}`,
328
+ `${pc.dim("Language")} ${label(LANGUAGES, lang)}`,
329
+ `${pc.dim("Framework")} ${label(FRAMEWORKS, framework)}`,
330
+ `${pc.dim("Styling")} ${label(STYLES, style)}`,
331
+ `${pc.dim("Features")} ${features.length ? features.join(", ") : "none"}`,
332
+ ].join("\n");
333
+ p.note(summary, "Your project");
334
+ if (interactive) {
335
+ const go = guard(await p.confirm({ message: "Create the project?", initialValue: true }));
336
+ if (!go) bail("Nothing was created.");
337
+ }
338
+
339
+ // Scaffold ----------------------------------------------------------------------
340
+ const s = spinner();
341
+ s.start(`Scaffolding project in ${pc.cyan(targetDir)}`);
342
+ let warnings = [];
343
+ try {
344
+ warnings = await scaffold(targetDir, { framework, lang, style, keys, packageName, projectTitle, pm });
345
+ } catch (err) {
346
+ s.error("Scaffolding failed");
347
+ bail(err instanceof Error ? err.message : String(err));
348
+ }
349
+ s.stop(
350
+ framework === "next"
351
+ ? "Project files created (.env.local generated with a random JWT_SECRET)"
352
+ : "Project files created (.env.local generated)",
353
+ );
354
+ for (const w of warnings) p.log.warn(w);
355
+
356
+ // git init before install, so Husky can install its hooks during `install`.
357
+ let gitReady = false;
358
+ if (git) {
359
+ if (!hasGit()) p.log.warn("git not found - skipping repository initialization.");
360
+ else if (insideGitRepo(targetDir)) p.log.info("Already inside a git repository - skipping git init.");
361
+ else gitReady = await gitInit(targetDir);
362
+ }
363
+ const installed = install ? await installDependencies(targetDir, pm) : false;
364
+ // The project's own Prettier also sorts Tailwind classes (its plugin isn't bundled here).
365
+ if (installed && keys.has("prettier")) {
366
+ const exec = { npm: ["npx"], pnpm: ["pnpm", "exec"], yarn: ["yarn"], bun: ["bunx"] }[pm];
367
+ await run(exec[0], [...exec.slice(1), "prettier", "--write", "."], targetDir, {
368
+ shell: process.platform === "win32",
369
+ });
370
+ }
371
+ if (gitReady) await gitCommit(targetDir);
372
+
373
+ // Next steps -----------------------------------------------------------------------
374
+ const rel = path.relative(process.cwd(), targetDir) || ".";
375
+ const steps = [rel !== "." && `cd ${rel}`, !installed && `${pm} install`];
376
+ if (framework === "next") {
377
+ steps.push(
378
+ keys.has("docker")
379
+ ? `${runScriptCmd(pm, "docker:db")} ${pc.dim("# MongoDB in Docker (or set MONGODB_URI)")}`
380
+ : pc.dim("# set MONGODB_URI in .env.local"),
381
+ );
382
+ if (keys.has("seed")) steps.push(`${runScriptCmd(pm, "seed")} ${pc.dim("# optional demo users")}`);
383
+ }
384
+ steps.push(runScriptCmd(pm, "dev"));
385
+ if (keys.has("playwright")) {
386
+ steps.push(pc.dim(`# before e2e tests: ${pm === "npm" ? "npx" : pm} playwright install chromium`));
387
+ }
388
+ p.note(steps.filter(Boolean).join("\n"), "Next steps");
389
+ p.outro(
390
+ framework === "next"
391
+ ? `Open ${pc.cyan("http://localhost:3000")} and register - ${pc.bold("the first account becomes admin")}.`
392
+ : `Open ${pc.cyan("http://localhost:5173")}. Happy hacking!`,
393
+ );
394
+ }
395
+
396
+ main().catch((err) => {
397
+ p.cancel(err instanceof Error ? err.message : String(err));
398
+ process.exit(1);
399
+ });