create-cslug 0.0.0 → 0.4.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 (80) hide show
  1. package/README.md +11 -1
  2. package/docs/README.md +32 -0
  3. package/package.json +30 -4
  4. package/src/bin.ts +58 -0
  5. package/src/index.ts +10 -0
  6. package/src/scaffold.ts +133 -0
  7. package/templates/api/AGENTS.md +8 -0
  8. package/templates/api/README.md +12 -0
  9. package/templates/api/_env.example +5 -0
  10. package/templates/api/_env.test +7 -0
  11. package/templates/api/_gitignore +6 -0
  12. package/templates/api/app/providers/app-service-provider.ts +8 -0
  13. package/templates/api/bootstrap/app.ts +8 -0
  14. package/templates/api/bootstrap/providers.ts +12 -0
  15. package/templates/api/config/app.ts +10 -0
  16. package/templates/api/config/cache.ts +10 -0
  17. package/templates/api/config/database.ts +8 -0
  18. package/templates/api/config/env.ts +9 -0
  19. package/templates/api/config/http.ts +9 -0
  20. package/templates/api/config/i18n.ts +7 -0
  21. package/templates/api/config/index.ts +14 -0
  22. package/templates/api/config/redis.ts +6 -0
  23. package/templates/api/cslug.config.ts +8 -0
  24. package/templates/api/database/migrations/.gitkeep +0 -0
  25. package/templates/api/database/seeders/database-seeder.ts +4 -0
  26. package/templates/api/docker-compose.yml +9 -0
  27. package/templates/api/resources/lang/en.json +7 -0
  28. package/templates/api/routes/api.ts +9 -0
  29. package/templates/api/storage/.gitkeep +0 -0
  30. package/templates/api/tests/feature/api.test.ts.tpl +12 -0
  31. package/templates/api/tsconfig.json +18 -0
  32. package/templates/full/_env.example +8 -0
  33. package/templates/full/_env.test +8 -0
  34. package/templates/full/app/controllers/auth/register-controller.ts +30 -0
  35. package/templates/full/app/jobs/.gitkeep +0 -0
  36. package/templates/full/app/mail/welcome-mail.ts +20 -0
  37. package/templates/full/bootstrap/providers.ts +23 -0
  38. package/templates/full/config/env.ts +14 -0
  39. package/templates/full/config/index.ts +22 -0
  40. package/templates/full/config/mail.ts +12 -0
  41. package/templates/full/config/queue.ts +11 -0
  42. package/templates/full/config/storage.ts +9 -0
  43. package/templates/full/cslug.config.ts +15 -0
  44. package/templates/full/docker-compose.yml +12 -0
  45. package/templates/full/resources/lang/en.json +32 -0
  46. package/templates/full/resources/mail/layout.vue +20 -0
  47. package/templates/full/resources/mail/welcome.vue +14 -0
  48. package/templates/full/routes/schedule.ts +6 -0
  49. package/templates/full/tests/feature/welcome-mail.test.ts.tpl +21 -0
  50. package/templates/tailwind/resources/styles/tailwind.css +1 -0
  51. package/templates/web/app/controllers/auth/register-controller.ts +26 -0
  52. package/templates/web/app/controllers/auth/session-controller.ts +24 -0
  53. package/templates/web/app/controllers/home-controller.ts +16 -0
  54. package/templates/web/app/repositories/user-repository.ts +6 -0
  55. package/templates/web/app/tables/user-table.ts +12 -0
  56. package/templates/web/app/validators/login-validator.ts +6 -0
  57. package/templates/web/app/validators/register-validator.ts +26 -0
  58. package/templates/web/bootstrap/providers.ts +16 -0
  59. package/templates/web/bunfig.toml +3 -0
  60. package/templates/web/config/auth.ts +7 -0
  61. package/templates/web/config/index.ts +19 -0
  62. package/templates/web/config/session.ts +8 -0
  63. package/templates/web/cslug.config.ts +13 -0
  64. package/templates/web/database/factories/user-factory.ts +9 -0
  65. package/templates/web/database/migrations/00000000_000001_create_users.sql +13 -0
  66. package/templates/web/database/seeders/database-seeder.ts +7 -0
  67. package/templates/web/public/.gitkeep +0 -0
  68. package/templates/web/resources/client.ts +4 -0
  69. package/templates/web/resources/lang/en.json +25 -0
  70. package/templates/web/resources/styles/app.scss +80 -0
  71. package/templates/web/resources/views/auth/login.vue +26 -0
  72. package/templates/web/resources/views/auth/register.vue +34 -0
  73. package/templates/web/resources/views/dashboard.vue +13 -0
  74. package/templates/web/resources/views/errors/404.vue +13 -0
  75. package/templates/web/resources/views/home.vue +13 -0
  76. package/templates/web/resources/views/layouts/default.vue +39 -0
  77. package/templates/web/routes/web.ts +22 -0
  78. package/templates/web/tests/feature/auth.test.ts.tpl +57 -0
  79. package/templates/web/tsconfig.json +19 -0
  80. package/index.js +0 -3
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
1
  # create-cslug
