@guren/server 1.2.0 → 1.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 (44) hide show
  1. package/dist/{Application-DN9Ndl37.d.ts → Application-BvBqgc2k.d.ts} +204 -22
  2. package/dist/{AuthManager-SfhCNkAU.d.ts → AuthManager-C84xF5ks.d.ts} +1 -1
  3. package/dist/{BroadcastManager-CGWl9rUO.d.ts → BroadcastManager-D8KoJxiV.d.ts} +21 -0
  4. package/dist/{CacheManager-BkvHEOZX.d.ts → CacheManager-BmDzUKrF.d.ts} +17 -0
  5. package/dist/{ConsoleKernel-DxmUxdAz.d.ts → ConsoleKernel-Dw9X9qZY.d.ts} +1 -1
  6. package/dist/{I18nManager-BiSoczfV.d.ts → I18nManager-CmUqj6bU.d.ts} +1 -1
  7. package/dist/{McpServiceProvider-JW6PDVMD.js → McpServiceProvider-TZWQWXCT.js} +2 -2
  8. package/dist/{Scheduler-BstvSca7.d.ts → Scheduler-pZiT8i57.d.ts} +2 -0
  9. package/dist/{api-token-BSSCLlFW.d.ts → api-token-COQHXyM_.d.ts} +123 -1
  10. package/dist/auth/index.d.ts +5 -5
  11. package/dist/auth/index.js +3 -1
  12. package/dist/authorization/index.js +2 -2
  13. package/dist/broadcasting/index.d.ts +2 -2
  14. package/dist/broadcasting/index.js +2 -1
  15. package/dist/cache/index.d.ts +2 -2
  16. package/dist/cache/index.js +2 -1
  17. package/dist/{chunk-EGU5KB7V.js → chunk-4SBGSJNT.js} +31 -1
  18. package/dist/{chunk-THSX7OOR.js → chunk-63SKW5PS.js} +3 -0
  19. package/dist/{chunk-2T6JN4VR.js → chunk-AUXQISW5.js} +169 -14
  20. package/dist/chunk-DCYKSYAT.js +63 -0
  21. package/dist/{chunk-ZRBLZY3M.js → chunk-FZD2AKJI.js} +1 -1
  22. package/dist/{chunk-HLXL2AYJ.js → chunk-JIT7QVMJ.js} +2 -2
  23. package/dist/{chunk-HKQSAFSN.js → chunk-MC752CQT.js} +15 -0
  24. package/dist/{chunk-WVY45EIW.js → chunk-NQCZQAJL.js} +93 -28
  25. package/dist/{chunk-VT5KRDPH.js → chunk-NYQGAWDN.js} +49 -1
  26. package/dist/{chunk-44F7JQ7I.js → chunk-XMQZENBP.js} +35 -1
  27. package/dist/{client-CKXJLsTe.d.ts → client-BQwF2b9Y.d.ts} +7 -0
  28. package/dist/{email-verification-CAeArjui.d.ts → email-verification-H_WlpsVH.d.ts} +1 -1
  29. package/dist/{errors-JOOPDDQ6.js → errors-PUNHAFL2.js} +1 -1
  30. package/dist/i18n/index.d.ts +2 -2
  31. package/dist/index.d.ts +129 -19
  32. package/dist/index.js +314 -105
  33. package/dist/lambda/index.d.ts +8 -8
  34. package/dist/mcp/index.d.ts +54 -20
  35. package/dist/mcp/index.js +2 -2
  36. package/dist/notifications/index.d.ts +8 -8
  37. package/dist/queue/index.d.ts +8 -8
  38. package/dist/redis/index.d.ts +11 -21
  39. package/dist/redis/index.js +42 -6
  40. package/dist/runtime/index.d.ts +8 -8
  41. package/dist/runtime/index.js +1 -1
  42. package/dist/scheduling/index.d.ts +2 -2
  43. package/dist/scheduling/index.js +2 -1
  44. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  logDevServerBanner,
3
3
  parseImportMap,
4
4
  startViteDevServer
