@guren/server 2.2.0 → 2.4.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.
Files changed (40) hide show
  1. package/dist/{DocsViewerServiceProvider-D7RGJPGM.js → DocsViewerServiceProvider-RUYDFBMW.js} +2 -2
  2. package/dist/McpServiceProvider-FRJ5O7LT.js +8 -0
  3. package/dist/auth/index.js +2 -1
  4. package/dist/broadcasting/index.js +2 -1
  5. package/dist/{chunk-SIP34GBE.js → chunk-2SC566CD.js} +14 -18
  6. package/dist/chunk-3KV5X2FL.js +31 -0
  7. package/dist/{chunk-CDZUNKI6.js → chunk-5WL2FTC4.js} +3 -3
  8. package/dist/{chunk-WIXGT4TN.js → chunk-A5JJ7XTH.js} +8 -2
  9. package/dist/{chunk-4VE3LYOM.js → chunk-DRNPVBAA.js} +20 -5
  10. package/dist/{chunk-LVJCZCAV.js → chunk-H3B23O6T.js} +10 -118
  11. package/dist/{chunk-BZMZEFRG.js → chunk-LHR6OHI7.js} +11 -0
  12. package/dist/{chunk-PZKUDFMW.js → chunk-NENDACRP.js} +20 -4
  13. package/dist/{chunk-JBG4AR24.js → chunk-Q2P6YLRR.js} +8 -2
  14. package/dist/{chunk-BUQXOZCT.js → chunk-TVV5YNEC.js} +8 -4
  15. package/dist/chunk-V4DNC2ER.js +114 -0
  16. package/dist/docs-viewer/endpoint.d.ts +11 -1
  17. package/dist/encryption/index.js +17 -15
  18. package/dist/health/index.js +1 -1
  19. package/dist/http/Application.d.ts +67 -1
  20. package/dist/http/FormRequest.d.ts +10 -7
  21. package/dist/http/dev-assets.d.ts +11 -0
  22. package/dist/http/dev-banner.d.ts +11 -0
  23. package/dist/http/inertia-assets.d.ts +9 -0
  24. package/dist/http/middleware/loopback-guard.d.ts +16 -3
  25. package/dist/http/middleware/response-headers.d.ts +18 -0
  26. package/dist/http/middleware/validation-errors-cookie.d.ts +31 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +376 -112
  29. package/dist/mcp/create-mcp-server.d.ts +8 -0
  30. package/dist/mcp/endpoint.d.ts +19 -1
  31. package/dist/mcp/index.js +3 -3
  32. package/dist/redis/index.js +43 -8
  33. package/dist/redis/redis-values.d.ts +17 -0
  34. package/dist/runtime/index.js +102 -69
  35. package/dist/support/contained-path.d.ts +26 -0
  36. package/dist/support/expiry.d.ts +47 -0
  37. package/dist/support/expiry.js +12 -0
  38. package/dist/support/inertia-defaults.d.ts +13 -0
  39. package/package.json +6 -2
  40. package/dist/McpServiceProvider-GRDYNEQG.js +0 -8
