create-guren-app 1.7.2 → 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 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 'drizzle-orm/mysql-core'
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 'drizzle-orm/sqlite-core'
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
- let harnessInstalled = false;
2262
- if (installed) {
2263
- consola.start("Setting up AI agent harness...");
2264
- harnessInstalled = await runAppCli(targetDir, ["agent:init"]);
2265
- if (harnessInstalled) {
2266
- consola.success("AI agent harness installed (CLAUDE.md, .claude/, .mcp.json)");
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-guren-app",
3
- "version": "1.7.2",
3
+ "version": "1.8.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,3 +1,3 @@
1
- import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'
1
+ import { sqliteTable, integer, text } from '@guren/orm/drizzle/sqlite'
2
2
 
3
3
  export const schema = {}
@@ -18,9 +18,9 @@
18
18
  "test": "bun test"
19
19
  },
20
20
  "dependencies": {
21
- "@guren/cli": "^2.4.0",
22
- "@guren/core": "^1.6.0",
23
- "@guren/orm": "^2.3.0",
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": {
@@ -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
- params: Record<string, never>
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 HasParams<T extends ApiRouteName> =
104
- [keyof ApiRoutes[T]['params']] extends [never] ? false : true
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
- HasParams<T> extends true
108
- ? { params: ApiRouteParams<T>; body?: unknown; query?: Record<string, unknown> }
109
- : { params?: never; body?: unknown; query?: Record<string, unknown> }
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
- export function createApiClient<TRoutes extends Record<string, { method: string; path: string; params: unknown }>>(
124
- config: { baseUrl: string; headers?: Record<string, string> },
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: [keyof TRoutes[TName]['params']] extends [never]
130
- ? [options?: { body?: unknown; query?: Record<string, unknown> }]
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, unknown>; body?: unknown; query?: Record<string, unknown> } | undefined
137
- let path = route.path
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: route.method,
156
- headers: { 'Content-Type': 'application/json', ...config.headers },
291
+ method,
292
+ headers,
293
+ credentials: config.credentials ?? 'same-origin',
157
294
  }
158
- if (opts?.body && route.method !== 'GET') {
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 NormalizeParamKey<TValue extends string> = TValue extends `${infer Key}?` ? Key : TValue
33
- type PathParamKeys<TPath extends string> =
34
- TPath extends `${string}:${infer Param}/${infer Rest}`
35
- ? NormalizeParamKey<Param> | PathParamKeys<`/${Rest}`>
36
- : TPath extends `${string}:${infer Param}`
37
- ? NormalizeParamKey<Param>
38
- : never
39
-
40
- export type RouteParams<TName extends RouteName> =
41
- [PathParamKeys<RouteManifest[TName]['path']>] extends [never]
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<RouteManifest[TName]['path']>]: string | number }
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
- [PathParamKeys<RouteManifest[TName]['path']>] extends [never]
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 /:[A-Za-z0-9_-]+/u.test(path)
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(/:([A-Za-z0-9_-]+)/gu, (match, key) => {
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
 
@@ -24,6 +24,17 @@ the database container.
24
24
  - `/` — landing page with the latest posts
25
25
  - `/posts` — paginated post list, `/posts/:id` — a single post
26
26
  - `/posts/create`, `/posts/:id/edit` — write and edit, signed in only
27
+ - `QUERY /posts/search` — JSON search endpoint using the HTTP QUERY method
28
+ ([RFC 10008](https://www.rfc-editor.org/info/rfc10008/)): safe like GET, but
29
+ the criteria travel in a JSON body. The posts page calls it through the
30
+ generated typed client (`.guren/api-client.gen.ts`), or try it directly:
31
+
32
+ ```bash
33
+ curl --request QUERY http://localhost:3333/posts/search \
34
+ --header 'content-type: application/json' \
35
+ --data '{"keywords":["guren"]}'
36
+ ```
37
+
27
38
  - `/login`, `/register`, `/dashboard`, `/profile` — session authentication
28
39
 
29
40
  Posts belong to their author. `app/Providers/AuthorizationProvider.ts` binds
@@ -3,7 +3,7 @@ import { pages } from '@/.guren/pages.gen'
3
3
  import { Post } from '../../Models/Post.js'
4
4
  import type { UserRecord } from '../../Models/User.js'
5
5
  import { PostResource, type PostResourceData } from '../Resources/PostResource.js'
6
- import { PostIdParamSchema, PostPayloadSchema, ListPostsQuerySchema } from '../Validators/PostValidator.js'
6
+ import { PostIdParamSchema, PostPayloadSchema, PostSearchSchema, ListPostsQuerySchema } from '../Validators/PostValidator.js'
7
7
 
8
8
  type PostsIndexProps = PaginatedPageProps<PostResourceData>
9
9
 
@@ -25,6 +25,31 @@ export default class PostController extends Controller {
25
25
  } satisfies PostsIndexProps)
26
26
  }
27
27
 
28
+ // Serves the HTTP QUERY route `posts.search` — a safe read that carries its
29
+ // criteria in a JSON body. Matches posts with any keyword in title or
30
+ // excerpt; `%` and `_` in a keyword act as SQL LIKE wildcards, which this
31
+ // starter treats as a feature. All keyword OR pairs sit inside one
32
+ // `where(callback)`, keeping this an any-keyword match while AND filters
33
+ // added later (a published flag, tenancy) apply to every hit instead of
34
+ // being OR'd away.
35
+ async search(): Promise<Response> {
36
+ const { keywords, limit } = await this.validateBody(PostSearchSchema)
37
+
38
+ const posts = await Post.newQuery()
39
+ .with('author')
40
+ .where((q) => {
41
+ for (const keyword of keywords) {
42
+ const pattern = `%${keyword}%`
43
+ q.orWhere('title', 'like', pattern).orWhere('excerpt', 'like', pattern)
44
+ }
45
+ })
46
+ .orderBy('id', 'desc')
47
+ .limit(limit)
48
+ .get()
49
+
50
+ return this.json({ data: PostResource.collection(posts) })
51
+ }
52
+
28
53
  async show(): Promise<Response> {
29
54
  const { id } = this.validateParams(PostIdParamSchema)
30
55
  const post = await Post.findWithOrFail(id, 'author')
@@ -8,6 +8,14 @@ export const ListPostsQuerySchema = z.object({
8
8
  page: z.coerce.number().int().min(1).default(1),
9
9
  })
10
10
 
11
+ export const PostSearchSchema = z.object({
12
+ keywords: z
13
+ .array(z.string().trim().min(1, 'Keywords must not be blank.'))
14
+ .min(1, 'Provide at least one keyword.')
15
+ .max(10, 'Provide at most 10 keywords.'),
16
+ limit: z.number().int().min(1).max(50).default(10),
17
+ })
18
+
11
19
  export const PostPayloadSchema = z.object({
12
20
  title: z.string().trim().min(1, 'Title is required.').max(255, 'Title must be 255 characters or fewer.'),
13
21
  excerpt: z.string().trim().min(1, 'Excerpt is required.').max(500, 'Excerpt must be 500 characters or fewer.'),
@@ -1,8 +1,4 @@
1
- // Imported from drizzle-orm/mysql-core rather than @guren/orm/drizzle, which
2
- // re-exports `text` and `timestamp` from pg-core only — taking them from there
3
- // would build a MySQL table out of PostgreSQL column builders. Drizzle happens
4
- // to emit the same DDL either way today; this does not rely on that.
5
- import { mysqlTable, int, varchar, text, timestamp } from 'drizzle-orm/mysql-core'
1
+ import { mysqlTable, int, varchar, text, timestamp } from '@guren/orm/drizzle/mysql'
6
2
 
7
3
  export const users = mysqlTable('users', {
8
4
  id: int('id').primaryKey().autoincrement(),
@@ -1,4 +1,4 @@
1
- import { pgTable, serial, integer, text, timestamp } from '@guren/orm/drizzle'
1
+ import { pgTable, serial, integer, text, timestamp } from '@guren/orm/drizzle/pg'
2
2
 
3
3
  export const users = pgTable('users', {
4
4
  id: serial('id').primaryKey(),
@@ -1,4 +1,4 @@
1
- import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'
1
+ import { sqliteTable, integer, text } from '@guren/orm/drizzle/sqlite'
2
2
 
3
3
  export const users = sqliteTable('users', {
4
4
  id: integer('id').primaryKey({ autoIncrement: true }),
@@ -1,20 +1,99 @@
1
+ import { useState, type FormEvent } from 'react'
1
2
  import { Head, Link } from '@inertiajs/react'
2
3
  import type { PaginatedPageProps } from '@guren/core'
3
4
  import type { PostResourceData } from '@/app/Http/Resources/PostResource'
4
5
  import { route } from '@/.guren/routes.gen'
6
+ import { createApiClient, type ApiRoutes } from '@/.guren/api-client.gen'
5
7
  import Layout from '../../components/Layout.js'
6
8
 
7
9
  interface Props extends PaginatedPageProps<PostResourceData> {}
8
10
 
11
+ // posts.search is an HTTP QUERY route (RFC 10008): safe like GET, but the
12
+ // criteria travel in a JSON body — HTML forms and Inertia navigation cannot
13
+ // send it, so the page calls it through the generated typed client. The
14
+ // client types the request body from the schema bound to the route, and
15
+ // json() from the `resource` hint the route declares — both come from the
16
+ // route definition, so this file never restates the wire shape.
17
+ const api = createApiClient<ApiRoutes>({ baseUrl: '' })
18
+
9
19
  export default function PostsIndex({ data, pagination }: Props) {
20
+ const [keywords, setKeywords] = useState('')
21
+ const [results, setResults] = useState<PostResourceData[] | null>(null)
22
+ const [searching, setSearching] = useState(false)
23
+ const [error, setError] = useState<string | null>(null)
24
+
25
+ async function search(event: FormEvent) {
26
+ event.preventDefault()
27
+ const terms = keywords.split(/\s+/).filter((term) => term.length > 0)
28
+ if (terms.length === 0) {
29
+ setResults(null)
30
+ setError(null)
31
+ return
32
+ }
33
+
34
+ setSearching(true)
35
+ setError(null)
36
+ try {
37
+ const response = await api.request('posts.search', { body: { keywords: terms } })
38
+ if (!response.ok) {
39
+ setError('Search failed — try fewer or shorter keywords.')
40
+ return
41
+ }
42
+ const payload = await response.json()
43
+ setResults(payload.data)
44
+ } catch {
45
+ setError('Search failed — check your connection and try again.')
46
+ } finally {
47
+ setSearching(false)
48
+ }
49
+ }
50
+
51
+ const posts = results ?? data
52
+
10
53
  return (
11
54
  <Layout>
12
55
  <Head title="Posts" />
13
56
  <section className="space-y-6">
14
57
  <h1 className="text-3xl font-semibold text-emerald-300">Posts</h1>
15
58
 
59
+ <form className="flex gap-2" onSubmit={search}>
60
+ <input
61
+ type="search"
62
+ value={keywords}
63
+ onChange={(event) => setKeywords(event.target.value)}
64
+ placeholder="Search posts…"
65
+ className="w-full rounded border border-slate-700 bg-slate-950 px-3 py-2 text-slate-100 outline-none ring-emerald-400 transition focus:border-emerald-400 focus:ring"
66
+ />
67
+ <button
68
+ type="submit"
69
+ disabled={searching}
70
+ className="rounded border border-emerald-500 px-4 py-2 text-sm text-emerald-200 transition hover:bg-emerald-500/10 disabled:opacity-50"
71
+ >
72
+ Search
73
+ </button>
74
+ </form>
75
+
76
+ {error !== null && <p className="text-sm text-rose-400">{error}</p>}
77
+
78
+ {results !== null && (
79
+ <p className="text-sm text-slate-400">
80
+ {results.length} {results.length === 1 ? 'result' : 'results'} ·{' '}
81
+ <button
82
+ type="button"
83
+ onClick={() => {
84
+ setKeywords('')
85
+ setResults(null)
86
+ setError(null)
87
+ }}
88
+ className="text-emerald-300 transition hover:text-emerald-200"
89
+ >
90
+ Clear
91
+ </button>
92
+ </p>
93
+ )}
94
+
16
95
  <div className="space-y-4">
17
- {data.map((post) => (
96
+ {posts.map((post) => (
18
97
  <article key={post.id} className="rounded-lg border border-slate-800 bg-slate-900/40 p-5">
19
98
  <Link
20
99
  href={route('posts.show', { id: post.id })}
@@ -30,7 +109,7 @@ export default function PostsIndex({ data, pagination }: Props) {
30
109
  ))}
31
110
  </div>
32
111
 
33
- {pagination?.links?.pages && (
112
+ {results === null && pagination?.links?.pages && (
34
113
  <nav className="flex gap-2">
35
114
  {pagination.links.pages.map((page) => (
36
115
  <Link
@@ -1,7 +1,8 @@
1
1
  import { Router, requireAuthenticated, requireGuest } from '@guren/core'
2
2
  import HomeController from '../app/Http/Controllers/HomeController.js'
3
3
  import PostController from '../app/Http/Controllers/PostController.js'
4
- import { PostPayloadSchema } from '../app/Http/Validators/PostValidator.js'
4
+ import { PostPayloadSchema, PostSearchSchema } from '../app/Http/Validators/PostValidator.js'
5
+ import { PostResource } from '../app/Http/Resources/PostResource.js'
5
6
  import { registerAuthRoutes } from './auth.js'
6
7
 
7
8
  export function registerWebRoutes(baseRouter: Router): void {
@@ -30,5 +31,17 @@ export function registerWebRoutes(baseRouter: Router): void {
30
31
 
31
32
  posts.get('/', [PostController, 'index']).name('posts.index')
32
33
  posts.get('/:id', [PostController, 'show']).name('posts.show')
34
+
35
+ // HTTP QUERY (RFC 10008): safe and idempotent like GET, but carries its
36
+ // search criteria in a JSON body. Only fetch-based clients can send it —
37
+ // the posts page calls it through the generated API client. The
38
+ // `resource` hint declares the response shape the controller builds with
39
+ // PostResource, so the client's json() comes back typed — no runtime
40
+ // validation, just the type codegen already extracts from the Resource.
41
+ posts.query('/search', {
42
+ name: 'posts.search',
43
+ body: PostSearchSchema,
44
+ resource: { data: [PostResource] },
45
+ }, [PostController, 'search'])
33
46
  })
34
47
  }
@@ -0,0 +1,22 @@
1
+ import { beforeAll, describe, it } from 'bun:test'
2
+ import { TestApp } from '@guren/testing'
3
+ import app from '../src/app.js'
4
+
5
+ // posts.search is an HTTP QUERY route (RFC 10008). Its controller validates
6
+ // the body with validateBody() before building any query — the schema bound
7
+ // to the route feeds codegen and `guren audit`, while body parsing stays in
8
+ // the controller so the request stream is read once — so an invalid payload
9
+ // gets a 422 without the database ever being touched. That keeps this starter
10
+ // test green without migrations or fixtures; cover the happy path with real
11
+ // feature tests once your test database is set up.
12
+ describe('posts.search', () => {
13
+ let http: TestApp
14
+
15
+ beforeAll(async () => {
16
+ http = await TestApp.fromApp(app)
17
+ })
18
+
19
+ it('rejects a search without keywords', async () => {
20
+ await http.query('/posts/search', { keywords: [] }).assertStatus(422)
21
+ })
22
+ })
@@ -8,6 +8,8 @@
8
8
  * `body` is the *request* shape — what you send. Coercing schemas are rendered
9
9
  * as they travel: `z.coerce.date()` is a `string` here, not the `Date` the
10
10
  * controller ends up with. `response` is the parsed shape you get back.
11
+ * Params are not stored on the entries: they are derived from each entry's
12
+ * `path` literal, the same string the server routes on.
11
13
  */
12
14
  export interface ApiRoutes {
13
15
  // No named routes found
@@ -17,21 +19,70 @@ export type ApiRouteName = keyof ApiRoutes
17
19
 
18
20
  export type ApiRouteMethod<T extends ApiRouteName> = ApiRoutes[T]['method']
19
21
  export type ApiRoutePath<T extends ApiRouteName> = ApiRoutes[T]['path']
20
- export type ApiRouteParams<T extends ApiRouteName> = ApiRoutes[T]['params']
21
22
 
22
- type HasParams<T extends ApiRouteName> =
23
- [keyof ApiRoutes[T]['params']] extends [never] ? false : true
23
+ type SegmentParamKey<TSegment extends string> = TSegment extends `:${infer TParam}`
24
+ ? TParam extends `${infer TName}{${string}`
25
+ ? TName
26
+ : TParam extends `${infer TName}?`
27
+ ? TName
28
+ : TParam
29
+ : never
30
+ type PathParamKeys<TPath extends string> = TPath extends `${infer THead}/${infer TRest}`
31
+ ? SegmentParamKey<THead> | PathParamKeys<TRest>
32
+ : SegmentParamKey<TPath>
33
+ type HasPathParams<TPath extends string> = [PathParamKeys<TPath>] extends [never] ? false : true
34
+ type PathParamsOf<TPath extends string> =
35
+ HasPathParams<TPath> extends false
36
+ ? Record<string, never>
37
+ : { [TKey in PathParamKeys<TPath>]: string | number }
38
+
39
+ export type ApiRouteParams<T extends ApiRouteName> = PathParamsOf<ApiRoutePath<T>>
40
+
41
+ // The request body type a route declares through its bound schema — `unknown`
42
+ // for routes without one.
43
+ type BodyOf<TRoute> = TRoute extends { body: infer TBody } ? TBody : unknown
44
+
45
+ // The parsed shape a route declares through its bound output schema —
46
+ // `unknown` for routes without one.
47
+ type ResponseOf<TRoute> = TRoute extends { response: infer TResponse } ? TResponse : unknown
48
+
49
+ // The runtime object is the plain fetch `Response`; only `json()` is narrowed
50
+ // to the route's declared response shape.
51
+ export interface TypedResponse<TData> extends Response {
52
+ json(): Promise<TData>
53
+ }
24
54
 
25
- export type ApiRequestOptions<T extends ApiRouteName> =
26
- HasParams<T> extends true
27
- ? { params: ApiRouteParams<T>; body?: unknown; query?: Record<string, unknown> }
28
- : { params?: never; body?: unknown; query?: Record<string, unknown> }
55
+ // Params derive from the path literal, so nothing about how the entries above
56
+ // are emitted can silently flip `request()`'s call arity. Deliberately not
57
+ // distributed over a union route name (the conditional checks
58
+ // `HasPathParams<...>`, never a bare type parameter): the union of paths
59
+ // yields the union of their param keys, so an un-narrowed name requires every
60
+ // member's params — substituting a param a member's path lacks is a runtime
61
+ // no-op, while the reverse (accepting one member's empty params) would send a
62
+ // path with its `:param` unresolved.
63
+ type RequestOptionsOf<TRoute extends { path: string }> =
64
+ HasPathParams<TRoute['path']> extends false
65
+ ? { params?: never; body?: BodyOf<TRoute>; query?: Record<string, unknown> }
66
+ : { params: PathParamsOf<TRoute['path']>; body?: BodyOf<TRoute>; query?: Record<string, unknown> }
67
+
68
+ // Param-less routes may omit the options argument entirely; the same
69
+ // predicate that shapes the options decides the arity.
70
+ type RequestArgsOf<TRoute extends { path: string }> =
71
+ HasPathParams<TRoute['path']> extends false
72
+ ? [options?: RequestOptionsOf<TRoute>]
73
+ : [options: RequestOptionsOf<TRoute>]
74
+
75
+ export type ApiRequestOptions<T extends ApiRouteName> = RequestOptionsOf<ApiRoutes[T]>
29
76
 
30
77
  // The wire contract these mirror is owned by Guren's CSRF middleware: it
31
78
  // writes the XSRF-TOKEN cookie and reads either header name. Change them
32
79
  // together.
33
80
  const XSRF_COOKIE_NAME = 'XSRF-TOKEN'
34
81
  const XSRF_HEADER_NAME = 'X-XSRF-TOKEN'
82
+ // QUERY (RFC 10008) is deliberately NOT listed even though the server's CSRF
83
+ // default skips it: the redundant token header is harmless there, and keeping
84
+ // it is what makes a server that opts QUERY into protection (the middleware's
85
+ // `methods` option) work with this client unchanged.
35
86
  const CSRF_SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
36
87
  const CSRF_HEADER_NAMES = [XSRF_HEADER_NAME.toLowerCase(), 'x-csrf-token']
37
88
 
@@ -86,6 +137,17 @@ function isSameOrigin(url: string): boolean {
86
137
  * Cookies follow the `credentials` option (`'same-origin'` by default; use
87
138
  * `'include'` cross-origin, with a CORS setup that allows it).
88
139
  *
140
+ * Routes that bind a `body` schema type the `body` option with that schema's
141
+ * request shape; routes without one accept `unknown`. Routes that bind an
142
+ * `output` schema type the response: `json()` on the returned `Response`
143
+ * resolves to that schema's parsed shape. A `resource` response hint types
144
+ * `json()` the same way from the `Data` types extracted out of
145
+ * app/Http/Resources — declared, not validated: the server never checks the
146
+ * payload against it at runtime. Without either, `json()` resolves to
147
+ * `unknown` — validate before trusting it. Either way the typed shape
148
+ * describes the success body only: error statuses carry their own (a 422
149
+ * from validation is `{ errors: ... }`), so check `ok` before reading it.
150
+ *
89
151
  * @example
90
152
  * ```typescript
91
153
  * import type { ApiRoutes } from '@/.guren/api-client.gen'
@@ -95,26 +157,41 @@ function isSameOrigin(url: string): boolean {
95
157
  * const post = await client.request('posts.show', { params: { id: 1 } })
96
158
  * ```
97
159
  */
98
- export function createApiClient<TRoutes extends Record<string, { method: string; path: string; params: unknown }>>(
160
+ // Token-based substitution shared with the route manifest module: whole
161
+ // `:param` tokens are replaced by key lookup, so a key the path lacks is a
162
+ // true no-op — the property the union-name rule above relies on — and a
163
+ // param name that prefixes another (`:id` vs `:identifier`) cannot corrupt
164
+ // it the way a per-key `path.replace(':key', ...)` loop would.
165
+ function substituteParams(path: string, params?: Record<string, string | number>): string {
166
+ if (!params) {
167
+ return path
168
+ }
169
+
170
+ return path.replace(/(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu, (match, prefix, key) => {
171
+ if (!Object.prototype.hasOwnProperty.call(params, key)) {
172
+ return match
173
+ }
174
+
175
+ return `${prefix}${encodeURIComponent(String(params[key]))}`
176
+ })
177
+ }
178
+
179
+ // The mapped-object constraint (rather than `Record<...>`) is what lets the
180
+ // generated `ApiRoutes` interface satisfy it — interfaces have no implicit
181
+ // index signature, so `Record<string, ...>` would reject them.
182
+ export function createApiClient<TRoutes extends { [K in keyof TRoutes]: { method: string; path: string } }>(
99
183
  config: { baseUrl: string; headers?: Record<string, string>; credentials?: RequestInit['credentials'] },
100
184
  ) {
101
185
  return {
102
186
  async request<TName extends keyof TRoutes & string>(
103
187
  name: TName,
104
- ...args: [keyof TRoutes[TName]['params']] extends [never]
105
- ? [options?: { body?: unknown; query?: Record<string, unknown> }]
106
- : [options: { params: TRoutes[TName]['params']; body?: unknown; query?: Record<string, unknown> }]
107
- ): Promise<Response> {
188
+ ...args: RequestArgsOf<TRoutes[TName]>
189
+ ): Promise<TypedResponse<ResponseOf<TRoutes[TName]>>> {
108
190
  const route = (routes as Record<string, { method: string; path: string }>)[name]
109
191
  if (!route) throw new Error(`Route [${name}] not defined.`)
110
192
 
111
- const opts = (args as unknown[])[0] as { params?: Record<string, unknown>; body?: unknown; query?: Record<string, unknown> } | undefined
112
- let path = route.path
113
- if (opts?.params) {
114
- for (const [key, value] of Object.entries(opts.params)) {
115
- path = path.replace(`:${key}`, encodeURIComponent(String(value)))
116
- }
117
- }
193
+ const opts = (args as unknown[])[0] as { params?: Record<string, string | number>; body?: unknown; query?: Record<string, unknown> } | undefined
194
+ const path = substituteParams(route.path, opts?.params)
118
195
 
119
196
  let url = `${config.baseUrl}${path}`
120
197
  if (opts?.query) {
@@ -22,7 +22,9 @@ export function isPageId(value: string): value is PageId {
22
22
  * Auto-extracted Props types from page components.
23
23
  */
24
24
  export interface PagePropsMap {
25
- 'Home': Record<string, unknown>
25
+ 'Home': {
26
+ message: string
27
+ }
26
28
  }
27
29
 
28
30
  export type InferPageProps<TId extends PageId> =
@@ -43,5 +45,5 @@ function defineGeneratedPage<TId extends string, TProps extends PagePropsRecord
43
45
  }
44
46
 
45
47
  export const pages = {
46
- Home: defineGeneratedPage('Home', pageManifest['Home'])
48
+ Home: defineGeneratedPage<'Home', PagePropsMap['Home']>('Home', pageManifest['Home'])
47
49
  } as const
@@ -7,33 +7,38 @@ export const routeManifest = {
7
7
 
8
8
  export type RouteManifest = typeof routeManifest
9
9
  export type RouteName = keyof RouteManifest
10
- export type RouteMethod = RouteManifest[RouteName]['method']
11
- export type RoutePath = RouteManifest[RouteName]['path']
10
+ export type RouteMethod = [RouteName] extends [never] ? string : RouteManifest[RouteName]['method']
11
+ export type RoutePath = [RouteName] extends [never] ? string : RouteManifest[RouteName]['path']
12
12
 
13
13
  type PrimitiveQueryValue = string | number | boolean | null | undefined
14
14
  type QueryValue = PrimitiveQueryValue | readonly PrimitiveQueryValue[]
15
15
  export type RouteQuery = Record<string, QueryValue>
16
16
 
17
- type NormalizeParamKey<TValue extends string> = TValue extends `${infer Key}?` ? Key : TValue
18
- type PathParamKeys<TPath extends string> =
19
- TPath extends `${string}:${infer Param}/${infer Rest}`
20
- ? NormalizeParamKey<Param> | PathParamKeys<`/${Rest}`>
21
- : TPath extends `${string}:${infer Param}`
22
- ? NormalizeParamKey<Param>
23
- : never
24
-
25
- export type RouteParams<TName extends RouteName> =
26
- [PathParamKeys<RouteManifest[TName]['path']>] extends [never]
17
+ type SegmentParamKey<TSegment extends string> = TSegment extends `:${infer TParam}`
18
+ ? TParam extends `${infer TName}{${string}`
19
+ ? TName
20
+ : TParam extends `${infer TName}?`
21
+ ? TName
22
+ : TParam
23
+ : never
24
+ type PathParamKeys<TPath extends string> = TPath extends `${infer THead}/${infer TRest}`
25
+ ? SegmentParamKey<THead> | PathParamKeys<TRest>
26
+ : SegmentParamKey<TPath>
27
+ type HasPathParams<TPath extends string> = [PathParamKeys<TPath>] extends [never] ? false : true
28
+ type PathParamsOf<TPath extends string> =
29
+ HasPathParams<TPath> extends false
27
30
  ? Record<string, never>
28
- : { [TKey in PathParamKeys<RouteManifest[TName]['path']>]: string | number }
31
+ : { [TKey in PathParamKeys<TPath>]: string | number }
32
+
33
+ export type RouteParams<TName extends RouteName> = PathParamsOf<RouteManifest[TName]['path']>
29
34
 
30
35
  type RouteArgs<TName extends RouteName> =
31
- [PathParamKeys<RouteManifest[TName]['path']>] extends [never]
36
+ HasPathParams<RouteManifest[TName]['path']> extends false
32
37
  ? [query?: RouteQuery]
33
38
  : [params: RouteParams<TName>, query?: RouteQuery]
34
39
 
35
40
  export function route<TName extends RouteName>(name: TName, ...args: RouteArgs<TName>): string {
36
- const definition = routeManifest[name]
41
+ const definition: { method: RouteMethod; path: RoutePath } | undefined = routeManifest[name]
37
42
  if (!definition) {
38
43
  throw new Error(`Route [${String(name)}] not defined.`)
39
44
  }
@@ -50,7 +55,7 @@ export const routes = {
50
55
  } as const
51
56
 
52
57
  function hasPathParams(path: string): boolean {
53
- return /:[A-Za-z0-9_-]+/u.test(path)
58
+ return /(?:^|\/):[A-Za-z0-9_-]/u.test(path)
54
59
  }
55
60
 
56
61
  function substituteParams(path: string, params?: Record<string, string | number>): string {
@@ -58,12 +63,12 @@ function substituteParams(path: string, params?: Record<string, string | number>
58
63
  return path
59
64
  }
60
65
 
61
- return path.replace(/:([A-Za-z0-9_-]+)/gu, (match, key) => {
66
+ return path.replace(/(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu, (match, prefix, key) => {
62
67
  if (!Object.prototype.hasOwnProperty.call(params, key)) {
63
68
  return match
64
69
  }
65
70
 
66
- return encodeURIComponent(String(params[key]))
71
+ return `${prefix}${encodeURIComponent(String(params[key]))}`
67
72
  })
68
73
  }
69
74
 
@@ -1,4 +1,4 @@
1
- import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'
1
+ import { sqliteTable, integer, text } from '@guren/orm/drizzle/sqlite'
2
2
 
3
3
  export const users = sqliteTable('users', {
4
4
  id: integer('id').primaryKey({ autoIncrement: true }),
@@ -19,10 +19,10 @@
19
19
  "db:seed": "bunx guren db:seed"
20
20
  },
21
21
  "dependencies": {
22
- "@guren/cli": "^2.4.0",
23
- "@guren/core": "^1.6.0",
24
- "@guren/inertia-client": "^1.1.0",
25
- "@guren/orm": "^2.3.0",
22
+ "@guren/cli": "^2.5.0",
23
+ "@guren/core": "^1.6.1",
24
+ "@guren/inertia-client": "^1.1.1",
25
+ "@guren/orm": "^2.4.0",
26
26
  "@inertiajs/react": "^3.6.1",
27
27
  "drizzle-orm": "1.0.0-rc.4",
28
28
  "react": "^19.0.0",