create-guren-app 1.7.1 → 1.8.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/README.md +4 -1
- package/dist/cli.js +80 -12
- package/package.json +1 -1
- package/templates/api-only/bin/serve.ts +6 -36
- package/templates/api-only/db/schema.ts +1 -1
- package/templates/api-only/package.json +4 -4
- package/templates/blog/.guren/api-client.gen.ts +177 -39
- package/templates/blog/.guren/routes.gen.ts +23 -16
- package/templates/blog/README.md +11 -0
- package/templates/blog/app/Http/Controllers/PostController.ts +26 -1
- package/templates/blog/app/Http/Validators/LoginValidator.ts +2 -2
- package/templates/blog/app/Http/Validators/PostValidator.ts +8 -0
- package/templates/blog/app/Http/Validators/ProfileValidator.ts +2 -2
- package/templates/blog/app/Http/Validators/RegisterValidator.ts +2 -2
- package/templates/blog/app/Models/User.ts +3 -5
- package/templates/blog/db/schema.mysql.ts +1 -5
- package/templates/blog/db/schema.postgres.ts +1 -1
- package/templates/blog/db/schema.sqlite.ts +1 -1
- package/templates/blog/resources/js/pages/posts/Index.tsx +81 -2
- package/templates/blog/routes/web.ts +14 -1
- package/templates/blog/tests/PostController.test.ts +22 -0
- package/templates/default/.guren/api-client.gen.ts +96 -19
- package/templates/default/.guren/pages.gen.ts +4 -2
- package/templates/default/.guren/routes.gen.ts +23 -18
- package/templates/default/bin/serve.ts +6 -36
- package/templates/default/db/schema.ts +1 -1
- package/templates/default/package.json +5 -5
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ npx create-guren-app my-app
|
|
|
15
15
|
| `--db <sqlite\|postgres\|mysql>` | Database driver (prompted when omitted) |
|
|
16
16
|
| `--blueprint <name>` | Starter blueprint (`default`, `api`, `worker`) |
|
|
17
17
|
| `--auth` | Include authentication scaffolding |
|
|
18
|
+
| `--agents <list>` | AI agents to set up the agent harness for (`claude`, `codex`, `cursor`, `copilot`, `opencode`, `all`, or `none` to skip) |
|
|
18
19
|
| `--no-install` | Skip `bun install` |
|
|
19
20
|
| `--git` / `--no-git` | Initialize a git repository with an initial commit |
|
|
20
21
|
|
|
@@ -22,4 +23,6 @@ The scaffolded app ships a `.gitignore`, so `--git` commits only the project
|
|
|
22
23
|
files — never the generated `.env` (it holds a freshly generated `APP_KEY`).
|
|
23
24
|
When omitted, `--git` is prompted in an interactive terminal and defaults to off
|
|
24
25
|
elsewhere. It is skipped entirely when the target directory already sits inside
|
|
25
|
-
a git repository.
|
|
26
|
+
a git repository. `--agents` works the same way: prompted interactively
|
|
27
|
+
(multi-select, Claude Code preselected) and defaulting to `claude` in
|
|
28
|
+
non-interactive environments.
|
package/dist/cli.js
CHANGED
|
@@ -1800,7 +1800,7 @@ export type AppSeederContext = ${seederContext}
|
|
|
1800
1800
|
}
|
|
1801
1801
|
function generateSchema(driver) {
|
|
1802
1802
|
if (driver === "postgres") {
|
|
1803
|
-
return `import { pgTable, serial, text, timestamp } from '@guren/orm/drizzle'
|
|
1803
|
+
return `import { pgTable, serial, text, timestamp } from '@guren/orm/drizzle/pg'
|
|
1804
1804
|
|
|
1805
1805
|
export const users = pgTable('users', {
|
|
1806
1806
|
id: serial('id').primaryKey(),
|
|
@@ -1811,7 +1811,7 @@ export const users = pgTable('users', {
|
|
|
1811
1811
|
`;
|
|
1812
1812
|
}
|
|
1813
1813
|
if (driver === "mysql") {
|
|
1814
|
-
return `import { mysqlTable, int, varchar, timestamp } from '
|
|
1814
|
+
return `import { mysqlTable, int, varchar, timestamp } from '@guren/orm/drizzle/mysql'
|
|
1815
1815
|
|
|
1816
1816
|
export const users = mysqlTable('users', {
|
|
1817
1817
|
id: int('id').primaryKey().autoincrement(),
|
|
@@ -1821,7 +1821,7 @@ export const users = mysqlTable('users', {
|
|
|
1821
1821
|
})
|
|
1822
1822
|
`;
|
|
1823
1823
|
}
|
|
1824
|
-
return `import { sqliteTable, integer, text } from '
|
|
1824
|
+
return `import { sqliteTable, integer, text } from '@guren/orm/drizzle/sqlite'
|
|
1825
1825
|
|
|
1826
1826
|
export const users = sqliteTable('users', {
|
|
1827
1827
|
id: integer('id').primaryKey({ autoIncrement: true }),
|
|
@@ -2123,6 +2123,60 @@ async function resolveDatabase(flagValue) {
|
|
|
2123
2123
|
const value = typeof result === "string" ? result : "sqlite";
|
|
2124
2124
|
return value ?? "sqlite";
|
|
2125
2125
|
}
|
|
2126
|
+
var AGENT_CHOICES = ["claude", "codex", "cursor", "copilot", "opencode"];
|
|
2127
|
+
var AGENT_CHOICE_SET = new Set(AGENT_CHOICES);
|
|
2128
|
+
var AGENT_CHOICES_HELP = `Supported values are: ${AGENT_CHOICES.join(", ")}, all, none.`;
|
|
2129
|
+
var DEFAULT_AGENTS = ["claude"];
|
|
2130
|
+
async function resolveAgents(flagValue) {
|
|
2131
|
+
const raw = Array.isArray(flagValue) ? flagValue.join(",") : flagValue;
|
|
2132
|
+
if (typeof raw === "string") {
|
|
2133
|
+
const parts = new Set(
|
|
2134
|
+
raw.split(",").map((part) => part.trim().toLowerCase()).filter(Boolean)
|
|
2135
|
+
);
|
|
2136
|
+
if (parts.size === 0) {
|
|
2137
|
+
throw new Error(`Invalid --agents value. ${AGENT_CHOICES_HELP}`);
|
|
2138
|
+
}
|
|
2139
|
+
if (parts.has("none")) {
|
|
2140
|
+
if (parts.size > 1) {
|
|
2141
|
+
throw new Error('--agents "none" cannot be combined with other values.');
|
|
2142
|
+
}
|
|
2143
|
+
return null;
|
|
2144
|
+
}
|
|
2145
|
+
for (const part of parts) {
|
|
2146
|
+
if (part !== "all" && !AGENT_CHOICE_SET.has(part)) {
|
|
2147
|
+
throw new Error(`Invalid agent "${part}". ${AGENT_CHOICES_HELP}`);
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
return parts.has("all") ? ["all"] : [...parts];
|
|
2151
|
+
}
|
|
2152
|
+
if (!process3.stdin.isTTY) {
|
|
2153
|
+
return DEFAULT_AGENTS;
|
|
2154
|
+
}
|
|
2155
|
+
const result = await consola.prompt("Which AI coding agents should the agent harness support?", {
|
|
2156
|
+
type: "multiselect",
|
|
2157
|
+
options: [
|
|
2158
|
+
{ value: "claude", label: "Claude Code" },
|
|
2159
|
+
{ value: "codex", label: "Codex" },
|
|
2160
|
+
{ value: "cursor", label: "Cursor" },
|
|
2161
|
+
{ value: "copilot", label: "GitHub Copilot" },
|
|
2162
|
+
{ value: "opencode", label: "OpenCode" }
|
|
2163
|
+
],
|
|
2164
|
+
initial: DEFAULT_AGENTS,
|
|
2165
|
+
required: false
|
|
2166
|
+
});
|
|
2167
|
+
if (!Array.isArray(result)) {
|
|
2168
|
+
return DEFAULT_AGENTS;
|
|
2169
|
+
}
|
|
2170
|
+
if (result.length === 0) {
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
const agents = result.map(
|
|
2174
|
+
(entry) => String(
|
|
2175
|
+
typeof entry === "object" && entry !== null && "value" in entry ? entry.value : entry
|
|
2176
|
+
)
|
|
2177
|
+
).filter((value) => AGENT_CHOICE_SET.has(value));
|
|
2178
|
+
return agents.length > 0 ? agents : DEFAULT_AGENTS;
|
|
2179
|
+
}
|
|
2126
2180
|
async function resolveGitInit(flagValue, target) {
|
|
2127
2181
|
if (flagValue === false) {
|
|
2128
2182
|
return false;
|
|
@@ -2221,6 +2275,10 @@ var command = defineCommand({
|
|
|
2221
2275
|
git: {
|
|
2222
2276
|
type: "boolean",
|
|
2223
2277
|
description: "Initialize a git repository and create an initial commit (prompted when interactive, off otherwise)"
|
|
2278
|
+
},
|
|
2279
|
+
agents: {
|
|
2280
|
+
type: "string",
|
|
2281
|
+
description: "AI agents to set up the harness for: claude, codex, cursor, copilot, opencode, all, or none (prompted when interactive; default: claude)"
|
|
2224
2282
|
}
|
|
2225
2283
|
},
|
|
2226
2284
|
async run({ args }) {
|
|
@@ -2239,6 +2297,7 @@ var command = defineCommand({
|
|
|
2239
2297
|
const blueprint = getAppBlueprint(typeof args.blueprint === "string" ? args.blueprint : void 0);
|
|
2240
2298
|
const renderingMode = blueprint.name === "api" ? "spa" : await resolveRenderingMode(args.mode);
|
|
2241
2299
|
const database = await resolveDatabase(args.db);
|
|
2300
|
+
const agents = await resolveAgents(args.agents);
|
|
2242
2301
|
const shouldInitGit = await resolveGitInit(args.git, { dir: targetDir, wasEmpty: targetWasEmpty });
|
|
2243
2302
|
await scaffoldAppBlueprint({
|
|
2244
2303
|
blueprint: blueprint.name,
|
|
@@ -2258,16 +2317,25 @@ var command = defineCommand({
|
|
|
2258
2317
|
if (shouldInstall) {
|
|
2259
2318
|
installed = await installDependencies(targetDir);
|
|
2260
2319
|
}
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2320
|
+
if (agents === null) {
|
|
2321
|
+
consola.info(
|
|
2322
|
+
"Skipping the AI agent harness. Add it later with `bunx guren agent:init --target <agents>`."
|
|
2323
|
+
);
|
|
2324
|
+
} else {
|
|
2325
|
+
const targetList = agents.join(",");
|
|
2326
|
+
let harnessInstalled = false;
|
|
2327
|
+
if (installed) {
|
|
2328
|
+
consola.start("Setting up AI agent harness...");
|
|
2329
|
+
harnessInstalled = await runAppCli(targetDir, ["agent:init", "--target", targetList]);
|
|
2330
|
+
if (harnessInstalled) {
|
|
2331
|
+
consola.success(`AI agent harness installed for: ${targetList}`);
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
if (!harnessInstalled) {
|
|
2335
|
+
consola.warn(
|
|
2336
|
+
`AI agent harness was not installed automatically. Run \`bunx guren agent:init --target ${targetList}\` inside the app after installing dependencies.`
|
|
2337
|
+
);
|
|
2267
2338
|
}
|
|
2268
|
-
}
|
|
2269
|
-
if (!harnessInstalled) {
|
|
2270
|
-
consola.warn("AI agent harness was not installed automatically. Run `bunx guren agent:init` inside the app after installing dependencies.");
|
|
2271
2339
|
}
|
|
2272
2340
|
let authInstalled = false;
|
|
2273
2341
|
if (includeAuth) {
|
package/package.json
CHANGED
|
@@ -9,41 +9,11 @@ try {
|
|
|
9
9
|
|
|
10
10
|
// `PORT=0` means "any free port", so this tests for a number, not truthiness.
|
|
11
11
|
const parsedPort = Number.parseInt(process.env.PORT ?? '', 10)
|
|
12
|
-
const
|
|
12
|
+
const port = Number.isInteger(parsedPort) ? parsedPort : 3333
|
|
13
13
|
const hostname = process.env.HOST ?? '0.0.0.0'
|
|
14
14
|
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const attempts = canWalkPorts ? 20 : 1
|
|
21
|
-
|
|
22
|
-
// This file owns the retry, so the framework must not retry underneath it —
|
|
23
|
-
// newer framework versions walk inside listen() themselves, and the two loops
|
|
24
|
-
// would nest into a much wider search reported against the wrong ports.
|
|
25
|
-
process.env.GUREN_STRICT_PORT = '1'
|
|
26
|
-
|
|
27
|
-
for (let offset = 0; offset < attempts; offset += 1) {
|
|
28
|
-
const port = requestedPort + offset
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
await app.listen({ port, hostname })
|
|
32
|
-
break
|
|
33
|
-
} catch (error) {
|
|
34
|
-
if (!isAddressInUse(error) || offset === attempts - 1) {
|
|
35
|
-
throw error
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
console.warn(`Port ${port} is in use, trying ${port + 1}...`)
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function isAddressInUse(error: unknown): boolean {
|
|
43
|
-
return Boolean(
|
|
44
|
-
error &&
|
|
45
|
-
typeof error === 'object' &&
|
|
46
|
-
'code' in error &&
|
|
47
|
-
(error as { code?: unknown }).code === 'EADDRINUSE',
|
|
48
|
-
)
|
|
49
|
-
}
|
|
15
|
+
// The walk past a busy port lives in listen() now, which is also the only
|
|
16
|
+
// place that can report which port it ended up on. Set GUREN_STRICT_PORT=1 to
|
|
17
|
+
// fail fast instead — what an automated consumer wants when it has to know
|
|
18
|
+
// the app under test is the one answering.
|
|
19
|
+
await app.listen({ port, hostname })
|
|
@@ -18,13 +18,13 @@
|
|
|
18
18
|
"test": "bun test"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@guren/cli": "^2.
|
|
22
|
-
"@guren/core": "^1.
|
|
23
|
-
"@guren/orm": "^2.
|
|
21
|
+
"@guren/cli": "^2.5.0",
|
|
22
|
+
"@guren/core": "^1.6.1",
|
|
23
|
+
"@guren/orm": "^2.4.0",
|
|
24
24
|
"drizzle-orm": "1.0.0-rc.4"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@guren/testing": "^1.
|
|
27
|
+
"@guren/testing": "^1.5.0",
|
|
28
28
|
"bun-types": "^1.3.1",
|
|
29
29
|
"drizzle-kit": "1.0.0-rc.4",
|
|
30
30
|
"typescript": "^5.4.0"
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Generated — DO NOT EDIT
|
|
2
2
|
// Run `guren codegen` to regenerate.
|
|
3
3
|
|
|
4
|
+
import type { Data } from './data.gen'
|
|
5
|
+
|
|
4
6
|
/**
|
|
5
7
|
* Typed API route registry.
|
|
6
8
|
* Use with `createApiClient<ApiRoutes>()` for end-to-end type safety.
|
|
@@ -8,89 +10,81 @@
|
|
|
8
10
|
* `body` is the *request* shape — what you send. Coercing schemas are rendered
|
|
9
11
|
* as they travel: `z.coerce.date()` is a `string` here, not the `Date` the
|
|
10
12
|
* controller ends up with. `response` is the parsed shape you get back.
|
|
13
|
+
* Params are not stored on the entries: they are derived from each entry's
|
|
14
|
+
* `path` literal, the same string the server routes on.
|
|
11
15
|
*/
|
|
12
16
|
export interface ApiRoutes {
|
|
13
17
|
'dashboard': {
|
|
14
18
|
method: 'GET'
|
|
15
19
|
path: '/dashboard'
|
|
16
|
-
params: Record<string, never>
|
|
17
20
|
}
|
|
18
21
|
'home': {
|
|
19
22
|
method: 'GET'
|
|
20
23
|
path: '/'
|
|
21
|
-
params: Record<string, never>
|
|
22
24
|
}
|
|
23
25
|
'login': {
|
|
24
26
|
method: 'GET'
|
|
25
27
|
path: '/login'
|
|
26
|
-
params: Record<string, never>
|
|
27
28
|
}
|
|
28
29
|
'login.store': {
|
|
29
30
|
method: 'POST'
|
|
30
31
|
path: '/login'
|
|
31
|
-
params: Record<string, never>
|
|
32
32
|
}
|
|
33
33
|
'logout': {
|
|
34
34
|
method: 'POST'
|
|
35
35
|
path: '/logout'
|
|
36
|
-
params: Record<string, never>
|
|
37
36
|
}
|
|
38
37
|
'posts.create': {
|
|
39
38
|
method: 'GET'
|
|
40
39
|
path: '/posts/create'
|
|
41
|
-
params: Record<string, never>
|
|
42
40
|
}
|
|
43
41
|
'posts.destroy': {
|
|
44
42
|
method: 'DELETE'
|
|
45
43
|
path: '/posts/:id'
|
|
46
|
-
params: { id: string | number }
|
|
47
44
|
}
|
|
48
45
|
'posts.edit': {
|
|
49
46
|
method: 'GET'
|
|
50
47
|
path: '/posts/:id/edit'
|
|
51
|
-
params: { id: string | number }
|
|
52
48
|
}
|
|
53
49
|
'posts.index': {
|
|
54
50
|
method: 'GET'
|
|
55
51
|
path: '/posts'
|
|
56
|
-
|
|
52
|
+
}
|
|
53
|
+
'posts.search': {
|
|
54
|
+
method: 'QUERY'
|
|
55
|
+
path: '/posts/search'
|
|
56
|
+
body: { keywords: string[]; limit?: number }
|
|
57
|
+
response: { data: Array<Data.Post> }
|
|
57
58
|
}
|
|
58
59
|
'posts.show': {
|
|
59
60
|
method: 'GET'
|
|
60
61
|
path: '/posts/:id'
|
|
61
|
-
params: { id: string | number }
|
|
62
62
|
}
|
|
63
63
|
'posts.store': {
|
|
64
64
|
method: 'POST'
|
|
65
65
|
path: '/posts'
|
|
66
|
-
params: Record<string, never>
|
|
67
66
|
body: { title: string; excerpt: string; body: string }
|
|
68
67
|
}
|
|
69
68
|
'posts.update': {
|
|
70
69
|
method: 'PUT'
|
|
71
70
|
path: '/posts/:id'
|
|
72
|
-
params: { id: string | number }
|
|
73
71
|
body: { title: string; excerpt: string; body: string }
|
|
74
72
|
}
|
|
75
73
|
'profile.edit': {
|
|
76
74
|
method: 'GET'
|
|
77
75
|
path: '/profile'
|
|
78
|
-
params: Record<string, never>
|
|
79
76
|
}
|
|
80
77
|
'profile.update': {
|
|
81
78
|
method: 'PUT'
|
|
82
79
|
path: '/profile'
|
|
83
|
-
params: Record<string, never>
|
|
84
80
|
}
|
|
85
81
|
'register': {
|
|
86
82
|
method: 'GET'
|
|
87
83
|
path: '/register'
|
|
88
|
-
params: Record<string, never>
|
|
89
84
|
}
|
|
90
85
|
'register.store': {
|
|
91
86
|
method: 'POST'
|
|
92
87
|
path: '/register'
|
|
93
|
-
params: Record<string, never>
|
|
94
88
|
}
|
|
95
89
|
}
|
|
96
90
|
|
|
@@ -98,19 +92,135 @@ export type ApiRouteName = keyof ApiRoutes
|
|
|
98
92
|
|
|
99
93
|
export type ApiRouteMethod<T extends ApiRouteName> = ApiRoutes[T]['method']
|
|
100
94
|
export type ApiRoutePath<T extends ApiRouteName> = ApiRoutes[T]['path']
|
|
101
|
-
export type ApiRouteParams<T extends ApiRouteName> = ApiRoutes[T]['params']
|
|
102
95
|
|
|
103
|
-
type
|
|
104
|
-
|
|
96
|
+
type SegmentParamKey<TSegment extends string> = TSegment extends `:${infer TParam}`
|
|
97
|
+
? TParam extends `${infer TName}{${string}`
|
|
98
|
+
? TName
|
|
99
|
+
: TParam extends `${infer TName}?`
|
|
100
|
+
? TName
|
|
101
|
+
: TParam
|
|
102
|
+
: never
|
|
103
|
+
type PathParamKeys<TPath extends string> = TPath extends `${infer THead}/${infer TRest}`
|
|
104
|
+
? SegmentParamKey<THead> | PathParamKeys<TRest>
|
|
105
|
+
: SegmentParamKey<TPath>
|
|
106
|
+
type HasPathParams<TPath extends string> = [PathParamKeys<TPath>] extends [never] ? false : true
|
|
107
|
+
type PathParamsOf<TPath extends string> =
|
|
108
|
+
HasPathParams<TPath> extends false
|
|
109
|
+
? Record<string, never>
|
|
110
|
+
: { [TKey in PathParamKeys<TPath>]: string | number }
|
|
111
|
+
|
|
112
|
+
export type ApiRouteParams<T extends ApiRouteName> = PathParamsOf<ApiRoutePath<T>>
|
|
113
|
+
|
|
114
|
+
// The request body type a route declares through its bound schema — `unknown`
|
|
115
|
+
// for routes without one.
|
|
116
|
+
type BodyOf<TRoute> = TRoute extends { body: infer TBody } ? TBody : unknown
|
|
117
|
+
|
|
118
|
+
// The parsed shape a route declares through its bound output schema —
|
|
119
|
+
// `unknown` for routes without one.
|
|
120
|
+
type ResponseOf<TRoute> = TRoute extends { response: infer TResponse } ? TResponse : unknown
|
|
121
|
+
|
|
122
|
+
// The runtime object is the plain fetch `Response`; only `json()` is narrowed
|
|
123
|
+
// to the route's declared response shape.
|
|
124
|
+
export interface TypedResponse<TData> extends Response {
|
|
125
|
+
json(): Promise<TData>
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Params derive from the path literal, so nothing about how the entries above
|
|
129
|
+
// are emitted can silently flip `request()`'s call arity. Deliberately not
|
|
130
|
+
// distributed over a union route name (the conditional checks
|
|
131
|
+
// `HasPathParams<...>`, never a bare type parameter): the union of paths
|
|
132
|
+
// yields the union of their param keys, so an un-narrowed name requires every
|
|
133
|
+
// member's params — substituting a param a member's path lacks is a runtime
|
|
134
|
+
// no-op, while the reverse (accepting one member's empty params) would send a
|
|
135
|
+
// path with its `:param` unresolved.
|
|
136
|
+
type RequestOptionsOf<TRoute extends { path: string }> =
|
|
137
|
+
HasPathParams<TRoute['path']> extends false
|
|
138
|
+
? { params?: never; body?: BodyOf<TRoute>; query?: Record<string, unknown> }
|
|
139
|
+
: { params: PathParamsOf<TRoute['path']>; body?: BodyOf<TRoute>; query?: Record<string, unknown> }
|
|
140
|
+
|
|
141
|
+
// Param-less routes may omit the options argument entirely; the same
|
|
142
|
+
// predicate that shapes the options decides the arity.
|
|
143
|
+
type RequestArgsOf<TRoute extends { path: string }> =
|
|
144
|
+
HasPathParams<TRoute['path']> extends false
|
|
145
|
+
? [options?: RequestOptionsOf<TRoute>]
|
|
146
|
+
: [options: RequestOptionsOf<TRoute>]
|
|
105
147
|
|
|
106
|
-
export type ApiRequestOptions<T extends ApiRouteName> =
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
148
|
+
export type ApiRequestOptions<T extends ApiRouteName> = RequestOptionsOf<ApiRoutes[T]>
|
|
149
|
+
|
|
150
|
+
// The wire contract these mirror is owned by Guren's CSRF middleware: it
|
|
151
|
+
// writes the XSRF-TOKEN cookie and reads either header name. Change them
|
|
152
|
+
// together.
|
|
153
|
+
const XSRF_COOKIE_NAME = 'XSRF-TOKEN'
|
|
154
|
+
const XSRF_HEADER_NAME = 'X-XSRF-TOKEN'
|
|
155
|
+
// QUERY (RFC 10008) is deliberately NOT listed even though the server's CSRF
|
|
156
|
+
// default skips it: the redundant token header is harmless there, and keeping
|
|
157
|
+
// it is what makes a server that opts QUERY into protection (the middleware's
|
|
158
|
+
// `methods` option) work with this client unchanged.
|
|
159
|
+
const CSRF_SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
|
|
160
|
+
const CSRF_HEADER_NAMES = [XSRF_HEADER_NAME.toLowerCase(), 'x-csrf-token']
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Read the `XSRF-TOKEN` cookie issued by Guren's CSRF middleware.
|
|
164
|
+
*
|
|
165
|
+
* Reached through `globalThis` so this module stays importable — and
|
|
166
|
+
* type-checkable — outside the browser, where `document` does not exist.
|
|
167
|
+
*/
|
|
168
|
+
function readXsrfToken(): string | undefined {
|
|
169
|
+
const cookies = (globalThis as { document?: { cookie?: string } }).document?.cookie
|
|
170
|
+
if (!cookies) return undefined
|
|
171
|
+
for (const part of cookies.split(';')) {
|
|
172
|
+
const entry = part.trim()
|
|
173
|
+
if (!entry.startsWith(`${XSRF_COOKIE_NAME}=`)) continue
|
|
174
|
+
const value = entry.slice(XSRF_COOKIE_NAME.length + 1)
|
|
175
|
+
try {
|
|
176
|
+
return decodeURIComponent(value)
|
|
177
|
+
} catch {
|
|
178
|
+
return value
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return undefined
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Whether `url` targets the page's own origin.
|
|
186
|
+
*
|
|
187
|
+
* The `XSRF-TOKEN` cookie belongs to that origin, so it must never ride along
|
|
188
|
+
* to a third-party `baseUrl`: that would hand this page's CSRF token to
|
|
189
|
+
* another server, which a permissive CORS policy there is enough to accept.
|
|
190
|
+
* Outside the browser there is no origin — and no cookie — so nothing is sent.
|
|
191
|
+
*/
|
|
192
|
+
function isSameOrigin(url: string): boolean {
|
|
193
|
+
const location = (globalThis as { location?: { href?: string; origin?: string } }).location
|
|
194
|
+
if (!location?.href || !location.origin) return false
|
|
195
|
+
try {
|
|
196
|
+
return new URL(url, location.href).origin === location.origin
|
|
197
|
+
} catch {
|
|
198
|
+
return false
|
|
199
|
+
}
|
|
200
|
+
}
|
|
110
201
|
|
|
111
202
|
/**
|
|
112
203
|
* Create a typed API client for consuming Guren routes.
|
|
113
204
|
*
|
|
205
|
+
* Same-origin state-changing requests automatically copy the `XSRF-TOKEN`
|
|
206
|
+
* cookie into the `X-XSRF-TOKEN` header, which is what Guren's CSRF
|
|
207
|
+
* middleware expects. Pass your own `X-XSRF-TOKEN` / `X-CSRF-TOKEN` header
|
|
208
|
+
* to opt out — you have to, for a `baseUrl` on another origin (the cookie is
|
|
209
|
+
* never sent there) or for a server configured with `csrf({ cookie: false })`.
|
|
210
|
+
* Cookies follow the `credentials` option (`'same-origin'` by default; use
|
|
211
|
+
* `'include'` cross-origin, with a CORS setup that allows it).
|
|
212
|
+
*
|
|
213
|
+
* Routes that bind a `body` schema type the `body` option with that schema's
|
|
214
|
+
* request shape; routes without one accept `unknown`. Routes that bind an
|
|
215
|
+
* `output` schema type the response: `json()` on the returned `Response`
|
|
216
|
+
* resolves to that schema's parsed shape. A `resource` response hint types
|
|
217
|
+
* `json()` the same way from the `Data` types extracted out of
|
|
218
|
+
* app/Http/Resources — declared, not validated: the server never checks the
|
|
219
|
+
* payload against it at runtime. Without either, `json()` resolves to
|
|
220
|
+
* `unknown` — validate before trusting it. Either way the typed shape
|
|
221
|
+
* describes the success body only: error statuses carry their own (a 422
|
|
222
|
+
* from validation is `{ errors: ... }`), so check `ok` before reading it.
|
|
223
|
+
*
|
|
114
224
|
* @example
|
|
115
225
|
* ```typescript
|
|
116
226
|
* import type { ApiRoutes } from '@/.guren/api-client.gen'
|
|
@@ -120,26 +230,41 @@ export type ApiRequestOptions<T extends ApiRouteName> =
|
|
|
120
230
|
* const post = await client.request('posts.show', { params: { id: 1 } })
|
|
121
231
|
* ```
|
|
122
232
|
*/
|
|
123
|
-
|
|
124
|
-
|
|
233
|
+
// Token-based substitution shared with the route manifest module: whole
|
|
234
|
+
// `:param` tokens are replaced by key lookup, so a key the path lacks is a
|
|
235
|
+
// true no-op — the property the union-name rule above relies on — and a
|
|
236
|
+
// param name that prefixes another (`:id` vs `:identifier`) cannot corrupt
|
|
237
|
+
// it the way a per-key `path.replace(':key', ...)` loop would.
|
|
238
|
+
function substituteParams(path: string, params?: Record<string, string | number>): string {
|
|
239
|
+
if (!params) {
|
|
240
|
+
return path
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return path.replace(/(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu, (match, prefix, key) => {
|
|
244
|
+
if (!Object.prototype.hasOwnProperty.call(params, key)) {
|
|
245
|
+
return match
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return `${prefix}${encodeURIComponent(String(params[key]))}`
|
|
249
|
+
})
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// The mapped-object constraint (rather than `Record<...>`) is what lets the
|
|
253
|
+
// generated `ApiRoutes` interface satisfy it — interfaces have no implicit
|
|
254
|
+
// index signature, so `Record<string, ...>` would reject them.
|
|
255
|
+
export function createApiClient<TRoutes extends { [K in keyof TRoutes]: { method: string; path: string } }>(
|
|
256
|
+
config: { baseUrl: string; headers?: Record<string, string>; credentials?: RequestInit['credentials'] },
|
|
125
257
|
) {
|
|
126
258
|
return {
|
|
127
259
|
async request<TName extends keyof TRoutes & string>(
|
|
128
260
|
name: TName,
|
|
129
|
-
...args:
|
|
130
|
-
|
|
131
|
-
: [options: { params: TRoutes[TName]['params']; body?: unknown; query?: Record<string, unknown> }]
|
|
132
|
-
): Promise<Response> {
|
|
261
|
+
...args: RequestArgsOf<TRoutes[TName]>
|
|
262
|
+
): Promise<TypedResponse<ResponseOf<TRoutes[TName]>>> {
|
|
133
263
|
const route = (routes as Record<string, { method: string; path: string }>)[name]
|
|
134
264
|
if (!route) throw new Error(`Route [${name}] not defined.`)
|
|
135
265
|
|
|
136
|
-
const opts = (args as unknown[])[0] as { params?: Record<string,
|
|
137
|
-
|
|
138
|
-
if (opts?.params) {
|
|
139
|
-
for (const [key, value] of Object.entries(opts.params)) {
|
|
140
|
-
path = path.replace(`:${key}`, encodeURIComponent(String(value)))
|
|
141
|
-
}
|
|
142
|
-
}
|
|
266
|
+
const opts = (args as unknown[])[0] as { params?: Record<string, string | number>; body?: unknown; query?: Record<string, unknown> } | undefined
|
|
267
|
+
const path = substituteParams(route.path, opts?.params)
|
|
143
268
|
|
|
144
269
|
let url = `${config.baseUrl}${path}`
|
|
145
270
|
if (opts?.query) {
|
|
@@ -151,11 +276,23 @@ export function createApiClient<TRoutes extends Record<string, { method: string;
|
|
|
151
276
|
if (qs) url += `?${qs}`
|
|
152
277
|
}
|
|
153
278
|
|
|
279
|
+
const method = route.method.toUpperCase()
|
|
280
|
+
const headers: Record<string, string> = { 'Content-Type': 'application/json', ...config.headers }
|
|
281
|
+
if (
|
|
282
|
+
!CSRF_SAFE_METHODS.includes(method) &&
|
|
283
|
+
!Object.keys(headers).some((key) => CSRF_HEADER_NAMES.includes(key.toLowerCase())) &&
|
|
284
|
+
isSameOrigin(url)
|
|
285
|
+
) {
|
|
286
|
+
const token = readXsrfToken()
|
|
287
|
+
if (token) headers[XSRF_HEADER_NAME] = token
|
|
288
|
+
}
|
|
289
|
+
|
|
154
290
|
const init: RequestInit = {
|
|
155
|
-
method
|
|
156
|
-
headers
|
|
291
|
+
method,
|
|
292
|
+
headers,
|
|
293
|
+
credentials: config.credentials ?? 'same-origin',
|
|
157
294
|
}
|
|
158
|
-
if (opts?.body &&
|
|
295
|
+
if (opts?.body && method !== 'GET') {
|
|
159
296
|
init.body = JSON.stringify(opts.body)
|
|
160
297
|
}
|
|
161
298
|
|
|
@@ -174,6 +311,7 @@ const routes: Record<string, { method: string; path: string }> = {
|
|
|
174
311
|
'posts.destroy': { method: 'DELETE', path: '/posts/:id' },
|
|
175
312
|
'posts.edit': { method: 'GET', path: '/posts/:id/edit' },
|
|
176
313
|
'posts.index': { method: 'GET', path: '/posts' },
|
|
314
|
+
'posts.search': { method: 'QUERY', path: '/posts/search' },
|
|
177
315
|
'posts.show': { method: 'GET', path: '/posts/:id' },
|
|
178
316
|
'posts.store': { method: 'POST', path: '/posts' },
|
|
179
317
|
'posts.update': { method: 'PUT', path: '/posts/:id' },
|
|
@@ -11,6 +11,7 @@ export const routeManifest = {
|
|
|
11
11
|
'posts.destroy': { method: 'DELETE', path: '/posts/:id' },
|
|
12
12
|
'posts.edit': { method: 'GET', path: '/posts/:id/edit' },
|
|
13
13
|
'posts.index': { method: 'GET', path: '/posts' },
|
|
14
|
+
'posts.search': { method: 'QUERY', path: '/posts/search' },
|
|
14
15
|
'posts.show': { method: 'GET', path: '/posts/:id' },
|
|
15
16
|
'posts.store': { method: 'POST', path: '/posts' },
|
|
16
17
|
'posts.update': { method: 'PUT', path: '/posts/:id' },
|
|
@@ -29,26 +30,31 @@ type PrimitiveQueryValue = string | number | boolean | null | undefined
|
|
|
29
30
|
type QueryValue = PrimitiveQueryValue | readonly PrimitiveQueryValue[]
|
|
30
31
|
export type RouteQuery = Record<string, QueryValue>
|
|
31
32
|
|
|
32
|
-
type
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
33
|
+
type SegmentParamKey<TSegment extends string> = TSegment extends `:${infer TParam}`
|
|
34
|
+
? TParam extends `${infer TName}{${string}`
|
|
35
|
+
? TName
|
|
36
|
+
: TParam extends `${infer TName}?`
|
|
37
|
+
? TName
|
|
38
|
+
: TParam
|
|
39
|
+
: never
|
|
40
|
+
type PathParamKeys<TPath extends string> = TPath extends `${infer THead}/${infer TRest}`
|
|
41
|
+
? SegmentParamKey<THead> | PathParamKeys<TRest>
|
|
42
|
+
: SegmentParamKey<TPath>
|
|
43
|
+
type HasPathParams<TPath extends string> = [PathParamKeys<TPath>] extends [never] ? false : true
|
|
44
|
+
type PathParamsOf<TPath extends string> =
|
|
45
|
+
HasPathParams<TPath> extends false
|
|
42
46
|
? Record<string, never>
|
|
43
|
-
: { [TKey in PathParamKeys<
|
|
47
|
+
: { [TKey in PathParamKeys<TPath>]: string | number }
|
|
48
|
+
|
|
49
|
+
export type RouteParams<TName extends RouteName> = PathParamsOf<RouteManifest[TName]['path']>
|
|
44
50
|
|
|
45
51
|
type RouteArgs<TName extends RouteName> =
|
|
46
|
-
|
|
52
|
+
HasPathParams<RouteManifest[TName]['path']> extends false
|
|
47
53
|
? [query?: RouteQuery]
|
|
48
54
|
: [params: RouteParams<TName>, query?: RouteQuery]
|
|
49
55
|
|
|
50
56
|
export function route<TName extends RouteName>(name: TName, ...args: RouteArgs<TName>): string {
|
|
51
|
-
const definition = routeManifest[name]
|
|
57
|
+
const definition: { method: RouteMethod; path: RoutePath } | undefined = routeManifest[name]
|
|
52
58
|
if (!definition) {
|
|
53
59
|
throw new Error(`Route [${String(name)}] not defined.`)
|
|
54
60
|
}
|
|
@@ -75,6 +81,7 @@ export const routes = {
|
|
|
75
81
|
destroy: (params: RouteParams<'posts.destroy'>, query?: RouteQuery) => route('posts.destroy', params, query),
|
|
76
82
|
edit: (params: RouteParams<'posts.edit'>, query?: RouteQuery) => route('posts.edit', params, query),
|
|
77
83
|
index: (query?: RouteQuery) => route('posts.index', query),
|
|
84
|
+
search: (query?: RouteQuery) => route('posts.search', query),
|
|
78
85
|
show: (params: RouteParams<'posts.show'>, query?: RouteQuery) => route('posts.show', params, query),
|
|
79
86
|
store: (query?: RouteQuery) => route('posts.store', query),
|
|
80
87
|
update: (params: RouteParams<'posts.update'>, query?: RouteQuery) => route('posts.update', params, query)
|
|
@@ -92,7 +99,7 @@ export const routes = {
|
|
|
92
99
|
} as const
|
|
93
100
|
|
|
94
101
|
function hasPathParams(path: string): boolean {
|
|
95
|
-
return
|
|
102
|
+
return /(?:^|\/):[A-Za-z0-9_-]/u.test(path)
|
|
96
103
|
}
|
|
97
104
|
|
|
98
105
|
function substituteParams(path: string, params?: Record<string, string | number>): string {
|
|
@@ -100,12 +107,12 @@ function substituteParams(path: string, params?: Record<string, string | number>
|
|
|
100
107
|
return path
|
|
101
108
|
}
|
|
102
109
|
|
|
103
|
-
return path.replace(
|
|
110
|
+
return path.replace(/(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu, (match, prefix, key) => {
|
|
104
111
|
if (!Object.prototype.hasOwnProperty.call(params, key)) {
|
|
105
112
|
return match
|
|
106
113
|
}
|
|
107
114
|
|
|
108
|
-
return encodeURIComponent(String(params[key]))
|
|
115
|
+
return `${prefix}${encodeURIComponent(String(params[key]))}`
|
|
109
116
|
})
|
|
110
117
|
}
|
|
111
118
|
|