create-guren-app 1.0.0-rc.30 → 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/cli.js +1 -1
- package/package.json +1 -1
- package/templates/api-only/package.json +5 -5
- package/templates/default/.claude/rules/controllers-http.md +95 -0
- package/templates/default/.claude/rules/orm-models.md +118 -0
- package/templates/default/.claude/rules/routes-codegen.md +96 -0
- package/templates/default/.claude/rules/testing.md +93 -0
- package/templates/default/.claude/skills/feature/SKILL.md +2 -0
- package/templates/default/.claude/skills/guren-api/SKILL.md +6 -4
- package/templates/default/.claude/skills/scaffold/SKILL.md +2 -0
- package/templates/default/CLAUDE.md +52 -71
- package/templates/default/package.json +8 -8
package/dist/cli.js
CHANGED
|
@@ -1703,7 +1703,7 @@ var blueprintRegistry = {
|
|
|
1703
1703
|
const packageJson = JSON.parse(rawPackage);
|
|
1704
1704
|
packageJson.scripts ??= {};
|
|
1705
1705
|
packageJson.dependencies ??= {};
|
|
1706
|
-
const gurenVersion = packageJson.dependencies["@guren/core"] ?? packageJson.dependencies["@guren/server"] ?? packageJson.dependencies["@guren/orm"] ?? "^0.
|
|
1706
|
+
const gurenVersion = packageJson.dependencies["@guren/core"] ?? packageJson.dependencies["@guren/server"] ?? packageJson.dependencies["@guren/orm"] ?? "^1.0.0";
|
|
1707
1707
|
packageJson.scripts.typecheck ??= "tsc --noEmit";
|
|
1708
1708
|
packageJson.scripts.smoke ??= "bun run ./smoke.ts";
|
|
1709
1709
|
packageJson.dependencies["@guren/core"] ??= gurenVersion;
|
package/package.json
CHANGED
|
@@ -17,14 +17,14 @@
|
|
|
17
17
|
"test": "bun test"
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@guren/cli": "^1.0.0
|
|
21
|
-
"@guren/core": "^1.0.0
|
|
22
|
-
"@guren/orm": "^1.0.0
|
|
23
|
-
"drizzle-orm": "1.0.0-rc.
|
|
20
|
+
"@guren/cli": "^1.0.0",
|
|
21
|
+
"@guren/core": "^1.0.0",
|
|
22
|
+
"@guren/orm": "^1.0.0",
|
|
23
|
+
"drizzle-orm": "1.0.0-rc.4"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"bun-types": "^1.3.1",
|
|
27
|
-
"drizzle-kit": "1.0.0-rc.
|
|
27
|
+
"drizzle-kit": "1.0.0-rc.4",
|
|
28
28
|
"mysql2": "^3.11.3",
|
|
29
29
|
"postgres": "^3.4.3",
|
|
30
30
|
"typescript": "^5.4.0"
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Guren controllers — validation signatures, 422 shape, Inertia pages, auth helpers, resources
|
|
3
|
+
globs:
|
|
4
|
+
- "app/Http/**"
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Controllers & HTTP (@guren/core)
|
|
8
|
+
|
|
9
|
+
Controllers extend `Controller` and expose one async method per route action.
|
|
10
|
+
|
|
11
|
+
## Validation — exact signatures
|
|
12
|
+
|
|
13
|
+
Any Zod-like schema (anything with `safeParse`) is accepted:
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
protected async validateBody<T>(schema: ZodLikeSchema<T>): Promise<T> // request body
|
|
17
|
+
protected validateQuery<T>(schema: ZodLikeSchema<T>): T // query string
|
|
18
|
+
protected validateParams<T>(schema: ZodLikeSchema<T>): T // route params
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
All throw `ValidationException` on failure, rendered as **HTTP 422** with body:
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{ "message": "The given data was invalid.", "errors": { "field": ["msg1", "msg2"] } }
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Non-throwing variants return a discriminated union — note errors flatten to
|
|
28
|
+
**one string per field** here (`Record<string, string>`, not `string[]`):
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
protected async validateBodySafe<T>(schema): Promise<SafeValidationResult<T>>
|
|
32
|
+
protected validateQuerySafe<T>(schema): SafeValidationResult<T>
|
|
33
|
+
protected validateParamsSafe<T>(schema): SafeValidationResult<T>
|
|
34
|
+
// SafeValidationResult<T> = { success: true; data: T } | { success: false; errors: Record<string, string> }
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Business-logic errors: `throw ValidationException.withMessages({ email: 'Already registered' })`
|
|
38
|
+
(values may be `string` or `string[]`).
|
|
39
|
+
|
|
40
|
+
## Inertia responses
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
import { pages } from '@/.guren/pages.gen'
|
|
44
|
+
return this.inertia(pages.posts.Show, { post }) // props compile-checked via PagePropsMap
|
|
45
|
+
return this.inertia('posts/Show', { post }) // string overload, untyped props
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Page prop types come from each page component's `interface Props`, extracted by
|
|
49
|
+
`bunx guren codegen` into `PagePropsMap`. If props don't type-check, re-run codegen.
|
|
50
|
+
Optional third arg: `InertiaResponseOptions` (e.g. `{ status: 422 }`).
|
|
51
|
+
|
|
52
|
+
## Route model binding
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// routes: router.get('/posts/:id', { bind: { id: Post }, name: 'posts.show' }, [PostController, 'show'])
|
|
56
|
+
async show() {
|
|
57
|
+
const post = this.model(Post) // typed record, already resolved via findOrFail (404 on miss)
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Auth helpers
|
|
62
|
+
|
|
63
|
+
`this.auth` (requires `AuthServiceProvider`) exposes:
|
|
64
|
+
`check(): Promise<boolean>` · `guest(): Promise<boolean>` · `user<T>(): Promise<T | null>` ·
|
|
65
|
+
`userOrFail<T>(): Promise<T>` (throws → 401) · `id(): Promise<unknown>` ·
|
|
66
|
+
`login(user, remember?)` · `attempt(credentials, remember?): Promise<boolean>` · `logout()`
|
|
67
|
+
|
|
68
|
+
Authorization (policies/gates):
|
|
69
|
+
`await this.authorize('update', [Post, post])` (throws 403) ·
|
|
70
|
+
`await this.can('update', [Post, post]): Promise<boolean>` ·
|
|
71
|
+
API tokens: `this.apiToken()` → `{ userId, abilities }` or throws 401.
|
|
72
|
+
|
|
73
|
+
## Response helpers
|
|
74
|
+
|
|
75
|
+
- `this.json(data, init?)` / `this.text(body, init?)`
|
|
76
|
+
- `this.redirect(url, { status?, headers? })` — defaults 302 for GET, **303 for non-GET** (correct for Inertia form posts)
|
|
77
|
+
- `await this.files('avatar')` → `File[]` (uploaded files, empties filtered)
|
|
78
|
+
|
|
79
|
+
## API Resources (app/Http/Resources)
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { Resource } from '@guren/core'
|
|
83
|
+
|
|
84
|
+
export class PostResource extends Resource<PostRecord> {
|
|
85
|
+
toArray() { // abstract — must implement; typed toArray is exported as Data.Post by codegen
|
|
86
|
+
return { id: this.resource.id, title: this.resource.title }
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
new PostResource(post).toJSON() // toArray() + additional() data
|
|
90
|
+
PostResource.collection(posts) // ResourceData[]
|
|
91
|
+
new PostResource(post).additional({ meta: 1 })
|
|
92
|
+
this.when(cond, value) // conditional field inside toArray()
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`JsonResource<T>` is a no-transform passthrough (`toArray()` returns `{ ...resource }`).
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Guren ORM (@guren/orm) — model definition, queries, relations, pagination, mass assignment
|
|
3
|
+
globs:
|
|
4
|
+
- "app/Models/**"
|
|
5
|
+
- "db/**"
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# ORM Models (@guren/orm)
|
|
9
|
+
|
|
10
|
+
## Defining a model
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
import { defineModel, type BelongsToRecord } from '@guren/orm'
|
|
14
|
+
import { posts } from '../../db/schema.js'
|
|
15
|
+
|
|
16
|
+
export type PostRecord = typeof posts.$inferSelect
|
|
17
|
+
|
|
18
|
+
export class Post extends defineModel(posts) {
|
|
19
|
+
static fillable = ['title', 'body', 'authorId']
|
|
20
|
+
static override relationTypes: { author: BelongsToRecord<UserRecord> } = { author: null }
|
|
21
|
+
}
|
|
22
|
+
Post.belongsTo('author', () => import('./User.js').then((m) => m.User), 'authorId', 'id')
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`class Post extends Model<typeof posts> { static table = posts }` also works.
|
|
26
|
+
Auth user models: `defineModel(users, { base: AuthenticatableModel })`.
|
|
27
|
+
|
|
28
|
+
## Statics
|
|
29
|
+
|
|
30
|
+
`find(id)` → record | null · `findOrFail(id)` throws `ModelNotFoundException` (renders 404) ·
|
|
31
|
+
`first(where?)` → record | null · `all()` · `create(data)` · `forceCreate(data)` ·
|
|
32
|
+
`update(where, data)` · `forceUpdate(where, data)` · `delete(where)` ·
|
|
33
|
+
`paginate(options?)` · `transaction(async (trx) => ...)`
|
|
34
|
+
|
|
35
|
+
## Where clauses
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
await Post.where({ status: 'active', authorId: 1 }).get() // object form = AND
|
|
39
|
+
await Post.where({ id: [1, 2, 3] }).get() // array value = IN
|
|
40
|
+
await Post.where('views', '>', 100).orWhere('featured', true).get()
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Operators (exact set): `=` `!=` `>` `<` `>=` `<=` `like` `in` `not in` `is null` `is not null`
|
|
44
|
+
|
|
45
|
+
## QueryBuilder chain
|
|
46
|
+
|
|
47
|
+
`Post.where(...)` returns a `QueryBuilder`. Chainable:
|
|
48
|
+
`where` / `orWhere` / `whereNull(field)` / `whereNotNull(field)` /
|
|
49
|
+
`whereIn(field, values)` / `whereNotIn(field, values)` /
|
|
50
|
+
`orderBy(field, 'asc' | 'desc')` (repeatable) / `limit(n)` / `offset(n)` /
|
|
51
|
+
`with(...relations)` / `scope(name)`
|
|
52
|
+
|
|
53
|
+
Terminate with: `get()` / `first()` / `firstOrFail()` / `count()` /
|
|
54
|
+
`paginate(page?, perPage?)` or `paginate({ page, perPage })` /
|
|
55
|
+
`update(data)` / `forceUpdate(data)` / `delete()`
|
|
56
|
+
|
|
57
|
+
## Pagination
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
const result = await Post.paginate({ page: 1, perPage: 15, where: {...}, orderBy: 'createdAt' })
|
|
61
|
+
// PaginateOptions: { page? (1-based, default 1), perPage? (default 15), where?, orderBy? }
|
|
62
|
+
// PaginatedResult: { data: TRecord[], meta: { total, perPage, currentPage, totalPages, hasMore, from, to } }
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
For Inertia/HTTP pagination links wrap it with `paginate` from `@guren/core`:
|
|
66
|
+
`paginate(result, { path, query?, fragment? })` — those three fields are `PaginatorOptions`.
|
|
67
|
+
|
|
68
|
+
## Relations — declaration signatures
|
|
69
|
+
|
|
70
|
+
- `hasOne(name, related, foreignKey, localKey)`
|
|
71
|
+
- `hasMany(name, related, foreignKey, localKey)`
|
|
72
|
+
- `belongsTo(name, related, foreignKey, ownerKey)`
|
|
73
|
+
- `belongsToMany(name, related, pivotTable, foreignPivotKey, relatedPivotKey, parentKey = 'id', relatedKey = 'id')` — 7 args; `pivotTable` is the Drizzle table
|
|
74
|
+
- `hasManyThrough(name, related, through, firstKey, secondKey, localKey = 'id', secondLocalKey = 'id')`
|
|
75
|
+
- `morphMany` / `morphTo` also exist
|
|
76
|
+
|
|
77
|
+
`related` is a model class or lazy loader: `() => import('./Tag.js').then((m) => m.Tag)`.
|
|
78
|
+
|
|
79
|
+
Typed relation results — declare `static relationTypes` using these exported types:
|
|
80
|
+
`HasManyRecord<T>` = `T[]` · `HasOneRecord<T>` = `T | null` · `BelongsToRecord<T>` = `T | null` ·
|
|
81
|
+
`BelongsToManyRecord<T>` = `T[]` · `HasManyThroughRecord<T>` = `T[]`
|
|
82
|
+
|
|
83
|
+
## Eager loading
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
await Post.with('tags') // Array<record & { tags: TagRecord[] }>; nested: with('author.posts')
|
|
87
|
+
await Post.with(['author', 'tags'], { published: true }) // optional where filter
|
|
88
|
+
await Post.findWith(1, 'tags') // single record + relations, or null
|
|
89
|
+
await Post.findWithOrFail(1, ['author']) // throws ModelNotFoundException
|
|
90
|
+
await Post.withCount('tags') // adds tagsCount: number (no nested names)
|
|
91
|
+
await Post.withPaginate('tags', { page: 1 }) // PaginatedResult with relations
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## No attach/detach/sync — use a pivot model
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
export class PostTag extends defineModel(postTags) {}
|
|
98
|
+
await PostTag.create({ postId, tagId }) // attach
|
|
99
|
+
await PostTag.delete({ postId, tagId }) // detach
|
|
100
|
+
// sync: PostTag.delete({ postId }) then re-create the desired set
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## No firstOrCreate / updateOrCreate — hand-roll it
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
const existing = await Tag.first({ name })
|
|
107
|
+
const tag = existing ?? await Tag.create({ name })
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
For concurrency safety add a unique index and catch the constraint error, or wrap in
|
|
111
|
+
`Tag.transaction(async (trx) => ...)`.
|
|
112
|
+
|
|
113
|
+
## Mass assignment
|
|
114
|
+
|
|
115
|
+
- With `static fillable = [...]` set, `create()`/`update()` **throw `MassAssignmentException`**
|
|
116
|
+
on any unlisted input key (`static strictFillable = false` restores silent discarding)
|
|
117
|
+
- Without `fillable`, keys in `static guarded` (default `['id']`) are silently stripped
|
|
118
|
+
- `forceCreate()` / `forceUpdate()` bypass filtering — trusted server-side data only
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Guren routing & codegen — RouteContractOptions, schema binding, the Zod→ApiRoutes matrix, middleware
|
|
3
|
+
globs:
|
|
4
|
+
- "routes/**"
|
|
5
|
+
- "app/Http/Validators/**"
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Routes & Codegen
|
|
9
|
+
|
|
10
|
+
## Registering routes
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
import { Router, requireAuthenticated } from '@guren/core'
|
|
14
|
+
|
|
15
|
+
export function registerWebRoutes(router: Router): void {
|
|
16
|
+
router.get('/posts', [PostController, 'index']).name('posts.index')
|
|
17
|
+
router.post('/posts', { name: 'posts.store', body: CreatePostSchema }, [PostController, 'store'])
|
|
18
|
+
|
|
19
|
+
router.aliasMiddleware('auth', requireAuthenticated({ redirectTo: '/login' }))
|
|
20
|
+
router.middleware('auth').group((group) => {
|
|
21
|
+
group.get('/dashboard', [DashboardController, 'index'])
|
|
22
|
+
})
|
|
23
|
+
router.group('/admin', (admin) => { /* path-prefixed */ })
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Options object (second arg) is `RouteContractOptions`:
|
|
28
|
+
`name?` · `middlewares?: MiddlewareHandler[]` · `params?` / `query?` / `body?` / `output?`
|
|
29
|
+
(Zod schemas) · `bind?: Record<string, BindableModel>` · plus OpenAPI metadata
|
|
30
|
+
(`summary?`, `description?`, `tags?`, `operationId?`, `deprecated?`).
|
|
31
|
+
|
|
32
|
+
Schemas attached here do double duty: requests are **validated automatically**
|
|
33
|
+
(422 before the controller runs) and `bunx guren codegen` extracts them into typed manifests.
|
|
34
|
+
|
|
35
|
+
`router.resource('/posts', PostController, { name?, param?, only?, except? })` registers
|
|
36
|
+
index/create/store/show/edit/update/destroy (GET/POST/PUT/DELETE, `:id` param) named `posts.index` etc.
|
|
37
|
+
Model binding: `bind: { id: Post }` + `this.model(Post)` in the controller.
|
|
38
|
+
|
|
39
|
+
## Route Schema Binding: concrete input → output
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
const CreatePostSchema = z.object({
|
|
43
|
+
title: z.string().trim().min(1),
|
|
44
|
+
body: z.string(),
|
|
45
|
+
published: z.boolean().optional().default(false),
|
|
46
|
+
tagIds: z.array(z.coerce.number().int()).optional(),
|
|
47
|
+
})
|
|
48
|
+
router.post('/posts', { name: 'posts.store', body: CreatePostSchema }, [PostController, 'store'])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
generates this entry in `.guren/api-client.gen.ts`:
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
export interface ApiRoutes {
|
|
55
|
+
'posts.store': {
|
|
56
|
+
method: 'POST'
|
|
57
|
+
path: '/posts'
|
|
58
|
+
params: Record<string, never> // path params come from ':id' segments, typed string | number
|
|
59
|
+
body: { title: string; body: string; published?: boolean; tagIds?: number[] }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Only **named** routes are emitted. `output:` schemas add a `response:` field.
|
|
65
|
+
Consume with `createApiClient<ApiRoutes>({ baseUrl })` → `client.request('posts.store', { body })`.
|
|
66
|
+
|
|
67
|
+
## Which Zod constructs survive type extraction
|
|
68
|
+
|
|
69
|
+
Codegen walks schemas at runtime (Zod v3 and v4):
|
|
70
|
+
|
|
71
|
+
- **Typed**: primitives (`string`/`number`/`boolean`/`bigint`/`date`), `literal`, `enum`,
|
|
72
|
+
`array`, nested `object`, `union` / `discriminatedUnion`, `intersection`, `record`,
|
|
73
|
+
`nullable` (`| null`)
|
|
74
|
+
- **Unwrapped transparently**: `.optional()` and `.default()` (field becomes `key?:`),
|
|
75
|
+
`.catch()`, `.readonly()`, `.brand()`, `.lazy()`
|
|
76
|
+
- **Validation checks don't change the type**: `.min()`, `.max()`, `.trim()`, `.email()`,
|
|
77
|
+
regex etc. stay `string`; `z.coerce.number()` is `number`
|
|
78
|
+
- **Input side only**: `.transform()` / `.refine()` chains extract the schema's *input*
|
|
79
|
+
type — transform output types are NOT reflected
|
|
80
|
+
- **Degrades**: `tuple` → `unknown[]`, `z.nativeEnum()` → `string | number`,
|
|
81
|
+
unrecognized constructs → `unknown`
|
|
82
|
+
|
|
83
|
+
So `z.string().trim().min(1).optional().default('x')` survives as `key?: string`.
|
|
84
|
+
If a generated type comes out as `unknown`, simplify the construct instead of reading `node_modules`.
|
|
85
|
+
|
|
86
|
+
## When to re-run codegen
|
|
87
|
+
|
|
88
|
+
`bunx guren codegen` (or `bun run codegen`) regenerates `.guren/pages.gen.ts`,
|
|
89
|
+
`routes.gen.ts`, `data.gen.ts`, `api-client.gen.ts`. Re-run after changing:
|
|
90
|
+
|
|
91
|
+
- `routes/web.ts` (route names, paths, schemas)
|
|
92
|
+
- page components' `interface Props` in `resources/js/pages/`
|
|
93
|
+
- Resource classes in `app/Http/Resources/`
|
|
94
|
+
|
|
95
|
+
`bun run dev` runs codegen on start, and the Vite plugin watches those paths and
|
|
96
|
+
regenerates on change. In tests/CI, run it explicitly if generated types are stale.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Guren testing (@guren/testing) — TestApp client methods and the full assertion surface
|
|
3
|
+
globs:
|
|
4
|
+
- "tests/**"
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Testing (@guren/testing + bun:test)
|
|
8
|
+
|
|
9
|
+
Requests run in-process through `app.fetch()` — no server, no port.
|
|
10
|
+
|
|
11
|
+
## Creating a TestApp
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { TestApp } from '@guren/testing'
|
|
15
|
+
|
|
16
|
+
const app = await TestApp.create() // boots the real Application
|
|
17
|
+
const app = await TestApp.create({ boot, providers, routes }) // all optional
|
|
18
|
+
const app = TestApp.fromFetch(app.fetch) // wrap an existing fetch fn (not async)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Both set `GUREN_TESTING=1` so `actingAs()` header auth is accepted.
|
|
22
|
+
|
|
23
|
+
## Client methods
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
app.get(path) // → PendingTestResponse (awaitable AND chainable)
|
|
27
|
+
app.post(path, body?) // body auto-JSON-encoded unless FormData
|
|
28
|
+
app.put(path, body?) / app.patch(path, body?) / app.delete(path, body?)
|
|
29
|
+
|
|
30
|
+
app.actingAs(user) // returns a NEW TestApp with the user injected
|
|
31
|
+
app.json() // returns a NEW TestApp with Accept: application/json
|
|
32
|
+
app.withHeader(name, value) / app.withHeaders(record) // also return new TestApp
|
|
33
|
+
const csrf = await app.withCsrf() // primes session + XSRF cookies; use for mutating requests hitting CSRF
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Chainable assertions (on PendingTestResponse)
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
await app.get('/posts').assertOk().assertJsonCount(3, 'data')
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Exact list:
|
|
43
|
+
`assertStatus(code: number)` · `assertOk()` (200) · `assertCreated()` (201) ·
|
|
44
|
+
`assertNoContent()` (204) · `assertRedirect(url?: string)` (3xx, optional Location match) ·
|
|
45
|
+
`assertNotFound()` (404) · `assertForbidden()` (403) · `assertUnauthorized()` (401) ·
|
|
46
|
+
`assertUnprocessable()` (422) ·
|
|
47
|
+
`assertJson(expected: Record<string, unknown>)` (exact deep match) ·
|
|
48
|
+
`assertJsonCount(count: number, key?: string)` ·
|
|
49
|
+
`assertJsonStructure(keys: string[])` (top-level keys exist) ·
|
|
50
|
+
`assertJsonPath(path: string, value: unknown)` (dot-path, deep equal) ·
|
|
51
|
+
`assertInertia(component: string, props?: Record<string, unknown>)` ·
|
|
52
|
+
`assertCookie(name: string, value?: string)` · `assertCookieMissing(name: string)` ·
|
|
53
|
+
`assertHeader(name: string, value?: string)` · `assertHeaderMissing(name: string)`
|
|
54
|
+
|
|
55
|
+
## Awaited response (TestResponse)
|
|
56
|
+
|
|
57
|
+
Awaiting yields a `TestResponse` with extras not available on the chain:
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
const res = await app.get('/posts')
|
|
61
|
+
res.status // number
|
|
62
|
+
res.headers // Headers
|
|
63
|
+
await res.text() // body string
|
|
64
|
+
await res.json<T>() // parsed body
|
|
65
|
+
res.assertBadRequest() // 400
|
|
66
|
+
res.assertServerError() // 500
|
|
67
|
+
res.assertSuccessful() // any 2xx
|
|
68
|
+
await res.assertJsonContains({ k: v }) // partial top-level match
|
|
69
|
+
await res.assertBodyContains('text')
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Patterns
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
import { describe, test, expect, beforeAll } from 'bun:test'
|
|
76
|
+
|
|
77
|
+
describe('PostController', () => {
|
|
78
|
+
let app: TestApp
|
|
79
|
+
beforeAll(async () => { app = await TestApp.create() })
|
|
80
|
+
|
|
81
|
+
test('store validates input', async () => {
|
|
82
|
+
await app.json().post('/posts', {}).assertUnprocessable()
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
test('store creates post for authed user', async () => {
|
|
86
|
+
const csrf = await app.actingAs(user).withCsrf()
|
|
87
|
+
await csrf.post('/posts', { title: 'Hi', body: '...' }).assertRedirect('/posts')
|
|
88
|
+
})
|
|
89
|
+
})
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Validation failures return 422 with `{ message, errors: Record<string, string[]> }` —
|
|
93
|
+
assert with `assertJsonPath('errors.title.0', 'Title is required')`.
|
|
@@ -7,6 +7,8 @@ description: Generate a complete CRUD feature with all related components in one
|
|
|
7
7
|
|
|
8
8
|
You are a full-feature scaffolding assistant for the Guren framework.
|
|
9
9
|
|
|
10
|
+
> When filling in generated code, follow the API rules in `.claude/rules/` (orm-models, controllers-http, routes-codegen, testing) — they carry the verified signatures.
|
|
11
|
+
|
|
10
12
|
## Your Role
|
|
11
13
|
|
|
12
14
|
Generate all components needed for a complete CRUD feature in one workflow. This is the "batteries-included" approach — creating everything an entity needs to work end-to-end with full type safety.
|
|
@@ -7,6 +7,8 @@ description: Guren framework API documentation, code patterns, and examples. Cov
|
|
|
7
7
|
|
|
8
8
|
You are a documentation assistant for the Guren framework.
|
|
9
9
|
|
|
10
|
+
> The authoritative signature-level API reference lives in `.claude/rules/*.md` (auto-loaded per edited path); this skill is a subsystem tour for interactive Q&A.
|
|
11
|
+
|
|
10
12
|
## Your Role
|
|
11
13
|
|
|
12
14
|
Help users understand and use Guren framework APIs by providing examples, patterns, and source file locations.
|
|
@@ -92,8 +94,8 @@ export class User extends AuthenticatableModel<UserRecord> {
|
|
|
92
94
|
}
|
|
93
95
|
```
|
|
94
96
|
|
|
95
|
-
- `fillable` (whitelist) — only listed fields pass through to `create()` / `update()`
|
|
96
|
-
- `guarded` (blacklist, default: `['id']`) — listed fields are stripped; ignored when `fillable` is set
|
|
97
|
+
- `fillable` (whitelist) — only listed fields pass through to `create()` / `update()`; unlisted input keys **throw `MassAssignmentException`** (set `static strictFillable = false` for silent discarding). Use `forceCreate()` / `forceUpdate()` for trusted server-side data.
|
|
98
|
+
- `guarded` (blacklist, default: `['id']`) — listed fields are silently stripped; ignored when `fillable` is set
|
|
97
99
|
- Both are enforced by `Model.filterFillable()`, called automatically before persistence
|
|
98
100
|
- Always define `fillable` on models that accept user input — this is the second defense layer after Zod validation
|
|
99
101
|
|
|
@@ -118,10 +120,10 @@ await User.with('posts.comments') // nested, dot notation
|
|
|
118
120
|
await User.where('active', true).with('posts').get() // QueryBuilder
|
|
119
121
|
await User.findWith(1, 'posts') // single record + relations
|
|
120
122
|
await User.withCount('posts') // users[0].postsCount: number (no rows loaded)
|
|
121
|
-
await Post.withPaginate({ page: 1 }
|
|
123
|
+
await Post.withPaginate('author', { page: 1 }) // paginated + relations
|
|
122
124
|
```
|
|
123
125
|
|
|
124
|
-
Also available: `hasOne`, `belongsToMany(pivotTable,
|
|
126
|
+
Also available: `hasOne`, `belongsToMany(name, related, pivotTable, foreignPivotKey, relatedPivotKey, parentKey?, relatedKey?)`, `hasManyThrough`, `morphMany`/`morphTo`. There are **no `attach`/`detach`/`sync` pivot helpers and no `firstOrCreate`/`updateOrCreate`** — manage pivot rows via a model on the pivot table (`PivotModel.create(...)` / `PivotModel.delete(...)`), and hand-roll find-or-create with `Model.first(where)` + `Model.create(...)`. Full guide: `docs/en/guides/database.md` (Relationships section).
|
|
125
127
|
|
|
126
128
|
### Routes
|
|
127
129
|
Source: `packages/server/src/mvc/Router.ts`
|
|
@@ -7,6 +7,8 @@ description: Generate individual Guren framework components using bunx guren mak
|
|
|
7
7
|
|
|
8
8
|
You are a component scaffolding assistant for the Guren framework.
|
|
9
9
|
|
|
10
|
+
> When editing the generated files, the verified API signatures live in `.claude/rules/*.md` (auto-loaded per edited path).
|
|
11
|
+
|
|
10
12
|
## Your Role
|
|
11
13
|
|
|
12
14
|
Help users generate individual framework components using the Guren CLI. Understand context and suggest related components.
|
|
@@ -4,6 +4,23 @@
|
|
|
4
4
|
|
|
5
5
|
A fullstack TypeScript application built with the Guren framework (Laravel-inspired, running on Bun).
|
|
6
6
|
|
|
7
|
+
## AI Agents: Start Here
|
|
8
|
+
|
|
9
|
+
Before exploring `node_modules`, use the built-in introspection commands:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bunx guren context # project map: models, routes, controllers, pages (add --json for JSON)
|
|
13
|
+
bunx guren check # validate route ↔ controller ↔ page consistency — run after changes
|
|
14
|
+
bunx guren codegen # regenerate .guren/*.gen.ts typed manifests (also runs via `bun run dev`)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Detailed, verified API rules live in `.claude/rules/*.md` and load automatically
|
|
18
|
+
based on the files you are editing (glob-scoped): `orm-models.md` (models, queries,
|
|
19
|
+
relations), `controllers-http.md` (validation, Inertia, auth), `routes-codegen.md`
|
|
20
|
+
(route options, schema binding, codegen), `testing.md` (TestApp assertions).
|
|
21
|
+
Read the matching rule file before reading `node_modules/@guren/*` — it covers the
|
|
22
|
+
exact signatures.
|
|
23
|
+
|
|
7
24
|
## Project Structure
|
|
8
25
|
|
|
9
26
|
```
|
|
@@ -59,9 +76,12 @@ bunx guren make:listener <Name> --event=<EventName>
|
|
|
59
76
|
bunx guren make:mail <Name>
|
|
60
77
|
bunx guren make:test <Name>
|
|
61
78
|
|
|
62
|
-
# Database
|
|
63
|
-
|
|
64
|
-
bun run db:
|
|
79
|
+
# Database workflow: edit db/schema.ts first, then
|
|
80
|
+
bunx guren make:migration <name> # generate SQL migration via drizzle-kit into db/migrations/
|
|
81
|
+
bun run db:migrate # apply pending migrations
|
|
82
|
+
bunx guren db:status # show applied/pending state
|
|
83
|
+
bun run db:seed # run seeders
|
|
84
|
+
# Migrations are forward-only (no rollback). Dev reset: bunx guren db:reset --seed
|
|
65
85
|
|
|
66
86
|
# Build & test
|
|
67
87
|
bun run build
|
|
@@ -92,94 +112,54 @@ http://localhost:3333/_guren/mcp
|
|
|
92
112
|
| `guren_make_component` | 個別コンポーネント生成 |
|
|
93
113
|
| `guren_codegen` | 型マニフェスト生成(routes.gen.ts, pages.gen.ts等) |
|
|
94
114
|
|
|
95
|
-
## Architecture
|
|
115
|
+
## Architecture Overview
|
|
96
116
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
import { z } from 'zod'
|
|
101
|
-
|
|
102
|
-
const CreatePostSchema = z.object({
|
|
103
|
-
title: z.string().min(1),
|
|
104
|
-
body: z.string().min(1),
|
|
105
|
-
})
|
|
117
|
+
The request lifecycle: `routes/web.ts` registers routes on a `Router`, each pointing
|
|
118
|
+
at a `[Controller, 'method']` tuple. Controllers validate input with Zod schemas,
|
|
119
|
+
query models, and render Inertia pages or JSON.
|
|
106
120
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
121
|
+
```typescript
|
|
122
|
+
// routes/web.ts
|
|
123
|
+
router.get('/posts', [PostController, 'index']).name('posts.index')
|
|
124
|
+
router.post('/posts', { name: 'posts.store', body: CreatePostSchema }, [PostController, 'store'])
|
|
110
125
|
|
|
126
|
+
// app/Http/Controllers/PostController.ts
|
|
111
127
|
export class PostController extends Controller {
|
|
112
|
-
async index() {
|
|
113
|
-
const result = await Post.paginate({ page: 1, perPage: 15 })
|
|
114
|
-
const paginator = paginate(result, { path: this.request.path ?? '/posts' })
|
|
115
|
-
return this.inertia(pages.posts.Index, {
|
|
116
|
-
data: result.data.map((post) => new PostResource(post).toJSON()),
|
|
117
|
-
pagination: paginator,
|
|
118
|
-
})
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
async show() {
|
|
122
|
-
const { id } = this.validateParams(PostIdParamSchema)
|
|
123
|
-
const post = await Post.findOrFail(id)
|
|
124
|
-
return this.inertia(pages.posts.Show, { post: new PostResource(post).toJSON() })
|
|
125
|
-
}
|
|
126
|
-
|
|
127
128
|
async store() {
|
|
128
|
-
const data = await this.validateBody(CreatePostSchema)
|
|
129
|
-
const user = await this.auth.userOrFail()
|
|
129
|
+
const data = await this.validateBody(CreatePostSchema) // 422 on failure
|
|
130
|
+
const user = await this.auth.userOrFail() // 401 if unauthenticated
|
|
130
131
|
const post = await Post.create({ ...data, authorId: user.id })
|
|
131
132
|
return this.redirect('/posts')
|
|
132
133
|
}
|
|
133
134
|
}
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
**Validation helpers** (accepts any Zod-like schema with `safeParse`):
|
|
137
|
-
- `this.validateBody(schema)` — parse request body, throw 422 on failure
|
|
138
|
-
- `this.validateQuery(schema)` — parse query parameters
|
|
139
|
-
- `this.validateParams(schema)` — parse route parameters
|
|
140
135
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
import { posts } from '@/db/schema'
|
|
145
|
-
|
|
146
|
-
export class Post extends Model<typeof posts> {
|
|
147
|
-
static table = posts
|
|
136
|
+
// app/Models/Post.ts
|
|
137
|
+
export class Post extends defineModel(posts) {
|
|
138
|
+
static fillable = ['title', 'body', 'authorId']
|
|
148
139
|
}
|
|
149
|
-
|
|
150
|
-
// Usage
|
|
151
|
-
const post = await Post.find(1) // returns null if not found
|
|
152
|
-
const post = await Post.findOrFail(1) // throws ModelNotFoundException (404)
|
|
153
|
-
const all = await Post.where('published', true).get()
|
|
154
140
|
```
|
|
155
141
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
142
|
+
- Models: `await Post.findOrFail(id)` throws a 404; `Post.where(...)` starts a query
|
|
143
|
+
builder chain. Full API in `.claude/rules/orm-models.md`.
|
|
144
|
+
- Attaching a Zod schema to a route both validates the request automatically and
|
|
145
|
+
feeds `bunx guren codegen` typed manifests. Details in `.claude/rules/routes-codegen.md`.
|
|
146
|
+
- Middleware: `defineMiddleware(async (c, next) => { ... })` from `@guren/core`;
|
|
147
|
+
register aliases via `router.aliasMiddleware('auth', requireAuthenticated({ redirectTo: '/login' }))`.
|
|
159
148
|
|
|
160
|
-
|
|
161
|
-
router.get('/posts', PostController.index)
|
|
162
|
-
router.post('/posts', PostController.store)
|
|
163
|
-
router.resource('/posts', PostController)
|
|
149
|
+
## Testing
|
|
164
150
|
|
|
165
|
-
|
|
166
|
-
group.get('/dashboard', DashboardController.index)
|
|
167
|
-
})
|
|
168
|
-
}
|
|
169
|
-
```
|
|
151
|
+
Uses `bun:test` + `@guren/testing`. Requests run in-process via `app.fetch()` — no server needed.
|
|
170
152
|
|
|
171
|
-
### Middleware
|
|
172
153
|
```typescript
|
|
173
|
-
import {
|
|
154
|
+
import { TestApp } from '@guren/testing'
|
|
174
155
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
179
|
-
await next()
|
|
180
|
-
})
|
|
156
|
+
const app = await TestApp.create()
|
|
157
|
+
await app.get('/posts').assertOk()
|
|
158
|
+
await app.actingAs(user).json().post('/posts', { title: 'Hi' }).assertCreated()
|
|
181
159
|
```
|
|
182
160
|
|
|
161
|
+
Full client and assertion reference: `.claude/rules/testing.md`.
|
|
162
|
+
|
|
183
163
|
## Key Files
|
|
184
164
|
|
|
185
165
|
| Path | Purpose |
|
|
@@ -190,3 +170,4 @@ export const requireAuth = defineMiddleware(async (c, next) => {
|
|
|
190
170
|
| `routes/web.ts` | Web route definitions |
|
|
191
171
|
| `app/Providers/` | Service providers |
|
|
192
172
|
| `resources/js/pages/` | React page components |
|
|
173
|
+
| `.claude/rules/` | Glob-scoped API rules (auto-loaded per edited path) |
|
|
@@ -17,21 +17,21 @@
|
|
|
17
17
|
"db:seed": "bunx guren db:seed"
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@guren/cli": "^1.0.0
|
|
21
|
-
"@guren/core": "^1.0.0
|
|
22
|
-
"@guren/inertia-client": "^1.0.0
|
|
23
|
-
"@guren/orm": "^1.0.0
|
|
24
|
-
"@inertiajs/react": "^
|
|
25
|
-
"drizzle-orm": "1.0.0-rc.
|
|
20
|
+
"@guren/cli": "^1.0.0",
|
|
21
|
+
"@guren/core": "^1.0.0",
|
|
22
|
+
"@guren/inertia-client": "^1.0.0",
|
|
23
|
+
"@guren/orm": "^1.0.0",
|
|
24
|
+
"@inertiajs/react": "^3.6.1",
|
|
25
|
+
"drizzle-orm": "1.0.0-rc.4",
|
|
26
26
|
"react": "^19.0.0",
|
|
27
27
|
"react-dom": "^19.0.0",
|
|
28
|
-
"zod": "^4.
|
|
28
|
+
"zod": "^4.4.3"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/react": "^19.0.0",
|
|
32
32
|
"@types/react-dom": "^19.0.0",
|
|
33
33
|
"bun-types": "^1.3.1",
|
|
34
|
-
"drizzle-kit": "1.0.0-rc.
|
|
34
|
+
"drizzle-kit": "1.0.0-rc.4",
|
|
35
35
|
"mysql2": "^3.11.3",
|
|
36
36
|
"postgres": "^3.4.3",
|
|
37
37
|
"typescript": "^5.4.0",
|