2
2
 
3
- `bun create cslug my-app` will scaffold a new cslug app. Not released yet; this name is reserved for the project.
3
+ Create a [cslug](https://github.com/cslugts/cslug) app:
4
+
5
+ ```bash
6
+ bun create cslug my-app # pages, Vue islands and auth (--web, the default)
7
+ bun create cslug my-api --api # a JSON API: no views, no Vue
8
+ bun create cslug my-app --full # web + queue, scheduler, mail and storage
9
+ bun create cslug my-app --tailwind # add Tailwind CSS (with --web or --full)
10
+ ```
11
+
12
+ `--no-install` skips `bun install`, `--no-git` skips `git init`. Docs: [docs/README.md](docs/README.md),
13
+ [guide 01](../../guides/01-getting-started.md).
package/docs/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # create-cslug
2
+
3
+ `bun create cslug <dir>` runs this package's `create-cslug` binary. It writes a new app into `<dir>` (which must be
4
+ missing or empty), runs `bun install` and `git init`, and prints the next steps.
5
+
6
+ ## Presets
7
+
8
+ | Preset | Packages | Adds |
9
+ |---|---|---|
10
+ | `--api` | core, validation, http, database, redis, cli · dev: testing | `routes/api.ts` with `/api/v1/hello`, config, a feature test |
11
+ | `--web` (default) | api + vue, auth · `vue`, `sass`, `vue-tsc` | Home page, register / log in / log out, a dashboard behind `auth()`, the `users` table and factory, layout and styles, auth tests |
12
+ | `--full` | web + queue, mail, storage | Worker and scheduler in `cslug.config.ts`, `routes/schedule.ts`, mail config and a queued `WelcomeMail` on a Vue template, storage config, Mailpit in docker-compose |
13
+ | `--tailwind` | `tailwindcss`, `bun-plugin-tailwind` | `resources/styles/tailwind.css`, imported by `resources/client.ts`; `assets.tailwind: true` |
14
+
15
+ Every `@cslug/*` package is pinned to the scaffolder's own version: all packages of a release share one version.
16
+
17
+ ## What is written
18
+
19
+ - `.env` from `.env.example` with a fresh `APP_KEY`; `.env.test` (used by `bun test`) with its own key.
20
+ - The app name comes from the folder: `my-app` → package `my-app`, title "My App" in `config/app.ts` and the
21
+ translations, database `my_app` (and `my_app_test`).
22
+ - `bunfig.toml` (web, full) preloads `@cslug/vue/register`, so tests can import `.vue` files and mailables directly.
23
+
24
+ ## Templates
25
+
26
+ `templates/<layer>/` holds literal files: `api`, then `web`, then `full` (a later layer replaces a file of the same
27
+ path), then `tailwind`. `{{name}}`, `{{title}}`, `{{db}}`, `{{tailwind}}`, `{{styles}}` and `{{testKey}}` are
28
+ filled in; a leading `_` in a file name becomes a dot (npm does not publish `.gitignore`), and a `.tpl` suffix is
29
+ dropped (so template tests do not run in the cslug repository).
30
+
31
+ In the repository, `bun run check:create` scaffolds each preset, links it to the local packages, then typechecks
32
+ it, builds its assets and runs its tests.
package/package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "name": "create-cslug",
3
- "version": "0.0.0",
4
- "description": "Scaffolder for cslug apps: `bun create cslug my-app` (in development).",
3
+ "version": "0.4.0",
4
+ "description": "Create a cslug app: bun create cslug <dir>.",
5
5
  "license": "MIT",
