@opensaas/stack-cli 0.1.1 → 0.1.2

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.
@@ -1,367 +1,34 @@
1
- import * as path from 'path'
2
- import * as fs from 'fs'
1
+ import { spawn } from 'child_process'
3
2
  import chalk from 'chalk'
4
- import ora from 'ora'
5
- import prompts from 'prompts'
6
-
7
- export async function initCommand(projectName: string | undefined) {
8
- console.log(chalk.bold.cyan('\nšŸš€ Create OpenSaas Project\n'))
9
-
10
- // Prompt for project name if not provided
11
- if (!projectName) {
12
- const response = await prompts({
13
- type: 'text',
14
- name: 'name',
15
- message: 'Project name:',
16
- initial: 'my-opensaas-app',
17
- validate: (value) => {
18
- if (!value) return 'Project name is required'
19
- if (!/^[a-z0-9-]+$/.test(value)) {
20
- return 'Project name must contain only lowercase letters, numbers, and hyphens'
21
- }
22
- return true
23
- },
24
- })
25
-
26
- if (!response.name) {
27
- console.log(chalk.yellow('\nāŒ Cancelled'))
28
- process.exit(0)
29
- }
30
-
31
- projectName = response.name
32
- }
33
-
34
- // Type guard to ensure projectName is defined
35
- if (!projectName) {
36
- console.error(chalk.red('\nāŒ Project name is required'))
37
- process.exit(1)
38
- }
39
-
40
- const projectPath = path.join(process.cwd(), projectName)
41
-
42
- // Check if directory already exists
43
- if (fs.existsSync(projectPath)) {
44
- console.error(chalk.red(`\nāŒ Directory "${projectName}" already exists`))
45
- process.exit(1)
46
- }
47
-
48
- const spinner = ora('Creating project structure...').start()
49
-
50
- try {
51
- // Create project directory
52
- fs.mkdirSync(projectPath, { recursive: true })
53
-
54
- // Create basic structure
55
- fs.mkdirSync(path.join(projectPath, 'app'), { recursive: true })
56
- fs.mkdirSync(path.join(projectPath, 'lib'), { recursive: true })
57
- fs.mkdirSync(path.join(projectPath, 'prisma'), { recursive: true })
58
-
59
- spinner.text = 'Writing configuration files...'
60
-
61
- // Create package.json
62
- const packageJson = {
63
- name: projectName,
64
- version: '0.1.0',
65
- private: true,
66
- scripts: {
67
- dev: 'next dev',
68
- build: 'next build',
69
- start: 'next start',
70
- generate: 'opensaas generate',
71
- 'db:push': 'prisma db push',
72
- 'db:studio': 'prisma studio',
73
- },
74
- dependencies: {
75
- '@opensaas/stack-core': '^0.1.0',
76
- '@prisma/client': '^5.7.1',
77
- next: '^14.0.4',
78
- react: '^18.2.0',
79
- 'react-dom': '^18.2.0',
80
- },
81
- devDependencies: {
82
- '@opensaas/stack-cli': '^0.1.0',
83
- '@types/node': '^20.10.0',
84
- '@types/react': '^19.2.2',
85
- '@types/react-dom': '^19.2.2',
86
- prisma: '^5.7.1',
87
- tsx: '^4.7.0',
88
- typescript: '^5.3.3',
89
- },
90
- }
91
-
92
- fs.writeFileSync(path.join(projectPath, 'package.json'), JSON.stringify(packageJson, null, 2))
93
-
94
- // Create tsconfig.json
95
- const tsConfig = {
96
- compilerOptions: {
97
- target: 'ES2022',
98
- lib: ['dom', 'dom.iterable', 'esnext'],
99
- allowJs: true,
100
- skipLibCheck: true,
101
- strict: true,
102
- noEmit: true,
103
- esModuleInterop: true,
104
- module: 'esnext',
105
- moduleResolution: 'bundler',
106
- resolveJsonModule: true,
107
- isolatedModules: true,
108
- jsx: 'preserve',
109
- incremental: true,
110
- plugins: [{ name: 'next' }],
111
- paths: {
112
- '@/*': ['./*'],
113
- },
114
- },
115
- include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],
116
- exclude: ['node_modules'],
117
- }
118
-
119
- fs.writeFileSync(path.join(projectPath, 'tsconfig.json'), JSON.stringify(tsConfig, null, 2))
120
-
121
- // Create next.config.js
122
- const nextConfig = `/** @type {import('next').NextConfig} */
123
- const nextConfig = {
124
- experimental: {
125
- serverComponentsExternalPackages: ['@prisma/client', '@opensaas/stack-core'],
126
- },
127
- }
128
-
129
- module.exports = nextConfig
130
- `
131
- fs.writeFileSync(path.join(projectPath, 'next.config.js'), nextConfig)
132
-
133
- // Create .env
134
- const env = `DATABASE_URL="file:./dev.db"
135
- `
136
- fs.writeFileSync(path.join(projectPath, '.env'), env)
137
-
138
- // Create .gitignore
139
- const gitignore = `# Dependencies
140
- node_modules
141
- .pnp
142
- .pnp.js
143
-
144
- # Testing
145
- coverage
146
-
147
- # Next.js
148
- .next
149
- out
150
-
151
- # Production
152
- build
153
- dist
154
-
155
- # Misc
156
- .DS_Store
157
- *.pem
158
-
159
- # Debug
160
- npm-debug.log*
161
- yarn-debug.log*
162
- yarn-error.log*
163
-
164
- # Local env files
165
- .env
166
- .env.local
167
- .env.development.local
168
- .env.test.local
169
- .env.production.local
170
-
171
- # Vercel
172
- .vercel
173
-
174
- # TypeScript
175
- *.tsbuildinfo
176
-
177
- # OpenSaas generated
178
- .opensaas
179
-
180
- # Prisma
181
- prisma/dev.db
182
- prisma/dev.db-journal
183
- `
184
- fs.writeFileSync(path.join(projectPath, '.gitignore'), gitignore)
185
-
186
- // Create opensaas.config.ts
187
- const config = `import { config, list } from '@opensaas/stack-core'
188
- import { text, relationship, password } from '@opensaas/stack-core/fields'
189
- import type { AccessControl } from '@opensaas/stack-core'
190
-
191
- // Access control helpers
192
- const isSignedIn: AccessControl = ({ session }) => {
193
- return !!session
194
- }
195
-
196
- export default config({
197
- db: {
198
- provider: 'sqlite',
199
- url: process.env.DATABASE_URL || 'file:./dev.db',
200
- },
201
-
202
- lists: {
203
- User: list({
204
- fields: {
205
- name: text({ validation: { isRequired: true } }),
206
- email: text({
207
- validation: { isRequired: true },
208
- isIndexed: 'unique',
209
- }),
210
- password: password({ validation: { isRequired: true } }),
211
- },
212
- }),
213
- },
214
-
215
- session: {
216
- getSession: async () => {
217
- // TODO: Integrate with your auth system
218
- return null
219
- }
220
- },
221
-
222
- ui: {
223
- basePath: '/admin',
224
- }
225
- })
226
- `
227
- fs.writeFileSync(path.join(projectPath, 'opensaas.config.ts'), config)
228
-
229
- // Create lib/context.ts
230
- const contextFile = `import { PrismaClient } from '@prisma/client'
231
- import { getContext as createContext } from '@opensaas/stack-core'
232
- import config from '../opensaas.config'
233
- import type { Context } from '../.opensaas/types'
234
-
235
- // Singleton Prisma client
236
- const globalForPrisma = globalThis as unknown as {
237
- prisma: PrismaClient | undefined
238
- }
239
-
240
- export const prisma = globalForPrisma.prisma ?? new PrismaClient()
241
-
242
- if (process.env.NODE_ENV !== 'production') {
243
- globalForPrisma.prisma = prisma
244
- }
245
3
 
246
4
  /**
247
- * Get an access-controlled context for the current session
5
+ * Initialize a new OpenSaas Stack project.
6
+ *
7
+ * This command delegates to create-opensaas-app for the actual scaffolding.
8
+ * It's kept here for backwards compatibility with `opensaas init`.
9
+ *
10
+ * @param args - Command line arguments (project name and flags)
248
11
  */
249
- export async function getContext(): Promise<Context> {
250
- const session = config.session ? await config.session.getSession() : null
251
- const context = await createContext<PrismaClient>(config, prisma, session)
252
- return context as Context
253
- }
254
- `
255
- fs.writeFileSync(path.join(projectPath, 'lib', 'context.ts'), contextFile)
256
-
257
- // Create app/page.tsx
258
- const page = `export default function Home() {
259
- return (
260
- <main className="flex min-h-screen flex-col items-center justify-center p-24">
261
- <h1 className="text-4xl font-bold mb-4">Welcome to OpenSaas</h1>
262
- <p className="text-gray-600">Your project is ready to go!</p>
263
-
264
- <div className="mt-8 space-y-2">
265
- <p className="text-sm">Next steps:</p>
266
- <ol className="text-sm text-gray-600 list-decimal list-inside space-y-1">
267
- <li>Run <code className="bg-gray-100 px-2 py-1 rounded">npm run generate</code></li>
268
- <li>Run <code className="bg-gray-100 px-2 py-1 rounded">npm run db:push</code></li>
269
- <li>Edit <code className="bg-gray-100 px-2 py-1 rounded">opensaas.config.ts</code> to define your schema</li>
270
- </ol>
271
- </div>
272
- </main>
273
- )
274
- }
275
- `
276
- fs.writeFileSync(path.join(projectPath, 'app', 'page.tsx'), page)
277
-
278
- // Create app/layout.tsx
279
- const layout = `export const metadata = {
280
- title: '${projectName}',
281
- description: 'Built with OpenSaas',
282
- }
283
-
284
- export default function RootLayout({
285
- children,
286
- }: {
287
- children: React.ReactNode
288
- }) {
289
- return (
290
- <html lang="en">
291
- <body>{children}</body>
292
- </html>
293
- )
294
- }
295
- `
296
- fs.writeFileSync(path.join(projectPath, 'app', 'layout.tsx'), layout)
297
-
298
- // Create README.md
299
- const readme = `# ${projectName}
300
-
301
- Built with [OpenSaas Stack](https://github.com/your-org/opensaas-stack)
302
-
303
- ## Getting Started
304
-
305
- 1. Install dependencies:
306
- \`\`\`bash
307
- npm install
308
- # or
309
- pnpm install
310
- \`\`\`
311
-
312
- 2. Generate Prisma schema and types:
313
- \`\`\`bash
314
- npm run generate
315
- \`\`\`
316
-
317
- 3. Push schema to database:
318
- \`\`\`bash
319
- npm run db:push
320
- \`\`\`
321
-
322
- 4. Run the development server:
323
- \`\`\`bash
324
- npm run dev
325
- \`\`\`
326
-
327
- Open [http://localhost:3000](http://localhost:3000) to see your app.
328
-
329
- ## Project Structure
330
-
331
- - \`opensaas.config.ts\` - Your schema definition with access control
332
- - \`lib/context.ts\` - Database context with access control
333
- - \`app/\` - Next.js app router pages
334
- - \`prisma/\` - Generated Prisma schema
335
- - \`.opensaas/\` - Generated TypeScript types
336
-
337
- ## Learn More
338
-
339
- - [OpenSaas Documentation](https://github.com/your-org/opensaas-stack)
340
- - [Next.js Documentation](https://nextjs.org/docs)
341
- - [Prisma Documentation](https://www.prisma.io/docs)
342
- `
343
- fs.writeFileSync(path.join(projectPath, 'README.md'), readme)
344
-
345
- spinner.succeed(chalk.green('Project created successfully!'))
346
-
347
- console.log(chalk.bold.green(`\n✨ Created ${projectName}\n`))
348
- console.log(chalk.gray('Next steps:\n'))
349
- console.log(chalk.cyan(` cd ${projectName}`))
350
- console.log(chalk.cyan(' npm install'))
351
- console.log(chalk.cyan(' npm run generate'))
352
- console.log(chalk.cyan(' npm run db:push'))
353
- console.log(chalk.cyan(' npm run dev'))
354
- console.log()
355
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
356
- } catch (error: any) {
357
- spinner.fail(chalk.red('Failed to create project'))
358
- console.error(chalk.red('\nāŒ Error:'), error.message)
359
-
360
- // Cleanup on failure
361
- if (fs.existsSync(projectPath)) {
362
- fs.rmSync(projectPath, { recursive: true, force: true })
363
- }
12
+ export async function initCommand(args: string[]) {
13
+ console.log(chalk.dim('Delegating to create-opensaas-app...\n'))
14
+
15
+ // Forward all arguments to create-opensaas-app
16
+ const child = spawn('npx', ['create-opensaas-app@latest', ...args], {
17
+ stdio: 'inherit',
18
+ shell: true,
19
+ })
20
+
21
+ return new Promise<void>((resolve, reject) => {
22
+ child.on('close', (code) => {
23
+ if (code !== 0) {
24
+ reject(new Error(`create-opensaas-app exited with code ${code}`))
25
+ } else {
26
+ resolve()
27
+ }
28
+ })
364
29
 
365
- process.exit(1)
366
- }
30
+ child.on('error', (err) => {
31
+ reject(err)
32
+ })
33
+ })
367
34
  }
package/src/index.ts CHANGED
@@ -18,10 +18,14 @@ program
18
18
 
19
19
  program
20
20
  .command('init [project-name]')
21
- .description('Create a new OpenSaas project')
22
- .option('-t, --template <template>', 'Project template to use')
23
- .action(async (projectName) => {
24
- await initCommand(projectName)
21
+ .description('Create a new OpenSaas project (delegates to create-opensaas-app)')
22
+ .option('--with-auth', 'Include authentication (Better-auth)')
23
+ .allowUnknownOption() // Allow passing through other options
24
+ .action(async (projectName, options) => {
25
+ const args = []
26
+ if (projectName) args.push(projectName)
27
+ if (options.withAuth) args.push('--with-auth')
28
+ await initCommand(args)
25
29
  })
26
30
 
27
31
  program