@guren/server 2.28.1 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { C as setInertiaSsrRenderer, D as isDeferredProp, E as isAlwaysProp, O as ensureErrorStackTracePolyfill, S as setInertiaDocument, T as defer, a as renderDocument, b as inertia, c as getRequestLocale, d as mountModuleRoutes, f as definePlugin, g as shareInertiaProps, h as setInertiaSharedProps, i as Controller, l as getRequestTranslator, m as resolveSharedInertiaProps, n as Resource, o as LOCALE_CONTEXT_KEY, p as getInertiaSharedPropsResolver, r as collect, s as detectLocaleMiddleware, t as JsonResource, u as defineModule, w as always } from "./Resource-BhOua2OB.js";
1
+ import { C as setInertiaSsrRenderer, D as isDeferredProp, E as isAlwaysProp, O as ensureErrorStackTracePolyfill, S as setInertiaDocument, T as defer, a as renderDocument, b as inertia, c as getRequestLocale, d as mountModuleRoutes, f as definePlugin, g as shareInertiaProps, h as setInertiaSharedProps, i as Controller, l as getRequestTranslator, m as resolveSharedInertiaProps, n as Resource, o as LOCALE_CONTEXT_KEY, p as getInertiaSharedPropsResolver, r as collect, s as detectLocaleMiddleware, t as JsonResource, u as defineModule, w as always } from "./Resource-ZMJH4lyD.js";
2
2
  import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, r as formatValidationErrors } from "./request-CLOYytGP.js";
3
3
  import { i as setValidatedInput, n as getValidatedInput } from "./validated-input-D84J8wcC.js";
4
4
  import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
5
5
  import { n as ValidationException } from "./errors-JpkcCjjn.js";