5
- } from "./chunk-HLXL2AYJ.js";
5
+ } from "./chunk-JIT7QVMJ.js";
6
6
  import {
7
7
  PendingSchedule,
8
8
  Schedule,
@@ -16,7 +16,7 @@ import {
16
16
  matchesCron,
17
17
  parseCron,
18
18
  toTimezone
19
- } from "./chunk-HKQSAFSN.js";
19
+ } from "./chunk-MC752CQT.js";
20
20
  import {
21
21
  LocalDriver,
22
22
  MemoryDriver as MemoryDriver3,
@@ -63,9 +63,11 @@ import {
63
63
  setMailManager
64
64
  } from "./chunk-EDRGAM6G.js";
65
65
  import {
66
+ MCP_ENDPOINT_PATH,
66
67
  ProviderManager,
67
- ServiceProvider
68
- } from "./chunk-VT5KRDPH.js";
68
+ ServiceProvider,
69
+ isMcpEndpointEnabled
70
+ } from "./chunk-NYQGAWDN.js";
69
71
  import {
70
72
  DatabaseChannel,
71
73
  MailChannel,
@@ -143,7 +145,10 @@ import {
143
145
  getApiTokenOrFail,
144
146
  getSessionFromContext,
145
147
  getUserApiTokens,
148
+ hostMatchesAllowlist,
149
+ isAppRelativePath,
146
150
  isEmailVerified,
151
+ normalizeRedirectTarget,
147
152
  parseApiToken,
148
153
  parseOAuthRedirectUrl,
149
154
  parsePasswordResetUrl,
@@ -151,6 +156,7 @@ import {
151
156
  requireVerifiedEmail,
152
157
  revokeAllApiTokens,
153
158
  revokeApiToken,
159
+ sanitizeOAuthRedirect,
154
160
  tokenCan,
155
161
  tokenCanAll,
156
162
  tokenCanAny,
@@ -158,7 +164,7 @@ import {
158
164
  verifyEmailToken,
159
165
  verifyOAuthState,
160
166
  verifyPasswordResetToken
161
- } from "./chunk-2T6JN4VR.js";
167
+ } from "./chunk-AUXQISW5.js";
162
168
  import {
163
169
  Gate,
164
170
  Policy,
@@ -175,7 +181,7 @@ import {
175
181
  getGate,
176
182
  setGate,
177
183
  withAuthorization
178
- } from "./chunk-ZRBLZY3M.js";
184
+ } from "./chunk-FZD2AKJI.js";
179
185
  import {
180
186
  AuthorizationException,
181
187
  ExceptionHandler,
@@ -189,7 +195,7 @@ import {
189
195
  getExceptionHandler,
190
196
  renderErrorPage,
191
197
  setExceptionHandler
192
- } from "./chunk-THSX7OOR.js";
198
+ } from "./chunk-63SKW5PS.js";
193
199
  import {
194
200
  AuthenticationException,
195
201
  HttpException
@@ -208,7 +214,7 @@ import {
208
214
  getBroadcastManager,
209
215
  parseRequestPayload,
210
216
  setBroadcastManager
211
- } from "./chunk-44F7JQ7I.js";
217
+ } from "./chunk-XMQZENBP.js";
212
218
  import {
213
219
  CacheManager,
214
220
  FileStore,
@@ -216,7 +222,11 @@ import {
216
222
  RedisStore,
217
223
  TaggedCache,
218
224
  createCacheManager
219
- } from "./chunk-EGU5KB7V.js";
225
+ } from "./chunk-4SBGSJNT.js";
226
+ import {
227
+ claimHotDisposable,
228
+ isHotReloadRuntime
229
+ } from "./chunk-DCYKSYAT.js";
220
230
  import {
221
231
  Encrypter,
222
232
  createEncrypter,
@@ -381,6 +391,8 @@ var Router = class {
381
391
  middlewareAliases = /* @__PURE__ */ new Map();
382
392
  middlewareGroups = /* @__PURE__ */ new Map();
383
393
  modelBindings = /* @__PURE__ */ new Map();
394
+ /** Model class names for router-level bind(param, Model) calls — resolver-only binds carry no name. */
395
+ modelBindingNames = /* @__PURE__ */ new Map();
384
396
  aliasMiddleware(name, handler) {
385
397
  this.middlewareAliases.set(name, handler);
386
398
  return this;
@@ -395,6 +407,7 @@ var Router = class {
395
407
  bind(param, modelOrResolver) {
396
408
  if (typeof modelOrResolver === "function" && "findOrFail" in modelOrResolver) {
397
409
  const model = modelOrResolver;
410
+ if (model.name) this.modelBindingNames.set(param, model.name);
398
411
  this.modelBindings.set(param, async (value) => {
399
412
  return model.findOrFail(value);
400
413
  });
@@ -476,9 +489,10 @@ var Router = class {
476
489
  this.middlewareAliases.clear();
477
490
  this.middlewareGroups.clear();
478
491
  this.modelBindings.clear();
492
+ this.modelBindingNames.clear();
479
493
  }
480
494
  definitions() {
481
- return this.registry.map(({ method, path, name, schemas, openapi, routeMiddlewareNames, middlewares, handler }) => ({
495
+ return this.registry.map(({ method, path, name, schemas, openapi, routeMiddlewareNames, middlewares, handler, bindings }) => ({
482
496
  method,
483
497
  path,
484
498
  name,
@@ -486,6 +500,7 @@ var Router = class {
486
500
  middlewareNames: [...routeMiddlewareNames],
487
501
  hasInlineMiddleware: middlewares.length > 0,
488
502
  controller: isControllerAction(handler) ? { name: handler[0].name, action: String(handler[1]) } : void 0,
503
+ bindings: serializeBindings(path, bindings, this.modelBindingNames),
489
504
  ...openapi
490
505
  }));
491
506
  }
@@ -814,6 +829,17 @@ function buildResponse(result) {
814
829
  }
815
830
  return new Response(String(result));
816
831
  }
832
+ function serializeBindings(path, routeBindings, routerBindingNames) {
833
+ const entries = /* @__PURE__ */ new Map();
834
+ for (const param of path.match(/:(\w+)/g) ?? []) {
835
+ const name = routerBindingNames.get(param.slice(1));
836
+ if (name) entries.set(param.slice(1), name);
837
+ }
838
+ for (const [param, model] of routeBindings ?? []) {
839
+ if (model.name) entries.set(param, model.name);
840
+ }
841
+ return entries.size > 0 ? Object.fromEntries(entries) : void 0;
842
+ }
817
843
  function isControllerAction(action) {
818
844
  return Array.isArray(action);
819
845
  }
@@ -832,7 +858,50 @@ function joinPaths(prefixStack, path) {
832
858
  return "/" + combined.replace(/\/+/gu, "/");
833
859
  }
834
860
 
861
+ // src/container/definePlugin.ts
862
+ function definePlugin(definition) {
863
+ const className = `${definition.name}PluginProvider`;
864
+ return (config) => {
865
+ class ConfiguredPluginProvider extends ServiceProvider {
866
+ static deferred = definition.deferred ?? false;
867
+ static provides = definition.provides ?? [];
868
+ register() {
869
+ return definition.register(this.container, config);
870
+ }
871
+ boot() {
872
+ return definition.boot?.(this.container, config);
873
+ }
874
+ }
875
+ Object.defineProperty(ConfiguredPluginProvider, "name", { value: className });
876
+ return ConfiguredPluginProvider;
877
+ };
878
+ }
879
+
880
+ // src/container/defineModule.ts
881
+ function defineModule(definition) {
882
+ return {
883
+ name: definition.name,
884
+ prefix: definition.prefix,
885
+ routes: definition.routes,
886
+ providers: definition.providers ?? []
887
+ };
888
+ }
889
+ async function mountModuleRoutes(router, gurenModule) {
890
+ const registrar = gurenModule.routes;
891
+ if (!registrar) return;
892
+ if (!gurenModule.prefix) {
893
+ await registrar(router);
894
+ return;
895
+ }
896
+ let pending = void 0;
897
+ router.group(gurenModule.prefix, (grouped) => {
898
+ pending = registrar(grouped);
899
+ });
900
+ await pending;
901
+ }
902
+
835
903
  // src/http/middleware/csrf.ts
904
+ import { getCookie } from "hono/cookie";
836
905
  var CSRF_TOKEN_KEY = "_csrf_token";
837
906
  var CSRF_HEADER_NAME = "X-CSRF-TOKEN";
838
907
  var XSRF_HEADER_NAME = "X-XSRF-TOKEN";
@@ -840,11 +909,29 @@ var XSRF_COOKIE_NAME = "XSRF-TOKEN";
840
909
  var CSRF_FORM_FIELD = "_token";
841
910
  var DEFAULT_PROTECTED_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
842
911
  var DEFAULT_COOKIE_SECURE = typeof process !== "undefined" ? process.env.NODE_ENV === "production" : true;
843
- function generateToken() {
844
- const bytes = new Uint8Array(32);
912
+ var CSRF_CONTEXT_KEY = "guren:csrf-token";
913
+ var CSRF_PURPOSE = "csrf";
914
+ function createCsrfSigner() {
915
+ return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "csrf-token"));
916
+ }
917
+ function randomNonce() {
918
+ const bytes = new Uint8Array(16);
845
919
  globalThis.crypto.getRandomValues(bytes);
846
920
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
847
921
  }
922
+ function bindableSessionId(session) {
923
+ return session && !session.isNew ? session.id : void 0;
924
+ }
925
+ function mintCsrfToken(sessionId) {
926
+ const signer = createCsrfSigner();
927
+ return sessionId ? signer.sign({ sid: sessionId }, { purpose: CSRF_PURPOSE }) : signer.sign({ n: randomNonce() }, { purpose: CSRF_PURPOSE });
928
+ }
929
+ function verifiedClaims(token) {
930
+ return createCsrfSigner().verify(token, { purpose: CSRF_PURPOSE });
931
+ }
932
+ function claimsUsableFor(claims, boundId) {
933
+ return claims.sid !== void 0 ? claims.sid === boundId : boundId === void 0;
934
+ }
848
935
  function matchesPattern(path, pattern) {
849
936
  if (pattern.endsWith("/*")) {
850
937
  const prefix = pattern.slice(0, -2);
@@ -855,16 +942,25 @@ function matchesPattern(path, pattern) {
855
942
  function isExcluded(path, excludePatterns) {
856
943
  return excludePatterns.some((pattern) => matchesPattern(path, pattern));
857
944
  }
945
+ function isMcpEndpointRequest(path) {
946
+ return path === MCP_ENDPOINT_PATH && isMcpEndpointEnabled();
947
+ }
858
948
  function getCsrfToken(ctx) {
859
- const session = getSessionFromContext(ctx);
860
- if (!session) {
861
- throw new Error("CSRF middleware requires session middleware to be registered first.");
949
+ const pending = ctx.get(CSRF_CONTEXT_KEY);
950
+ if (pending) {
951
+ return pending;
862
952
  }
863
- let token = session.get(CSRF_TOKEN_KEY);
864
- if (!token) {
865
- token = generateToken();
866
- session.set(CSRF_TOKEN_KEY, token);
953
+ const boundId = bindableSessionId(getSessionFromContext(ctx));
954
+ const cookieToken = getCookie(ctx, XSRF_COOKIE_NAME);
955
+ if (cookieToken) {
956
+ const claims = verifiedClaims(cookieToken);
957
+ if (claims && claimsUsableFor(claims, boundId)) {
958
+ ctx.set(CSRF_CONTEXT_KEY, cookieToken);
959
+ return cookieToken;
960
+ }
867
961
  }
962
+ const token = mintCsrfToken(boundId);
963
+ ctx.set(CSRF_CONTEXT_KEY, token);
868
964
  return token;
869
965
  }
870
966
  function csrfField(ctx) {
@@ -875,22 +971,22 @@ function verifyCsrfToken(ctx, token) {
875
971
  if (!token) {
876
972
  return false;
877
973
  }
878
- const session = getSessionFromContext(ctx);
879
- if (!session) {
880
- return false;
881
- }
882
- const sessionToken = session.get(CSRF_TOKEN_KEY);
883
- if (!sessionToken) {
884
- return false;
885
- }
886
- if (token.length !== sessionToken.length) {
887
- return false;
888
- }
889
- let result = 0;
890
- for (let i = 0; i < token.length; i++) {
891
- result |= token.charCodeAt(i) ^ sessionToken.charCodeAt(i);
974
+ const claims = verifiedClaims(token);
975
+ if (claims) {
976
+ if (claims.sid !== void 0) {
977
+ const boundId = bindableSessionId(getSessionFromContext(ctx));
978
+ if (boundId !== void 0 && secureCompare(claims.sid, boundId)) {
979
+ return true;
980
+ }
981
+ } else {
982
+ const cookieToken = getCookie(ctx, XSRF_COOKIE_NAME);
983
+ if (cookieToken && secureCompare(token, cookieToken)) {
984
+ return true;
985
+ }
986
+ }
892
987
  }
893
- return result === 0;
988
+ const sessionToken = getSessionFromContext(ctx)?.get(CSRF_TOKEN_KEY);
989
+ return sessionToken !== void 0 && secureCompare(token, sessionToken);
894
990
  }
895
991
  async function getTokenFromRequest(ctx) {
896
992
  const headerToken = ctx.req.header(CSRF_HEADER_NAME);
@@ -936,10 +1032,6 @@ function createCsrfMiddleware(options = {}) {
936
1032
  } = options;
937
1033
  const protectedMethods = new Set(methods.map((m) => m.toUpperCase()));
938
1034
  return async (ctx, next) => {
939
- const session = getSessionFromContext(ctx);
940
- if (!session) {
941
- throw new Error("CSRF middleware requires session middleware to be registered first.");
942
- }
943
1035
  const method = ctx.req.method.toUpperCase();
944
1036
  const path = new URL(ctx.req.url).pathname;
945
1037
  if (!protectedMethods.has(method)) {
@@ -950,7 +1042,7 @@ function createCsrfMiddleware(options = {}) {
950
1042
  }
951
1043
  return;
952
1044
  }
953
- if (isExcluded(path, exclude)) {
1045
+ if (isExcluded(path, exclude) || isMcpEndpointRequest(path)) {
954
1046
  await next();
955
1047
  return;
956
1048
  }
@@ -1029,16 +1121,31 @@ function validateSafe(schema, data) {
1029
1121
  // src/http/middleware/rate-limit.ts
1030
1122
  var BaseMemoryStore = class {
1031
1123
  cleanupInterval;
1124
+ /**
1125
+ * This store's claim on its hot-reload slot, if it holds one.
1126
+ *
1127
+ * Unlike the cache sweep, this interval is not `unref()`ed, so a leaked one
1128
+ * both duplicates work and keeps the process alive on its own.
1129
+ */
1130
+ hotReloadClaim;
1032
1131
  constructor(cleanupIntervalMs = 6e4) {
1033
- if (cleanupIntervalMs > 0) {
1034
- this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs);
1132
+ if (cleanupIntervalMs <= 0) {
1133
+ return;
1035
1134
  }
1135
+ this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs);
1136
+ this.hotReloadClaim = claimHotDisposable(
1137
+ "rate-limit-store",
1138
+ isHotReloadRuntime() ? new Error().stack : void 0,
1139
+ this.constructor.name,
1140
+ () => this.destroy()
1141
+ );
1036
1142
  }
1037
1143
  destroy() {
1038
1144
  if (this.cleanupInterval) {
1039
1145
  clearInterval(this.cleanupInterval);
1040
1146
  this.cleanupInterval = void 0;
1041
1147
  }
1148
+ this.hotReloadClaim?.release();
1042
1149
  }
1043
1150
  };
1044
1151
  var MemoryRateLimitStore = class extends BaseMemoryStore {
@@ -1443,8 +1550,8 @@ function createRedirectSafetyMiddleware(options = {}) {
1443
1550
  };
1444
1551
  }
1445
1552
  function isSafeRedirectUrl(url2, requestUrl, allowedHosts = []) {
1446
- const normalized = url2.replace(/\\/g, "/");
1447
- if (normalized.startsWith("/") && !normalized.startsWith("//")) {
1553
+ const normalized = normalizeRedirectTarget(url2);
1554
+ if (isAppRelativePath(normalized)) {
1448
1555
  return true;
1449
1556
  }
1450
1557
  try {
@@ -1453,20 +1560,10 @@ function isSafeRedirectUrl(url2, requestUrl, allowedHosts = []) {
1453
1560
  if (target.host === current.host && target.protocol === current.protocol) {
1454
1561
  return true;
1455
1562
  }
1456
- for (const allowed of allowedHosts) {
1457
- if (allowed.startsWith("*.")) {
1458
- const suffix = allowed.slice(1).toLowerCase();
1459
- if (target.hostname.toLowerCase().endsWith(suffix) && target.hostname.length > suffix.length) {
1460
- return true;
1461
- }
1462
- } else if (target.host.toLowerCase() === allowed.toLowerCase()) {
1463
- return true;
1464
- }
1465
- }
1563
+ return hostMatchesAllowlist(target, allowedHosts);
1466
1564
  } catch {
1467
1565
  return false;
1468
1566
  }
1469
- return false;
1470
1567
  }
1471
1568
 
1472
1569
  // src/http/middleware/force-https.ts
@@ -1538,6 +1635,98 @@ function requestLoggingMiddleware() {
1538
1635
  });
1539
1636
  }
1540
1637
 
1638
+ // src/http/middleware/detect-locale.ts
1639
+ import { createMiddleware as createMiddleware3 } from "hono/factory";
1640
+ import { getCookie as getCookie2 } from "hono/cookie";
1641
+ import { parseAccept } from "hono/utils/accept";
1642
+ var LOCALE_CONTEXT_KEY = "locale";
1643
+ var DEFAULT_SOURCES = ["query", "cookie", "header"];
1644
+ function detectLocaleMiddleware(options) {
1645
+ const supported = options.supported.map((locale) => locale.trim()).filter(Boolean);
1646
+ if (supported.length === 0) {
1647
+ throw new Error("detectLocaleMiddleware requires at least one supported locale.");
1648
+ }
1649
+ const fallback = options.fallback ?? supported[0];
1650
+ const sources = options.sources ?? DEFAULT_SOURCES;
1651
+ const queryParam = options.queryParam ?? "locale";
1652
+ const cookieName = options.cookieName ?? "locale";
1653
+ const byLowerCase = new Map(supported.map((locale) => [locale.toLowerCase(), locale]));
1654
+ const match = (candidate) => {
1655
+ const value = candidate?.trim().toLowerCase();
1656
+ if (!value) {
1657
+ return void 0;
1658
+ }
1659
+ return byLowerCase.get(value) ?? byLowerCase.get(value.split("-")[0]);
1660
+ };
1661
+ const matchHeader = (header) => {
1662
+ if (!header) {
1663
+ return void 0;
1664
+ }
1665
+ for (const accept of parseAccept(header)) {
1666
+ if (accept.type === "*" || accept.q <= 0) {
1667
+ continue;
1668
+ }
1669
+ const matched = match(accept.type);
1670
+ if (matched) {
1671
+ return matched;
1672
+ }
1673
+ }
1674
+ return void 0;
1675
+ };
1676
+ const translators = /* @__PURE__ */ new Map();
1677
+ const resolveTranslator = async (locale) => {
1678
+ if (options.i18n === false) {
1679
+ return void 0;
1680
+ }
1681
+ const cached = translators.get(locale);
1682
+ if (cached) {
1683
+ return cached;
1684
+ }
1685
+ const i18n = options.i18n ?? tryGlobalI18n();
1686
+ if (!i18n) {
1687
+ return void 0;
1688
+ }
1689
+ await i18n.loadLocale(locale).catch(() => {
1690
+ });
1691
+ const translator = i18n.forLocale(locale);
1692
+ const binding = {
1693
+ t: translator.t.bind(translator),
1694
+ tc: translator.tc.bind(translator)
1695
+ };
1696
+ translators.set(locale, binding);
1697
+ return binding;
1698
+ };
1699
+ return createMiddleware3(async (c, next) => {
1700
+ const readers = {
1701
+ query: () => match(c.req.query(queryParam)),
1702
+ cookie: () => match(getCookie2(c, cookieName)),
1703
+ header: () => matchHeader(c.req.header("Accept-Language"))
1704
+ };
1705
+ let resolved = fallback;
1706
+ for (const source of sources) {
1707
+ const matched = readers[source]();
1708
+ if (matched) {
1709
+ resolved = matched;
1710
+ break;
1711
+ }
1712
+ }
1713
+ c.set(LOCALE_CONTEXT_KEY, resolved);
1714
+ const binding = await resolveTranslator(resolved);
1715
+ if (binding) {
1716
+ c.set("t", binding.t);
1717
+ c.set("tc", binding.tc);
1718
+ }
1719
+ await next();
1720
+ });
1721
+ }
1722
+ function tryGlobalI18n() {
1723
+ try {
1724
+ return getI18n();
1725
+ } catch {
1726
+ return void 0;
1727
+ }
1728
+ }
1729
+
1541
1730
  // src/http/middleware/index.ts
1542
1731
  function defineMiddleware(handler) {
1543
1732
  return handler;
@@ -1710,6 +1899,14 @@ var ErrorServiceProvider = class extends ServiceProvider {
1710
1899
  import { isAbsolute, resolve as resolvePath } from "path";
1711
1900
  import { pathToFileURL } from "url";
1712
1901
  ensureErrorStackTracePolyfill();
1902
+ var documentOptions;
1903
+ function setInertiaDocument(options) {
1904
+ documentOptions = options;
1905
+ }
1906
+ var defaultSsrRenderer;
1907
+ function setInertiaSsrRenderer(renderer) {
1908
+ defaultSsrRenderer = renderer;
1909
+ }
1713
1910
  var DEFAULT_TITLE = "Guren";
1714
1911
  var DEV_FALLBACK_IMPORT_MAP = {
1715
1912
  react: "https://esm.sh/react@19.0.0?dev",
@@ -1784,7 +1981,16 @@ async function renderDocument(page, options) {
1784
1981
  const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
1785
1982
  const serializedPage = serializePage(page);
1786
1983
  const stylesheetLinks = renderStyles(styles);
1787
- const docsHeadBootstrap = renderDocsHeadBootstrap(page.component);
1984
+ const criticalCss = resolveDocumentValue(
1985
+ "criticalCss",
1986
+ options,
1987
+ page.component
1988
+ );
1989
+ const prepaintScript = resolveDocumentValue(
1990
+ "prepaintScript",
1991
+ options,
1992
+ page.component
1993
+ );
1788
1994
  const ssrResult = await tryRenderSsr(page, options);
1789
1995
  const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
1790
1996
  const hasCustomTitle = headElements.some(
@@ -1794,14 +2000,17 @@ async function renderDocument(page, options) {
1794
2000
  '<meta charset="utf-8" />',
1795
2001
  '<meta name="viewport" content="width=device-width, initial-scale=1" />',
1796
2002
  hasCustomTitle ? "" : `<title>${title}</title>`,
1797
- docsHeadBootstrap,
2003
+ // Both must precede the stylesheet links: they exist to settle the first
2004
+ // paint before the app's own CSS arrives.
2005
+ criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
2006
+ prepaintScript ? `<script>${prepaintScript}</script>` : "",
1798
2007
  stylesheetLinks,
1799
2008
  ...headElements,
1800
2009
  Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}</script>` : "",
1801
2010
  `<script>window.__INERTIA_PAGE__ = ${serializedPage};</script>`
1802
2011
  ].filter((segment) => segment && segment.length > 0);
1803
2012
  const appMarkup = ssrResult?.body ?? `<script data-page="app" type="application/json">${serializedPage}</script><div id="app"></div>`;
1804
- const bodyClass = resolveBodyClass(page.component);
2013
+ const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
1805
2014
  const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
1806
2015
  const lang = escapeAttribute(options.lang ?? "en");
1807
2016
  return `<!DOCTYPE html>
@@ -1821,7 +2030,7 @@ async function tryRenderSsr(page, options) {
1821
2030
  return void 0;
1822
2031
  }
1823
2032
  const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
1824
- const renderer = ssrOptions?.render ?? await loadSsrRenderer(
2033
+ const renderer = ssrOptions?.render ?? defaultSsrRenderer ?? await loadSsrRenderer(
1825
2034
  ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY
1826
2035
  );
1827
2036
  if (!renderer) {
@@ -1909,36 +2118,13 @@ function normalizeHeadElement(element) {
1909
2118
  (_match, file2, query = "") => `href="/public/assets/${file2}${query}"`
1910
2119
  );
1911
2120
  }
1912
- function resolveBodyClass(componentName) {
1913
- return componentName.startsWith("Docs/") ? "docs-theme" : "";
1914
- }
1915
- function renderDocsHeadBootstrap(componentName) {
1916
- if (!componentName.startsWith("Docs/")) {
1917
- return "";
2121
+ function resolveDocumentValue(key, options, componentName) {
2122
+ const override = options[key];
2123
+ if (override !== void 0) {
2124
+ return override;
1918
2125
  }
1919
- const criticalStyles = [
1920
- "html,body{background:#ffffff;color:#1f2937;}",
1921
- "body.docs-theme{background:#ffffff;color:#1f2937;}",
1922
- "html.dark,html.dark body,html.dark body.docs-theme{background:#1a1a2e;color:#e0def4;}",
1923
- ".size-4{width:1rem;height:1rem;}",
1924
- ".size-5{width:1.25rem;height:1.25rem;}",
1925
- ".size-6{width:1.5rem;height:1.5rem;}",
1926
- ".size-8{width:2rem;height:2rem;}",
1927
- ".size-9{width:2.25rem;height:2.25rem;}"
1928
- ].join("");
1929
- const prepaintScript = [
1930
- "(function(){",
1931
- "try{",
1932
- "var mode=localStorage.getItem('guren-color-mode')||'system';",
1933
- "var dark=mode==='dark'||(mode!=='light'&&window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches);",
1934
- "var root=document.documentElement;",
1935
- "root.classList.toggle('dark',dark);",
1936
- "root.style.colorScheme=dark?'dark':'light';",
1937
- "}catch(_){",
1938
- "}",
1939
- "})();"
1940
- ].join("");
1941
- return `<style id="guren-docs-critical">${criticalStyles}</style><script>${prepaintScript}</script>`;
2126
+ const value = documentOptions?.[key];
2127
+ return (typeof value === "function" ? value({ component: componentName }) : value) ?? "";
1942
2128
  }
1943
2129
  function serializePage(page) {
1944
2130
  return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
@@ -2201,7 +2387,11 @@ var Application = class {
2201
2387
  this.hono.use("*", attachAuthContext((ctx) => this.authManager.createAuthContext(ctx)));
2202
2388
  }
2203
2389
  this.providerManager.register(AuthorizationServiceProvider);
2204
- const userProviders = Array.isArray(this.options.providers) ? this.options.providers : [];
2390
+ const moduleProviders = (this.options.modules ?? []).flatMap((module) => module.providers);
2391
+ const userProviders = [
2392
+ ...Array.isArray(this.options.providers) ? this.options.providers : [],
2393
+ ...moduleProviders
2394
+ ];
2205
2395
  const hasUserErrorProvider = userProviders.some(
2206
2396
  (provider) => provider === ErrorServiceProvider || provider.prototype instanceof ErrorServiceProvider
2207
2397
  );
@@ -2245,8 +2435,13 @@ var Application = class {
2245
2435
  * Mounts the application router onto the Hono instance.
2246
2436
  */
2247
2437
  async mountRoutes() {
2248
- if (this.options.routes && !this.routesRegistered) {
2249
- await this.options.routes(this.router);
2438
+ if (!this.routesRegistered) {
2439
+ if (this.options.routes) {
2440
+ await this.options.routes(this.router);
2441
+ }
2442
+ for (const gurenModule of this.options.modules ?? []) {
2443
+ await mountModuleRoutes(this.router, gurenModule);
2444
+ }
2250
2445
  this.routesRegistered = true;
2251
2446
  }
2252
2447
  this.router.mount(this.hono, { container: this.container });
@@ -2284,16 +2479,15 @@ var Application = class {
2284
2479
  this.hono.use("*", createHostAuthorizationMiddleware(hostAuthorization));
2285
2480
  }
2286
2481
  /**
2287
- * Mounts the MCP endpoint at /_guren/mcp when explicitly enabled.
2288
- * Requires GUREN_MCP=1 environment variable. Never active in production.
2482
+ * Mounts the MCP endpoint at /_guren/mcp when enabled.
2289
2483
  * This allows AI coding agents to introspect the project.
2290
2484
  */
2291
2485
  async mountMcpEndpoint() {
2292
- if (typeof process === "undefined" || process.env?.NODE_ENV === "production" || process.env?.GUREN_MCP !== "1") {
2486
+ if (!isMcpEndpointEnabled()) {
2293
2487
  return;
2294
2488
  }
2295
2489
  try {
2296
- const { McpServiceProvider } = await import("./McpServiceProvider-JW6PDVMD.js");
2490
+ const { McpServiceProvider } = await import("./McpServiceProvider-TZWQWXCT.js");
2297
2491
  const provider = new McpServiceProvider(this.container);
2298
2492
  provider.register();
2299
2493
  await provider.boot();
@@ -2346,7 +2540,10 @@ var Application = class {
2346
2540
  const server = Bun.serve({
2347
2541
  port,
2348
2542
  hostname,
2349
- fetch: (request) => this.fetch(request)
2543
+ // `{ server }` is Bun's convention for reaching the live server from a
2544
+ // handler; middleware reads `ctx.env.server.requestIP()` through it to
2545
+ // learn the socket peer (the MCP access guard, the rate limiter).
2546
+ fetch: (request, server2) => this.fetch(request, { server: server2 })
2350
2547
  });
2351
2548
  this.bunServer = server;
2352
2549
  setActiveBunServer(server);
@@ -2617,23 +2814,27 @@ var Controller = class {
2617
2814
  /**
2618
2815
  * Default `<html lang>` for Inertia responses when `options.lang` is not
2619
2816
  * provided: the request-scoped `locale` context variable (set by locale
2620
- * middleware) wins over the app-wide i18n locale.
2817
+ * middleware) wins over the app-wide i18n locale (the router-injected
2818
+ * container binding, then the `setI18n()` global).
2621
2819
  */
2622
2820
  #defaultInertiaLang() {
2623
2821
  const vars = this.ctx.var;
2624
- const requestLocale = vars?.locale;
2822
+ const requestLocale = vars?.[LOCALE_CONTEXT_KEY];
2625
2823
  if (typeof requestLocale === "string" && requestLocale.length > 0) {
2626
2824
  return requestLocale;
2627
2825
  }
2628
- const container = vars?.container;
2629
- if (container?.has?.("i18n")) {
2630
- const i18n = container.make?.("i18n");
2631
- const locale = i18n?.getLocale?.();
2632
- if (typeof locale === "string" && locale.length > 0) {
2633
- return locale;
2826
+ let i18n;
2827
+ if (this._container?.has?.("i18n")) {
2828
+ i18n = this._container.make("i18n");
2829
+ } else {
2830
+ try {
2831
+ i18n = getI18n();
2832
+ } catch {
2833
+ i18n = void 0;
2634
2834
  }
2635
2835
  }
2636
- return void 0;
2836
+ const locale = i18n?.getLocale?.();
2837
+ return typeof locale === "string" && locale.length > 0 ? locale : void 0;
2637
2838
  }
2638
2839
  json(data, init = {}) {
2639
2840
  return new Response(JSON.stringify(data), {
@@ -3159,7 +3360,7 @@ var Validator = class _Validator {
3159
3360
  async validateOrThrow(data) {
3160
3361
  const result = await this.validate(data);
3161
3362
  if (!result.success) {
3162
- const { ValidationException: ValidationException2 } = await import("./errors-JOOPDDQ6.js");
3363
+ const { ValidationException: ValidationException2 } = await import("./errors-PUNHAFL2.js");
3163
3364
  throw new ValidationException2(result.errors);
3164
3365
  }
3165
3366
  return result.data;
@@ -6347,6 +6548,7 @@ export {
6347
6548
  JobProcessed,
6348
6549
  JsonLoader,
6349
6550
  JsonResource,
6551
+ LOCALE_CONTEXT_KEY,
6350
6552
  LOG_LEVEL_PRIORITY,
6351
6553
  Listener,
6352
6554
  LocalDriver as LocalStorageDriver,
@@ -6515,9 +6717,12 @@ export {
6515
6717
  defineFactory,
6516
6718
  defineGate,
6517
6719
  defineMiddleware,
6720
+ defineModule,
6721
+ definePlugin,
6518
6722
  definePolicy,
6519
6723
  deriveAppKey,
6520
6724
  deriveAppKeyring,
6725
+ detectLocaleMiddleware,
6521
6726
  different,
6522
6727
  email as emailRule,
6523
6728
  encodeCursor,
@@ -6583,6 +6788,7 @@ export {
6583
6788
  mimes,
6584
6789
  min,
6585
6790
  minFileSize,
6791
+ mountModuleRoutes,
6586
6792
  needsRehash,
6587
6793
  normalizeAppKey,
6588
6794
  notIn,
@@ -6631,6 +6837,7 @@ export {
6631
6837
  revokeApiToken,
6632
6838
  same,
6633
6839
  sample,
6840
+ sanitizeOAuthRedirect,
6634
6841
  secureCompare,
6635
6842
  selectPluralForm,
6636
6843
  setBroadcastManager,
@@ -6639,7 +6846,9 @@ export {
6639
6846
  setExceptionHandler,
6640
6847
  setGate,
6641
6848
  setI18n,
6849
+ setInertiaDocument,
6642
6850
  setInertiaSharedProps,
6851
+ setInertiaSsrRenderer,
6643
6852
  setLogManager,
6644
6853
  setMailManager,
6645
6854
  setNotificationManager,