@guren/server 2.4.0 → 2.5.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.
@@ -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.5.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.3.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);
@@ -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
@@ -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-62AB24ZU.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 {
@@ -711,6 +714,12 @@ var RouterMiddlewareGroupBuilder = class {
711
714
  delete(path, handlerOrOptions, ...rest) {
712
715
  return this.router.applyMiddlewareScope(this.items, () => this.router.delete(path, handlerOrOptions, ...rest));
713
716
  }
717
+ query(path, handlerOrOptions, ...rest) {
718
+ return this.router.applyMiddlewareScope(this.items, () => this.router.query(path, handlerOrOptions, ...rest));
719
+ }
720
+ on(method, path, handlerOrOptions, ...rest) {
721
+ return this.router.applyMiddlewareScope(this.items, () => this.router.on(method, path, handlerOrOptions, ...rest));
722
+ }
714
723
  };
715
724
  function createRouteBuilder(route, namedRoutes) {
716
725
  return {
@@ -1669,6 +1678,7 @@ function isExcluded2(path, patterns) {
1669
1678
 
1670
1679
  // src/http/middleware/cors.ts
1671
1680
  import { cors } from "hono/cors";
1681
+ var DEFAULT_ALLOW_METHODS = ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "QUERY"];
1672
1682
  function createCorsMiddleware(options = {}) {
1673
1683
  if (options.credentials && !options.origin) {
1674
1684
  throw new Error(
@@ -1678,11 +1688,11 @@ function createCorsMiddleware(options = {}) {
1678
1688
  const origin = options.origin ?? (() => "");
1679
1689
  return cors({
1680
1690
  origin,
1681
- allowMethods: options.allowMethods,
1682
- allowHeaders: options.allowHeaders,
1683
- exposeHeaders: options.exposeHeaders,
1684
- maxAge: options.maxAge,
1685
- credentials: options.credentials
1691
+ allowMethods: options.allowMethods ?? DEFAULT_ALLOW_METHODS,
1692
+ ...options.allowHeaders !== void 0 && { allowHeaders: options.allowHeaders },
1693
+ ...options.exposeHeaders !== void 0 && { exposeHeaders: options.exposeHeaders },
1694
+ ...options.maxAge !== void 0 && { maxAge: options.maxAge },
1695
+ ...options.credentials !== void 0 && { credentials: options.credentials }
1686
1696
  });
1687
1697
  }
1688
1698
 
@@ -2698,6 +2708,9 @@ function clearManagedViteEnv() {
2698
2708
  }
2699
2709
  if (process.env[MANAGED_VITE_ENV_FLAG] === "1") {
2700
2710
  delete process.env.VITE_DEV_SERVER_URL;
2711
+ if (process.env.GUREN_INERTIA_ENTRY?.endsWith(DEFAULT_DEV_ENTRY_PATH)) {
2712
+ delete process.env.GUREN_INERTIA_ENTRY;
2713
+ }
2701
2714
  }
2702
2715
  delete process.env[MANAGED_VITE_ENV_FLAG];
2703
2716
  }
@@ -2717,6 +2730,43 @@ function syncManagedInertiaDevEntry(devServerUrl) {
2717
2730
  function getGlobalState() {
2718
2731
  return globalThis;
2719
2732
  }
2733
+ function bunStopTimeoutMs() {
2734
+ return shutdownTimeoutMs("GUREN_BUN_STOP_TIMEOUT_MS");
2735
+ }
2736
+ function shutdownTimeoutMs(envName) {
2737
+ const parsed = typeof process !== "undefined" ? Number.parseInt(process.env[envName] ?? "", 10) : Number.NaN;
2738
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 5e3;
2739
+ }
2740
+ async function awaitBounded(work, timeoutMs, onTimeout) {
2741
+ let timer;
2742
+ try {
2743
+ const timedOut = await Promise.race([
2744
+ work.then(() => false),
2745
+ new Promise((resolve2) => {
2746
+ timer = setTimeout(() => resolve2(true), timeoutMs);
2747
+ })
2748
+ ]);
2749
+ if (timedOut) {
2750
+ onTimeout(timeoutMs);
2751
+ }
2752
+ } finally {
2753
+ clearTimeout(timer);
2754
+ }
2755
+ }
2756
+ async function stopBunServerBounded(server, closeActiveConnections) {
2757
+ const stopped = (async () => {
2758
+ try {
2759
+ await server.stop?.(closeActiveConnections);
2760
+ } catch (error) {
2761
+ console.warn("Failed to stop Bun server:", error);
2762
+ }
2763
+ })();
2764
+ await awaitBounded(stopped, bunStopTimeoutMs(), (timeoutMs) => {
2765
+ console.warn(
2766
+ `Bun server did not stop within ${timeoutMs}ms \u2014 no longer waiting on it. In-flight requests may still be draining.`
2767
+ );
2768
+ });
2769
+ }
2720
2770
  async function stopActiveBunServer(closeActiveConnections = false) {
2721
2771
  const state = getGlobalState();
2722
2772
  const previous = state.__gurenActiveServer;
@@ -2725,69 +2775,84 @@ async function stopActiveBunServer(closeActiveConnections = false) {
2725
2775
  return;
2726
2776
  }
2727
2777
  try {
2728
- await Promise.resolve(previous.stop(closeActiveConnections));
2729
- } catch (error) {
2730
- console.warn("Failed to stop previous Bun server:", error);
2778
+ await stopBunServerBounded(previous, closeActiveConnections);
2731
2779
  } finally {
2732
- state.__gurenActiveServer = void 0;
2780
+ releaseActiveBunServer(previous);
2733
2781
  }
2734
2782
  }
2735
2783
  function setActiveBunServer(server) {
2736
2784
  getGlobalState().__gurenActiveServer = server;
2737
2785
  }
2786
+ function releaseActiveBunServer(server) {
2787
+ if (getGlobalState().__gurenActiveServer === server) {
2788
+ setActiveBunServer();
2789
+ }
2790
+ }
2791
+ function registerProcessTeardown(onSignal, onExit) {
2792
+ process.once("SIGINT", onSignal);
2793
+ process.once("SIGTERM", onSignal);
2794
+ process.on("exit", onExit);
2795
+ return () => {
2796
+ process.off("SIGINT", onSignal);
2797
+ process.off("SIGTERM", onSignal);
2798
+ process.off("exit", onExit);
2799
+ };
2800
+ }
2738
2801
  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;
2802
+ return shutdownTimeoutMs("GUREN_VITE_CLOSE_TIMEOUT_MS");
2741
2803
  }
2742
2804
  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
- );
2805
+ const close = (async () => {
2806
+ try {
2807
+ await server.close();
2808
+ } catch (error) {
2809
+ console.warn("Failed to stop Vite dev server:", error);
2759
2810
  }
2760
- } finally {
2761
- clearTimeout(timer);
2762
- }
2811
+ })();
2812
+ await awaitBounded(close, viteCloseTimeoutMs(), (timeoutMs) => {
2813
+ console.warn(
2814
+ `Vite dev server did not close within ${timeoutMs}ms \u2014 abandoning it. A stale asset server may still hold its port.`
2815
+ );
2816
+ });
2763
2817
  }
2764
2818
  async function stopActiveViteDevServer() {
2765
2819
  const previous = getGlobalState().__gurenActiveViteDevServer;
2766
2820
  try {
2767
2821
  if (previous) {
2768
- await closeViteDevServerBounded(previous);
2822
+ await closeViteDevServerBounded(previous.server);
2769
2823
  }
2770
2824
  } finally {
2771
- setActiveViteDevServer();
2772
- clearManagedViteEnv();
2825
+ previous?.disposeTeardown();
2826
+ if (getGlobalState().__gurenActiveViteDevServer === previous) {
2827
+ setActiveViteDevServer();
2828
+ }
2773
2829
  }
2774
2830
  }
2775
- function setActiveViteDevServer(server, localUrl) {
2776
- const state = getGlobalState();
2777
- state.__gurenActiveViteDevServer = server;
2778
- state.__gurenActiveViteDevServerUrl = server ? localUrl : void 0;
2831
+ function publishManagedViteEnv(localUrl) {
2832
+ if (typeof process === "undefined") {
2833
+ return;
2834
+ }
2835
+ process.env.VITE_DEV_SERVER_URL = localUrl;
2836
+ process.env[MANAGED_VITE_ENV_FLAG] = "1";
2837
+ syncManagedInertiaDevEntry(localUrl);
2838
+ }
2839
+ function setActiveViteDevServer(active) {
2840
+ getGlobalState().__gurenActiveViteDevServer = active;
2841
+ if (active) {
2842
+ publishManagedViteEnv(active.localUrl);
2843
+ } else {
2844
+ clearManagedViteEnv();
2845
+ }
2779
2846
  }
2780
2847
  function reusableActiveViteDevServer(viteOption) {
2781
2848
  if (typeof viteOption === "object") {
2782
2849
  return void 0;
2783
2850
  }
2784
- const state = getGlobalState();
2785
- const server = state.__gurenActiveViteDevServer;
2786
- const localUrl = state.__gurenActiveViteDevServerUrl;
2787
- if (!server || !localUrl || !server.httpServer?.listening) {
2851
+ const active = getGlobalState().__gurenActiveViteDevServer;
2852
+ if (!active || !active.server.httpServer?.listening) {
2788
2853
  return void 0;
2789
2854
  }
2790
- return { server, localUrl };
2855
+ return active;
2791
2856
  }
2792
2857
  var Application = class {
2793
2858
  constructor(options = {}) {
@@ -2845,11 +2910,20 @@ var Application = class {
2845
2910
  router;
2846
2911
  providerManager;
2847
2912
  authManager;
2848
- viteDevServer;
2849
2913
  bunServer;
2850
2914
  boundAddress;
2851
- viteTeardownRegistered = false;
2852
- bunTeardownRegistered = false;
2915
+ /**
2916
+ * Detaches the Bun half's process teardown handlers, and doubles as the "are
2917
+ * they attached?" memo. One field rather than a separate boolean: a memo and
2918
+ * an undo that can disagree is how handlers end up attached while a flag says
2919
+ * otherwise — see {@link registerProcessTeardown}.
2920
+ *
2921
+ * The Vite half's disposer lives in {@link ActiveViteDevServer} instead,
2922
+ * because the application that detaches those handlers is not always the one
2923
+ * that attached them: adoption moves the server to a new owner, and the
2924
+ * outgoing owner is only reachable through the slot.
2925
+ */
2926
+ disposeBunTeardown;
2853
2927
  autoSessionAttached = false;
2854
2928
  routesRegistered = false;
2855
2929
  bootPromise;
@@ -2978,21 +3052,25 @@ var Application = class {
2978
3052
  if (!Bun) {
2979
3053
  throw new Error("Bun runtime is required to call Application.listen");
2980
3054
  }
3055
+ const supersededServer = getGlobalState().__gurenActiveServer;
2981
3056
  await stopActiveBunServer(true);
2982
3057
  const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite, portFallback } = options;
2983
3058
  const externalAssetsUrl = typeof process !== "undefined" && process.env?.[MANAGED_VITE_ENV_FLAG] !== "1" ? process.env?.VITE_DEV_SERVER_URL : void 0;
2984
3059
  let resolvedAssetsUrl = assetsUrl ?? externalAssetsUrl;
2985
3060
  const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
2986
3061
  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";
3062
+ const displaced2 = getGlobalState().__gurenActiveViteDevServer;
3063
+ displaced2?.disposeTeardown();
3064
+ if (displaced2 && displaced2.server !== viteServer) {
3065
+ void closeViteDevServerBounded(displaced2.server);
2993
3066
  }
2994
- syncManagedInertiaDevEntry(localUrl);
2995
- this.registerViteTeardown();
3067
+ setActiveViteDevServer({
3068
+ server: viteServer,
3069
+ localUrl,
3070
+ owner: this,
3071
+ disposeTeardown: this.registerViteTeardown()
3072
+ });
3073
+ resolvedAssetsUrl = localUrl;
2996
3074
  };
2997
3075
  const reusableVite = shouldStartVite ? reusableActiveViteDevServer(vite) : void 0;
2998
3076
  let startedViteHere = false;
@@ -3004,7 +3082,6 @@ var Application = class {
3004
3082
  if (shouldStartVite && !reusableVite) {
3005
3083
  const viteOptions = typeof vite === "object" ? vite : void 0;
3006
3084
  try {
3007
- await this.closeViteDevServer();
3008
3085
  const { server: server2, localUrl } = await startViteDevServer({
3009
3086
  root: viteOptions?.root ?? process.cwd(),
3010
3087
  config: viteOptions?.config,
@@ -3062,6 +3139,10 @@ var Application = class {
3062
3139
  hostname: boundHostname,
3063
3140
  url: toConnectableUrl(boundHostname, boundPort)
3064
3141
  };
3142
+ const displaced = this.bunServer;
3143
+ if (displaced && displaced !== server && displaced !== supersededServer) {
3144
+ await stopBunServerBounded(displaced, true);
3145
+ }
3065
3146
  this.bunServer = server;
3066
3147
  this.boundAddress = address;
3067
3148
  setActiveBunServer(server);
@@ -3089,10 +3170,11 @@ var Application = class {
3089
3170
  * carries.
3090
3171
  *
3091
3172
  * 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.
3173
+ * the framework — {@link Application.stop}, a later `listen()`, the
3174
+ * process-exit teardown — clears what this reads, but one stopped by reaching
3175
+ * past the framework to the Bun server's own `stop()` does not, and this keeps
3176
+ * reporting its address. Treat it as "where `listen()` put this app", not as a
3177
+ * health check.
3096
3178
  */
3097
3179
  get address() {
3098
3180
  if (!this.bunServer || getGlobalState().__gurenActiveServer !== this.bunServer) {
@@ -3100,6 +3182,50 @@ var Application = class {
3100
3182
  }
3101
3183
  return this.boundAddress;
3102
3184
  }
3185
+ /**
3186
+ * Stops the server {@link listen} started, undoing that call.
3187
+ *
3188
+ * Safe to call when nothing is listening, and safe to call twice — both are
3189
+ * no-ops. A later `listen()` starts cleanly, so an app may be stopped and
3190
+ * restarted in one process.
3191
+ *
3192
+ * `closeActiveConnections` forces in-flight requests closed instead of
3193
+ * waiting for them, matching Bun's own `stop()` parameter. It defaults to
3194
+ * `false` (graceful) because a caller reaching for a public stop is usually
3195
+ * shutting down deliberately; the hot-reload path inside `listen()` forces
3196
+ * the close, since a reload must not wait on the server it is replacing.
3197
+ *
3198
+ * The managed Vite dev server is taken down too. `listen()` is what started
3199
+ * it, and `listen()`'s own bind-failure path already closes the one it
3200
+ * started — leaving it running here would strand an asset server, and its
3201
+ * published env vars, in a process with no application server. That close is
3202
+ * best-effort on the same terms as every other path: it is bounded by
3203
+ * {@link viteCloseTimeoutMs}, and a Vite server that overruns the bound is
3204
+ * warned about and abandoned rather than holding this call open. A dev server
3205
+ * a later `listen()` has adopted is left alone — it belongs to that call now.
3206
+ *
3207
+ * The stop itself is bounded by {@link bunStopTimeoutMs}: a graceful stop
3208
+ * waits on in-flight requests, and one that never finishes would otherwise
3209
+ * hold this call open forever.
3210
+ */
3211
+ async stop(closeActiveConnections = false) {
3212
+ const server = this.bunServer;
3213
+ if (server) {
3214
+ try {
3215
+ await stopBunServerBounded(server, closeActiveConnections);
3216
+ } finally {
3217
+ releaseActiveBunServer(server);
3218
+ }
3219
+ }
3220
+ if (this.bunServer !== server) {
3221
+ return;
3222
+ }
3223
+ this.bunServer = void 0;
3224
+ this.boundAddress = void 0;
3225
+ this.disposeBunTeardown?.();
3226
+ this.disposeBunTeardown = void 0;
3227
+ await this.closeViteDevServer();
3228
+ }
3103
3229
  /**
3104
3230
  * Register a service provider.
3105
3231
  */
@@ -3120,50 +3246,67 @@ var Application = class {
3120
3246
  logDevServerBanner(options) {
3121
3247
  logDevServerBanner(options);
3122
3248
  }
3249
+ /**
3250
+ * Closes the managed Vite dev server, but only while this application still
3251
+ * owns it.
3252
+ *
3253
+ * Ownership is the whole check. A `listen()` elsewhere in the process may
3254
+ * have adopted the running server — same object, new owner — and closing it
3255
+ * then would take the asset server, and its published env vars, out from
3256
+ * under an application that is actively serving from it. The record in the
3257
+ * slot is the one place that distinction exists, so it is read here rather
3258
+ * than mirrored on the instance.
3259
+ */
3123
3260
  async closeViteDevServer() {
3124
- if (!this.viteDevServer) {
3261
+ const active = getGlobalState().__gurenActiveViteDevServer;
3262
+ if (active?.owner !== this) {
3125
3263
  return;
3126
3264
  }
3127
3265
  try {
3128
- await closeViteDevServerBounded(this.viteDevServer);
3266
+ await closeViteDevServerBounded(active.server);
3129
3267
  } finally {
3130
- if (getGlobalState().__gurenActiveViteDevServer === this.viteDevServer) {
3268
+ active.disposeTeardown();
3269
+ if (getGlobalState().__gurenActiveViteDevServer === active) {
3131
3270
  setActiveViteDevServer();
3132
3271
  }
3133
- this.viteDevServer = void 0;
3134
- this.viteTeardownRegistered = false;
3135
- clearManagedViteEnv();
3136
3272
  }
3137
3273
  }
3274
+ /**
3275
+ * Attaches this application's Vite teardown handlers and returns the disposer
3276
+ * that detaches them. The disposer is stored in the active-record slot rather
3277
+ * than on this instance, because whoever takes ownership next is the one that
3278
+ * has to call it — and a disposer another app could spend would leave this
3279
+ * instance believing its handlers are attached when they are not.
3280
+ */
3138
3281
  registerViteTeardown() {
3139
- if (this.viteTeardownRegistered || !this.viteDevServer || typeof process === "undefined") {
3140
- return;
3282
+ if (typeof process === "undefined") {
3283
+ return () => {
3284
+ };
3141
3285
  }
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();
3286
+ return registerProcessTeardown(
3287
+ () => {
3288
+ this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
3289
+ },
3290
+ () => {
3291
+ const active = getGlobalState().__gurenActiveViteDevServer;
3292
+ if (active?.owner === this) {
3293
+ void active.server.close();
3294
+ }
3151
3295
  }
3152
- });
3296
+ );
3153
3297
  }
3154
3298
  registerBunTeardown() {
3155
- if (this.bunTeardownRegistered || typeof process === "undefined") {
3299
+ if (this.disposeBunTeardown || typeof process === "undefined") {
3156
3300
  return;
3157
3301
  }
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
- });
3302
+ this.disposeBunTeardown = registerProcessTeardown(
3303
+ () => {
3304
+ stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
3305
+ },
3306
+ () => {
3307
+ void stopActiveBunServer();
3308
+ }
3309
+ );
3167
3310
  }
3168
3311
  };
3169
3312
  function createApp(options = {}) {
@@ -72,7 +72,7 @@ export interface RouteOpenApiMetadata {
72
72
  * Represents a registered route definition for introspection.
73
73
  */
74
74
  export interface RouteDefinition {
75
- /** HTTP method (GET, POST, PUT, PATCH, DELETE) */
75
+ /** Uppercased HTTP method (GET, POST, PUT, PATCH, DELETE, QUERY, or any custom method registered via on()) */
76
76
  method: string;
77
77
  /** URL path pattern (e.g., '/users/:id') */
78
78
  path: string;
@@ -193,6 +193,15 @@ export declare class Router<M extends string = never> {
193
193
  delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
194
194
  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
195
  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>;
196
+ /**
197
+ * Registers a route for the HTTP QUERY method (RFC 10008): safe and
198
+ * idempotent like GET, but the request carries a body like POST. Handlers
199
+ * must not mutate state — CSRF protection deliberately skips QUERY on that
200
+ * assumption (see `createCsrfMiddleware`'s `methods` option to opt in).
201
+ */
202
+ query<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
203
+ 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>;
204
+ 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
205
  group(prefix: string, callback: (router: Router<M>) => void): this;
197
206
  route(name: string, params?: Record<string, string | number>): string;
198
207
  hasRoute(name: string): boolean;
@@ -235,5 +244,11 @@ declare class RouterMiddlewareGroupBuilder<M extends string = never> {
235
244
  delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
236
245
  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
246
  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>;
247
+ query<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
248
+ 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>;
249
+ 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>;
250
+ on<C extends ControllerConstructor>(method: string, path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
251
+ 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>;
252
+ 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
253
  }
239
254
  export {};
@@ -4,7 +4,7 @@ import {
4
4
  logDevServerBanner,
5
5
  parseImportMap,
6
6
  startViteDevServer
7
- } from "../chunk-NENDACRP.js";
7
+ } from "../chunk-62AB24ZU.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.5.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.3.0",
117
117
  "@modelcontextprotocol/sdk": "^1.30.0",
118
118
  "chalk": "^5.3.0",
119
119
  "consola": "^3.4.2",