package/dist/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import {
2
+ DEFAULT_DEV_STYLES_ENTRY,
3
+ formatHostPort,
4
+ isWildcardHost,
2
5
  logDevServerBanner,
3
6
  parseImportMap,
4
7
  startViteDevServer
5
- } from "./chunk-PZKUDFMW.js";
8
+ } from "./chunk-NENDACRP.js";
6
9
  import {
7
10
  PendingSchedule,
8
11
  Schedule,
@@ -29,7 +32,7 @@ import {
29
32
  } from "./chunk-AZOYI43J.js";
30
33
  import {
31
34
  isDocsViewerEnabled
32
- } from "./chunk-WIXGT4TN.js";
35
+ } from "./chunk-A5JJ7XTH.js";
33
36
  import {
34
37
  I18nManager,
35
38
  JsonLoader,
@@ -72,11 +75,11 @@ import {
72
75
  import {
73
76
  MCP_ENDPOINT_PATH,
74
77
  isMcpEndpointEnabled
75
- } from "./chunk-JBG4AR24.js";
78
+ } from "./chunk-Q2P6YLRR.js";
76
79
  import {
77
80
  ProviderManager,
78
81
  ServiceProvider
79
- } from "./chunk-BZMZEFRG.js";
82
+ } from "./chunk-LHR6OHI7.js";
80
83
  import {
81
84
  DatabaseChannel,
82
85
  MailChannel,
@@ -180,7 +183,8 @@ import {
180
183
  verifyEmailToken,
181
184
  verifyOAuthState,
182
185
  verifyPasswordResetToken
183
- } from "./chunk-BUQXOZCT.js";
186
+ } from "./chunk-TVV5YNEC.js";
187
+ import "./chunk-3KV5X2FL.js";
184
188
  import {
185
189
  Gate,
186
190
  Policy,
@@ -230,7 +234,7 @@ import {
230
234
  getBroadcastManager,
231
235
  parseRequestPayload,
232
236
  setBroadcastManager
233
- } from "./chunk-4VE3LYOM.js";
237
+ } from "./chunk-DRNPVBAA.js";
234
238
  import {
235
239
  CacheManager,
236
240
  FileStore,
@@ -250,25 +254,11 @@ import {
250
254
  decrypt,
251
255
  encrypt,
252
256
  generateKey,
253
- generateOtp,
254
- generatePassword,
255
- generateSlug,
256
257
  getEncrypter,
257
- pick,
258
- random,
259
- randomBase64,
260
- randomBase64Url,
261
- randomHex,
262
- randomInt,
263
- randomString,
264
- sample,
265
258
  setEncrypter,
266
- shuffle,
267
259
  signUrl,
268
- urlSafeToken,
269
- uuid,
270
260
  verifySignedUrl
271
- } from "./chunk-LVJCZCAV.js";
261
+ } from "./chunk-H3B23O6T.js";
272
262
  import {
273
263
  MessageSigner,
274
264
  deriveAppKey,
@@ -293,6 +283,22 @@ import {
293
283
  verifyHmac,
294
284
  verifyPassword
295
285
  } from "./chunk-QQKTH5KX.js";
286
+ import {
287
+ generateOtp,
288
+ generatePassword,
289
+ generateSlug,
290
+ pick,
291
+ random,
292
+ randomBase64,
293
+ randomBase64Url,
294
+ randomHex,
295
+ randomInt,
296
+ randomString,
297
+ sample,
298
+ shuffle,
299
+ urlSafeToken,
300
+ uuid
301
+ } from "./chunk-V4DNC2ER.js";
296
302
  import {
297
303
  ApplicationShutdown,
298
304
  ApplicationStarted,
@@ -318,7 +324,7 @@ import {
318
324
  StorageCheck,
319
325
  createHealthManager,
320
326
  customCheck
321
- } from "./chunk-SIP34GBE.js";
327
+ } from "./chunk-2SC566CD.js";
322
328
 
323
329
  // src/support/error-polyfill.ts
324
330
  var patched = false;
@@ -1475,6 +1481,31 @@ var SlidingWindowRateLimitStore = class extends BaseMemoryStore {
1475
1481
  }
1476
1482
  };
1477
1483
 
1484
+ // src/http/middleware/response-headers.ts
1485
+ function applyResponseHeaders(ctx, headers) {
1486
+ const response = ctx.res;
1487
+ try {
1488
+ for (const [name, value] of headers) {
1489
+ if (!response.headers.has(name)) response.headers.set(name, value);
1490
+ }
1491
+ return;
1492
+ } catch (error) {
1493
+ if (!isImmutableHeadersError(error)) throw error;
1494
+ }
1495
+ const merged = new Headers(response.headers);
1496
+ for (const [name, value] of headers) {
1497
+ if (!merged.has(name)) merged.set(name, value);
1498
+ }
1499
+ ctx.res = new Response(response.body, {
1500
+ status: response.status,
1501
+ statusText: response.statusText,
1502
+ headers: merged
1503
+ });
1504
+ }
1505
+ function isImmutableHeadersError(error) {
1506
+ return error instanceof TypeError && /immutable/i.test(error.message);
1507
+ }
1508
+
1478
1509
  // src/http/middleware/security-headers.ts
