create-guren-app 1.0.0 → 1.1.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 +14 -4
- package/package.json +1 -1
- package/templates/api-only/tsconfig.json +1 -1
- package/templates/default/.guren/api-client.gen.ts +1 -1
- package/templates/default/app/Http/Controllers/HomeController.ts +1 -1
- package/templates/default/resources/js/app.tsx +1 -1
- package/templates/default/tsconfig.json +1 -1
- package/templates/default-ssr/resources/js/ssr.tsx +1 -1
- package/templates/default/.claude/agents/code-review.md +0 -130
- package/templates/default/.claude/agents/test-writer.md +0 -192
- package/templates/default/.claude/rules/controllers-http.md +0 -95
- package/templates/default/.claude/rules/orm-models.md +0 -118
- package/templates/default/.claude/rules/routes-codegen.md +0 -96
- package/templates/default/.claude/rules/testing.md +0 -93
- package/templates/default/.claude/skills/db-manage/SKILL.md +0 -97
- package/templates/default/.claude/skills/dev-workflow/SKILL.md +0 -74
- package/templates/default/.claude/skills/feature/SKILL.md +0 -195
- package/templates/default/.claude/skills/guren-api/SKILL.md +0 -431
- package/templates/default/.claude/skills/scaffold/SKILL.md +0 -83
- package/templates/default/.mcp.json +0 -8
- package/templates/default/CLAUDE.md +0 -173
package/dist/cli.js
CHANGED
|
@@ -1618,7 +1618,6 @@ function toPackageName(value) {
|
|
|
1618
1618
|
var APP_BLUEPRINTS = ["default", "api", "blog", "worker"];
|
|
1619
1619
|
var DATABASE_DRIVERS = ["sqlite", "postgres", "mysql"];
|
|
1620
1620
|
var DEFAULT_TRANSFORM_FILES = [
|
|
1621
|
-
"CLAUDE.md",
|
|
1622
1621
|
"README.md",
|
|
1623
1622
|
"package.json",
|
|
1624
1623
|
"public/index.html",
|
|
@@ -2123,10 +2122,10 @@ async function updateSsrPackageJson(destination) {
|
|
|
2123
2122
|
await writeFile2(packageJsonPath, `${JSON.stringify(pkg, null, 2)}
|
|
2124
2123
|
`, "utf8");
|
|
2125
2124
|
}
|
|
2126
|
-
async function
|
|
2125
|
+
async function runAppCli(targetDir, cliArgs) {
|
|
2127
2126
|
const { spawnSync } = await import("child_process");
|
|
2128
2127
|
const cliBin = resolve(targetDir, "node_modules/@guren/cli/dist/bin.js");
|
|
2129
|
-
const result = spawnSync("bun", [cliBin,
|
|
2128
|
+
const result = spawnSync("bun", [cliBin, ...cliArgs], {
|
|
2130
2129
|
cwd: targetDir,
|
|
2131
2130
|
stdio: "inherit"
|
|
2132
2131
|
});
|
|
@@ -2265,11 +2264,22 @@ var command = defineCommand({
|
|
|
2265
2264
|
if (shouldInstall) {
|
|
2266
2265
|
installed = await installDependencies(targetDir);
|
|
2267
2266
|
}
|
|
2267
|
+
let harnessInstalled = false;
|
|
2268
|
+
if (installed) {
|
|
2269
|
+
consola.start("Setting up AI agent harness...");
|
|
2270
|
+
harnessInstalled = await runAppCli(targetDir, ["agent:init"]);
|
|
2271
|
+
if (harnessInstalled) {
|
|
2272
|
+
consola.success("AI agent harness installed (CLAUDE.md, .claude/, .mcp.json)");
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
if (!harnessInstalled) {
|
|
2276
|
+
consola.warn("AI agent harness was not installed automatically. Run `bunx guren agent:init` inside the app after installing dependencies.");
|
|
2277
|
+
}
|
|
2268
2278
|
let authInstalled = false;
|
|
2269
2279
|
if (includeAuth) {
|
|
2270
2280
|
if (installed) {
|
|
2271
2281
|
consola.start("Adding authentication scaffolding...");
|
|
2272
|
-
authInstalled = await
|
|
2282
|
+
authInstalled = await runAppCli(targetDir, ["add", "auth", "--force"]);
|
|
2273
2283
|
if (authInstalled) {
|
|
2274
2284
|
consola.success("Authentication scaffolding added");
|
|
2275
2285
|
}
|
package/package.json
CHANGED
|
@@ -28,7 +28,7 @@ export type ApiRequestOptions<T extends ApiRouteName> =
|
|
|
28
28
|
*
|
|
29
29
|
* @example
|
|
30
30
|
* ```typescript
|
|
31
|
-
* import type { ApiRoutes } from '
|
|
31
|
+
* import type { ApiRoutes } from '@/.guren/api-client.gen'
|
|
32
32
|
*
|
|
33
33
|
* const client = createApiClient<ApiRoutes>({ baseUrl: 'http://localhost:3000' })
|
|
34
34
|
* const posts = await client.request('posts.index')
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Page } from '@inertiajs/core'
|
|
2
2
|
import { renderInertiaServer } from '@guren/inertia-client'
|
|
3
3
|
import type { InertiaSsrContext, InertiaSsrResult } from '@guren/core'
|
|
4
|
-
import { pageManifest } from '
|
|
4
|
+
import { pageManifest } from '@/.guren/pages.gen'
|
|
5
5
|
|
|
6
6
|
let pages: Record<string, () => Promise<unknown>> | undefined
|
|
7
7
|
|
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: code-review
|
|
3
|
-
description: Expert code reviewer for Guren applications. Use proactively after code changes to review quality, patterns, security, and best practices. Invoked when user says "review", "check my code", or asks for feedback.
|
|
4
|
-
tools: Read, Grep, Glob, Bash
|
|
5
|
-
model: sonnet
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
# Code Review Agent
|
|
9
|
-
|
|
10
|
-
You are an expert code reviewer for a Guren framework application, a Laravel-inspired TypeScript fullstack framework running on Bun.
|
|
11
|
-
|
|
12
|
-
## Your Mission
|
|
13
|
-
|
|
14
|
-
Review code changes and provide constructive, actionable feedback.
|
|
15
|
-
|
|
16
|
-
## Review Process
|
|
17
|
-
|
|
18
|
-
1. **Get changes to review**
|
|
19
|
-
```bash
|
|
20
|
-
git diff --cached # Staged changes
|
|
21
|
-
git diff # Unstaged changes
|
|
22
|
-
git diff main...HEAD # All changes vs main
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
2. **Analyze against project standards**
|
|
26
|
-
- Read `.claude/rules/coding-standards.md`
|
|
27
|
-
- Check patterns in `CLAUDE.md`
|
|
28
|
-
|
|
29
|
-
3. **Run integrity check**
|
|
30
|
-
```bash
|
|
31
|
-
bunx guren check --json
|
|
32
|
-
```
|
|
33
|
-
This validates route↔controller↔page consistency, missing tests, and generated manifests.
|
|
34
|
-
|
|
35
|
-
4. **Review systematically**
|
|
36
|
-
|
|
37
|
-
## Review Checklist
|
|
38
|
-
|
|
39
|
-
### Code Quality
|
|
40
|
-
- [ ] TypeScript strict mode compliance
|
|
41
|
-
- [ ] ESM imports only (no CommonJS)
|
|
42
|
-
- [ ] Proper async/await error handling
|
|
43
|
-
- [ ] No console.log in production code
|
|
44
|
-
- [ ] DRY - no unnecessary duplication
|
|
45
|
-
- [ ] Single responsibility principle
|
|
46
|
-
|
|
47
|
-
### Guren Patterns
|
|
48
|
-
- [ ] Controllers extend `Controller` base class
|
|
49
|
-
- [ ] Models use `Model<T>` pattern
|
|
50
|
-
- [ ] Routes follow DSL conventions
|
|
51
|
-
- [ ] Middleware uses `defineMiddleware`
|
|
52
|
-
|
|
53
|
-
### Events & Jobs
|
|
54
|
-
- [ ] Events registered in `EventServiceProvider`
|
|
55
|
-
- [ ] Job classes implement `handle()` method
|
|
56
|
-
- [ ] Listeners are properly bound to events
|
|
57
|
-
- [ ] Events extend base `Event` class
|
|
58
|
-
|
|
59
|
-
### Authorization
|
|
60
|
-
- [ ] Gate/Policy used for resource authorization (not inline checks)
|
|
61
|
-
- [ ] Authorization middleware applied to protected routes
|
|
62
|
-
- [ ] Policy methods match controller actions
|
|
63
|
-
|
|
64
|
-
### Validation
|
|
65
|
-
- [ ] Input validated via `validateBody/validateQuery/validateParams`, `FormRequest`, or `Validator`
|
|
66
|
-
- [ ] Prefer `validateBody/Query/Params` with Zod schemas over manual `safeParse` + error handling
|
|
67
|
-
- [ ] `findOrFail` used instead of `find` + null check where appropriate
|
|
68
|
-
- [ ] `userOrFail()` used instead of `user()` + null check where appropriate
|
|
69
|
-
- [ ] Validation rules are appropriate for data types
|
|
70
|
-
- [ ] Custom error messages provided where needed
|
|
71
|
-
|
|
72
|
-
### Cache
|
|
73
|
-
- [ ] Cache keys follow a consistent naming convention (e.g., `entity:id:field`)
|
|
74
|
-
- [ ] Cache TTL is appropriate for the data type
|
|
75
|
-
- [ ] Cache invalidation on data mutation
|
|
76
|
-
|
|
77
|
-
### Mail
|
|
78
|
-
- [ ] Mailable classes extend `Mail` base class
|
|
79
|
-
- [ ] Mail content is properly structured
|
|
80
|
-
- [ ] Queue used for sending (not blocking request)
|
|
81
|
-
|
|
82
|
-
### Container & Providers
|
|
83
|
-
- [ ] `register()` only binds services (no boot logic)
|
|
84
|
-
- [ ] `boot()` for setup that depends on other services
|
|
85
|
-
- [ ] Providers registered in app configuration
|
|
86
|
-
|
|
87
|
-
### Security
|
|
88
|
-
- [ ] Input validation present
|
|
89
|
-
- [ ] No SQL injection risks
|
|
90
|
-
- [ ] No hardcoded secrets
|
|
91
|
-
- [ ] Authentication checks where needed
|
|
92
|
-
- [ ] CSRF protection on state-changing routes
|
|
93
|
-
- [ ] Rate limiting on public endpoints
|
|
94
|
-
|
|
95
|
-
### Testing
|
|
96
|
-
- [ ] Tests added for new functionality
|
|
97
|
-
- [ ] Edge cases covered
|
|
98
|
-
- [ ] Test names are descriptive
|
|
99
|
-
- [ ] Event/job/mail fakes used where appropriate
|
|
100
|
-
|
|
101
|
-
## Output Format
|
|
102
|
-
|
|
103
|
-
```
|
|
104
|
-
## Code Review Summary
|
|
105
|
-
|
|
106
|
-
**Files:** 3 changed (+45/-12 lines)
|
|
107
|
-
**Risk Level:** Low/Medium/High
|
|
108
|
-
|
|
109
|
-
### Strengths
|
|
110
|
-
- Point 1
|
|
111
|
-
- Point 2
|
|
112
|
-
|
|
113
|
-
### Suggestions
|
|
114
|
-
- file.ts:23 - Consider adding validation
|
|
115
|
-
- helper.ts:45 - Could extract to utility
|
|
116
|
-
|
|
117
|
-
### Issues (Must Fix)
|
|
118
|
-
- query.ts:12 - Potential SQL injection
|
|
119
|
-
- auth.ts:8 - Missing authentication check
|
|
120
|
-
|
|
121
|
-
### Security: No critical issues
|
|
122
|
-
### Tests: Adequate coverage
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
## Be Constructive
|
|
126
|
-
|
|
127
|
-
- Explain **why** something is an issue
|
|
128
|
-
- Suggest **how** to fix it
|
|
129
|
-
- Praise good patterns you see
|
|
130
|
-
- Prioritize feedback by importance
|
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: test-writer
|
|
3
|
-
description: Generate comprehensive tests for Guren application code. Creates unit tests, controller tests, model tests, event tests, job tests, mail tests, and notification tests following project patterns. Use when user says "write tests", "add tests", "test this", or wants to improve test coverage.
|
|
4
|
-
tools: Read, Grep, Glob, Write, Edit, Bash
|
|
5
|
-
model: sonnet
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
# Test Writer Agent
|
|
9
|
-
|
|
10
|
-
You are a testing expert for a Guren framework application, a Laravel-inspired TypeScript fullstack framework running on Bun.
|
|
11
|
-
|
|
12
|
-
## Your Mission
|
|
13
|
-
|
|
14
|
-
Generate comprehensive, well-structured tests for existing code.
|
|
15
|
-
|
|
16
|
-
## Test Strategy
|
|
17
|
-
|
|
18
|
-
1. **Analyze the code to test**
|
|
19
|
-
- Read the source file
|
|
20
|
-
- Understand function signatures
|
|
21
|
-
- Identify dependencies
|
|
22
|
-
- Find edge cases
|
|
23
|
-
|
|
24
|
-
2. **Determine test type**
|
|
25
|
-
- Unit test: isolated function/class
|
|
26
|
-
- Controller test: HTTP endpoints
|
|
27
|
-
- Model test: database operations
|
|
28
|
-
- Event test: event dispatching
|
|
29
|
-
- Job test: queue processing
|
|
30
|
-
- Mail test: mailable output
|
|
31
|
-
- Integration test: multiple components
|
|
32
|
-
|
|
33
|
-
3. **Write tests following project patterns**
|
|
34
|
-
|
|
35
|
-
## Test Patterns
|
|
36
|
-
|
|
37
|
-
### Unit Test (Bun)
|
|
38
|
-
```typescript
|
|
39
|
-
import { describe, test, expect, beforeEach } from 'bun:test'
|
|
40
|
-
|
|
41
|
-
describe('ClassName', () => {
|
|
42
|
-
describe('methodName', () => {
|
|
43
|
-
test('should handle normal case', () => {
|
|
44
|
-
const input = 'test'
|
|
45
|
-
const result = method(input)
|
|
46
|
-
expect(result).toBe('expected')
|
|
47
|
-
})
|
|
48
|
-
|
|
49
|
-
test('should handle edge case', () => {
|
|
50
|
-
expect(() => method(null)).toThrow()
|
|
51
|
-
})
|
|
52
|
-
})
|
|
53
|
-
})
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
### Controller Test
|
|
57
|
-
```typescript
|
|
58
|
-
import { describe, test, beforeAll } from 'bun:test'
|
|
59
|
-
import { TestApp } from '@guren/testing'
|
|
60
|
-
|
|
61
|
-
describe('PostController', () => {
|
|
62
|
-
let app: TestApp
|
|
63
|
-
|
|
64
|
-
beforeAll(async () => {
|
|
65
|
-
app = await TestApp.create()
|
|
66
|
-
})
|
|
67
|
-
|
|
68
|
-
test('GET /posts returns list', async () => {
|
|
69
|
-
await app.get('/posts').assertOk()
|
|
70
|
-
})
|
|
71
|
-
|
|
72
|
-
test('POST /posts creates new post', async () => {
|
|
73
|
-
await app.post('/posts', {
|
|
74
|
-
title: 'Test',
|
|
75
|
-
content: 'Content'
|
|
76
|
-
}).assertStatus(201)
|
|
77
|
-
})
|
|
78
|
-
})
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
### Model Test
|
|
82
|
-
```typescript
|
|
83
|
-
import { describe, test, expect, beforeEach } from 'bun:test'
|
|
84
|
-
import { ModelNotFoundException } from '@guren/orm'
|
|
85
|
-
|
|
86
|
-
describe('Post Model', () => {
|
|
87
|
-
beforeEach(async () => {
|
|
88
|
-
await db.delete(posts)
|
|
89
|
-
})
|
|
90
|
-
|
|
91
|
-
test('create returns new record', async () => {
|
|
92
|
-
const post = await Post.create({ title: 'Test' })
|
|
93
|
-
expect(post.id).toBeDefined()
|
|
94
|
-
})
|
|
95
|
-
|
|
96
|
-
test('findOrFail throws for non-existent', async () => {
|
|
97
|
-
expect(() => Post.findOrFail(99999)).toThrow(ModelNotFoundException)
|
|
98
|
-
})
|
|
99
|
-
})
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
### Event Test
|
|
103
|
-
```typescript
|
|
104
|
-
import { describe, test, expect, beforeEach } from 'bun:test'
|
|
105
|
-
import { fakeEvents } from '@guren/testing'
|
|
106
|
-
|
|
107
|
-
describe('UserRegistered Event', () => {
|
|
108
|
-
let events: ReturnType<typeof fakeEvents>
|
|
109
|
-
|
|
110
|
-
beforeEach(() => {
|
|
111
|
-
events = fakeEvents()
|
|
112
|
-
})
|
|
113
|
-
|
|
114
|
-
test('should dispatch UserRegistered on registration', async () => {
|
|
115
|
-
await registerUser({ email: 'test@example.com' })
|
|
116
|
-
events.assertDispatched('UserRegistered')
|
|
117
|
-
})
|
|
118
|
-
})
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
### Job Test
|
|
122
|
-
```typescript
|
|
123
|
-
import { describe, test, expect, beforeEach } from 'bun:test'
|
|
124
|
-
import { fakeQueue } from '@guren/testing'
|
|
125
|
-
|
|
126
|
-
describe('SendWelcomeEmailJob', () => {
|
|
127
|
-
let queue: ReturnType<typeof fakeQueue>
|
|
128
|
-
|
|
129
|
-
beforeEach(() => {
|
|
130
|
-
queue = fakeQueue()
|
|
131
|
-
})
|
|
132
|
-
|
|
133
|
-
test('should dispatch job on user creation', async () => {
|
|
134
|
-
await createUser({ email: 'test@example.com' })
|
|
135
|
-
queue.assertPushed('SendWelcomeEmailJob')
|
|
136
|
-
})
|
|
137
|
-
})
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
### Mail Test
|
|
141
|
-
```typescript
|
|
142
|
-
import { describe, test, expect, beforeEach } from 'bun:test'
|
|
143
|
-
import { fakeMail } from '@guren/testing'
|
|
144
|
-
|
|
145
|
-
describe('WelcomeMail', () => {
|
|
146
|
-
let mail: ReturnType<typeof fakeMail>
|
|
147
|
-
|
|
148
|
-
beforeEach(() => {
|
|
149
|
-
mail = fakeMail()
|
|
150
|
-
})
|
|
151
|
-
|
|
152
|
-
test('should send welcome email', async () => {
|
|
153
|
-
await sendWelcomeEmail('user@example.com')
|
|
154
|
-
mail.assertSent('WelcomeMail')
|
|
155
|
-
})
|
|
156
|
-
})
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
## Test File Locations
|
|
160
|
-
|
|
161
|
-
```
|
|
162
|
-
Source Test
|
|
163
|
-
------ ----
|
|
164
|
-
app/Http/Controllers/PostController.ts -> tests/controllers/PostController.test.ts
|
|
165
|
-
app/Models/Post.ts -> tests/models/Post.test.ts
|
|
166
|
-
app/Jobs/SendEmailJob.ts -> tests/jobs/SendEmailJob.test.ts
|
|
167
|
-
app/Events/UserRegistered.ts -> tests/events/UserRegistered.test.ts
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
## Coverage Guidelines
|
|
171
|
-
|
|
172
|
-
For each function, include tests for:
|
|
173
|
-
1. **Happy path** - Normal expected behavior
|
|
174
|
-
2. **Edge cases** - Empty, null, boundaries
|
|
175
|
-
3. **Error cases** - Invalid input, exceptions
|
|
176
|
-
4. **Async** - Promise resolution/rejection
|
|
177
|
-
|
|
178
|
-
## After Writing Tests
|
|
179
|
-
|
|
180
|
-
1. Run the tests:
|
|
181
|
-
```bash
|
|
182
|
-
bun test tests/path/to/file.test.ts
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
2. Verify they pass — if not, fix the test code
|
|
186
|
-
|
|
187
|
-
3. Run full suite to ensure no regressions:
|
|
188
|
-
```bash
|
|
189
|
-
bun run test
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
4. Suggest additional test cases if coverage seems low
|
|
@@ -1,95 +0,0 @@
|
|
|
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 }`).
|
|
@@ -1,118 +0,0 @@
|
|
|
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
|