6
- "bin": { "create-cslug": "./index.js" },
7
- "files": ["index.js", "README.md"]
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/create-cslug"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/create-cslug",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework",
17
+ "create"
18
+ ],
19
+ "bin": {
20
+ "create-cslug": "src/bin.ts"
21
+ },
22
+ "exports": {
23
+ ".": "./src/index.ts"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "templates",
28
+ "docs",
29
+ "README.md"
30
+ ],
31
+ "engines": {
32
+ "bun": ">=1.3.14"
33
+ }
8
34
  }
package/src/bin.ts ADDED
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `bun create cslug <dir> [--api | --web | --full] [--tailwind] [--no-install] [--no-git]`
4
+ */
5
+ import { parseArgs } from 'node:util'
6
+ import { type Preset, scaffold } from './scaffold'
7
+
8
+ const USAGE = `Usage: bun create cslug <dir> [options]
9
+
10
+ --web pages, Vue islands and auth (default)
11
+ --api a JSON API: no views, no Vue
12
+ --full web + queue, scheduler, mail and storage
13
+ --tailwind add Tailwind CSS (with --web or --full)
14
+ --no-install do not run bun install
15
+ --no-git do not run git init`
16
+
17
+ const { values, positionals } = parseArgs({
18
+ args: Bun.argv.slice(2),
19
+ allowPositionals: true,
20
+ allowNegative: true,
21
+ options: {
22
+ api: { type: 'boolean' },
23
+ web: { type: 'boolean' },
24
+ full: { type: 'boolean' },
25
+ tailwind: { type: 'boolean' },
26
+ install: { type: 'boolean', default: true },
27
+ git: { type: 'boolean', default: true },
28
+ help: { type: 'boolean', short: 'h' },
29
+ },
30
+ })
31
+
32
+ const presets = (['api', 'web', 'full'] as const).filter((p) => values[p])
33
+ const dir = positionals[0]
34
+ if (values.help || !dir || presets.length > 1) {
35
+ console.log(USAGE)
36
+ process.exit(values.help ? 0 : 1)
37
+ }
38
+ const preset: Preset = presets[0] ?? 'web'
39
+
40
+ try {
41
+ const files = await scaffold({ dir, preset, tailwind: values.tailwind })
42
+ console.log(`✔ ${dir}: ${files.length} files (${preset}${values.tailwind ? ' + tailwind' : ''})`)
43
+ } catch (error) {
44
+ console.error(`✗ ${(error as Error).message}`)
45
+ process.exit(1)
46
+ }
47
+
48
+ const run = async (cmd: string[]) =>
49
+ (await Bun.spawn(cmd, { cwd: dir, stdout: 'inherit', stderr: 'inherit' }).exited) === 0
50
+ if (values.install && !(await run(['bun', 'install']))) console.error('✗ bun install failed: run it in the app')
51
+ if (values.git) await run(['git', 'init', '--quiet'])
52
+
53
+ console.log(`
54
+ Next:
55
+ cd ${dir}
56
+ docker compose up -d
57
+ ${values.install ? '' : 'bun install\n '}bunx cslug migrate
58
+ bunx cslug dev`)
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** create-cslug: the `bun create cslug` scaffolder (presets api, web, full; optional Tailwind). */
2
+ export {
3
+ type AppPackageJson,
4
+ names,
5
+ type Preset,
6
+ packageJson,
7
+ type ScaffoldOptions,
8
+ scaffold,
9
+ VERSION,
10
+ } from './scaffold'
@@ -0,0 +1,133 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { mkdir } from 'node:fs/promises'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { Glob } from 'bun'
5
+
6
+ export type Preset = 'api' | 'web' | 'full'
7
+ export type ScaffoldOptions = { dir: string; preset?: Preset; tailwind?: boolean; version?: string }
8
+
9
+ const TEMPLATES = join(import.meta.dir, '../templates')
10
+ /** Each preset is a layer on top of the previous ones (then `tailwind`); a later layer replaces a file of the same path. */
11
+ const LAYERS: Record<Preset, Preset[]> = { api: ['api'], web: ['api', 'web'], full: ['api', 'web', 'full'] }
12
+ const PACKAGES: Record<Preset, string[]> = {
13
+ api: ['core', 'validation', 'http', 'database', 'redis', 'cli'],
14
+ web: ['vue', 'auth'],
15
+ full: ['queue', 'mail', 'storage'],
16
+ }
17
+
18
+ /** This package's version: every @cslug/* package of a release has the same one. */
19
+ export const VERSION: string = (await Bun.file(join(import.meta.dir, '../package.json')).json()).version
20
+
21
+ const words = (name: string) => name.split(/[^a-zA-Z0-9]+/).filter(Boolean)
22
+ const randomKey = () => `base64:${Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64')}`
23
+
24
+ /** `my-app` → `{ name: 'my-app', title: 'My App', db: 'my_app' }`. Names start with a letter. */
25
+ export function names(dir: string) {
26
+ const parts = words(basename(resolve(dir)))
27
+ if (!parts.length || !/^[a-z]/i.test(parts[0] as string))
28
+ throw new Error(`"${basename(dir)}" is not a usable app name (letters, digits and dashes; start with a letter)`)
29
+ return {
30
+ name: parts.join('-').toLowerCase(),
31
+ title: parts.map((w) => w[0]?.toUpperCase() + w.slice(1)).join(' '),
32
+ db: parts.join('_').toLowerCase(),
33
+ }
34
+ }
35
+
36
+ /** The app's package.json: exact @cslug/* versions for the preset, the `#app/*` import aliases, scripts. */
37
+ export type AppPackageJson = {
38
+ name: string
39
+ private: true
40
+ type: 'module'
41
+ scripts: Record<string, string>
42
+ imports: Record<string, string>
43
+ dependencies: Record<string, string>
44
+ devDependencies: Record<string, string>
45
+ }
46
+
47
+ export function packageJson(name: string, preset: Preset, tailwind: boolean, version: string): AppPackageJson {
48
+ const web = preset !== 'api'
49
+ const cslug = LAYERS[preset].flatMap((layer) => PACKAGES[layer])
50
+ return {
51
+ name,
52
+ private: true,
53
+ type: 'module',
54
+ scripts: {
55
+ dev: 'cslug dev',
56
+ start: 'cslug start',
57
+ ...(web ? { build: 'cslug build' } : {}),
58
+ typecheck: web ? 'cslug typecheck' : 'tsc --noEmit',
59
+ test: 'bun test',
60
+ lint: 'biome check .',
61
+ },
62
+ imports: {
63
+ '#app/*': './app/*.ts',
64
+ '#config/*': './config/*.ts',
65
+ '#routes/*': './routes/*.ts',
66
+ '#database/*': './database/*.ts',
67
+ ...(web
68
+ ? {
69
+ '#views/*': './resources/views/*',
70
+ '#components/*': './resources/components/*',
71
+ '#resources/*': './resources/*',
72
+ }
73
+ : {}),
74
+ },
75
+ dependencies: {
76
+ ...Object.fromEntries(cslug.map((p) => [`@cslug/${p}`, version])),
77
+ ...(web ? { vue: '^3.5.0' } : {}),
78
+ },
79
+ devDependencies: {
80
+ '@biomejs/biome': '^2.0.0',
81
+ '@cslug/testing': version,
82
+ '@types/bun': '^1.3.14',
83
+ typescript: '^5.9.0',
84
+ ...(web ? { sass: '^1.80.0', 'vue-tsc': '^3.0.0' } : {}),
85
+ ...(tailwind ? { tailwindcss: '^4.0.0', 'bun-plugin-tailwind': '>=0.1.0' } : {}),
86
+ },
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Write a new app into `dir` (missing or empty). Template files are copied layer by layer with `{{placeholders}}`
92
+ * filled; a leading `_` in a file name becomes a dot (npm does not publish `.gitignore`) and a `.tpl` suffix is dropped
93
+ * (template tests must not run in this repository). `.env` gets a fresh APP_KEY.
94
+ * Returns the paths written, relative to `dir`.
95
+ */
96
+ export async function scaffold(options: ScaffoldOptions): Promise<string[]> {
97
+ const preset = options.preset ?? 'web'
98
+ const tailwind = options.tailwind ?? false
99
+ if (tailwind && preset === 'api') throw new Error('--tailwind needs pages: use it with --web or --full')
100
+ const dir = resolve(options.dir)
101
+ if (existsSync(dir) && readdirSync(dir).length) throw new Error(`${dir} exists and is not empty`)
102
+ const { name, title, db } = names(dir)
103
+ const vars: Record<string, string> = {
104
+ name,
105
+ title,
106
+ db,
107
+ tailwind: String(tailwind),
108
+ testKey: randomKey(),
109
+ styles: `import './styles/app.scss'${tailwind ? "\nimport './styles/tailwind.css'" : ''}`,
110
+ }
111
+ const files = new Map<string, string>()
112
+ for (const layer of [...LAYERS[preset], ...(tailwind ? ['tailwind'] : [])])
113
+ for await (const path of new Glob('**/*').scan({ cwd: join(TEMPLATES, layer), dot: true })) {
114
+ const text = await Bun.file(join(TEMPLATES, layer, path)).text()
115
+ const target = path.replace(/(^|\/)_(?=[^/]*$)/, '$1.').replace(/\.tpl$/, '')
116
+ files.set(
117
+ target,
118
+ text.replace(/\{\{(\w+)\}\}/g, (match, key: string) => vars[key] ?? match),
119
+ )
120
+ }
121
+ files.set(
122
+ 'package.json',
123
+ `${JSON.stringify(packageJson(name, preset, tailwind, options.version ?? VERSION), null, 2)}\n`,
124
+ )
125
+ const example = files.get('.env.example') ?? ''
126
+ files.set('.env', example.replace(/^APP_KEY=.*$/m, `APP_KEY=${randomKey()}`))
127
+
128
+ for (const [path, text] of files) {
129
+ await mkdir(dirname(join(dir, path)), { recursive: true })
130
+ await Bun.write(join(dir, path), text)
131
+ }
132
+ return [...files.keys()].sort()
133
+ }
@@ -0,0 +1,8 @@
1
+ # AGENTS.md
2
+
3
+ A cslug app (Bun + TypeScript + PostgreSQL + Redis). The framework's guides are at
4
+ https://github.com/cslugts/cslug/tree/main/guides.
5
+
6
+ - `bun test` must pass; `bun run typecheck` too.
7
+ - Files are kebab-case and named after their export; classes are wired with `@inject(A, B)`.
8
+ - Time comes from `Clock`, money is integer minor units, ids are UUIDv7.
@@ -0,0 +1,12 @@
1
+ # {{title}}
2
+
3
+ A [cslug](https://github.com/cslugts/cslug) app.
4
+
5
+ ```bash
6
+ docker compose up -d # postgres, redis
7
+ cslug migrate
8
+ cslug dev
9
+ bun test
10
+ ```
11
+
12
+ Guides: https://github.com/cslugts/cslug/tree/main/guides
@@ -0,0 +1,5 @@
1
+ APP_ENV=development
2
+ APP_URL=http://localhost:3000
3
+ APP_KEY= # `cslug key:generate --write`
4
+ DATABASE_URL=postgres://cslug:cslug@localhost:5432/{{db}}
5
+ REDIS_URL=redis://localhost:6379
@@ -0,0 +1,7 @@
1
+ # Used by `bun test` (Bun loads .env.test). Variables already set in the environment win.
2
+ # Test-only values: never use this key anywhere else.
3
+ APP_ENV=test
4
+ APP_URL=http://localhost:3000
5
+ APP_KEY={{testKey}}
6
+ DATABASE_URL=postgres://cslug:cslug@localhost:5432/{{db}}_test
7
+ REDIS_URL=redis://localhost:6379/15
@@ -0,0 +1,6 @@
1
+ node_modules/
2
+ .env
3
+ .cslug/
4
+ public/build/
5
+ storage/*
6
+ !storage/.gitkeep
@@ -0,0 +1,8 @@
1
+ import { ServiceProvider } from '@cslug/core'
2
+
3
+ /** One-off wiring for the app. Split into more providers when it grows past a screen. */
4
+ export class AppServiceProvider extends ServiceProvider {
5
+ register() {
6
+ // bindings go here, e.g. this.app.singleton(PaymentGateway, StripeGateway)
7
+ }
8
+ }
@@ -0,0 +1,8 @@
1
+ import { Application } from '@cslug/core'
2
+ import { configs } from '#config/index'
3
+ import { providers } from './providers'
4
+
5
+ /** The only place an Application is built. Used by the CLI, the server, workers and tests. */
6
+ export function createApp() {
7
+ return new Application({ root: `${import.meta.dir}/..`, configs }).useProviders(providers)
8
+ }
@@ -0,0 +1,12 @@
1
+ import { DatabaseProvider } from '@cslug/database'
2
+ import { HttpProvider } from '@cslug/http'
3
+ import { RedisProvider } from '@cslug/redis'
4
+ import { AppServiceProvider } from '#app/providers/app-service-provider'
5
+
6
+ /** One provider per installed @cslug/* package. Core (config, events, logger, i18n) needs none. */
7
+ export const providers = [
8
+ DatabaseProvider,
9
+ RedisProvider, // binds Redis drivers for Cache, Lock, RateLimiter, SessionStore
10
+ HttpProvider,
11
+ AppServiceProvider,
12
+ ]
@@ -0,0 +1,10 @@
1
+ import { defineConfig } from '@cslug/core'
2
+ import { env } from './env'
3
+
4
+ export default defineConfig({
5
+ name: '{{title}}',
6
+ env: env.APP_ENV,
7
+ url: env.APP_URL,
8
+ key: env.APP_KEY,
9
+ timezone: 'UTC',
10
+ })
@@ -0,0 +1,10 @@
1
+ import { defineConfig } from '@cslug/core'
2
+
3
+ export default defineConfig({
4
+ default: 'redis',
5
+ prefix: '{{name}}:',
6
+ stores: {
7
+ redis: { driver: 'redis', connection: 'default' },
8
+ memory: { driver: 'memory', max: 1000 },
9
+ },
10
+ })
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from '@cslug/core'
2
+ import { env } from './env'
3
+
4
+ export default defineConfig({
5
+ url: env.DATABASE_URL,
6
+ pool: { max: 10, idleTimeout: '30s', connectTimeout: '5s' },
7
+ slowQueryMs: 200,
8
+ })
@@ -0,0 +1,9 @@
1
+ import { defineEnv, v } from '@cslug/core'
2
+
3
+ export const env = defineEnv({
4
+ APP_ENV: v.enum(['development', 'test', 'staging', 'production']).default('development'),
5
+ APP_URL: v.url(),
6
+ APP_KEY: v.secret().min(32),
7
+ DATABASE_URL: v.url(),
8
+ REDIS_URL: v.url().default('redis://localhost:6379'),
9
+ })
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from '@cslug/core'
2
+
3
+ export default defineConfig({
4
+ port: 3000,
5
+ shutdownTimeout: '10s',
6
+ bodyLimit: '1mb',
7
+ trustedProxies: ['loopback'],
8
+ cors: { origins: [] },
9
+ })
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from '@cslug/core'
2
+
3
+ export default defineConfig({
4
+ locales: ['en'],
5
+ default: 'en',
6
+ detect: ['cookie', 'header'],
7
+ })
@@ -0,0 +1,14 @@
1
+ import type { Typed } from '@cslug/core'
2
+ import app from './app'
3
+ import cache from './cache'
4
+ import database from './database'
5
+ import http from './http'
6
+ import i18n from './i18n'
7
+ import redis from './redis'
8
+
9
+ export const configs = { app, http, database, redis, cache, i18n }
10
+
11
+ declare module '@cslug/core' {
12
+ /** Types `config('...')`. */
13
+ interface Config extends Typed<typeof configs> {}
14
+ }
@@ -0,0 +1,6 @@
1
+ import { defineConfig } from '@cslug/core'
2
+ import { env } from './env'
3
+
4
+ export default defineConfig({
5
+ connections: { default: { url: env.REDIS_URL } },
6
+ })
@@ -0,0 +1,8 @@
1
+ import { defineCslugConfig } from '@cslug/cli'
2
+
3
+ /** Framework-level settings: the processes `cslug start` runs. App settings live in config/. */
4
+ export default defineCslugConfig({
5
+ processes: {
6
+ web: { instances: 1 },
7
+ },
8
+ })
File without changes
@@ -0,0 +1,4 @@
1
+ import { seeder } from '@cslug/database'
2
+
3
+ /** `cslug db:seed`: development data. */
4
+ export default seeder(async () => {})
@@ -0,0 +1,9 @@
1
+ # Development services: `docker compose up -d`
2
+ services:
3
+ postgres:
4
+ image: postgres:17
5
+ environment: { POSTGRES_USER: cslug, POSTGRES_PASSWORD: cslug, POSTGRES_DB: {{db}} }
6
+ ports: ["5432:5432"]
7
+ redis:
8
+ image: redis:7
9
+ ports: ["6379:6379"]
@@ -0,0 +1,7 @@
1
+ {
2
+ "app": { "name": "{{title}}" },
3
+ "validation": {
4
+ "required": "This field is required.",
5
+ "unique": "This value is already taken."
6
+ }
7
+ }
@@ -0,0 +1,9 @@
1
+ import { defineRoutes } from '@cslug/http'
2
+ import { throttle } from '@cslug/http/middleware'
3
+
4
+ export default defineRoutes((r) => {
5
+ // /health/live and /health/ready come from HttpProvider
6
+ r.group({ prefix: '/api/v1', middleware: [throttle('60/min')], as: 'api' }, (r) => {
7
+ r.get('/hello', () => ({ message: 'Hello from {{title}}' })).name('hello')
8
+ })
9
+ })
File without changes
@@ -0,0 +1,12 @@
1
+ import { test } from 'bun:test'
2
+ import { testApp } from '@cslug/testing'
3
+
4
+ const app = testApp()
5
+
6
+ test('the API answers', async () => {
7
+ await app.get('/api/v1/hello').assertOk().assertJson({ message: 'Hello from {{title}}' })
8
+ })
9
+
10
+ test('the health endpoint is up', async () => {
11
+ await app.get('/health/live').assertOk()
12
+ })
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ESNext", "DOM"],
7
+ "types": ["bun"],
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "noImplicitOverride": true,
11
+ "verbatimModuleSyntax": true,
12
+ "allowImportingTsExtensions": true,
13
+ "noEmit": true,
14
+ "skipLibCheck": true
15
+ },
16
+ "include": ["**/*.ts", ".cslug/**/*.d.ts"],
17
+ "exclude": ["node_modules", "storage"]
18
+ }
@@ -0,0 +1,8 @@
1
+ APP_ENV=development
2
+ APP_URL=http://localhost:3000
3
+ APP_KEY= # `cslug key:generate --write`
4
+ DATABASE_URL=postgres://cslug:cslug@localhost:5432/{{db}}
5
+ REDIS_URL=redis://localhost:6379
6
+ MAIL_TRANSPORT=smtp
7
+ SMTP_HOST=localhost
8
+ SMTP_PORT=1025 # Mailpit: http://localhost:8025
@@ -0,0 +1,8 @@
1
+ # Used by `bun test` (Bun loads .env.test). Variables already set in the environment win.
2
+ # Test-only values: never use this key anywhere else.
3
+ APP_ENV=test
4
+ APP_URL=http://localhost:3000
5
+ APP_KEY={{testKey}}
6
+ DATABASE_URL=postgres://cslug:cslug@localhost:5432/{{db}}_test
7
+ REDIS_URL=redis://localhost:6379/15
8
+ MAIL_TRANSPORT=log
@@ -0,0 +1,30 @@
1
+ import { Hash } from '@cslug/auth'
2
+ import { inject, t } from '@cslug/core'
3
+ import { type HttpContext, redirect, route } from '@cslug/http'
4
+ import { Mailer } from '@cslug/mail'
5
+ import { view } from '@cslug/vue'
6
+ import { WelcomeMail } from '#app/mail/welcome-mail'
7
+ import { UserRepository } from '#app/repositories/user-repository'
8
+ import { RegisterValidator } from '#app/validators/register-validator'
9
+ import Register from '#views/auth/register.vue'
10
+
11
+ @inject(UserRepository, Hash, Mailer)
12
+ export class RegisterController {
13
+ constructor(
14
+ private users: UserRepository,
15
+ private hash: Hash,
16
+ private mailer: Mailer,
17
+ ) {}
18
+
19
+ async create() {
20
+ return view(Register, {})
21
+ }
22
+
23
+ async store({ request, auth }: HttpContext) {
24
+ const { name, email, password } = await request.validate(RegisterValidator)
25
+ const user = await this.users.create({ name, email, passwordHash: await this.hash.make(password) })
26
+ await this.mailer.to(user).send(new WelcomeMail(name))
27
+ await auth.login(user)
28
+ return redirect().to(route('dashboard')).with('success', t('auth.welcome', { name }))
29
+ }
30
+ }
File without changes
@@ -0,0 +1,20 @@
1
+ import { t } from '@cslug/core'
2
+ import { Mailable } from '@cslug/mail'
3
+ import Welcome from '#resources/mail/welcome.vue'
4
+
5
+ /** Sent after registration (queued: rendered now, sent by the worker). */
6
+ export class WelcomeMail extends Mailable {
7
+ static queued = true
8
+
9
+ constructor(private readonly name: string) {
10
+ super()
11
+ }
12
+
13
+ build() {
14
+ return this.subject(t('mail.welcome.subject')).view(Welcome, { name: this.name })
15
+ }
16
+
17
+ static preview() {
18
+ return new WelcomeMail('Ada')
19
+ }
20
+ }
@@ -0,0 +1,23 @@
1
+ import { AuthProvider } from '@cslug/auth'
2
+ import { DatabaseProvider } from '@cslug/database'
3
+ import { HttpProvider } from '@cslug/http'
4
+ import { MailProvider } from '@cslug/mail'
5
+ import { QueueProvider, ScheduleProvider } from '@cslug/queue'
6
+ import { RedisProvider } from '@cslug/redis'
7
+ import { StorageProvider } from '@cslug/storage'
8
+ import { VueProvider } from '@cslug/vue'
9
+ import { AppServiceProvider } from '#app/providers/app-service-provider'
10
+
11
+ /** One provider per installed @cslug/* package. Core (config, events, logger, i18n) needs none. */
12
+ export const providers = [
13
+ DatabaseProvider,
14
+ RedisProvider, // binds Redis drivers for Cache, Lock, RateLimiter, SessionStore
15
+ QueueProvider,
16
+ ScheduleProvider,
17
+ MailProvider,
18
+ StorageProvider,
19
+ AuthProvider,
20
+ HttpProvider,
21
+ VueProvider,
22
+ AppServiceProvider,
23
+ ]