1479
1510
  function createSecurityHeaders(options = {}) {
1480
1511
  const {
@@ -1486,26 +1517,21 @@ function createSecurityHeaders(options = {}) {
1486
1517
  hsts = process.env.NODE_ENV === "production" ? { maxAge: 31536e3 } : false
1487
1518
  } = options;
1488
1519
  const hstsValue = hsts !== false ? buildHstsValue(hsts) : null;
1520
+ const headers = [];
1521
+ if (frameOptions !== false) headers.push(["X-Frame-Options", frameOptions]);
1522
+ if (contentTypeOptions !== false) headers.push(["X-Content-Type-Options", contentTypeOptions]);
1523
+ if (xssProtection !== false) headers.push(["X-XSS-Protection", xssProtection]);
1524
+ if (referrerPolicy !== false) headers.push(["Referrer-Policy", referrerPolicy]);
1525
+ if (crossDomainPolicies !== false) {
1526
+ headers.push(["X-Permitted-Cross-Domain-Policies", crossDomainPolicies]);
1527
+ }
1528
+ if (hstsValue) headers.push(["Strict-Transport-Security", hstsValue]);
1489
1529
  return async (ctx, next) => {
1490
- if (frameOptions !== false) {
1491
- ctx.header("X-Frame-Options", frameOptions);
1492
- }
1493
- if (contentTypeOptions !== false) {
1494
- ctx.header("X-Content-Type-Options", contentTypeOptions);
1495
- }
1496
- if (xssProtection !== false) {
1497
- ctx.header("X-XSS-Protection", xssProtection);
1498
- }
1499
- if (referrerPolicy !== false) {
1500
- ctx.header("Referrer-Policy", referrerPolicy);
1501
- }
1502
- if (crossDomainPolicies !== false) {
1503
- ctx.header("X-Permitted-Cross-Domain-Policies", crossDomainPolicies);
1504
- }
1505
- if (hstsValue) {
1506
- ctx.header("Strict-Transport-Security", hstsValue);
1530
+ try {
1531
+ await next();
1532
+ } finally {
1533
+ applyResponseHeaders(ctx, headers);
1507
1534
  }
1508
- await next();
1509
1535
  };
1510
1536
  }
1511
1537
  function buildHstsValue(options) {
@@ -1542,10 +1568,11 @@ function createCspMiddleware(options = {}) {
1542
1568
  ctx.set(CSP_NONCE_KEY, nonce);
1543
1569
  }
1544
1570
  const headerValue = buildCspHeader(directives, nonce, reportUri);
1545
- if (headerValue) {
1546
- ctx.header(headerName, headerValue);
1571
+ try {
1572
+ await next();
1573
+ } finally {
1574
+ if (headerValue) applyResponseHeaders(ctx, [[headerName, headerValue]]);
1547
1575
  }
1548
- await next();
1549
1576
  };
1550
1577
  }
1551
1578
  function camelToKebab(str) {
@@ -1725,8 +1752,11 @@ function createForceHttpsMiddleware(options = {}) {
1725
1752
  url2.protocol = "https:";
1726
1753
  return ctx.redirect(url2.toString(), 301);
1727
1754
  }
1728
- ctx.header("Strict-Transport-Security", hstsValue);
1729
- await next();
1755
+ try {
1756
+ await next();
1757
+ } finally {
1758
+ applyResponseHeaders(ctx, [["Strict-Transport-Security", hstsValue]]);
1759
+ }
1730
1760
  };
1731
1761
  }
1732
1762
 
@@ -2207,7 +2237,7 @@ async function inertia(component, props, options = {}) {
2207
2237
  const page = {
2208
2238
  component,
2209
2239
  props,
2210
- url: options.url ?? "",
2240
+ url: options.url ?? inertiaPageUrl(options.request) ?? "",
2211
2241
  version: resolvedVersion
2212
2242
  };
2213
2243
  const request = options.request;
@@ -2250,15 +2280,23 @@ async function inertia(component, props, options = {}) {
2250
2280
  }
2251
2281
  });
2252
2282
  }
2283
+ function inertiaPageUrl(request) {
2284
+ if (!request) {
2285
+ return void 0;
2286
+ }
2287
+ const { pathname, search } = new URL(request.url);
2288
+ return `${pathname}${search}`;
2289
+ }
2253
2290
  async function renderDocument(page, options) {
2254
2291
  const defaultEntry = process.env.GUREN_INERTIA_ENTRY ?? "/resources/js/app.tsx";
2255
2292
  const entry = options.entry ?? defaultEntry;
2256
2293
  const title = escapeHtml(options.title ?? DEFAULT_TITLE);
2257
- const styles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
2294
+ const isProduction = process.env.NODE_ENV === "production";
2295
+ const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
2296
+ const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
2258
2297
  const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, {
2259
2298
  context: "GUREN_INERTIA_IMPORT_MAP"
2260
2299
  });
