@guren/server 2.4.0 → 2.6.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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  McpServiceProvider
3
- } from "./chunk-5WL2FTC4.js";
3
+ } from "./chunk-YSOJKAAU.js";
4
4
  import "./chunk-Q2P6YLRR.js";
5
5
  import "./chunk-LHR6OHI7.js";
6
6
  export {
@@ -47,7 +47,7 @@ export type DefaultSanitizedKeys = 'password' | 'passwordHash' | 'password_hash'
47
47
  * conventional credential keys plus any extra keys passed as `Hidden`.
48
48
  *
49
49
  * The runtime strips exactly the *configured* password/remember-token
50
- * columns plus the model's `static hidden` — a static type cannot see
50
+ * columns plus the model's `hidden` fields — a static type cannot see
51
51
  * that configuration. If your columns use other names, or the model
52
52
  * hides additional fields, list them in `Hidden` explicitly. Only
53
53
  * meaningful for concrete record types (index-signature records like
@@ -1,4 +1,4 @@
1
- export type { AuthUser, GateCallback, GateDefinition, PolicyMethod, PolicyResult, Policy as PolicyInterface, PolicyClass, AuthorizationResponse, GateOptions, AuthorizeOptions, PolicyRegistration, ResourceAction, ResponseBuilder, } from './types.js';
1
+ export type { AuthUser, GateCallback, GateDefinition, PolicyMethod, PolicyResult, Policy as PolicyInterface, PolicyClass, AuthorizationResponse, GateOptions, AuthorizeOptions, AuthorizeResourceOptions, PolicyRegistration, ResourceAction, ResponseBuilder, } from './types.js';
2
2
  export { Gate, Response, isAuthorizationResponse, createGate, setGate, getGate, defineGate, can, cannot, authorize, } from './Gate.js';
3
3
  export { Policy, definePolicy } from './Policy.js';
4
4
  export { authorizeMiddleware, authorizeAllMiddleware, authorizeResourceMiddleware, withAuthorization, } from './middleware.js';
@@ -15,7 +15,7 @@ import {
15
15
  isAuthorizationResponse,
16
16
  setGate,
17
17
  withAuthorization
18
- } from "../chunk-7OB2YXRE.js";
18
+ } from "../chunk-T2FFUU6J.js";
19
19
  import "../chunk-63SKW5PS.js";
20
20
  import "../chunk-DAQKYKLH.js";
21
21
  export {
@@ -1,6 +1,6 @@
1
1
  import type { Context } from '../http/Application.js';
2
2
  import type { Middleware } from '../http/middleware/index.js';
3
- import type { AuthorizeOptions } from './types.js';
3
+ import type { AuthorizeOptions, AuthorizeResourceOptions } from './types.js';
4
4
  import { Gate } from './Gate.js';
5
5
  /**
6
6
  * Middleware to authorize an ability.
@@ -26,14 +26,25 @@ export declare function authorizeAllMiddleware(abilities: string[], modelResolve
26
26
  * Middleware factory for resource authorization.
27
27
  * Automatically maps HTTP methods to policy abilities.
28
28
  *
29
+ * Methods outside the built-in mapping (custom verbs registered via
30
+ * `router.on()`) are denied with a 403 rather than downgraded to a `view`
31
+ * check — the middleware cannot know whether an unknown verb mutates, so
32
+ * guessing would let a view-only user reach a mutating handler. Map custom
33
+ * verbs explicitly with `options.abilityFor`.
34
+ *
29
35
  * @example
30
36
  * ```typescript
31
37
  * // Authorize resource actions based on HTTP method
32
38
  * app.use('/posts/:id', authorizeResourceMiddleware(getPost))
33
- * // GET -> view, POST -> create, PUT/PATCH -> update, DELETE -> delete
39
+ * // GET/HEAD/QUERY -> view, POST -> create, PUT/PATCH -> update, DELETE -> delete
40
+ *
41
+ * // Custom verbs must be mapped explicitly, or they are denied
42
+ * authorizeResourceMiddleware(getPost, {
43
+ * abilityFor: (method) => (method === 'PURGE' ? 'delete' : undefined),
44
+ * })
34
45
  * ```
35
46
  */
36
- export declare function authorizeResourceMiddleware(modelResolver: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeOptions): Middleware;
47
+ export declare function authorizeResourceMiddleware(modelResolver: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeResourceOptions): Middleware;
37
48
  /**
38
49
  * Create a gate-aware context with authorization helpers.
39
50
  */
@@ -82,6 +82,18 @@ export interface AuthorizeOptions {
82
82
  */
83
83
  status?: number;
84
84
  }
85
+ /**
86
+ * Options for `authorizeResourceMiddleware`.
87
+ */
88
+ export interface AuthorizeResourceOptions extends AuthorizeOptions {
89
+ /**
90
+ * Map an HTTP method (always uppercased) to a policy ability, overriding
91
+ * or extending the built-in mapping. Return `undefined` to fall back to
92
+ * the default mapping; a method with no ability from either source is
93
+ * denied with a 403.
94
+ */
95
+ abilityFor?: (method: string) => string | undefined;
96
+ }
85
97
  /**
86
98
  * Policy registration.
87
99
  */
@@ -6,7 +6,7 @@ import standard from "figlet/importable-fonts/Standard.js";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@guren/server",
9
- version: "2.4.0",
9
+ version: "2.6.0",
10
10
  type: "module",
11
11
  license: "MIT",
12
12
  repository: {
@@ -119,7 +119,7 @@ var package_default = {
119
119
  test: "bun test"
120
120
  },
121
121
  dependencies: {
122
- "@guren/orm": "^2.2.2",
122
+ "@guren/orm": "^2.4.0",
123
123
  "@modelcontextprotocol/sdk": "^1.30.0",
124
124
  chalk: "^5.3.0",
125
125
  consola: "^3.4.2",
@@ -419,27 +419,21 @@ function authorizeAllMiddleware(abilities, modelResolver, options = {}) {
419
419
  await next();
420
420
  };
421
421
  }
422
+ var RESOURCE_ABILITY_BY_METHOD = {
423
+ GET: "view",
424
+ HEAD: "view",
425
+ QUERY: "view",
426
+ POST: "create",
427
+ PUT: "update",
428
+ PATCH: "update",
429
+ DELETE: "delete"
430
+ };
422
431
  function authorizeResourceMiddleware(modelResolver, options = {}) {
423
432
  return async (ctx, next) => {
424
433
  const method = ctx.req.method.toUpperCase();
425
- let ability;
426
- switch (method) {
427
- case "GET":
428
- case "HEAD":
429
- ability = "view";
430
- break;
431
- case "POST":
432
- ability = "create";
433
- break;
434
- case "PUT":
435
- case "PATCH":
436
- ability = "update";
437
- break;
438
- case "DELETE":
439
- ability = "delete";
440
- break;
441
- default:
442
- ability = "view";
434
+ const ability = options.abilityFor?.(method) ?? RESOURCE_ABILITY_BY_METHOD[method];
435
+ if (ability === void 0) {
436
+ throw new AuthorizationException(options.message ?? "This action is unauthorized.");
443
437
  }
444
438
  const gate = getGate();
445
439
  const user = await gate.resolveUser(ctx);
@@ -190,6 +190,7 @@ function createMcpServer(options) {
190
190
  const options2 = { cwd, force: true };
191
191
  const generated = [];
192
192
  const skipped = [];
193
+ const warnings = [];
193
194
  let failed = false;
194
195
  const run = async (artifacts, generate) => {
195
196
  try {
@@ -199,6 +200,7 @@ function createMcpServer(options) {
199
200
  } else {
200
201
  generated.push(...artifacts);
201
202
  }
203
+ if (result?.warnings) warnings.push(...result.warnings);
202
204
  return result;
203
205
  } catch (error) {
204
206
  failed = true;
@@ -213,16 +215,16 @@ function createMcpServer(options) {
213
215
  () => cli.generateRouteTypes(options2)
214
216
  );
215
217
  await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options2));
216
- await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options2));
218
+ const data = await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options2));
217
219
  await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options2));
218
220
  await run([".guren/api-client.gen.ts"], () => {
219
221
  if (!routes?.definitions) {
220
222
  throw new Error("route generation produced no manifest to build a client from");
221
223
  }
222
- return cli.generateApiClientTypes(routes.definitions, options2);
224
+ return cli.generateApiClientTypes(routes.definitions, { ...options2, resources: data?.definitions });
223
225
  });
224
226
  return {
225
- content: [{ type: "text", text: JSON.stringify({ generated, skipped }, null, 2) }],
227
+ content: [{ type: "text", text: JSON.stringify({ generated, skipped, warnings }, null, 2) }],
226
228
  // A generator that found nothing to describe is not a failure — an
227
229
  // app with no page components is a normal shape — so only a thrown
228
230
  // one makes the run an error, even when other artifacts landed.
@@ -10,7 +10,51 @@ import type { TranslationLoader } from '../i18n/index.js';
10
10
  import { type SecurityHeadersOptions } from './middleware/security-headers.js';
11
11
  import { type HostAuthorizationOptions } from './middleware/host-authorization.js';
12
12
  import { type DevBannerOptions } from './dev-banner.js';
13
- import { type StartViteDevServerOptions } from './vite-dev-server.js';
13
+ import { startViteDevServer, type StartViteDevServerOptions } from './vite-dev-server.js';
14
+ type BunServer = {
15
+ stop?: (closeConnections?: boolean) => void | Promise<void>;
16
+ requestIP?: (request: Request) => {
17
+ address?: string;
18
+ } | null;
19
+ port?: number;
20
+ hostname?: string;
21
+ };
22
+ type ViteServer = Awaited<ReturnType<typeof startViteDevServer>>['server'];
23
+ /**
24
+ * The one managed Vite dev server this process runs, and who owns it.
25
+ *
26
+ * The owner matters because a dev server outlives the `listen()` that started
27
+ * it: on a `bun --hot` reload the next `listen()` adopts the running server
28
+ * rather than restarting it, and both applications then hold the same object.
29
+ * Instance identity cannot tell those two apart — it is the same server — so
30
+ * "may I close this?" is answered here instead, by the slot naming exactly one
31
+ * owner at a time.
32
+ */
33
+ export interface ActiveViteDevServer {
34
+ readonly server: ViteServer;
35
+ readonly localUrl: string;
36
+ readonly owner: Application;
37
+ /**
38
+ * Detaches the owner's process teardown handlers. Whoever replaces this
39
+ * record calls it, because the outgoing owner is only reachable from here —
40
+ * and a set of handlers left attached would still close this server, and run
41
+ * its own `process.exit()`, on the next signal.
42
+ */
43
+ readonly disposeTeardown: () => void;
44
+ }
45
+ /**
46
+ * The ambient slots `listen()` plants on `globalThis` so a `bun --hot` reload,
47
+ * which re-runs the entrypoint but keeps `globalThis`, can find what the
48
+ * previous run left running.
49
+ *
50
+ * Exported so the tests that plant stand-ins in these slots can name them
51
+ * against this declaration instead of restating it. Not part of the public
52
+ * API: `src/index.ts` re-exports by name and does not list it.
53
+ */
54
+ export interface GurenGlobalSlots {
55
+ __gurenActiveServer?: BunServer;
56
+ __gurenActiveViteDevServer?: ActiveViteDevServer;
57
+ }
14
58
  export type BootCallback = (app: Hono) => void | Promise<void>;
15
59
  /**
16
60
  * Service provider class constructor type.
@@ -145,6 +189,11 @@ export interface ListenAddress {
145
189
  *
146
190
  * It embeds a DI Container as the backbone of the framework, binding core
147
191
  * services and managing providers through the container's ProviderManager.
192
+ *
193
+ * Lifecycle rule for `listen()`/`stop()` and their helpers: re-check ownership
194
+ * after every `await`. Any server or slot they remembered can have been
195
+ * superseded by a concurrent call while they waited, and only the current
196
+ * owner may clear shared state.
148
197
  */
149
198
  export declare class Application {
150
199
  private readonly options;
@@ -153,11 +202,20 @@ export declare class Application {
153
202
  readonly router: Router;
154
203
  private readonly providerManager;
155
204
  private readonly authManager;
156
- private viteDevServer?;
157
205
  private bunServer?;
158
206
  private boundAddress?;
159
- private viteTeardownRegistered;
160
- private bunTeardownRegistered;
207
+ /**
208
+ * Detaches the Bun half's process teardown handlers, and doubles as the "are
209
+ * they attached?" memo. One field rather than a separate boolean: a memo and
210
+ * an undo that can disagree is how handlers end up attached while a flag says
211
+ * otherwise — see {@link registerProcessTeardown}.
212
+ *
213
+ * The Vite half's disposer lives in {@link ActiveViteDevServer} instead,
214
+ * because the application that detaches those handlers is not always the one
215
+ * that attached them: adoption moves the server to a new owner, and the
216
+ * outgoing owner is only reachable through the slot.
217
+ */
218
+ private disposeBunTeardown?;
161
219
  private autoSessionAttached;
162
220
  private routesRegistered;
163
221
  private bootPromise?;
@@ -227,12 +285,40 @@ export declare class Application {
227
285
  * carries.
228
286
  *
229
287
  * Liveness is only as good as the signal available: a server stopped through
230
- * the framework — a later `listen()`, the process-exit teardown — clears the
231
- * slot this reads, but one stopped by calling `stop()` on the Bun server
232
- * directly does not, and this keeps reporting its address. Treat it as
233
- * "where `listen()` put this app", not as a health check.
288
+ * the framework — {@link Application.stop}, a later `listen()`, the
289
+ * process-exit teardown — clears what this reads, but one stopped by reaching
290
+ * past the framework to the Bun server's own `stop()` does not, and this keeps
291
+ * reporting its address. Treat it as "where `listen()` put this app", not as a
292
+ * health check.
234
293
  */
235
294
  get address(): ListenAddress | undefined;
295
+ /**
296
+ * Stops the server {@link listen} started, undoing that call.
297
+ *
298
+ * Safe to call when nothing is listening, and safe to call twice — both are
299
+ * no-ops. A later `listen()` starts cleanly, so an app may be stopped and
300
+ * restarted in one process.
301
+ *
302
+ * `closeActiveConnections` forces in-flight requests closed instead of
303
+ * waiting for them, matching Bun's own `stop()` parameter. It defaults to
304
+ * `false` (graceful) because a caller reaching for a public stop is usually
305
+ * shutting down deliberately; the hot-reload path inside `listen()` forces
306
+ * the close, since a reload must not wait on the server it is replacing.
307
+ *
308
+ * The managed Vite dev server is taken down too. `listen()` is what started
309
+ * it, and `listen()`'s own bind-failure path already closes the one it
310
+ * started — leaving it running here would strand an asset server, and its
311
+ * published env vars, in a process with no application server. That close is
312
+ * best-effort on the same terms as every other path: it is bounded by
313
+ * {@link viteCloseTimeoutMs}, and a Vite server that overruns the bound is
314
+ * warned about and abandoned rather than holding this call open. A dev server
315
+ * a later `listen()` has adopted is left alone — it belongs to that call now.
316
+ *
317
+ * The stop itself is bounded by {@link bunStopTimeoutMs}: a graceful stop
318
+ * waits on in-flight requests, and one that never finishes would otherwise
319
+ * hold this call open forever.
320
+ */
321
+ stop(closeActiveConnections?: boolean): Promise<void>;
236
322
  /**
237
323
  * Register a service provider.
238
324
  */
@@ -245,7 +331,25 @@ export declare class Application {
245
331
  * Logs the rich development server banner to the console.
246
332
  */
247
333
  logDevServerBanner(options: DevBannerOptions): void;
334
+ /**
335
+ * Closes the managed Vite dev server, but only while this application still
336
+ * owns it.
337
+ *
338
+ * Ownership is the whole check. A `listen()` elsewhere in the process may
339
+ * have adopted the running server — same object, new owner — and closing it
340
+ * then would take the asset server, and its published env vars, out from
341
+ * under an application that is actively serving from it. The record in the
342
+ * slot is the one place that distinction exists, so it is read here rather
343
+ * than mirrored on the instance.
344
+ */
248
345
  private closeViteDevServer;
346
+ /**
347
+ * Attaches this application's Vite teardown handlers and returns the disposer
348
+ * that detaches them. The disposer is stored in the active-record slot rather
349
+ * than on this instance, because whoever takes ownership next is the one that
350
+ * has to call it — and a disposer another app could spend would leave this
351
+ * instance believing its handlers are attached when they are not.
352
+ */
249
353
  private registerViteTeardown;
250
354
  private registerBunTeardown;
251
355
  }
@@ -7,7 +7,7 @@ export interface CorsOptions {
7
7
  * - A function: dynamic origin evaluation
8
8
  */
9
9
  origin?: string | string[] | ((origin: string, ctx: unknown) => string | undefined | null);
10
- /** Allowed HTTP methods. Default: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'] */
10
+ /** Allowed HTTP methods. Default: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY'] */
11
11
  allowMethods?: string[];
12
12
  /** Allowed request headers. */
13
13
  allowHeaders?: string[];
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { parseRequestPayload, formatValidationErrors } from './http/request.js';
4
4
  export { Controller } from './mvc/Controller.js';
5
5
  export type { InertiaResponse, InferInertiaProps, ControllerInertiaProps, AuthPayload } from './mvc/Controller.js';
6
6
  export { Router } from './mvc/Router.js';
7
- export type { RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceRouteOptions, } from './mvc/Router.js';
7
+ export type { RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
8
8
  export { ViewEngine } from './mvc/ViewEngine.js';
9
9
  export { inertia, setInertiaSsrRenderer, setInertiaDocument } from './mvc/inertia/InertiaEngine.js';
10
10
  export { setInertiaSharedProps, getInertiaSharedPropsResolver, shareInertiaProps } from './mvc/inertia/shared.js';
@@ -52,7 +52,7 @@ export type { ErrorResponse, ExceptionHandlerOptions, ExceptionReporter, Excepti
52
52
  export { Command, Input, Output, BufferedOutput, ConsoleKernel, createConsoleKernel, parseSignature, } from './console/index.js';
53
53
  export type { ArgumentDefinition, OptionDefinition, ParsedSignature, CommandClass, CommandInstance, ConsoleKernelOptions, OutputInterface, InputInterface, ScheduledCommand, PromptInterface, ProgressInterface, } from './console/index.js';
54
54
  export { Gate, Response as AuthResponse, createGate, setGate, getGate, defineGate, can, cannot, authorize as authorizeAbility, Policy, definePolicy, authorizeMiddleware, authorizeAllMiddleware, authorizeResourceMiddleware, withAuthorization, } from './authorization/index.js';
55
- export type { AuthUser, GateCallback, GateDefinition, PolicyMethod, PolicyInterface, PolicyClass, AuthorizationResponse, GateOptions, AuthorizeOptions, PolicyRegistration, ResourceAction, ResponseBuilder, AuthorizedContext, } from './authorization/index.js';
55
+ export type { AuthUser, GateCallback, GateDefinition, PolicyMethod, PolicyInterface, PolicyClass, AuthorizationResponse, GateOptions, AuthorizeOptions, AuthorizeResourceOptions, PolicyRegistration, ResourceAction, ResponseBuilder, AuthorizedContext, } from './authorization/index.js';
56
56
  export { Encrypter, generateKey, generateAppKey, normalizeAppKey, parseAppKey, parsePreviousAppKeys, getAppKeyringFromEnv, deriveAppKey, deriveAppKeyring, createEncrypter, setEncrypter, getEncrypter, encrypt, decrypt, MessageSigner, signUrl, verifySignedUrl, hash, hmac, verifyHmac, sha256, sha512, md5, hashPassword, verifyPassword, needsRehash, secureCompare, check as checkHash, randomString, random, randomHex, randomBase64, randomBase64Url, uuid, randomInt, urlSafeToken, generatePassword, generateOtp, generateSlug, shuffle, pick, sample, } from './encryption/index.js';
57
57
  export type { AppKeyring, EncryptOptions, DecryptOptions, EncrypterConfig, EncryptedPayload, SignedMessageClaims, SignMessageOptions, VerifySignedMessageOptions, HashAlgorithm, HmacOptions, PasswordHashOptions, RandomStringOptions, SignedUrlOptions, VerifySignedUrlOptions, } from './encryption/index.js';
58
58
  export { createFacade, createFacades } from './facades/index.js';
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  logDevServerBanner,
6
6
  parseImportMap,
7
7
  startViteDevServer
8
- } from "./chunk-NENDACRP.js";
8
+ } from "./chunk-RGGEGXOE.js";
9
9
  import {
10
10
  PendingSchedule,
11
11
  Schedule,
@@ -201,7 +201,7 @@ import {
201
201
  getGate,
202
202
  setGate,
203
203
  withAuthorization
204
- } from "./chunk-7OB2YXRE.js";
204
+ } from "./chunk-T2FFUU6J.js";
205
205
  import {
206
206
  AuthorizationException,
207
207
  ExceptionHandler,
@@ -492,6 +492,9 @@ var Router = class {
492
492
  delete(path, handlerOrOptions, ...rest) {
493
493
  return this.register("DELETE", path, handlerOrOptions, rest);
494
494
  }
495
+ query(path, handlerOrOptions, ...rest) {
496
+ return this.register("QUERY", path, handlerOrOptions, rest);
497
+ }
495
498
  group(prefix, callback) {
496
499
  this.prefixStack.push(prefix);
497
500
  try {
@@ -549,11 +552,12 @@ var Router = class {
549
552
  this.modelBindingNames.clear();
550
553
  }
551
554
  definitions() {
552
- return this.registry.map(({ method, path, name, schemas, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings }) => ({
555
+ return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings }) => ({
553
556
  method,
554
557
  path,
555
558
  name,
556
559
  schemas,
560
+ resource: serializeResourceHint(resource),
557
561
  middlewareNames: [...routeMiddlewareNames],
558
562
  // Route-local only, so a group-scoped handler does not make every route
559
563
  // in the group report middleware it never attached (`guren audit` warns
@@ -672,6 +676,7 @@ var Router = class {
672
676
  };
673
677
  function applyRouteContract(route, options) {
674
678
  route.schemas = { params: options.params, query: options.query, body: options.body, output: options.output };
679
+ route.resource = options.resource;
675
680
  route.openapi = {
676
681
  summary: options.summary,
677
682
  description: options.description,
@@ -711,6 +716,12 @@ var RouterMiddlewareGroupBuilder = class {
711
716
  delete(path, handlerOrOptions, ...rest) {
712
717
  return this.router.applyMiddlewareScope(this.items, () => this.router.delete(path, handlerOrOptions, ...rest));
713
718
  }
719
+ query(path, handlerOrOptions, ...rest) {
720
+ return this.router.applyMiddlewareScope(this.items, () => this.router.query(path, handlerOrOptions, ...rest));
721
+ }
722
+ on(method, path, handlerOrOptions, ...rest) {
723
+ return this.router.applyMiddlewareScope(this.items, () => this.router.on(method, path, handlerOrOptions, ...rest));
724
+ }
714
725
  };
715
726
  function createRouteBuilder(route, namedRoutes) {
716
727
  return {
@@ -727,12 +738,16 @@ function createRouteBuilder(route, namedRoutes) {
727
738
  }
728
739
  };
729
740
  }
741
+ var PATH_PARAM_PATTERN = /(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu;
742
+ function extractPathParamNames(path) {
743
+ return Array.from(path.matchAll(PATH_PARAM_PATTERN), (match) => match[2]);
744
+ }
730
745
  function substituteParams(path, params) {
731
- return path.replace(/:([A-Za-z0-9_-]+)/gu, (match, key) => {
746
+ return path.replace(PATH_PARAM_PATTERN, (match, prefix, key) => {
732
747
  if (!Object.prototype.hasOwnProperty.call(params, key)) {
733
748
  return match;
734
749
  }
735
- return encodeURIComponent(String(params[key]));
750
+ return `${prefix}${encodeURIComponent(String(params[key]))}`;
736
751
  });
737
752
  }
738
753
  function createContractHandler(path, options, handler) {
@@ -910,7 +925,7 @@ async function resolveModelBindings(c, modelBindings, path) {
910
925
  }
911
926
  const resolved = [];
912
927
  const params = c.req.param();
913
- const pathParams = path?.match(/:([a-zA-Z0-9_-]+)/g)?.map((p) => p.slice(1)) ?? [];
928
+ const pathParams = path ? extractPathParamNames(path) : [];
914
929
  for (const param of pathParams) {
915
930
  const resolver = modelBindings.get(param);
916
931
  if (!resolver) continue;
@@ -950,15 +965,34 @@ function buildResponse(result) {
950
965
  }
951
966
  function serializeBindings(path, routeBindings, routerBindingNames) {
952
967
  const entries = /* @__PURE__ */ new Map();
953
- for (const param of path.match(/:(\w+)/g) ?? []) {
954
- const name = routerBindingNames.get(param.slice(1));
955
- if (name) entries.set(param.slice(1), name);
968
+ for (const param of extractPathParamNames(path)) {
969
+ const name = routerBindingNames.get(param);
970
+ if (name) entries.set(param, name);
956
971
  }
957
972
  for (const [param, model] of routeBindings ?? []) {
958
973
  if (model.name) entries.set(param, model.name);
959
974
  }
960
975
  return entries.size > 0 ? Object.fromEntries(entries) : void 0;
961
976
  }
977
+ function serializeResourceHint(hint) {
978
+ if (hint === void 0) {
979
+ return void 0;
980
+ }
981
+ if (typeof hint === "function") {
982
+ return hint.name || void 0;
983
+ }
984
+ if (Array.isArray(hint)) {
985
+ const inner = serializeResourceHint(hint[0]);
986
+ return inner === void 0 ? void 0 : [inner];
987
+ }
988
+ const entries = [];
989
+ for (const [key, value] of Object.entries(hint)) {
990
+ const serialized = serializeResourceHint(value);
991
+ if (serialized === void 0) return void 0;
992
+ entries.push([key, serialized]);
993
+ }
994
+ return Object.fromEntries(entries);
995
+ }
962
996
  function isControllerAction(action) {
963
997
  return Array.isArray(action);
964
998
  }
@@ -966,7 +1000,7 @@ function isRouteContractOptions(value) {
966
1000
  if (!value || typeof value !== "object" || Array.isArray(value)) {
967
1001
  return false;
968
1002
  }
969
- return "params" in value || "query" in value || "body" in value || "output" in value || "bind" in value || "name" in value || "middlewares" in value || "summary" in value || "description" in value || "tags" in value || "operationId" in value || "deprecated" in value;
1003
+ return "params" in value || "query" in value || "body" in value || "output" in value || "resource" in value || "bind" in value || "name" in value || "middlewares" in value || "summary" in value || "description" in value || "tags" in value || "operationId" in value || "deprecated" in value;
970
1004
  }
971
1005
  function joinPaths(prefixStack, path) {
972
1006
  const segments = [...prefixStack, path].filter(Boolean).map(trimSlashes).filter(Boolean);
@@ -1669,6 +1703,7 @@ function isExcluded2(path, patterns) {
1669
1703
 
1670
1704
  // src/http/middleware/cors.ts
1671
1705
  import { cors } from "hono/cors";
1706
+ var DEFAULT_ALLOW_METHODS = ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "QUERY"];
1672
1707
  function createCorsMiddleware(options = {}) {
1673
1708
  if (options.credentials && !options.origin) {
1674
1709
  throw new Error(
@@ -1678,11 +1713,11 @@ function createCorsMiddleware(options = {}) {
1678
1713
  const origin = options.origin ?? (() => "");
1679
1714
  return cors({
1680
1715
  origin,
1681
- allowMethods: options.allowMethods,
1682
- allowHeaders: options.allowHeaders,
1683
- exposeHeaders: options.exposeHeaders,
1684
- maxAge: options.maxAge,
1685
- credentials: options.credentials
1716
+ allowMethods: options.allowMethods ?? DEFAULT_ALLOW_METHODS,
1717
+ ...options.allowHeaders !== void 0 && { allowHeaders: options.allowHeaders },
1718
+ ...options.exposeHeaders !== void 0 && { exposeHeaders: options.exposeHeaders },
1719
+ ...options.maxAge !== void 0 && { maxAge: options.maxAge },
1720
+ ...options.credentials !== void 0 && { credentials: options.credentials }
1686
1721
  });
1687
1722
  }
1688
1723
 
@@ -2698,6 +2733,9 @@ function clearManagedViteEnv() {
2698
2733
  }
2699
2734
  if (process.env[MANAGED_VITE_ENV_FLAG] === "1") {
2700
2735
  delete process.env.VITE_DEV_SERVER_URL;
2736
+ if (process.env.GUREN_INERTIA_ENTRY?.endsWith(DEFAULT_DEV_ENTRY_PATH)) {
2737
+ delete process.env.GUREN_INERTIA_ENTRY;
2738
+ }
2701
2739
  }
2702
2740
  delete process.env[MANAGED_VITE_ENV_FLAG];
2703
2741
  }
@@ -2717,6 +2755,43 @@ function syncManagedInertiaDevEntry(devServerUrl) {
2717
2755
  function getGlobalState() {
2718
2756
  return globalThis;
2719
2757
  }
2758
+ function bunStopTimeoutMs() {
2759
+ return shutdownTimeoutMs("GUREN_BUN_STOP_TIMEOUT_MS");
2760
+ }
2761
+ function shutdownTimeoutMs(envName) {
2762
+ const parsed = typeof process !== "undefined" ? Number.parseInt(process.env[envName] ?? "", 10) : Number.NaN;
2763
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 5e3;
2764
+ }
2765
+ async function awaitBounded(work, timeoutMs, onTimeout) {
2766
+ let timer;
2767
+ try {
2768
+ const timedOut = await Promise.race([
2769
+ work.then(() => false),
2770
+ new Promise((resolve2) => {
2771
+ timer = setTimeout(() => resolve2(true), timeoutMs);
2772
+ })
2773
+ ]);
2774
+ if (timedOut) {
2775
+ onTimeout(timeoutMs);
2776
+ }
2777
+ } finally {
2778
+ clearTimeout(timer);
2779
+ }
2780
+ }
2781
+ async function stopBunServerBounded(server, closeActiveConnections) {
2782
+ const stopped = (async () => {
2783
+ try {
2784
+ await server.stop?.(closeActiveConnections);
2785
+ } catch (error) {
2786
+ console.warn("Failed to stop Bun server:", error);
2787
+ }
2788
+ })();
2789
+ await awaitBounded(stopped, bunStopTimeoutMs(), (timeoutMs) => {
2790
+ console.warn(
2791
+ `Bun server did not stop within ${timeoutMs}ms \u2014 no longer waiting on it. In-flight requests may still be draining.`
2792
+ );
2793
+ });
2794
+ }
2720
2795
  async function stopActiveBunServer(closeActiveConnections = false) {
2721
2796
  const state = getGlobalState();
2722
2797
  const previous = state.__gurenActiveServer;
@@ -2725,69 +2800,84 @@ async function stopActiveBunServer(closeActiveConnections = false) {
2725
2800
  return;
2726
2801
  }
2727
2802
  try {
2728
- await Promise.resolve(previous.stop(closeActiveConnections));
2729
- } catch (error) {
2730
- console.warn("Failed to stop previous Bun server:", error);
2803
+ await stopBunServerBounded(previous, closeActiveConnections);
2731
2804
  } finally {
2732
- state.__gurenActiveServer = void 0;
2805
+ releaseActiveBunServer(previous);
2733
2806
  }
2734
2807
  }
2735
2808
  function setActiveBunServer(server) {
2736
2809
  getGlobalState().__gurenActiveServer = server;
2737
2810
  }
2811
+ function releaseActiveBunServer(server) {
2812
+ if (getGlobalState().__gurenActiveServer === server) {
2813
+ setActiveBunServer();
2814
+ }
2815
+ }
2816
+ function registerProcessTeardown(onSignal, onExit) {
2817
+ process.once("SIGINT", onSignal);
2818
+ process.once("SIGTERM", onSignal);
2819
+ process.on("exit", onExit);
2820
+ return () => {
2821
+ process.off("SIGINT", onSignal);
2822
+ process.off("SIGTERM", onSignal);
2823
+ process.off("exit", onExit);
2824
+ };
2825
+ }
2738
2826
  function viteCloseTimeoutMs() {
2739
- const parsed = typeof process !== "undefined" ? Number.parseInt(process.env.GUREN_VITE_CLOSE_TIMEOUT_MS ?? "", 10) : Number.NaN;
2740
- return Number.isInteger(parsed) && parsed > 0 ? parsed : 5e3;
2827
+ return shutdownTimeoutMs("GUREN_VITE_CLOSE_TIMEOUT_MS");
2741
2828
  }
2742
2829
  async function closeViteDevServerBounded(server) {
2743
- let timer;
2744
- const close = server.close().catch((error) => {
2745
- console.warn("Failed to stop Vite dev server:", error);
2746
- });
2747
- try {
2748
- const timeoutMs = viteCloseTimeoutMs();
2749
- const timedOut = await Promise.race([
2750
- close.then(() => false),
2751
- new Promise((resolve2) => {
2752
- timer = setTimeout(() => resolve2(true), timeoutMs);
2753
- })
2754
- ]);
2755
- if (timedOut) {
2756
- console.warn(
2757
- `Vite dev server did not close within ${timeoutMs}ms \u2014 abandoning it. A stale asset server may still hold its port.`
2758
- );
2830
+ const close = (async () => {
2831
+ try {
2832
+ await server.close();
2833
+ } catch (error) {
2834
+ console.warn("Failed to stop Vite dev server:", error);
2759
2835
  }
2760
- } finally {
2761
- clearTimeout(timer);
2762
- }
2836
+ })();
2837
+ await awaitBounded(close, viteCloseTimeoutMs(), (timeoutMs) => {
2838
+ console.warn(
2839
+ `Vite dev server did not close within ${timeoutMs}ms \u2014 abandoning it. A stale asset server may still hold its port.`
2840
+ );
2841
+ });
2763
2842
  }
2764
2843
  async function stopActiveViteDevServer() {
2765
2844
  const previous = getGlobalState().__gurenActiveViteDevServer;
2766
2845
  try {
2767
2846
  if (previous) {
2768
- await closeViteDevServerBounded(previous);
2847
+ await closeViteDevServerBounded(previous.server);
2769
2848
  }
2770
2849
  } finally {
2771
- setActiveViteDevServer();
2772
- clearManagedViteEnv();
2850
+ previous?.disposeTeardown();
2851
+ if (getGlobalState().__gurenActiveViteDevServer === previous) {
2852
+ setActiveViteDevServer();
2853
+ }
2773
2854
  }
2774
2855
  }
2775
- function setActiveViteDevServer(server, localUrl) {
2776
- const state = getGlobalState();
2777
- state.__gurenActiveViteDevServer = server;
2778
- state.__gurenActiveViteDevServerUrl = server ? localUrl : void 0;
2856
+ function publishManagedViteEnv(localUrl) {
2857
+ if (typeof process === "undefined") {
2858
+ return;
2859
+ }
2860
+ process.env.VITE_DEV_SERVER_URL = localUrl;
2861
+ process.env[MANAGED_VITE_ENV_FLAG] = "1";
2862
+ syncManagedInertiaDevEntry(localUrl);
2863
+ }
2864
+ function setActiveViteDevServer(active) {
2865
+ getGlobalState().__gurenActiveViteDevServer = active;
2866
+ if (active) {
2867
+ publishManagedViteEnv(active.localUrl);
2868
+ } else {
2869
+ clearManagedViteEnv();
2870
+ }
2779
2871
  }
2780
2872
  function reusableActiveViteDevServer(viteOption) {
2781
2873
  if (typeof viteOption === "object") {
2782
2874
  return void 0;
2783
2875
  }
2784
- const state = getGlobalState();
2785
- const server = state.__gurenActiveViteDevServer;
2786
- const localUrl = state.__gurenActiveViteDevServerUrl;
2787
- if (!server || !localUrl || !server.httpServer?.listening) {
2876
+ const active = getGlobalState().__gurenActiveViteDevServer;
2877
+ if (!active || !active.server.httpServer?.listening) {
2788
2878
  return void 0;
2789
2879
  }
2790
- return { server, localUrl };
2880
+ return active;
2791
2881
  }
2792
2882
  var Application = class {
2793
2883
  constructor(options = {}) {
@@ -2845,11 +2935,20 @@ var Application = class {
2845
2935
  router;
2846
2936
  providerManager;
2847
2937
  authManager;
2848
- viteDevServer;
2849
2938
  bunServer;
2850
2939
  boundAddress;
2851
- viteTeardownRegistered = false;
2852
- bunTeardownRegistered = false;
2940
+ /**
2941
+ * Detaches the Bun half's process teardown handlers, and doubles as the "are
2942
+ * they attached?" memo. One field rather than a separate boolean: a memo and
2943
+ * an undo that can disagree is how handlers end up attached while a flag says
2944
+ * otherwise — see {@link registerProcessTeardown}.
2945
+ *
2946
+ * The Vite half's disposer lives in {@link ActiveViteDevServer} instead,
2947
+ * because the application that detaches those handlers is not always the one
2948
+ * that attached them: adoption moves the server to a new owner, and the
2949
+ * outgoing owner is only reachable through the slot.
2950
+ */
2951
+ disposeBunTeardown;
2853
2952
  autoSessionAttached = false;
2854
2953
  routesRegistered = false;
2855
2954
  bootPromise;
@@ -2914,7 +3013,7 @@ var Application = class {
2914
3013
  await this.mountRoutes();
2915
3014
  await this.mountDevEndpoint(
2916
3015
  isMcpEndpointEnabled(),
2917
- async () => (await import("./McpServiceProvider-FRJ5O7LT.js")).McpServiceProvider,
3016
+ async () => (await import("./McpServiceProvider-SL7DUZ4G.js")).McpServiceProvider,
2918
3017
  "GUREN_MCP=1 but the MCP endpoint could not load \u2014 is @modelcontextprotocol/sdk installed?"
2919
3018
  );
2920
3019
  await this.mountDevEndpoint(
@@ -2978,21 +3077,25 @@ var Application = class {
2978
3077
  if (!Bun) {
2979
3078
  throw new Error("Bun runtime is required to call Application.listen");
2980
3079
  }
3080
+ const supersededServer = getGlobalState().__gurenActiveServer;
2981
3081
  await stopActiveBunServer(true);
2982
3082
  const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite, portFallback } = options;
2983
3083
  const externalAssetsUrl = typeof process !== "undefined" && process.env?.[MANAGED_VITE_ENV_FLAG] !== "1" ? process.env?.VITE_DEV_SERVER_URL : void 0;
2984
3084
  let resolvedAssetsUrl = assetsUrl ?? externalAssetsUrl;
2985
3085
  const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
2986
3086
  const adoptViteDevServer = (viteServer, localUrl) => {
2987
- this.viteDevServer = viteServer;
2988
- setActiveViteDevServer(viteServer, localUrl);
2989
- resolvedAssetsUrl = localUrl;
2990
- if (typeof process !== "undefined") {
2991
- process.env.VITE_DEV_SERVER_URL = localUrl;
2992
- process.env[MANAGED_VITE_ENV_FLAG] = "1";
3087
+ const displaced2 = getGlobalState().__gurenActiveViteDevServer;
3088
+ displaced2?.disposeTeardown();
3089
+ if (displaced2 && displaced2.server !== viteServer) {
3090
+ void closeViteDevServerBounded(displaced2.server);
2993
3091
  }
2994
- syncManagedInertiaDevEntry(localUrl);
2995
- this.registerViteTeardown();
3092
+ setActiveViteDevServer({
3093
+ server: viteServer,
3094
+ localUrl,
3095
+ owner: this,
3096
+ disposeTeardown: this.registerViteTeardown()
3097
+ });
3098
+ resolvedAssetsUrl = localUrl;
2996
3099
  };
2997
3100
  const reusableVite = shouldStartVite ? reusableActiveViteDevServer(vite) : void 0;
2998
3101
  let startedViteHere = false;
@@ -3004,7 +3107,6 @@ var Application = class {
3004
3107
  if (shouldStartVite && !reusableVite) {
3005
3108
  const viteOptions = typeof vite === "object" ? vite : void 0;
3006
3109
  try {
3007
- await this.closeViteDevServer();
3008
3110
  const { server: server2, localUrl } = await startViteDevServer({
3009
3111
  root: viteOptions?.root ?? process.cwd(),
3010
3112
  config: viteOptions?.config,
@@ -3062,6 +3164,10 @@ var Application = class {
3062
3164
  hostname: boundHostname,
3063
3165
  url: toConnectableUrl(boundHostname, boundPort)
3064
3166
  };
3167
+ const displaced = this.bunServer;
3168
+ if (displaced && displaced !== server && displaced !== supersededServer) {
3169
+ await stopBunServerBounded(displaced, true);
3170
+ }
3065
3171
  this.bunServer = server;
3066
3172
  this.boundAddress = address;
3067
3173
  setActiveBunServer(server);
@@ -3089,10 +3195,11 @@ var Application = class {
3089
3195
  * carries.
3090
3196
  *
3091
3197
  * Liveness is only as good as the signal available: a server stopped through
3092
- * the framework — a later `listen()`, the process-exit teardown — clears the
3093
- * slot this reads, but one stopped by calling `stop()` on the Bun server
3094
- * directly does not, and this keeps reporting its address. Treat it as
3095
- * "where `listen()` put this app", not as a health check.
3198
+ * the framework — {@link Application.stop}, a later `listen()`, the
3199
+ * process-exit teardown — clears what this reads, but one stopped by reaching
3200
+ * past the framework to the Bun server's own `stop()` does not, and this keeps
3201
+ * reporting its address. Treat it as "where `listen()` put this app", not as a
3202
+ * health check.
3096
3203
  */
3097
3204
  get address() {
3098
3205
  if (!this.bunServer || getGlobalState().__gurenActiveServer !== this.bunServer) {
@@ -3100,6 +3207,50 @@ var Application = class {
3100
3207
  }
3101
3208
  return this.boundAddress;
3102
3209
  }
3210
+ /**
3211
+ * Stops the server {@link listen} started, undoing that call.
3212
+ *
3213
+ * Safe to call when nothing is listening, and safe to call twice — both are
3214
+ * no-ops. A later `listen()` starts cleanly, so an app may be stopped and
3215
+ * restarted in one process.
3216
+ *
3217
+ * `closeActiveConnections` forces in-flight requests closed instead of
3218
+ * waiting for them, matching Bun's own `stop()` parameter. It defaults to
3219
+ * `false` (graceful) because a caller reaching for a public stop is usually
3220
+ * shutting down deliberately; the hot-reload path inside `listen()` forces
3221
+ * the close, since a reload must not wait on the server it is replacing.
3222
+ *
3223
+ * The managed Vite dev server is taken down too. `listen()` is what started
3224
+ * it, and `listen()`'s own bind-failure path already closes the one it
3225
+ * started — leaving it running here would strand an asset server, and its
3226
+ * published env vars, in a process with no application server. That close is
3227
+ * best-effort on the same terms as every other path: it is bounded by
3228
+ * {@link viteCloseTimeoutMs}, and a Vite server that overruns the bound is
3229
+ * warned about and abandoned rather than holding this call open. A dev server
3230
+ * a later `listen()` has adopted is left alone — it belongs to that call now.
3231
+ *
3232
+ * The stop itself is bounded by {@link bunStopTimeoutMs}: a graceful stop
3233
+ * waits on in-flight requests, and one that never finishes would otherwise
3234
+ * hold this call open forever.
3235
+ */
3236
+ async stop(closeActiveConnections = false) {
3237
+ const server = this.bunServer;
3238
+ if (server) {
3239
+ try {
3240
+ await stopBunServerBounded(server, closeActiveConnections);
3241
+ } finally {
3242
+ releaseActiveBunServer(server);
3243
+ }
3244
+ }
3245
+ if (this.bunServer !== server) {
3246
+ return;
3247
+ }
3248
+ this.bunServer = void 0;
3249
+ this.boundAddress = void 0;
3250
+ this.disposeBunTeardown?.();
3251
+ this.disposeBunTeardown = void 0;
3252
+ await this.closeViteDevServer();
3253
+ }
3103
3254
  /**
3104
3255
  * Register a service provider.
3105
3256
  */
@@ -3120,50 +3271,67 @@ var Application = class {
3120
3271
  logDevServerBanner(options) {
3121
3272
  logDevServerBanner(options);
3122
3273
  }
3274
+ /**
3275
+ * Closes the managed Vite dev server, but only while this application still
3276
+ * owns it.
3277
+ *
3278
+ * Ownership is the whole check. A `listen()` elsewhere in the process may
3279
+ * have adopted the running server — same object, new owner — and closing it
3280
+ * then would take the asset server, and its published env vars, out from
3281
+ * under an application that is actively serving from it. The record in the
3282
+ * slot is the one place that distinction exists, so it is read here rather
3283
+ * than mirrored on the instance.
3284
+ */
3123
3285
  async closeViteDevServer() {
3124
- if (!this.viteDevServer) {
3286
+ const active = getGlobalState().__gurenActiveViteDevServer;
3287
+ if (active?.owner !== this) {
3125
3288
  return;
3126
3289
  }
3127
3290
  try {
3128
- await closeViteDevServerBounded(this.viteDevServer);
3291
+ await closeViteDevServerBounded(active.server);
3129
3292
  } finally {
3130
- if (getGlobalState().__gurenActiveViteDevServer === this.viteDevServer) {
3293
+ active.disposeTeardown();
3294
+ if (getGlobalState().__gurenActiveViteDevServer === active) {
3131
3295
  setActiveViteDevServer();
3132
3296
  }
3133
- this.viteDevServer = void 0;
3134
- this.viteTeardownRegistered = false;
3135
- clearManagedViteEnv();
3136
3297
  }
3137
3298
  }
3299
+ /**
3300
+ * Attaches this application's Vite teardown handlers and returns the disposer
3301
+ * that detaches them. The disposer is stored in the active-record slot rather
3302
+ * than on this instance, because whoever takes ownership next is the one that
3303
+ * has to call it — and a disposer another app could spend would leave this
3304
+ * instance believing its handlers are attached when they are not.
3305
+ */
3138
3306
  registerViteTeardown() {
3139
- if (this.viteTeardownRegistered || !this.viteDevServer || typeof process === "undefined") {
3140
- return;
3307
+ if (typeof process === "undefined") {
3308
+ return () => {
3309
+ };
3141
3310
  }
3142
- this.viteTeardownRegistered = true;
3143
- const exitHandler = () => {
3144
- this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
3145
- };
3146
- process.once("SIGINT", exitHandler);
3147
- process.once("SIGTERM", exitHandler);
3148
- process.on("exit", () => {
3149
- if (this.viteDevServer) {
3150
- void this.viteDevServer.close();
3311
+ return registerProcessTeardown(
3312
+ () => {
3313
+ this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
3314
+ },
3315
+ () => {
3316
+ const active = getGlobalState().__gurenActiveViteDevServer;
3317
+ if (active?.owner === this) {
3318
+ void active.server.close();
3319
+ }
3151
3320
  }
3152
- });
3321
+ );
3153
3322
  }
3154
3323
  registerBunTeardown() {
3155
- if (this.bunTeardownRegistered || typeof process === "undefined") {
3324
+ if (this.disposeBunTeardown || typeof process === "undefined") {
3156
3325
  return;
3157
3326
  }
3158
- this.bunTeardownRegistered = true;
3159
- const exitHandler = () => {
3160
- stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
3161
- };
3162
- process.once("SIGINT", exitHandler);
3163
- process.once("SIGTERM", exitHandler);
3164
- process.on("exit", () => {
3165
- void stopActiveBunServer();
3166
- });
3327
+ this.disposeBunTeardown = registerProcessTeardown(
3328
+ () => {
3329
+ stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
3330
+ },
3331
+ () => {
3332
+ void stopActiveBunServer();
3333
+ }
3334
+ );
3167
3335
  }
3168
3336
  };
3169
3337
  function createApp(options = {}) {
@@ -27,10 +27,12 @@ export interface ScaffoldOptions {
27
27
  * a manifest into an app that cannot compile one, and an agent reading this
28
28
  * result is exactly who needs to hear that a page it just wrote was ignored.
29
29
  *
30
- * `definitions` is the route manifest `generateRouteTypes` builds. It stays
31
- * opaque here — this package only carries it from one CLI call to the next
32
- * (`generateApiClientTypes` consumes it) and never reads inside it, so
33
- * mirroring the CLI's route shape would only create something to keep in sync.
30
+ * `definitions` is what a generator extracted: the route manifest from
31
+ * `generateRouteTypes`, the Resource definitions from `generateDataTypes`.
32
+ * It stays opaque here — this package only carries it from one CLI call to
33
+ * the next (`generateApiClientTypes` consumes both) and never reads inside
34
+ * it, so mirroring the CLI's shapes would only create something to keep in
35
+ * sync.
34
36
  */
35
37
  export interface CodegenResult {
36
38
  outputPath?: string;
@@ -38,6 +40,12 @@ export interface CodegenResult {
38
40
  skipped?: {
39
41
  message: string;
40
42
  } | null;
43
+ /**
44
+ * Diagnostics the generator wants surfaced to whoever asked for the run —
45
+ * a `resource` response hint naming an unknown Resource class, for
46
+ * instance. Non-fatal: the artifact was still written.
47
+ */
48
+ warnings?: string[];
41
49
  }
42
50
  /**
43
51
  * CLI functions that the MCP server wraps.
@@ -124,9 +132,13 @@ export interface GurenCliApi {
124
132
  generateChannelTypes(opts: CodegenOptions): Promise<CodegenResult | void>;
125
133
  /**
126
134
  * Takes the route manifest `generateRouteTypes` returns, so it can only run
127
- * after that succeeded.
135
+ * after that succeeded. `resources` is the Resource set `generateDataTypes`
136
+ * extracted — without it every `resource` response hint is "unknown
137
+ * Resource" and the client's `json()` stays untyped.
128
138
  */
129
- generateApiClientTypes(definitions: unknown[], opts: CodegenOptions): Promise<CodegenResult | void>;
139
+ generateApiClientTypes(definitions: unknown[], opts: CodegenOptions & {
140
+ resources?: unknown[];
141
+ }): Promise<CodegenResult | void>;
130
142
  /**
131
143
  * Route-dependent context generation that re-runs the CLI in a fresh
132
144
  * process. Optional because `@guren/cli` is resolved from the app at
package/dist/mcp/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  McpServiceProvider,
3
3
  createMcpServer
4
- } from "../chunk-5WL2FTC4.js";
4
+ } from "../chunk-YSOJKAAU.js";
5
5
  import "../chunk-Q2P6YLRR.js";
6
6
  import "../chunk-LHR6OHI7.js";
7
7
  export {
@@ -34,6 +34,34 @@ interface BindableModel {
34
34
  /** Bound values are model classes at runtime; the constructor name is the introspection payload. */
35
35
  readonly name?: string;
36
36
  }
37
+ /**
38
+ * A Resource class accepted as a response hint. Only the constructor name is
39
+ * introspected — the router never instantiates it, so any class whose
40
+ * instances expose `toJSON()` (every `Resource` subclass) qualifies.
41
+ */
42
+ interface ResponseResourceClass {
43
+ new (resource: any): {
44
+ toJSON(): unknown;
45
+ };
46
+ }
47
+ /**
48
+ * Type-level response hint for a route: a Resource class, a single-element
49
+ * array of a hint (a collection), or a plain object of hints (an envelope,
50
+ * e.g. `{ data: [PostResource] }`). Purely declarative — nothing is validated
51
+ * at runtime. `guren codegen` maps each Resource class to the `Data` type it
52
+ * extracts from `app/Http/Resources` and types the API client's `json()`
53
+ * with the assembled shape.
54
+ */
55
+ export type ResourceResponseHint = ResponseResourceClass | readonly [ResourceResponseHint] | {
56
+ readonly [key: string]: ResourceResponseHint;
57
+ };
58
+ /**
59
+ * Serialized form of {@link ResourceResponseHint} carried by
60
+ * {@link RouteDefinition}: Resource classes become their class names.
61
+ */
62
+ export type ResourceResponseShape = string | [ResourceResponseShape] | {
63
+ [key: string]: ResourceResponseShape;
64
+ };
37
65
  type SchemaLike<T = unknown> = ValidationSchema<T> | undefined;
38
66
  type InferSchema<TSchema extends SchemaLike<unknown>> = TSchema extends ValidationSchema<infer TValue> ? TValue : never;
39
67
  type RouteParamsFor<TSchema extends SchemaLike<unknown>> = [
@@ -59,6 +87,13 @@ export interface RouteContractOptions<TParamsSchema extends SchemaLike<unknown>
59
87
  query?: TQuerySchema;
60
88
  body?: TBodySchema;
61
89
  output?: TOutputSchema;
90
+ /**
91
+ * Type-level response hint (see {@link ResourceResponseHint}). Unlike
92
+ * `output`, nothing runs at request time — the route's JSON is assumed to
93
+ * follow the shape. When both are set, `output` wins in generated types:
94
+ * it is the one actually enforced.
95
+ */
96
+ resource?: ResourceResponseHint;
62
97
  bind?: Record<string, BindableModel>;
63
98
  }
64
99
  export interface RouteOpenApiMetadata {
@@ -72,7 +107,7 @@ export interface RouteOpenApiMetadata {
72
107
  * Represents a registered route definition for introspection.
73
108
  */
74
109
  export interface RouteDefinition {
75
- /** HTTP method (GET, POST, PUT, PATCH, DELETE) */
110
+ /** Uppercased HTTP method (GET, POST, PUT, PATCH, DELETE, QUERY, or any custom method registered via on()) */
76
111
  method: string;
77
112
  /** URL path pattern (e.g., '/users/:id') */
78
113
  path: string;
@@ -85,6 +120,13 @@ export interface RouteDefinition {
85
120
  body?: SchemaLike<unknown>;
86
121
  output?: SchemaLike<unknown>;
87
122
  };
123
+ /**
124
+ * Serialized response hint from `RouteContractOptions.resource` — Resource
125
+ * class names in place of the classes. Absent when no hint was declared or
126
+ * when any class in the hint has no usable name (a partially-typed response
127
+ * would claim a shape the wire does not have).
128
+ */
129
+ resource?: ResourceResponseShape;
88
130
  /** Named middleware (aliases or groups) applied to this route */
89
131
  middlewareNames?: string[];
90
132
  /** Whether inline (unnamed) middleware handlers are attached */
@@ -193,6 +235,15 @@ export declare class Router<M extends string = never> {
193
235
  delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
194
236
  delete<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
195
237
  delete<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
238
+ /**
239
+ * Registers a route for the HTTP QUERY method (RFC 10008): safe and
240
+ * idempotent like GET, but the request carries a body like POST. Handlers
241
+ * must not mutate state — CSRF protection deliberately skips QUERY on that
242
+ * assumption (see `createCsrfMiddleware`'s `methods` option to opt in).
243
+ */
244
+ query<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
245
+ query<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
246
+ query<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
196
247
  group(prefix: string, callback: (router: Router<M>) => void): this;
197
248
  route(name: string, params?: Record<string, string | number>): string;
198
249
  hasRoute(name: string): boolean;
@@ -235,5 +286,11 @@ declare class RouterMiddlewareGroupBuilder<M extends string = never> {
235
286
  delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
236
287
  delete<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
237
288
  delete<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
289
+ query<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
290
+ query<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
291
+ query<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
292
+ on<C extends ControllerConstructor>(method: string, path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
293
+ on<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(method: string, path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
294
+ on<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(method: string, path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
238
295
  }
239
296
  export {};
@@ -4,7 +4,7 @@ import {
4
4
  logDevServerBanner,
5
5
  parseImportMap,
6
6
  startViteDevServer
7
- } from "../chunk-NENDACRP.js";
7
+ } from "../chunk-RGGEGXOE.js";
8
8
  import {
9
9
  trimTrailingSlashes
10
10
  } from "../chunk-AZOYI43J.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.4.0",
3
+ "version": "2.6.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -113,7 +113,7 @@
113
113
  "test": "bun test"
114
114
  },
115
115
  "dependencies": {
116
- "@guren/orm": "^2.2.2",
116
+ "@guren/orm": "^2.4.0",
117
117
  "@modelcontextprotocol/sdk": "^1.30.0",
118
118
  "chalk": "^5.3.0",
119
119
  "consola": "^3.4.2",