6
- import { a as withAuthorization, c as capabilitiesOf, i as derivableAbility, l as mergeCapabilities, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as stampCapabilities } from "./authorization-CKOLYWvi.js";
6
+ import { a as withAuthorization, c as capabilitiesOf, i as derivableAbility, l as mergeCapabilities, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as stampCapabilities } from "./authorization-DUjeyGWh.js";
7
7
  import { a as mapToolResponse, c as AGENT_PREFLIGHT_VERDICT_HEADER, i as describeBuildFailure, n as advertisesStructuredOutput, o as isDispatchedToolRequest, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "./dispatch-ENWpBxbE.js";
8
8
  import { i as trimSlashes } from "./contained-path-BkNSBljW.js";
9
9
  import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
@@ -20,15 +20,16 @@ import { _ as verifyApiToken, a as getApiToken, c as hasBearerHeader, d as revok
20
20
  import { a as runInRequestScope, i as keepAlive, n as filterSensitiveData, t as Logger } from "./Logger-DWXdtLSJ.js";
21
21
  import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-C2Im3l7t.js";
22
22
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
23
- import { r as isMcpEndpointEnabled } from "./endpoint-Coq0K_6I.js";
23
+ import { i as loadRuntimeErrorsModule, r as captureRuntimeError, s as isMcpEndpointEnabled, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-BclelWhA.js";
24
24
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
25
25
  import { a as setBroadcastManager, c as PresenceChannel, d as createWebSocketOriginGuard, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-N4cRV42s.js";
26
26
  import { c as tc, d as Translator, f as getPluralizationRule, i as getI18n, l as tryGetI18n, m as selectPluralForm, n as I18nManager, o as setI18n, p as pluralizationRules, r as createI18n, s as t, t as MemoryLoader, u as JsonLoader } from "./i18n-DmMKcbqj.js";
27
- import { a as cannot, f as setGate, g as tryGetRequestContainer, h as getRequestContainer, i as can, l as getGate, m as CONTAINER_CONTEXT_KEY, n as Response$1, o as createGate, p as AuthorizationException, r as authorize, s as defineGate, t as Gate } from "./Gate-CYfoGQqh.js";
27
+ import { n as getRequestContainer, r as tryGetRequestContainer, t as CONTAINER_CONTEXT_KEY } from "./request-container-BbuH0JJy.js";
28
28
  import { n as isAgentToolRequest } from "./agent-request-Caj6bnbj.js";
29
+ import { a as cannot, f as setGate, i as can, l as getGate, n as Response$1, o as createGate, p as AuthorizationException, r as authorize, s as defineGate, t as Gate } from "./Gate-DFiuutZm.js";
29
30
  import { r as isDocsViewerEnabled } from "./endpoint-CTIzcagh.js";
30
31
  import { n as isWildcardHost, t as formatHostPort } from "./host-port-t6wQFaRu.js";
31
- import { c as isViteProduction, d as startViteDevServer, i as clientManifestCandidates, l as loadViteManifest, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-wPxfAzjW.js";
32
+ import { C as stopBunServerBounded, S as stopActiveViteDevServer, _ as registerBunTeardown, b as setActiveBunServer, c as isViteProduction, d as startViteDevServer, g as hotReloadStopBound, h as getGlobalState, i as clientManifestCandidates, l as loadViteManifest, m as closeOwnedViteDevServer, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as adoptViteDevServer, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl, v as releaseActiveBunServer, x as stopActiveBunServer, y as reusableActiveViteDevServer } from "./vite-manifest-DO0pU1vm.js";
32
33
  import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
33
34
  import { a as RequestFinished, c as UserLoggedOut, d as EventManager, f as createEventManager, i as JobProcessed, l as createQueueEventDispatcher, n as ApplicationStarted, o as RequestReceived, p as Event, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as Listener } from "./events-DQavGm8W.js";
34
35
  import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-Bp2uamzD.js";
@@ -391,7 +392,7 @@ var Router = class {
391
392
  return this;
392
393
  }
393
394
  mount(app, options = {}) {
394
- for (const route of this.registry) {
395
+ const prepared = this.registry.map((route) => {
395
396
  const resolvedMiddlewares = this.resolveMiddlewareNames(route.routeMiddlewareNames);
396
397
  const handler = isPrototypeHandler(route.handler) ? createPrototypeRouteHandler(route, {
397
398
  container: options.container,
@@ -404,8 +405,12 @@ var Router = class {
404
405
  if (contractMiddleware) chain.push(contractMiddleware);
405
406
  if (preflightMiddleware) chain.push(preflightMiddleware);
406
407
  chain.push(handler);
407
- mountRoute(app, route.method, route.path, ...chain);
408
- }
408
+ return {
409
+ route,
410
+ chain
411
+ };
412
+ });
413
+ for (const { route, chain } of prepared) mountRoute(app, route.method, route.path, ...chain);
409
414
  }
410
415
  clear() {
411
416
  this.registry.splice(0, this.registry.length);
@@ -464,6 +469,18 @@ var Router = class {
464
469
  action: String(handler[1])
465
470
  } : { index });
466
471
  }
472
+ /** Model identities behind the serialized binding names, indexed like definitions (RFC 0032). */
473
+ registeredModelBindings() {
474
+ return this.registry.map(({ path, bindings }) => {
475
+ const result = Object.create(null);
476
+ for (const parameter of extractPathParamNames(path)) {
477
+ const model = this.modelBindings.get(parameter)?.model;
478
+ if (model) result[parameter] = model;
479
+ }
480
+ for (const [parameter, binding] of bindings ?? []) result[parameter] = binding.model;
481
+ return result;
482
+ });
483
+ }
467
484
  /**
468
485
  * Every alias and group resolved, and each route's chain in `mount()` order,
469
486
  * index-aligned with {@link definitions} (RFC 0026 §3). Like `definitions()`,
@@ -965,6 +982,31 @@ function joinPaths(prefixStack, path) {
965
982
  return "/" + segments.join("/").replace(/\/+/gu, "/");
966
983
  }
967
984
  //#endregion
985
+ //#region src/http/boot-sequence.ts
986
+ /** Successful steps stay complete; a rejected step must be safe for its owner to retry. */
987
+ var BootSequence = class {
988
+ steps;
989
+ next = 0;
990
+ pending;
991
+ constructor(steps) {
992
+ this.steps = steps;
993
+ }
994
+ run() {
995
+ this.pending ??= Promise.resolve().then(async () => {
996
+ try {
997
+ while (this.next < this.steps.length) {
998
+ await this.steps[this.next]();
999
+ this.next++;
1000
+ }
1001
+ } catch (error) {
1002
+ this.pending = void 0;
1003
+ throw error;
1004
+ }
1005
+ });
1006
+ return this.pending;
1007
+ }
1008
+ };
1009
+ //#endregion
968
1010
  //#region src/http/middleware/cookie-session-store.ts
969
1011
  const IV_BYTES = 12;
970
1012
  const TAG_BYTES = 16;
@@ -2187,6 +2229,7 @@ var ExceptionHandler = class {
2187
2229
  return process.env.NODE_ENV !== "production";
2188
2230
  }
2189
2231
  async handle(error, ctx) {
2232
+ if (!this.shouldNotReport(error)) captureRuntimeError(error, ctx, resolveExceptionStatus(error));
2190
2233
  await this.reportException(error);
2191
2234
  return this.renderException(error, ctx);
2192
2235
  }
@@ -3175,8 +3218,6 @@ function readSection(sources, key, warnings) {
3175
3218
  }
3176
3219
  //#endregion
3177
3220
  //#region src/http/Application.ts
3178
- const MANAGED_VITE_ENV_FLAG = "GUREN_MANAGED_VITE_DEV_SERVER";
3179
- const DEFAULT_DEV_ENTRY_PATH = "/resources/js/dev-entry.ts";
3180
3221
  /**
3181
3222
  * Opt-in strict port binding. The env var can only *subtract* the port walk,
3182
3223
  * never switch it on, so an operator can pin a port from outside an app whose
@@ -3221,201 +3262,9 @@ let devBanner;
3221
3262
  */
3222
3263
  async function loadDevBanner() {
3223
3264
  if (typeof process === "undefined") return devBanner;
3224
- if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-DnaL8Ku6.js").then((n) => n.n);
3265
+ if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-BAXzolUl.js").then((n) => n.n);
3225
3266
  return devBanner;
3226
3267
  }
3227
- function clearManagedViteEnv() {
3228
- if (typeof process === "undefined") return;
3229
- if (process.env[MANAGED_VITE_ENV_FLAG] === "1") {
3230
- delete process.env.VITE_DEV_SERVER_URL;
3231
- if (process.env.GUREN_INERTIA_ENTRY?.endsWith(DEFAULT_DEV_ENTRY_PATH)) delete process.env.GUREN_INERTIA_ENTRY;
3232
- }
3233
- delete process.env[MANAGED_VITE_ENV_FLAG];
3234
- }
3235
- function normalizeDevEntryUrl(baseUrl) {
3236
- return `${baseUrl.replace(/\/$/u, "")}${DEFAULT_DEV_ENTRY_PATH}`;
3237
- }
3238
- function syncManagedInertiaDevEntry(devServerUrl) {
3239
- if (typeof process === "undefined") return;
3240
- const nextEntry = normalizeDevEntryUrl(devServerUrl);
3241
- const currentEntry = process.env.GUREN_INERTIA_ENTRY;
3242
- if (!currentEntry || currentEntry.endsWith(DEFAULT_DEV_ENTRY_PATH)) process.env.GUREN_INERTIA_ENTRY = nextEntry;
3243
- }
3244
- function getGlobalState() {
3245
- return globalThis;
3246
- }
3247
- /**
3248
- * How long a server `stop()` may take before shutdown stops waiting. Abandoning
3249
- * this wait is safe in a way abandoning a Vite close is not: the socket has
3250
- * already stopped accepting connections, so what is left is a drain.
3251
- */
3252
- function bunStopTimeoutMs() {
3253
- return shutdownTimeoutMs("GUREN_BUN_STOP_TIMEOUT_MS");
3254
- }
3255
- /**
3256
- * How long a `bun --hot` reload waits on the server it replaces. That stop is
3257
- * forced, and the hot-reload teardown has already server-closed every broadcast
3258
- * WebSocket, so nothing is draining; on Bun 1.3.x `stop()` then never resolves
3259
- * (1.4.0 resolves at once). Quoted in docs/{en,ja}/guides/architecture.md.
3260
- */
3261
- const HOT_RELOAD_STOP_TIMEOUT_MS = 250;
3262
- function defaultStopBound() {
3263
- return {
3264
- timeoutMs: bunStopTimeoutMs(),
3265
- warn: true
3266
- };
3267
- }
3268
- /**
3269
- * Silent: on Bun 1.3.x it is hit on every reload, and there is nothing to
3270
- * report. `GUREN_BUN_STOP_TIMEOUT_MS` can only shorten it: it is set for a
3271
- * production drain, which a reload never is.
3272
- */
3273
- function hotReloadStopBound() {
3274
- return {
3275
- timeoutMs: Math.min(bunStopTimeoutMs(), HOT_RELOAD_STOP_TIMEOUT_MS),
3276
- warn: false
3277
- };
3278
- }
3279
- /**
3280
- * A positive integer of milliseconds, or 5000 when unset or unparseable. One
3281
- * parse for both bounds, so they cannot drift apart.
3282
- */
3283
- function shutdownTimeoutMs(envName) {
3284
- const parsed = typeof process !== "undefined" ? Number.parseInt(process.env[envName] ?? "", 10) : NaN;
3285
- return Number.isInteger(parsed) && parsed > 0 ? parsed : 5e3;
3286
- }
3287
- /**
3288
- * Awaits `work`, giving up after `timeoutMs`. Resolves either way: every caller
3289
- * is a shutdown path, and one that hangs is worse than one that gives up.
3290
- */
3291
- async function awaitBounded(work, timeoutMs, onTimeout) {
3292
- let timer;
3293
- try {
3294
- if (await Promise.race([work.then(() => false), new Promise((resolve) => {
3295
- timer = setTimeout(() => resolve(true), timeoutMs);
3296
- })])) onTimeout(timeoutMs);
3297
- } finally {
3298
- clearTimeout(timer);
3299
- }
3300
- }
3301
- /** `stop()` bounded by `bound` ({@link bunStopTimeoutMs} by default), warning rather than throwing. */
3302
- async function stopBunServerBounded(server, closeActiveConnections, bound = defaultStopBound()) {
3303
- await awaitBounded((async () => {
3304
- try {
3305
- await server.stop?.(closeActiveConnections);
3306
- } catch (error) {
3307
- console.warn("Failed to stop Bun server:", error);
3308
- }
3309
- })(), bound.timeoutMs, (timeoutMs) => {
3310
- if (!bound.warn) return;
3311
- console.warn(`Bun server did not stop within ${timeoutMs}ms — no longer waiting on it. In-flight requests may still be draining.`);
3312
- });
3313
- }
3314
- async function stopActiveBunServer(closeActiveConnections = false, bound) {
3315
- const state = getGlobalState();
3316
- const previous = state.__gurenActiveServer;
3317
- if (!previous?.stop) {
3318
- state.__gurenActiveServer = void 0;
3319
- return;
3320
- }
3321
- try {
3322
- await stopBunServerBounded(previous, closeActiveConnections, bound);
3323
- } finally {
3324
- releaseActiveBunServer(previous);
3325
- }
3326
- }
3327
- function setActiveBunServer(server) {
3328
- getGlobalState().__gurenActiveServer = server;
3329
- }
3330
- /**
3331
- * Gives up the process-wide slot, but only while it still holds `server`: a
3332
- * `listen()` that completed inside the caller's await has repointed it at a
3333
- * live server, which clearing would strip of its exit teardown.
3334
- */
3335
- function releaseActiveBunServer(server) {
3336
- if (getGlobalState().__gurenActiveServer === server) setActiveBunServer();
3337
- }
3338
- /**
3339
- * Attaches one SIGINT/SIGTERM/exit trio and returns the disposer for it. A
3340
- * boolean-guarded registrar would leave handlers attached and let the next
3341
- * `listen()` stack a second set on top — and `process.once` fires in
3342
- * registration order, so a stale handler's `process.exit()` can end the process
3343
- * ahead of the live set's shutdown.
3344
- */
3345
- function registerProcessTeardown(onSignal, onExit) {
3346
- process.once("SIGINT", onSignal);
3347
- process.once("SIGTERM", onSignal);
3348
- process.on("exit", onExit);
3349
- return () => {
3350
- process.off("SIGINT", onSignal);
3351
- process.off("SIGTERM", onSignal);
3352
- process.off("exit", onExit);
3353
- };
3354
- }
3355
- /**
3356
- * How long a Vite `close()` may take before shutdown abandons it — a browser tab
3357
- * holding its HMR socket can keep that wait alive indefinitely. A stranded asset
3358
- * server is recoverable noise; a `listen()` that never returns is not.
3359
- */
3360
- function viteCloseTimeoutMs() {
3361
- return shutdownTimeoutMs("GUREN_VITE_CLOSE_TIMEOUT_MS");
3362
- }
3363
- /**
3364
- * `close()` bounded by {@link viteCloseTimeoutMs}: resolves once the server
3365
- * closed, failed (warned), or ran out the clock (warned, abandoned).
3366
- */
3367
- async function closeViteDevServerBounded(server) {
3368
- await awaitBounded((async () => {
3369
- try {
3370
- await server.close();
3371
- } catch (error) {
3372
- console.warn("Failed to stop Vite dev server:", error);
3373
- }
3374
- })(), viteCloseTimeoutMs(), (timeoutMs) => {
3375
- console.warn(`Vite dev server did not close within ${timeoutMs}ms — abandoning it. A stale asset server may still hold its port.`);
3376
- });
3377
- }
3378
- /**
3379
- * Closes the managed Vite dev server whoever owns it. Only `listen()`'s restart
3380
- * path calls this — the one case where an owner's claim does not survive.
3381
- */
3382
- async function stopActiveViteDevServer() {
3383
- const previous = getGlobalState().__gurenActiveViteDevServer;
3384
- try {
3385
- if (previous) await closeViteDevServerBounded(previous.server);
3386
- } finally {
3387
- previous?.disposeTeardown();
3388
- if (getGlobalState().__gurenActiveViteDevServer === previous) setActiveViteDevServer();
3389
- }
3390
- }
3391
- function publishManagedViteEnv(localUrl) {
3392
- if (typeof process === "undefined") return;
3393
- process.env.VITE_DEV_SERVER_URL = localUrl;
3394
- process.env[MANAGED_VITE_ENV_FLAG] = "1";
3395
- syncManagedInertiaDevEntry(localUrl);
3396
- }
3397
- /**
3398
- * The one write point for the active-record slot. `VITE_DEV_SERVER_URL` and the
3399
- * managed flag travel with it, so a stale close cannot unpublish an adopter's
3400
- * URL while its record stays live, or the reverse.
3401
- */
3402
- function setActiveViteDevServer(active) {
3403
- getGlobalState().__gurenActiveViteDevServer = active;
3404
- if (active) publishManagedViteEnv(active.localUrl);
3405
- else clearManagedViteEnv();
3406
- }
3407
- /**
3408
- * The managed Vite dev server a previous `listen()` left running. Reusing it
3409
- * keeps the browser's HMR socket connected and skips the
3410
- * {@link viteCloseTimeoutMs} wait. Explicit `vite` options veto reuse: the
3411
- * running server was built from the *previous* call's options.
3412
- */
3413
- function reusableActiveViteDevServer(viteOption) {
3414
- if (typeof viteOption === "object") return;
3415
- const active = getGlobalState().__gurenActiveViteDevServer;
3416
- if (!active || !active.server.httpServer?.listening) return;
3417
- return active;
3418
- }
3419
3268
  /**
3420
3269
  * Wires an app-local router and a DI container into a running Hono instance.
3421
3270
  *
@@ -3444,10 +3293,13 @@ var Application = class {
3444
3293
  cookielessAuthPaths = /* @__PURE__ */ new Set();
3445
3294
  /** {@link configDefinitions} with where each was listed, which ConfigServiceProvider's errors name. */
3446
3295
  configEntries;
3447
- routesRegistered = false;
3296
+ routeRegistration;
3297
+ bootSequence;
3448
3298
  bootPromise;
3449
3299
  manifestPromise;
3450
3300
  bootAttempted = false;
3301
+ /** Settles once the dev-only runtime error buffer is bound; boot waits for it so McpServiceProvider sees the binding. */
3302
+ runtimeErrorsLoaded;
3451
3303
  constructor(options = {}) {
3452
3304
  this.options = options;
3453
3305
  this.configEntries = [...(options.config ?? []).map((definition, index) => ({
@@ -3468,6 +3320,15 @@ var Application = class {
3468
3320
  this.container.instance("hono", this.hono);
3469
3321
  this.container.instance("auth", this.authManager);
3470
3322
  this.container.instance("router", this.router);
3323
+ const runtimeErrors = loadRuntimeErrorsModule();
3324
+ if (runtimeErrors) {
3325
+ const root = process.cwd();
3326
+ this.runtimeErrorsLoaded = runtimeErrors.then(({ RuntimeErrorBuffer }) => {
3327
+ this.container.instance(RUNTIME_ERRORS_BINDING, new RuntimeErrorBuffer(root));
3328
+ }, (error) => {
3329
+ console.warn(`[guren] GUREN_MCP=1 but the runtime error collector could not load: ${error instanceof Error ? error.message : String(error)}`);
3330
+ });
3331
+ }
3471
3332
  if (options.inertia?.document) this.container.instance("inertia.document", options.inertia.document);
3472
3333
  if (options.inertia?.ssrRenderer) this.container.instance("inertia.ssrRenderer", options.inertia.ssrRenderer);
3473
3334
  if (options.inertia?.share) shareInertiaProps(options.inertia.share, this.container);
@@ -3549,11 +3410,8 @@ var Application = class {
3549
3410
  }
3550
3411
  /** Runs the registrars once; `introspect()` stops here, since mounting refuses an unregistered alias it reports. */
3551
3412
  async registerRoutes() {
3552
- if (!this.routesRegistered) {
3553
- if (this.options.routes) await this.options.routes(this.router);
3554
- for (const gurenModule of this.options.modules ?? []) await mountModuleRoutes(this.router, gurenModule);
3555
- this.routesRegistered = true;
3556
- }
3413
+ this.routeRegistration ??= new BootSequence([() => this.options.routes?.(this.router), ...(this.options.modules ?? []).map((gurenModule) => () => mountModuleRoutes(this.router, gurenModule))]);
3414
+ await this.routeRegistration.run();
3557
3415
  }
3558
3416
  /**
3559
3417
  * Every failure here is one a request would otherwise surface as a 500:
@@ -3582,9 +3440,9 @@ var Application = class {
3582
3440
  /**
3583
3441
  * Registers providers, runs the boot callback, mounts routes, boots providers.
3584
3442
  *
3585
- * Booting twice is a no-op — the first call's promise is reused, concurrent
3586
- * callers included. A boot that throws is not remembered, so a later call
3587
- * retries on the partially mounted app rather than starting clean.
3443
+ * Concurrent callers share a boot. On failure, a later call resumes at the
3444
+ * failed step; completed steps stay complete. A throwing hook must undo its
3445
+ * own partial effects or be safe to retry; otherwise construct a fresh app.
3588
3446
  */
3589
3447
  async boot() {
3590
3448
  if (isIntrospecting()) {
@@ -3592,11 +3450,11 @@ var Application = class {
3592
3450
  return;
3593
3451
  }
3594
3452
  if (this.manifestPromise) throw new Error("[guren] This application was introspected: its providers may have run introspect() in place of register(), so it cannot boot. Construct a new application to serve it.");
3595
- this.bootPromise ??= this.bootOnce();
3453
+ const attempt = this.bootPromise ??= this.bootOnce();
3596
3454
  try {
3597
- await this.bootPromise;
3455
+ await attempt;
3598
3456
  } catch (error) {
3599
- this.bootPromise = void 0;
3457
+ if (this.bootPromise === attempt) this.bootPromise = void 0;
3600
3458
  throw error;
3601
3459
  }
3602
3460
  }
@@ -3634,14 +3492,18 @@ var Application = class {
3634
3492
  }
3635
3493
  async bootOnce() {
3636
3494
  this.bootAttempted = true;
3495
+ if (this.runtimeErrorsLoaded) await this.runtimeErrorsLoaded;
3637
3496
  if (this.options.hostAuthorization !== void 0 && this.hasHttpConfig()) throw new Error("[guren] Host authorization is configured twice: createApp({ hostAuthorization }) and config/http.ts. Keep one.");
3638
3497
  await this.providerManager.registerAll();
3639
- await this.options.boot?.(this.hono);
3640
- await this.mountRoutes();
3641
- await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-PGFPlYTy.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @guren/cli installed?");
3642
- await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-BMbcTYVw.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
3643
- await this.providerManager.bootAll();
3644
- this.warnOnUnconfiguredAuth();
3498
+ this.bootSequence ??= new BootSequence([
3499
+ () => this.options.boot?.(this.hono),
3500
+ () => this.mountRoutes(),
3501
+ () => this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-CvFExxdJ.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @guren/cli installed?"),
3502
+ () => this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-BVPZjwQp.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?"),
3503
+ () => this.providerManager.bootAll(),
3504
+ () => this.warnOnUnconfiguredAuth()
3505
+ ]);
3506
+ await this.bootSequence.run();
3645
3507
  }
3646
3508
  /**
3647
3509
  * After every provider has booted: `auth` was asked for, yet the default
@@ -3724,28 +3586,18 @@ var Application = class {
3724
3586
  const supersededServer = getGlobalState().__gurenActiveServer;
3725
3587
  await stopActiveBunServer(true, isHotReloadRuntime() ? hotReloadStopBound() : void 0);
3726
3588
  const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite, portFallback } = options;
3727
- const externalAssetsUrl = typeof process !== "undefined" && process.env?.[MANAGED_VITE_ENV_FLAG] !== "1" ? process.env?.VITE_DEV_SERVER_URL : void 0;
3589
+ const externalAssetsUrl = typeof process !== "undefined" && process.env?.["GUREN_MANAGED_VITE_DEV_SERVER"] !== "1" ? process.env?.VITE_DEV_SERVER_URL : void 0;
3728
3590
  let resolvedAssetsUrl = assetsUrl ?? externalAssetsUrl;
3729
3591
  const shouldLogBanner = typeof process === "undefined" || process.env.NODE_ENV !== "production" && process.env?.GUREN_DEV_BANNER !== "0";
3730
3592
  if (shouldLogBanner) await loadDevBanner();
3731
3593
  const { websocket } = await import("hono/bun");
3732
3594
  const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
3733
- const adoptViteDevServer = (viteServer, localUrl) => {
3734
- const displaced = getGlobalState().__gurenActiveViteDevServer;
3735
- displaced?.disposeTeardown();
3736
- if (displaced && displaced.server !== viteServer) closeViteDevServerBounded(displaced.server);
3737
- setActiveViteDevServer({
3738
- server: viteServer,
3739
- localUrl,
3740
- owner: this,
3741
- disposeTeardown: this.registerViteTeardown()
3742
- });
3743
- resolvedAssetsUrl = localUrl;
3744
- };
3745
3595
  const reusableVite = shouldStartVite ? reusableActiveViteDevServer(vite) : void 0;
3746
3596
  let startedViteHere = false;
3747
- if (reusableVite) adoptViteDevServer(reusableVite.server, reusableVite.localUrl);
3748
- else await stopActiveViteDevServer();
3597
+ if (reusableVite) {
3598
+ adoptViteDevServer(this, reusableVite.server, reusableVite.localUrl);
3599
+ resolvedAssetsUrl = reusableVite.localUrl;
3600
+ } else await stopActiveViteDevServer();
3749
3601
  if (shouldStartVite && !reusableVite) {
3750
3602
  const viteOptions = typeof vite === "object" ? vite : void 0;
3751
3603
  try {
@@ -3755,11 +3607,11 @@ var Application = class {
3755
3607
  host: viteOptions?.host,
3756
3608
  port: viteOptions?.port
3757
3609
  });
3758
- adoptViteDevServer(server, localUrl);
3610
+ adoptViteDevServer(this, server, localUrl);
3611
+ resolvedAssetsUrl = localUrl;
3759
3612
  startedViteHere = true;
3760
3613
  } catch (error) {
3761
- console.error("Failed to start Vite dev server:", error);
3762
- process.exit(1);
3614
+ throw new Error(`Failed to start Vite dev server: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
3763
3615
  }
3764
3616
  }
3765
3617
  const attempts = resolvePortAttempts(portFallback, port);
@@ -3777,7 +3629,7 @@ var Application = class {
3777
3629
  break;
3778
3630
  } catch (error) {
3779
3631
  if (offset === attempts - 1 || !isAddressInUse(error)) {
3780
- if (startedViteHere) await this.closeViteDevServer();
3632
+ if (startedViteHere) await closeOwnedViteDevServer(this);
3781
3633
  throw error;
3782
3634
  }
3783
3635
  console.warn(`[guren] Port ${attemptPort} is in use, trying ${attemptPort + 1}...`);
@@ -3828,7 +3680,7 @@ var Application = class {
3828
3680
  * or when called twice. `closeActiveConnections` forces in-flight requests
3829
3681
  * closed, matching Bun's own `stop()`. The managed Vite dev server goes too,
3830
3682
  * unless a later `listen()` adopted it. Both closes are bounded
3831
- * ({@link bunStopTimeoutMs}, {@link viteCloseTimeoutMs}) and then abandoned.
3683
+ * (GUREN_BUN_STOP_TIMEOUT_MS and GUREN_VITE_CLOSE_TIMEOUT_MS) and then abandoned.
3832
3684
  */
3833
3685
  async stop(closeActiveConnections = false) {
3834
3686
  const server = this.bunServer;
@@ -3842,7 +3694,8 @@ var Application = class {
3842
3694
  this.boundAddress = void 0;
3843
3695
  this.disposeBunTeardown?.();
3844
3696
  this.disposeBunTeardown = void 0;
3845
- await this.closeViteDevServer();
3697
+ await closeOwnedViteDevServer(this);
3698
+ if (!this.bunServer) this.container.makeOptional(RUNTIME_ERRORS_BINDING)?.reset();
3846
3699
  }
3847
3700
  register(provider) {
3848
3701
  this.providerManager.register(provider);
@@ -3865,43 +3718,9 @@ var Application = class {
3865
3718
  }
3866
3719
  loadDevBanner().then((loaded) => loaded?.logDevServerBanner(options), (error) => console.error("Failed to load the dev server banner:", error));
3867
3720
  }
3868
- /**
3869
- * Closes the managed Vite dev server, but only while this application still
3870
- * owns it: another `listen()` may have adopted the same object, and closing it
3871
- * then would take the asset server out from under an app serving from it. The
3872
- * slot's record is the one place that distinction exists.
3873
- */
3874
- async closeViteDevServer() {
3875
- const active = getGlobalState().__gurenActiveViteDevServer;
3876
- if (active?.owner !== this) return;
3877
- try {
3878
- await closeViteDevServerBounded(active.server);
3879
- } finally {
3880
- active.disposeTeardown();
3881
- if (getGlobalState().__gurenActiveViteDevServer === active) setActiveViteDevServer();
3882
- }
3883
- }
3884
- /**
3885
- * Attaches this application's Vite teardown handlers and returns the disposer.
3886
- * It is stored in the active-record slot, not on this instance, because
3887
- * whoever takes ownership next is the one that has to call it.
3888
- */
3889
- registerViteTeardown() {
3890
- if (typeof process === "undefined") return () => {};
3891
- return registerProcessTeardown(() => {
3892
- this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
3893
- }, () => {
3894
- const active = getGlobalState().__gurenActiveViteDevServer;
3895
- if (active?.owner === this) active.server.close();
3896
- });
3897
- }
3898
3721
  registerBunTeardown() {
3899
3722
  if (this.disposeBunTeardown || typeof process === "undefined") return;
3900
- this.disposeBunTeardown = registerProcessTeardown(() => {
3901
- stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
3902
- }, () => {
3903
- stopActiveBunServer();
3904
- });
3723
+ this.disposeBunTeardown = registerBunTeardown();
3905
3724
  }
3906
3725
  };
3907
3726
  function createApp(options = {}) {
@@ -1,4 +1,4 @@
1
- import { _ as INERTIA_VARY, f as definePlugin, i as Controller, n as Resource, r as collect, t as JsonResource, u as defineModule, v as acceptsJson, x as serializePage, y as buildInertiaPage } from "../Resource-BhOua2OB.js";
1
+ import { _ as INERTIA_VARY, f as definePlugin, i as Controller, n as Resource, r as collect, t as JsonResource, u as defineModule, v as acceptsJson, x as serializePage, y as buildInertiaPage } from "../Resource-ZMJH4lyD.js";
2
2
  import { r as formatValidationErrors } from "../request-CLOYytGP.js";
3
3
  import { n as ValidationException } from "../errors-JpkcCjjn.js";
4
4
  import { n as ServiceProvider } from "../ServiceProvider-G0YclITd.js";
@@ -89,6 +89,12 @@ export type RouteSchemaEntry = JsonSchema | {
89
89
  export type RouteEntry = Omit<RouteDefinition, 'schemas' | 'controller' | 'middlewareNames' | 'module'> & {
90
90
  module: string | null;
91
91
  controller?: ControllerRef;
92
+ /** Populated only by graph introspection after matching the actual bound class identity. */
93
+ bindingSources?: Record<string, {
94
+ file: string;
95
+ exportName: string;
96
+ name: string;
97
+ }>;
92
98
  /** In the order `mount()` runs them: named, then group-scoped inline, then route-local inline. */
93
99
  middleware: MiddlewareEntry[];
94
100
  schemas: Partial<Record<'params' | 'query' | 'body' | 'output', RouteSchemaEntry>>;
@@ -1,3 +1,4 @@
1
+ import type { RuntimeErrorQuery } from './runtime-errors.js';
1
2
  import { ServiceProvider } from '../container/ServiceProvider.js';
2
3
  /**
3
4
  * What this provider calls on `@guren/cli`, spelled here: the package cannot be
@@ -5,8 +6,14 @@ import { ServiceProvider } from '../container/ServiceProvider.js';
5
6
  * build as `any`. Same seam as `DocsViewerServiceProvider`'s.
6
7
  */
7
8
  export interface DevMcpCliApi {
9
+ createDevCenterHandler?(options: {
10
+ cwd: string;
11
+ }): {
12
+ fetch(request: Request): Promise<Response>;
13
+ };
8
14
  createDevMcpHandler?(options: {
9
15
  cwd: string;
16
+ runtimeErrors?: (query: RuntimeErrorQuery) => unknown;
10
17
  }): {
11
18
  fetch(request: Request): Promise<Response>;
12
19
  };
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as McpServiceProvider } from "../McpServiceProvider-PGFPlYTy.js";
1
+ import { t as McpServiceProvider } from "../McpServiceProvider-CvFExxdJ.js";
2
2
  export { McpServiceProvider };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The half of the dev-only runtime error collector that every build carries:
3
+ * the binding names, the capture call ExceptionHandler makes, and the loader for
4
+ * `./runtime-errors`. The buffer (node:fs frame resolution, hono/route) stays
5
+ * behind that loader so a deploy bundle drops it.
6
+ */
7
+ import type { Context } from 'hono';
8
+ export declare const RUNTIME_ERRORS_BINDING = "dev.runtimeErrors";
9
+ export declare const RUNTIME_ERRORS_PATH = "/_guren/runtime/errors";
10
+ /** What the `RUNTIME_ERRORS_BINDING` binding answers; `RuntimeErrorBuffer` implements it. */
11
+ export interface RuntimeErrorCollector {
12
+ capture(error: Error, ctx: Context, status: number): void;
13
+ }
14
+ type RuntimeErrorsModule = typeof import('./runtime-errors.js');
15
+ /**
16
+ * The buffer module while the collector is enabled, else undefined. The NODE_ENV
17
+ * read is plain member access so a deploy build's `--define` settles the branch
18
+ * and the bundler drops the `import()` with it; `isMcpEndpointEnabled()` alone is
19
+ * a call no define can settle. `tests/mcp/runtime-errors.test.ts` pins the form.
20
+ */
21
+ export declare function loadRuntimeErrorsModule(): Promise<RuntimeErrorsModule> | undefined;
22
+ /** Only ExceptionHandler calls this, after applying its dontReport policy. */
23
+ export declare function captureRuntimeError(error: Error, ctx: Context, status: number): void;
24
+ export {};