2261
- const isProduction = process.env.NODE_ENV === "production";
2262
2300
  const importMapEntries = {
2263
2301
  ...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
2264
2302
  ...envImportMap,
@@ -2392,6 +2430,9 @@ function normalizeSsrSpecifier(specifier) {
2392
2430
  function isUrlLike(specifier) {
2393
2431
  return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
2394
2432
  }
2433
+ function isDevServerEntry(entry) {
2434
+ return /^https?:\/\//iu.test(entry);
2435
+ }
2395
2436
  function renderStyles(styles) {
2396
2437
  if (!styles.length) {
2397
2438
  return "";
@@ -2489,12 +2530,79 @@ var ViewEngine = class {
2489
2530
  }
2490
2531
  };
2491
2532
 
2533
+ // src/http/middleware/validation-errors-cookie.ts
2534
+ import { deleteCookie, getCookie as getCookie3 } from "hono/cookie";
2535
+ import { serialize } from "hono/utils/cookie";
2536
+ var VALIDATION_ERRORS_COOKIE = "guren_validation_errors";
2537
+ var COOKIE_MAX_AGE_SECONDS = 60;
2538
+ var MAX_COOKIE_VALUE_LENGTH = 3800;
2539
+ var CONSUMED_CONTEXT_KEY = "gurenValidationErrorsCookieConsumed";
2540
+ function validationErrorsSetCookie(errors) {
2541
+ const kept = {};
2542
+ for (const [field, message] of Object.entries(errors)) {
2543
+ const next = encodeURIComponent(JSON.stringify({ ...kept, [field]: message }));
2544
+ if (next.length > MAX_COOKIE_VALUE_LENGTH) {
2545
+ continue;
2546
+ }
2547
+ kept[field] = message;
2548
+ }
2549
+ return serialize(VALIDATION_ERRORS_COOKIE, JSON.stringify(kept), {
2550
+ path: "/",
2551
+ httpOnly: true,
2552
+ sameSite: "Lax",
2553
+ maxAge: COOKIE_MAX_AGE_SECONDS
2554
+ });
2555
+ }
2556
+ function readValidationErrorsCookie(ctx) {
2557
+ const raw = getCookie3(ctx, VALIDATION_ERRORS_COOKIE);
2558
+ if (!raw) {
2559
+ return void 0;
2560
+ }
2561
+ ctx.set(CONSUMED_CONTEXT_KEY, true);
2562
+ let parsed;
2563
+ try {
2564
+ parsed = JSON.parse(raw);
2565
+ } catch {
2566
+ return void 0;
2567
+ }
2568
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2569
+ return void 0;
2570
+ }
2571
+ const errors = {};
2572
+ for (const [field, message] of Object.entries(parsed)) {
2573
+ if (typeof message === "string") {
2574
+ errors[field] = message;
2575
+ }
2576
+ }
2577
+ return Object.keys(errors).length > 0 ? errors : void 0;
2578
+ }
2579
+ function createValidationErrorsCookieCleanup() {
2580
+ return async (ctx, next) => {
2581
+ await next();
2582
+ if (!ctx.get(CONSUMED_CONTEXT_KEY)) {
2583
+ return;
2584
+ }
2585
+ const setCookies = ctx.res.headers.getSetCookie?.() ?? [];
2586
+ if (setCookies.some((header) => header.startsWith(`${VALIDATION_ERRORS_COOKIE}=`))) {
2587
+ return;
2588
+ }
2589
+ deleteCookie(ctx, VALIDATION_ERRORS_COOKIE, { path: "/" });
2590
+ };
2591
+ }
2592
+
2492
2593
  // src/providers/InertiaServiceProvider.ts
2493
2594
  var InertiaServiceProvider = class extends ServiceProvider {
2494
2595
  register() {
2495
2596
  if (!ViewEngine.has("inertia")) {
2496
2597
  ViewEngine.register("inertia", inertia);
2497
2598
  }
2599
+ let hono;
2600
+ try {
2601
+ hono = this.container.make("hono");
2602
+ } catch {
2603
+ return;
2604
+ }
2605
+ hono.use("*", createValidationErrorsCookieCleanup());
2498
2606
  }
2499
2607
  boot() {
2500
2608
  this.registerValidationRenderer();
@@ -2522,18 +2630,21 @@ var InertiaServiceProvider = class extends ServiceProvider {
2522
2630
  422
2523
2631
  );
2524
2632
  }
2633
+ const flattened = {};
2634
+ for (const [key, messages] of Object.entries(error.errors ?? {})) {
2635
+ flattened[key] = messages[0] ?? "";
2636
+ }
2637
+ const referer = ctx.req.header("Referer") ?? "/";
2638
+ const headers = { Location: referer };
2525
2639
  const session = getSessionFromContext(ctx);
2526
2640
  if (session) {
2527
- const flattened = {};
2528
- for (const [key, messages] of Object.entries(error.errors ?? {})) {
2529
- flattened[key] = messages[0] ?? "";
2530
- }
2531
2641
  session.flash("errors", flattened);
2642
+ } else {
2643
+ headers["Set-Cookie"] = validationErrorsSetCookie(flattened);
2532
2644
  }
2533
- const referer = ctx.req.header("Referer") ?? "/";
2534
2645
  return new Response(null, {
2535
2646
  status: 303,
2536
- headers: { Location: referer }
2647
+ headers
2537
2648
  });
2538
2649
  });
2539
2650
  }
@@ -2545,8 +2656,12 @@ var InertiaServiceProvider = class extends ServiceProvider {
2545
2656
  registerSharedErrors() {
2546
2657
  shareInertiaProps(async (ctx) => {
2547
2658
  const session = getSessionFromContext(ctx);
2548
- const errors = session?.getFlash("errors");
2549
- return errors && Object.keys(errors).length > 0 ? { errors } : {};
2659
+ if (session) {
2660
+ const errors2 = session.getFlash("errors");
2661
+ return errors2 && Object.keys(errors2).length > 0 ? { errors: errors2 } : {};
2662
+ }
2663
+ const errors = readValidationErrorsCookie(ctx);
2664
+ return errors ? { errors } : {};
2550
2665
  }, this.container);
2551
2666
  }
2552
2667
  };
@@ -2554,6 +2669,29 @@ var InertiaServiceProvider = class extends ServiceProvider {
2554
2669
  // src/http/Application.ts
2555
2670
  var MANAGED_VITE_ENV_FLAG = "GUREN_MANAGED_VITE_DEV_SERVER";
2556
2671
  var DEFAULT_DEV_ENTRY_PATH = "/resources/js/dev-entry.ts";
2672
+ var STRICT_PORT_ENV_FLAG = "GUREN_STRICT_PORT";
2673
+ var DEFAULT_PORT_WALK_ATTEMPTS = 20;
2674
+ function isAddressInUse(error) {
2675
+ return Boolean(
2676
+ error && typeof error === "object" && "code" in error && error.code === "EADDRINUSE"
2677
+ );
2678
+ }
2679
+ function resolvePortAttempts(option, port) {
2680
+ if (port === 0) {
2681
+ return 1;
2682
+ }
2683
+ if (typeof process !== "undefined" && process.env?.[STRICT_PORT_ENV_FLAG] === "1") {
2684
+ return 1;
2685
+ }
2686
+ if (typeof option === "boolean") {
2687
+ return option ? DEFAULT_PORT_WALK_ATTEMPTS : 1;
2688
+ }
2689
+ return typeof process !== "undefined" && process.env.NODE_ENV === "production" ? 1 : DEFAULT_PORT_WALK_ATTEMPTS;
2690
+ }
2691
+ function toConnectableUrl(hostname, port) {
2692
+ const host = isWildcardHost(hostname) ? hostname === "::" ? "::1" : "127.0.0.1" : hostname;
2693
+ return `http://${formatHostPort(host, port)}`;
2694
+ }
2557
2695
  function clearManagedViteEnv() {
2558
2696
  if (typeof process === "undefined") {
2559
2697
  return;
@@ -2579,7 +2717,7 @@ function syncManagedInertiaDevEntry(devServerUrl) {
2579
2717
  function getGlobalState() {
2580
2718
  return globalThis;
2581
2719
  }
2582
- async function stopActiveBunServer() {
2720
+ async function stopActiveBunServer(closeActiveConnections = false) {
2583
2721
  const state = getGlobalState();
2584
2722
  const previous = state.__gurenActiveServer;
2585
2723
  if (!previous?.stop) {
@@ -2587,7 +2725,7 @@ async function stopActiveBunServer() {
2587
2725
  return;
2588
2726
  }
2589
2727
  try {
2590
- await Promise.resolve(previous.stop());
2728
+ await Promise.resolve(previous.stop(closeActiveConnections));
2591
2729
  } catch (error) {
2592
2730
  console.warn("Failed to stop previous Bun server:", error);
2593
2731
  } finally {
@@ -2597,25 +2735,59 @@ async function stopActiveBunServer() {
2597
2735
  function setActiveBunServer(server) {
2598
2736
  getGlobalState().__gurenActiveServer = server;
2599
2737
  }
2600
- async function stopActiveViteDevServer() {
2601
- const state = getGlobalState();
2602
- const previous = state.__gurenActiveViteDevServer;
2603
- if (!previous) {
2604
- state.__gurenActiveViteDevServer = void 0;
2605
- clearManagedViteEnv();
2606
- return;
2738
+ 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;
2741
+ }
2742
+ 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
+ );
2759
+ }
2760
+ } finally {
2761
+ clearTimeout(timer);
2607
2762
  }
2763
+ }
2764
+ async function stopActiveViteDevServer() {
2765
+ const previous = getGlobalState().__gurenActiveViteDevServer;
2608
2766
  try {
2609
- await previous.close();
2610
- } catch (error) {
2611
- console.warn("Failed to stop previous Vite dev server:", error);
2767
+ if (previous) {
2768
+ await closeViteDevServerBounded(previous);
2769
+ }
2612
2770
  } finally {
2613
- state.__gurenActiveViteDevServer = void 0;
2771
+ setActiveViteDevServer();
2614
2772
  clearManagedViteEnv();
2615
2773
  }
2616
2774
  }
2617
- function setActiveViteDevServer(server) {
2618
- getGlobalState().__gurenActiveViteDevServer = server;
2775
+ function setActiveViteDevServer(server, localUrl) {
2776
+ const state = getGlobalState();
2777
+ state.__gurenActiveViteDevServer = server;
2778
+ state.__gurenActiveViteDevServerUrl = server ? localUrl : void 0;
2779
+ }
2780
+ function reusableActiveViteDevServer(viteOption) {
2781
+ if (typeof viteOption === "object") {
2782
+ return void 0;
2783
+ }
2784
+ const state = getGlobalState();
2785
+ const server = state.__gurenActiveViteDevServer;
2786
+ const localUrl = state.__gurenActiveViteDevServerUrl;
2787
+ if (!server || !localUrl || !server.httpServer?.listening) {
2788
+ return void 0;
2789
+ }
2790
+ return { server, localUrl };
2619
2791
  }
2620
2792
  var Application = class {
2621
2793
  constructor(options = {}) {
@@ -2625,6 +2797,7 @@ var Application = class {
2625
2797
  this.router = new Router();
2626
2798
  this.authManager = new AuthManager();
2627
2799
  this.providerManager = new ProviderManager(this.container);
2800
+ this.mountSecurityDefaults();
2628
2801
  this.container.instance("app", this);
2629
2802
  this.container.instance("hono", this.hono);
2630
2803
  this.container.instance("auth", this.authManager);
@@ -2674,10 +2847,12 @@ var Application = class {
2674
2847
  authManager;
2675
2848
  viteDevServer;
2676
2849
  bunServer;
2850
+ boundAddress;
2677
2851
  viteTeardownRegistered = false;
2678
2852
  bunTeardownRegistered = false;
2679
2853
  autoSessionAttached = false;
2680
2854
  routesRegistered = false;
2855
+ bootPromise;
2681
2856
  get auth() {
2682
2857
  return this.authManager;
2683
2858
  }
@@ -2716,26 +2891,44 @@ var Application = class {
2716
2891
  }
2717
2892
  /**
2718
2893
  * Executes provider registration, boot callback, mounts routes, and boots providers.
2894
+ *
2895
+ * Booting twice is a no-op: the first call's promise is reused, so providers
2896
+ * and routes are never mounted a second time — including when two callers
2897
+ * boot concurrently, before the first has finished. A boot that throws is not
2898
+ * remembered, so a later call attempts boot again (it resumes on a partially
2899
+ * mounted app rather than starting clean). The security defaults are mounted
2900
+ * by the constructor and so are outside this entirely.
2719
2901
  */
2720
2902
  async boot() {
2721
- this.mountSecurityDefaults();
2903
+ this.bootPromise ??= this.bootOnce();
2904
+ try {
2905
+ await this.bootPromise;
2906
+ } catch (error) {
2907
+ this.bootPromise = void 0;
2908
+ throw error;
2909
+ }
2910
+ }
2911
+ async bootOnce() {
2722
2912
  await this.providerManager.registerAll();
2723
2913
  await this.options.boot?.(this.hono);
2724
2914
  await this.mountRoutes();
2725
2915
  await this.mountDevEndpoint(
2726
2916
  isMcpEndpointEnabled(),
2727
- async () => (await import("./McpServiceProvider-GRDYNEQG.js")).McpServiceProvider,
2917
+ async () => (await import("./McpServiceProvider-FRJ5O7LT.js")).McpServiceProvider,
2728
2918
  "GUREN_MCP=1 but the MCP endpoint could not load \u2014 is @modelcontextprotocol/sdk installed?"
2729
2919
  );
2730
2920
  await this.mountDevEndpoint(
2731
2921
  isDocsViewerEnabled(),
2732
- async () => (await import("./DocsViewerServiceProvider-D7RGJPGM.js")).DocsViewerServiceProvider,
2922
+ async () => (await import("./DocsViewerServiceProvider-RUYDFBMW.js")).DocsViewerServiceProvider,
2733
2923
  "GUREN_DOCS=1 but the docs viewer could not load \u2014 is @guren/cli resolvable from this app?"
2734
2924
  );
2735
2925
  await this.providerManager.bootAll();
2736
2926
  }
2737
2927
  /**
2738
2928
  * Registers default security middleware (headers + host authorization).
2929
+ *
2930
+ * Called once, from the constructor — see the note there for why it does
2931
+ * not belong in boot().
2739
2932
  */
2740
2933
  mountSecurityDefaults() {
2741
2934
  const { securityHeaders } = this.options;
@@ -2785,13 +2978,30 @@ var Application = class {
2785
2978
  if (!Bun) {
2786
2979
  throw new Error("Bun runtime is required to call Application.listen");
2787
2980
  }
2788
- await stopActiveBunServer();
2789
- await stopActiveViteDevServer();
2790
- const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite } = options;
2981
+ await stopActiveBunServer(true);
2982
+ const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite, portFallback } = options;
2791
2983
  const externalAssetsUrl = typeof process !== "undefined" && process.env?.[MANAGED_VITE_ENV_FLAG] !== "1" ? process.env?.VITE_DEV_SERVER_URL : void 0;
2792
2984
  let resolvedAssetsUrl = assetsUrl ?? externalAssetsUrl;
2793
- const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
2794
- if (shouldStartVite) {
2985
+ const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
2986
+ 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";
2993
+ }
2994
+ syncManagedInertiaDevEntry(localUrl);
2995
+ this.registerViteTeardown();
2996
+ };
2997
+ const reusableVite = shouldStartVite ? reusableActiveViteDevServer(vite) : void 0;
2998
+ let startedViteHere = false;
2999
+ if (reusableVite) {
3000
+ adoptViteDevServer(reusableVite.server, reusableVite.localUrl);
3001
+ } else {
3002
+ await stopActiveViteDevServer();
3003
+ }
3004
+ if (shouldStartVite && !reusableVite) {
2795
3005
  const viteOptions = typeof vite === "object" ? vite : void 0;
2796
3006
  try {
2797
3007
  await this.closeViteDevServer();
@@ -2801,39 +3011,94 @@ var Application = class {
2801
3011
  host: viteOptions?.host,
2802
3012
  port: viteOptions?.port
2803
3013
  });
2804
- this.viteDevServer = server2;
2805
- setActiveViteDevServer(server2);
2806
- resolvedAssetsUrl = localUrl;
2807
- if (typeof process !== "undefined") {
2808
- process.env.VITE_DEV_SERVER_URL = resolvedAssetsUrl;
2809
- process.env[MANAGED_VITE_ENV_FLAG] = "1";
2810
- }
2811
- syncManagedInertiaDevEntry(resolvedAssetsUrl);
2812
- this.registerViteTeardown();
3014
+ adoptViteDevServer(server2, localUrl);
3015
+ startedViteHere = true;
2813
3016
  } catch (error) {
2814
3017
  console.error("Failed to start Vite dev server:", error);
2815
3018
  process.exit(1);
2816
3019
  }
2817
3020
  }
2818
- const server = Bun.serve({
2819
- port,
2820
- hostname,
2821
- // `{ server }` is Bun's convention for reaching the live server from a
2822
- // handler; middleware reads `ctx.env.server.requestIP()` through it to
2823
- // learn the socket peer (the MCP access guard, the rate limiter).
2824
- fetch: (request, server2) => this.fetch(request, { server: server2 })
2825
- });
3021
+ const attempts = resolvePortAttempts(portFallback, port);
3022
+ let server;
3023
+ let attemptPort = port;
3024
+ for (let offset = 0; offset < attempts; offset += 1) {
3025
+ attemptPort = port + offset;
3026
+ try {
3027
+ server = Bun.serve({
3028
+ port: attemptPort,
3029
+ hostname,
3030
+ // `{ server }` is Bun's convention for reaching the live server from a
3031
+ // handler; middleware reads `ctx.env.server.requestIP()` through it to
3032
+ // learn the socket peer (the MCP access guard, the rate limiter).
3033
+ fetch: (request, server2) => this.fetch(request, { server: server2 })
3034
+ });
3035
+ break;
3036
+ } catch (error) {
3037
+ if (offset === attempts - 1 || !isAddressInUse(error)) {
3038
+ if (startedViteHere) {
3039
+ await this.closeViteDevServer();
3040
+ }
3041
+ throw error;
3042
+ }
3043
+ console.warn(`[guren] Port ${attemptPort} is in use, trying ${attemptPort + 1}...`);
3044
+ }
3045
+ }
3046
+ if (!server) {
3047
+ throw new Error("Bun.serve did not return a server instance");
3048
+ }
3049
+ let boundPort = server.port;
3050
+ if (typeof boundPort !== "number") {
3051
+ if (port === 0) {
3052
+ await server.stop?.(true);
3053
+ throw new Error(
3054
+ "Bun.serve did not report a bound port for `port: 0`. Application.listen cannot report the address it is serving on."
3055
+ );
3056
+ }
3057
+ boundPort = attemptPort;
3058
+ }
3059
+ const boundHostname = server.hostname ?? hostname;
3060
+ const address = {
3061
+ port: boundPort,
3062
+ hostname: boundHostname,
3063
+ url: toConnectableUrl(boundHostname, boundPort)
3064
+ };
2826
3065
  this.bunServer = server;
3066
+ this.boundAddress = address;
2827
3067
  setActiveBunServer(server);
2828
3068
  this.registerBunTeardown();
2829
- const shouldLogBanner = typeof process === "undefined" || process.env?.NODE_ENV !== "production" && process.env?.GUREN_DEV_BANNER !== "0";
3069
+ const shouldLogBanner = typeof process === "undefined" || process.env.NODE_ENV !== "production" && process.env?.GUREN_DEV_BANNER !== "0";
2830
3070
  if (shouldLogBanner) {
2831
3071
  this.logDevServerBanner({
2832
- hostname,
2833
- port,
3072
+ hostname: boundHostname,
3073
+ port: boundPort,
2834
3074
  assetsUrl: resolvedAssetsUrl ?? "http://localhost:5173"
2835
3075
  });
2836
3076
  }
3077
+ return address;
3078
+ }
3079
+ /**
3080
+ * The address {@link Application.listen} bound, or `undefined` before it has
3081
+ * been called and once this app's server has been superseded or torn down.
3082
+ *
3083
+ * The same object `listen()` returned, so callers that need the address
3084
+ * later — an OpenAPI `servers` entry, an absolute URL, a health report —
3085
+ * read it here instead of threading it out of the entrypoint.
3086
+ *
3087
+ * The stored value is preferred over re-reading the live server, because
3088
+ * `listen()` resolves the port through a fallback the socket no longer
3089
+ * carries.
3090
+ *
3091
+ * 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.
3096
+ */
3097
+ get address() {
3098
+ if (!this.bunServer || getGlobalState().__gurenActiveServer !== this.bunServer) {
3099
+ return void 0;
3100
+ }
3101
+ return this.boundAddress;
2837
3102
  }
2838
3103
  /**
2839
3104
  * Register a service provider.
@@ -2860,9 +3125,7 @@ var Application = class {
2860
3125
  return;
2861
3126
  }
2862
3127
  try {
2863
- await this.viteDevServer.close();
2864
- } catch (error) {
2865
- console.error("Error while shutting down Vite dev server:", error);
3128
+ await closeViteDevServerBounded(this.viteDevServer);
2866
3129
  } finally {
2867
3130
  if (getGlobalState().__gurenActiveViteDevServer === this.viteDevServer) {
2868
3131
  setActiveViteDevServer();
@@ -3072,17 +3335,14 @@ var Controller = class {
3072
3335
  }
3073
3336
  async inertia(componentOrPage, props, options = {}) {
3074
3337
  const ctx = this.ctx;
3075
- const { url: overrideUrl, ...rest } = options;
3076
- const url2 = overrideUrl ?? ctx.req.path ?? ctx.req.url ?? "";
3077
3338
  const component = typeof componentOrPage === "string" ? componentOrPage : componentOrPage.component ?? componentOrPage.id;
3078
3339
  const sharedProps = await resolveSharedInertiaProps(ctx, this._container);
3079
3340
  const propsWithShared = { ...sharedProps, ...props };
3080
3341
  const response = await inertia(component, propsWithShared, {
3081
- ...rest,
3342
+ ...options,
3082
3343
  // No 'en' fallback here (unlike the locale getter): unconfigured apps
3083
3344
  // keep the Inertia engine's own default lang.
3084
- lang: rest.lang ?? this.#resolveLocale(),
3085
- url: url2,
3345
+ lang: options.lang ?? this.#resolveLocale(),
3086
3346
  request: ctx.req.raw
3087
3347
  });
3088
3348
  response.__gurenInertia = {
@@ -3727,14 +3987,18 @@ var FormRequest = class {
3727
3987
  }
3728
3988
  /**
3729
3989
  * Get the authenticated user from the request context.
3990
+ *
3991
+ * Awaiting is load-bearing: `this.user() !== null` compiles and is always
3992
+ * true, because an unawaited call is a pending promise.
3730
3993
  */
3731
- user() {
3994
+ async user() {
3732
3995
  const auth = this.ctx.get(AUTH_CONTEXT_KEY);
3733
- return auth?.user?.() ?? null;
3996
+ return await auth?.user() ?? null;
3734
3997
  }
3735
3998
  /**
3736
3999
  * Handle the form request: authorize, parse body, validate, return typed data.
3737
- * @internal Called by Controller.validate()
4000
+ * Call it from a controller with the request context:
4001
+ * `const data = await new StorePostRequest().handle(this.ctx)`.
3738
4002
  */
3739
4003
  async handle(ctx) {
3740
4004
  this.ctx = ctx;
@@ -6750,7 +7014,7 @@ function debugErrorMiddleware() {
6750
7014
  try {
6751
7015
  await next();
6752
7016
  } catch (err) {
6753
- const isProduction = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
7017
+ const isProduction = typeof process !== "undefined" && process.env.NODE_ENV === "production";
6754
7018
  if (isProduction) {
6755
7019
  throw err;
6756
7020
  }
@@ -6872,7 +7136,7 @@ function renderRequestSection(request) {
6872
7136
  </section>`;
6873
7137
  }
6874
7138
  function renderEnvironmentSection() {
6875
- const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV ?? "undefined" : "undefined";
7139
+ const nodeEnv = typeof process !== "undefined" ? process.env.NODE_ENV ?? "undefined" : "undefined";
6876
7140
  const bunVersion = typeof process !== "undefined" ? process.versions?.bun ?? "N/A" : "N/A";
6877
7141
  const platform = typeof process !== "undefined" ? process.platform ?? "unknown" : "unknown";
6878
7142
  return `