@guren/server 1.3.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 (42) hide show
  1. package/dist/{Application-DImeY-VW.d.ts → Application-BvBqgc2k.d.ts} +194 -14
  2. package/dist/{AuthManager-BU8ZvenF.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-COKndy_V.d.ts → ConsoleKernel-Dw9X9qZY.d.ts} +1 -1
  6. package/dist/{McpServiceProvider-RNTDHZAZ.js → McpServiceProvider-TZWQWXCT.js} +2 -2
  7. package/dist/{Scheduler-BstvSca7.d.ts → Scheduler-pZiT8i57.d.ts} +2 -0
  8. package/dist/{api-token-CB12xnVg.d.ts → api-token-COQHXyM_.d.ts} +68 -1
  9. package/dist/auth/index.d.ts +5 -5
  10. package/dist/auth/index.js +1 -1
  11. package/dist/authorization/index.js +2 -2
  12. package/dist/broadcasting/index.d.ts +2 -2
  13. package/dist/broadcasting/index.js +2 -1
  14. package/dist/cache/index.d.ts +2 -2
  15. package/dist/cache/index.js +2 -1
  16. package/dist/{chunk-EGU5KB7V.js → chunk-4SBGSJNT.js} +31 -1
  17. package/dist/{chunk-THSX7OOR.js → chunk-63SKW5PS.js} +3 -0
  18. package/dist/{chunk-VY2JPS6V.js → chunk-AUXQISW5.js} +83 -11
  19. package/dist/chunk-DCYKSYAT.js +63 -0
  20. package/dist/{chunk-ZRBLZY3M.js → chunk-FZD2AKJI.js} +1 -1
  21. package/dist/{chunk-CSP7W3WY.js → chunk-JIT7QVMJ.js} +2 -2
  22. package/dist/{chunk-HKQSAFSN.js → chunk-MC752CQT.js} +15 -0
  23. package/dist/{chunk-J753UWAY.js → chunk-NQCZQAJL.js} +93 -28
  24. package/dist/{chunk-STZUODC3.js → chunk-NYQGAWDN.js} +44 -1
  25. package/dist/{chunk-44F7JQ7I.js → chunk-XMQZENBP.js} +35 -1
  26. package/dist/{client-CKXJLsTe.d.ts → client-BQwF2b9Y.d.ts} +7 -0
  27. package/dist/{email-verification-D9u7krkn.d.ts → email-verification-H_WlpsVH.d.ts} +1 -1
  28. package/dist/{errors-JOOPDDQ6.js → errors-PUNHAFL2.js} +1 -1
  29. package/dist/index.d.ts +16 -16
  30. package/dist/index.js +181 -85
  31. package/dist/lambda/index.d.ts +7 -7
  32. package/dist/mcp/index.d.ts +53 -19
  33. package/dist/mcp/index.js +2 -2
  34. package/dist/notifications/index.d.ts +7 -7
  35. package/dist/queue/index.d.ts +7 -7
  36. package/dist/redis/index.d.ts +11 -21
  37. package/dist/redis/index.js +42 -6
  38. package/dist/runtime/index.d.ts +7 -7
  39. package/dist/runtime/index.js +1 -1
  40. package/dist/scheduling/index.d.ts +2 -2
  41. package/dist/scheduling/index.js +2 -1
  42. package/package.json +2 -2
@@ -1,3 +1,8 @@
1
+ import {
2
+ claimHotDisposable,
3
+ isHotReloadRuntime
4
+ } from "./chunk-DCYKSYAT.js";
5
+
1
6
  // src/cache/stores/MemoryStore.ts
2
7
  var MemoryStore = class {
3
8
  cache = /* @__PURE__ */ new Map();
@@ -716,7 +721,17 @@ var CacheManager = class {
716
721
  defaultStoreName;
717
722
  storeFactories = /* @__PURE__ */ new Map();
718
723
  resolvedStores = /* @__PURE__ */ new Map();
724
+ /**
725
+ * Where this manager was built, for identifying its stores across hot reloads.
726
+ *
727
+ * Captured here rather than in `store()` because stores resolve lazily, from
728
+ * whichever request first asks for one — a call site that says nothing about
729
+ * which manager owns the result. Skipped outside `--hot`, where it would be a
730
+ * formatted stack string held for the manager's lifetime and never read.
731
+ */
732
+ builtAt;
719
733
  constructor(config = {}) {
734
+ this.builtAt = isHotReloadRuntime() ? new Error().stack : void 0;
720
735
  this.defaultStoreName = config.default ?? "memory";
721
736
  this.registerBuiltinDrivers();
722
737
  if (config.stores) {
@@ -768,10 +783,25 @@ var CacheManager = class {
768
783
  if (!factory) {
769
784
  throw new Error(`Cache store not found: ${storeName}`);
770
785
  }
771
- const store = new TaggableCacheStoreWrapper(factory());
786
+ const raw = factory();
787
+ this.stopPreviousStore(storeName, raw);
788
+ const store = new TaggableCacheStoreWrapper(raw);
772
789
  this.resolvedStores.set(storeName, store);
773
790
  return store;
774
791
  }
792
+ /**
793
+ * Under `bun --hot`, stops the sweep timer held by the store this one replaces.
794
+ *
795
+ * Registered from here rather than from `MemoryStore` itself because this is
796
+ * where the store's name is known, and the name is what keeps two memory
797
+ * stores in one config from sharing a slot and cancelling each other's sweep.
798
+ */
799
+ stopPreviousStore(storeName, store) {
800
+ const disposable = store;
801
+ if (typeof disposable.destroy === "function") {
802
+ claimHotDisposable("cache-store", this.builtAt, storeName, () => disposable.destroy?.());
803
+ }
804
+ }
775
805
  /**
776
806
  * Register a custom store factory.
777
807
  */
@@ -152,6 +152,9 @@ var ExceptionHandler = class {
152
152
  if (this.shouldNotReport(error)) {
153
153
  return;
154
154
  }
155
+ if (this.reporters.length === 0) {
156
+ console.error("Unhandled exception:", error);
157
+ }
155
158
  for (const reporter of this.reporters) {
156
159
  try {
157
160
  await reporter(error);
@@ -38,6 +38,13 @@ var MemorySessionStore = class {
38
38
  async destroy(id) {
39
39
  this.store.delete(id);
40
40
  }
41
+ async touch(id, ttlSeconds) {
42
+ const entry = this.store.get(id);
43
+ if (!entry || entry.expiresAt <= this.now()) {
44
+ return;
45
+ }
46
+ entry.expiresAt = this.now() + ttlSeconds * 1e3;
47
+ }
41
48
  };
42
49
  var DEFAULT_COOKIE_NAME = "guren.session";
43
50
  var DEFAULT_TTL_SECONDS = 60 * 60 * 2;
@@ -126,11 +133,16 @@ var SessionImpl = class {
126
133
  /**
127
134
  * Age flash data: move `new` → `old`, clear previous `old`.
128
135
  * Called at the start of each request by the session middleware.
136
+ * Only dirties the session when there was flash data to age — otherwise
137
+ * every request carrying a session would persist unconditionally.
129
138
  */
130
139
  ageFlashData() {
140
+ const hadFlash = this.hasFlash();
131
141
  this._flash.old = { ...this._flash.new };
132
142
  this._flash.new = {};
133
- this.dirty = true;
143
+ if (hadFlash) {
144
+ this.dirty = true;
145
+ }
134
146
  }
135
147
  markTouched() {
136
148
  this.dirty = true;
@@ -142,10 +154,16 @@ var SessionImpl = class {
142
154
  return this.regenerated;
143
155
  }
144
156
  shouldPersist() {
145
- return this.dirty || this.isNew;
157
+ return this.dirty || this.isNew && this.hasContent();
158
+ }
159
+ hasContent() {
160
+ return Object.keys(this.data).length > 0 || this.hasFlash();
161
+ }
162
+ hasFlash() {
163
+ return Object.keys(this._flash.new).length > 0 || Object.keys(this._flash.old).length > 0;
146
164
  }
147
165
  snapshot() {
148
- const hasFlash = Object.keys(this._flash.new).length > 0 || Object.keys(this._flash.old).length > 0;
166
+ const hasFlash = this.hasFlash();
149
167
  return {
150
168
  ...this.data,
151
169
  ...hasFlash ? { _flash: { new: { ...this._flash.new }, old: { ...this._flash.old } } } : {}
@@ -257,7 +275,11 @@ function createSessionMiddleware(options = {}) {
257
275
  }
258
276
  if (!session.shouldPersist()) {
259
277
  if (existingId) {
260
- await store.write(existingId, session.snapshot(), ttlSeconds);
278
+ if (store.touch) {
279
+ await store.touch(existingId, ttlSeconds);
280
+ } else {
281
+ await store.write(existingId, session.snapshot(), ttlSeconds);
282
+ }
261
283
  setCookie(ctx, cookieName, signer.sign(existingId), {
262
284
  path: cookiePath,
263
285
  domain: cookieDomain,
@@ -1355,6 +1377,13 @@ var MemoryOAuthStateStore = class {
1355
1377
  async delete(stateHash) {
1356
1378
  this.states.delete(stateHash);
1357
1379
  }
1380
+ async consume(stateHash) {
1381
+ const payload = this.states.get(stateHash);
1382
+ if (!payload) return null;
1383
+ this.states.delete(stateHash);
1384
+ if (payload.expiresAt.getTime() <= Date.now()) return null;
1385
+ return payload;
1386
+ }
1358
1387
  clear() {
1359
1388
  this.states.clear();
1360
1389
  }
@@ -1437,12 +1466,17 @@ async function createOAuthState(provider, store, config = {}, redirectTo, fixedS
1437
1466
  async function verifyOAuthState(state, provider, store, config = {}) {
1438
1467
  const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
1439
1468
  const stateHash = hashToken(state, hashAlgorithm);
1440
- const payload = await store.find(stateHash);
1469
+ const payload = typeof store.consume === "function" ? await store.consume(stateHash) : await findAndDeleteState(store, stateHash);
1441
1470
  if (!payload) return null;
1442
- await store.delete(stateHash);
1443
1471
  if (payload.provider !== provider) return null;
1444
1472
  return { ...payload, redirectTo: sanitizeOAuthRedirect(payload.redirectTo, config.allowedRedirectHosts) };
1445
1473
  }
1474
+ async function findAndDeleteState(store, stateHash) {
1475
+ const payload = await store.find(stateHash);
1476
+ if (!payload) return null;
1477
+ await store.delete(stateHash);
1478
+ return payload;
1479
+ }
1446
1480
  function sanitizeOAuthRedirect(redirectTo, allowedHosts = []) {
1447
1481
  const value = redirectTo?.trim();
1448
1482
  if (!value) {
@@ -1529,9 +1563,23 @@ async function fetchOAuthUserProfile(provider, token) {
1529
1563
  throw new AuthenticationException(`OAuth user fetch failed (${response.status}).`);
1530
1564
  }
1531
1565
  const raw = await response.json();
1532
- if (provider.mapProfile) {
1533
- return provider.mapProfile(raw, token);
1566
+ const profile = provider.mapProfile ? provider.mapProfile(raw, token) : defaultProfileFromUserInfo(raw, token, provider.emailVerifiedKey);
1567
+ if (!profile.email && provider.fetchFallbackEmail) {
1568
+ const fallback = await provider.fetchFallbackEmail(token);
1569
+ const email = typeof fallback === "string" ? fallback : fallback?.email;
1570
+ if (email) {
1571
+ const emailVerified = typeof fallback === "string" ? void 0 : fallback?.emailVerified;
1572
+ return { ...profile, email, emailVerified };
1573
+ }
1534
1574
  }
1575
+ return profile;
1576
+ }
1577
+ var DEFAULT_EMAIL_VERIFIED_KEY = "email_verified";
1578
+ function readEmailVerified(raw, key = DEFAULT_EMAIL_VERIFIED_KEY) {
1579
+ const value = raw[key];
1580
+ return typeof value === "boolean" ? value : void 0;
1581
+ }
1582
+ function defaultProfileFromUserInfo(raw, token, emailVerifiedKey) {
1535
1583
  const idCandidate = raw.id ?? raw.sub;
1536
1584
  const id = typeof idCandidate === "string" || typeof idCandidate === "number" ? String(idCandidate) : "";
1537
1585
  if (!id) {
@@ -1540,19 +1588,41 @@ async function fetchOAuthUserProfile(provider, token) {
1540
1588
  return {
1541
1589
  id,
1542
1590
  email: typeof raw.email === "string" ? raw.email : void 0,
1591
+ emailVerified: readEmailVerified(raw, emailVerifiedKey),
1543
1592
  name: typeof raw.name === "string" ? raw.name : void 0,
1544
1593
  avatar: typeof raw.avatar_url === "string" ? raw.avatar_url : typeof raw.picture === "string" ? raw.picture : typeof raw.avatar === "string" ? raw.avatar : void 0,
1545
1594
  token,
1546
1595
  raw
1547
1596
  };
1548
1597
  }
1598
+ async function fetchGitHubPrimaryEmail(token) {
1599
+ const response = await fetch("https://api.github.com/user/emails", {
1600
+ headers: {
1601
+ Accept: "application/vnd.github+json",
1602
+ Authorization: `Bearer ${token.accessToken}`,
1603
+ "User-Agent": "guren-oauth"
1604
+ }
1605
+ });
1606
+ if (!response.ok) {
1607
+ return void 0;
1608
+ }
1609
+ const emails = await response.json();
1610
+ if (!Array.isArray(emails)) {
1611
+ return void 0;
1612
+ }
1613
+ const primary = emails.find(
1614
+ (entry) => typeof entry === "object" && entry !== null && entry.primary === true && entry.verified === true && typeof entry.email === "string"
1615
+ );
1616
+ return primary ? { email: primary.email, emailVerified: true } : void 0;
1617
+ }
1549
1618
  function createGitHubOAuthProviderConfig(input) {
1550
1619
  return {
1551
1620
  ...input,
1552
1621
  authorizeUrl: "https://github.com/login/oauth/authorize",
1553
1622
  tokenUrl: "https://github.com/login/oauth/access_token",
1554
1623
  userInfoUrl: "https://api.github.com/user",
1555
- scopes: input.scopes ?? ["read:user", "user:email"]
1624
+ scopes: input.scopes ?? ["read:user", "user:email"],
1625
+ fetchFallbackEmail: fetchGitHubPrimaryEmail
1556
1626
  };
1557
1627
  }
1558
1628
  function createGoogleOAuthProviderConfig(input) {
@@ -1561,7 +1631,8 @@ function createGoogleOAuthProviderConfig(input) {
1561
1631
  authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
1562
1632
  tokenUrl: "https://oauth2.googleapis.com/token",
1563
1633
  userInfoUrl: "https://openidconnect.googleapis.com/v1/userinfo",
1564
- scopes: input.scopes ?? ["openid", "profile", "email"]
1634
+ scopes: input.scopes ?? ["openid", "profile", "email"],
1635
+ emailVerifiedKey: "email_verified"
1565
1636
  };
1566
1637
  }
1567
1638
  function createDiscordOAuthProviderConfig(input) {
@@ -1570,7 +1641,8 @@ function createDiscordOAuthProviderConfig(input) {
1570
1641
  authorizeUrl: "https://discord.com/api/oauth2/authorize",
1571
1642
  tokenUrl: "https://discord.com/api/oauth2/token",
1572
1643
  userInfoUrl: "https://discord.com/api/users/@me",
1573
- scopes: input.scopes ?? ["identify", "email"]
1644
+ scopes: input.scopes ?? ["identify", "email"],
1645
+ emailVerifiedKey: "verified"
1574
1646
  };
1575
1647
  }
1576
1648
  function buildOAuthRedirectUrl(baseUrl, token, email) {
@@ -0,0 +1,63 @@
1
+ // src/hot-reload/hot-disposables.ts
2
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("guren.server.hotDisposables");
3
+ function getRegistry() {
4
+ const scope = globalThis;
5
+ return scope[REGISTRY_KEY] ??= /* @__PURE__ */ new Map();
6
+ }
7
+ function isHotReloadRuntime() {
8
+ return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
9
+ }
10
+ var SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set(["unknown", "native", "<anonymous>"]);
11
+ var LOCATION_SUFFIX = /:\d+(?::\d+)?$/;
12
+ function parseFrameLocation(frame) {
13
+ const location = frame.match(/\(([^()]*)\)\s*$/)?.[1] ?? frame.match(/^\s*at\s+(.+?)\s*$/)?.[1];
14
+ if (!location || !LOCATION_SUFFIX.test(location)) {
15
+ return void 0;
16
+ }
17
+ return location.replace(LOCATION_SUFFIX, "");
18
+ }
19
+ function describeCallerFile(stack) {
20
+ for (const frame of stack?.split("\n").slice(2) ?? []) {
21
+ const path = parseFrameLocation(frame);
22
+ if (path && !SYNTHETIC_FRAME_PATHS.has(path)) {
23
+ return path;
24
+ }
25
+ }
26
+ return void 0;
27
+ }
28
+ function hotReloadKey(scope, stack, target) {
29
+ if (!isHotReloadRuntime()) {
30
+ return void 0;
31
+ }
32
+ const callerFile = describeCallerFile(stack);
33
+ return callerFile ? `${scope}|${callerFile}|${target}` : void 0;
34
+ }
35
+ function claimHotDisposable(scope, stack, target, dispose) {
36
+ const key = hotReloadKey(scope, stack, target);
37
+ if (!key) {
38
+ return void 0;
39
+ }
40
+ const registry = getRegistry();
41
+ const previous = registry.get(key);
42
+ registry.delete(key);
43
+ if (previous && previous !== dispose) {
44
+ try {
45
+ previous();
46
+ } catch (error) {
47
+ console.warn("[guren] Failed to stop the previous hot-reload disposable:", error);
48
+ }
49
+ }
50
+ registry.set(key, dispose);
51
+ return {
52
+ release() {
53
+ if (registry.get(key) === dispose) {
54
+ registry.delete(key);
55
+ }
56
+ }
57
+ };
58
+ }
59
+
60
+ export {
61
+ isHotReloadRuntime,
62
+ claimHotDisposable
63
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AuthorizationException
3
- } from "./chunk-THSX7OOR.js";
3
+ } from "./chunk-63SKW5PS.js";
4
4
 
5
5
  // src/authorization/Gate.ts
6
6
  var Response = {
@@ -6,7 +6,7 @@ import standard from "figlet/importable-fonts/Standard.js";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@guren/server",
9
- version: "1.3.0",
9
+ version: "1.4.0",
10
10
  type: "module",
11
11
  license: "MIT",
12
12
  repository: {
@@ -115,7 +115,7 @@ var package_default = {
115
115
  test: "bun test"
116
116
  },
117
117
  dependencies: {
118
- "@guren/orm": "^1.0.1",
118
+ "@guren/orm": "^1.2.0",
119
119
  "@modelcontextprotocol/sdk": "^1.27.1",
120
120
  chalk: "^5.3.0",
121
121
  consola: "^3.4.2",
@@ -1,3 +1,8 @@
1
+ import {
2
+ claimHotDisposable,
3
+ isHotReloadRuntime
4
+ } from "./chunk-DCYKSYAT.js";
5
+
1
6
  // src/scheduling/CronParser.ts
2
7
  function parseField(field, min, max) {
3
8
  const values = /* @__PURE__ */ new Set();
@@ -671,6 +676,8 @@ var Scheduler = class {
671
676
  interval = null;
672
677
  isRunning = false;
673
678
  lastCheck = null;
679
+ /** This scheduler's claim on its hot-reload slot while it is running. */
680
+ hotReloadClaim;
674
681
  constructor(options = {}) {
675
682
  this.options = {
676
683
  timezone: options.timezone ?? "UTC",
@@ -730,6 +737,12 @@ var Scheduler = class {
730
737
  }
731
738
  this.isRunning = true;
732
739
  this.options.logger("Scheduler started");
740
+ this.hotReloadClaim = claimHotDisposable(
741
+ "scheduler",
742
+ isHotReloadRuntime() ? new Error().stack : void 0,
743
+ this.options.timezone,
744
+ () => this.stop()
745
+ );
733
746
  this.tick();
734
747
  this.interval = setInterval(() => {
735
748
  this.tick();
@@ -749,6 +762,8 @@ var Scheduler = class {
749
762
  clearInterval(this.interval);
750
763
  this.interval = null;
751
764
  }
765
+ this.hotReloadClaim?.release();
766
+ this.hotReloadClaim = void 0;
752
767
  this.isRunning = false;
753
768
  this.options.logger("Scheduler stopped");
754
769
  }
@@ -1,9 +1,12 @@
1
1
  import {
2
- ServiceProvider
3
- } from "./chunk-STZUODC3.js";
2
+ MCP_ENDPOINT_PATH,
3
+ ServiceProvider,
4
+ createMcpAccessGuard,
5
+ isMcpEndpointEnabled
6
+ } from "./chunk-NYQGAWDN.js";
4
7
 
5
8
  // src/mcp/create-mcp-server.ts
6
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
9
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
7
10
  import { z } from "zod";
8
11
  function createMcpServer(options) {
9
12
  const { cwd, cli, version = "0.2.0" } = options;
@@ -23,6 +26,29 @@ function createMcpServer(options) {
23
26
  return { content: [{ type: "text", text }] };
24
27
  }
25
28
  );
29
+ server.tool(
30
+ "guren_entity_context",
31
+ "Get everything about one entity in a single bundle: model (table, columns, relationships, reverse references), routes with validation schemas, controller actions, Inertia pages with props, resource, policy, seeders, and tests. Prefer this over guren_get_context when working on a specific model.",
32
+ {
33
+ entity: z.string().describe('Model class name (e.g., "User"). Case-insensitive.'),
34
+ module: z.string().optional().describe('Module name to disambiguate same-named models across modules/; "app" selects the application root'),
35
+ format: z.enum(["json", "markdown"]).default("markdown").describe("Output format")
36
+ },
37
+ async ({ entity, module, format }) => {
38
+ try {
39
+ const ctx = await cli.generateEntityContext(entity, { cwd, module });
40
+ const text = format === "markdown" ? cli.renderEntityContextMarkdown(ctx) : JSON.stringify(ctx, null, 2);
41
+ return { content: [{ type: "text", text }] };
42
+ } catch (error) {
43
+ return {
44
+ content: [
45
+ { type: "text", text: error instanceof Error ? error.message : String(error) }
46
+ ],
47
+ isError: true
48
+ };
49
+ }
50
+ }
51
+ );
26
52
  server.tool(
27
53
  "guren_check",
28
54
  "Validate route-to-controller-to-page consistency, check for empty controller methods, missing test files, and missing generated manifests.",
@@ -151,35 +177,52 @@ function createMcpServer(options) {
151
177
  );
152
178
  server.tool(
153
179
  "guren_codegen",
154
- "Generate type-safe route, page, data, and channel type manifests (.guren/*.gen.ts files).",
180
+ "Generate the type-safe route, page, data, and channel manifests plus the API client (.guren/ and types/generated/).",
155
181
  {},
156
182
  async () => {
157
183
  const originalCwd = process.cwd();
158
184
  try {
159
185
  process.chdir(cwd);
186
+ const options2 = { cwd, force: true };
160
187
  const generated = [];
161
- try {
162
- await cli.generateRouteTypes({ cwd });
163
- generated.push(".guren/routes.gen.ts");
164
- } catch {
165
- }
166
- try {
167
- await cli.generatePageTypes({ cwd });
168
- generated.push(".guren/pages.gen.ts");
169
- } catch {
170
- }
171
- try {
172
- await cli.generateDataTypes({ cwd });
173
- generated.push(".guren/data.gen.ts");
174
- } catch {
175
- }
176
- try {
177
- await cli.generateChannelTypes({ cwd });
178
- generated.push(".guren/channels.gen.ts");
179
- } catch {
180
- }
188
+ const skipped = [];
189
+ let failed = false;
190
+ const run = async (artifacts, generate) => {
191
+ try {
192
+ const result = await generate();
193
+ if (result?.outputPath === "") {
194
+ skipped.push({ artifacts, reason: "nothing to generate" });
195
+ } else {
196
+ generated.push(...artifacts);
197
+ }
198
+ return result;
199
+ } catch (error) {
200
+ failed = true;
201
+ skipped.push({
202
+ artifacts,
203
+ reason: error instanceof Error ? error.message : String(error)
204
+ });
205
+ }
206
+ };
207
+ const routes = await run(
208
+ [".guren/routes.gen.ts", "types/generated/routes.d.ts"],
209
+ () => cli.generateRouteTypes(options2)
210
+ );
211
+ await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options2));
212
+ await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options2));
213
+ await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options2));
214
+ await run([".guren/api-client.gen.ts"], () => {
215
+ if (!routes?.definitions) {
216
+ throw new Error("route generation produced no manifest to build a client from");
217
+ }
218
+ return cli.generateApiClientTypes(routes.definitions, options2);
219
+ });
181
220
  return {
182
- content: [{ type: "text", text: JSON.stringify({ generated }, null, 2) }]
221
+ content: [{ type: "text", text: JSON.stringify({ generated, skipped }, null, 2) }],
222
+ // A generator that found nothing to describe is not a failure — an
223
+ // app with no page components is a normal shape — so only a thrown
224
+ // one makes the run an error, even when other artifacts landed.
225
+ isError: failed
183
226
  };
184
227
  } finally {
185
228
  process.chdir(originalCwd);
@@ -206,6 +249,26 @@ function createMcpServer(options) {
206
249
  };
207
250
  }
208
251
  );
252
+ server.resource(
253
+ "entity-context",
254
+ new ResourceTemplate("guren://context/{entity}", { list: void 0 }),
255
+ {
256
+ description: "Entity-centric context bundle: model, routes, controller, pages, resource, policy. For same-named models across modules, use the guren_entity_context tool with its module argument instead.",
257
+ mimeType: "text/markdown"
258
+ },
259
+ async (uri, variables) => {
260
+ const ctx = await cli.generateEntityContext(String(variables.entity), { cwd });
261
+ return {
262
+ contents: [
263
+ {
264
+ uri: uri.href,
265
+ mimeType: "text/markdown",
266
+ text: cli.renderEntityContextMarkdown(ctx)
267
+ }
268
+ ]
269
+ };
270
+ }
271
+ );
209
272
  server.resource(
210
273
  "guidelines",
211
274
  "guren://guidelines",
@@ -331,7 +394,7 @@ var McpServiceProvider = class extends ServiceProvider {
331
394
  register() {
332
395
  }
333
396
  async boot() {
334
- if (process.env.NODE_ENV === "production") {
397
+ if (!isMcpEndpointEnabled()) {
335
398
  return;
336
399
  }
337
400
  const app = this.container.make("app");
@@ -342,8 +405,10 @@ var McpServiceProvider = class extends ServiceProvider {
342
405
  // @ts-ignore — @guren/cli is available at runtime via the app's dependencies
343
406
  import("@guren/cli")
344
407
  ]);
345
- hono.all("/_guren/mcp", async (c) => {
346
- const mcpServer = createMcpServer({ cwd, cli });
408
+ const routeAwareCli = cli.createFreshContextApi ? { ...cli, ...cli.createFreshContextApi() } : cli;
409
+ hono.use(MCP_ENDPOINT_PATH, createMcpAccessGuard());
410
+ hono.all(MCP_ENDPOINT_PATH, async (c) => {
411
+ const mcpServer = createMcpServer({ cwd, cli: routeAwareCli });
347
412
  const transport = new WebStandardStreamableHTTPServerTransport({
348
413
  sessionIdGenerator: void 0
349
414
  });
@@ -133,7 +133,50 @@ var ProviderManager = class {
133
133
  }
134
134
  };
135
135
 
136
+ // src/mcp/endpoint.ts
137
+ var MCP_ENDPOINT_PATH = "/_guren/mcp";
138
+ function isMcpEndpointEnabled() {
139
+ return typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && process.env?.GUREN_MCP === "1";
140
+ }
141
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "[::1]"]);
142
+ var LOOPBACK_IPV4 = /^127\.\d+\.\d+\.\d+$/;
143
+ function isLoopbackOrigin(origin) {
144
+ try {
145
+ const { hostname } = new URL(origin);
146
+ return LOOPBACK_HOSTNAMES.has(hostname) || LOOPBACK_IPV4.test(hostname);
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ function isLoopbackAddress(address) {
152
+ const normalized = address.startsWith("::ffff:") ? address.slice("::ffff:".length) : address;
153
+ return normalized === "::1" || LOOPBACK_IPV4.test(normalized);
154
+ }
155
+ function clientAddress(ctx) {
156
+ const env = ctx.env;
157
+ if (typeof env?.server?.requestIP !== "function") {
158
+ return void 0;
159
+ }
160
+ return env.server.requestIP(ctx.req.raw)?.address;
161
+ }
162
+ function createMcpAccessGuard() {
163
+ return async (ctx, next) => {
164
+ const origin = ctx.req.header("origin");
165
+ if (origin !== void 0 && !isLoopbackOrigin(origin)) {
166
+ return ctx.json({ message: "Forbidden: cross-origin request to the MCP endpoint" }, 403);
167
+ }
168
+ const address = clientAddress(ctx);
169
+ if (address !== void 0 && !isLoopbackAddress(address)) {
170
+ return ctx.json({ message: "Forbidden: remote request to the MCP endpoint" }, 403);
171
+ }
172
+ await next();
173
+ };
174
+ }
175
+
136
176
  export {
137
177
  ServiceProvider,
138
- ProviderManager
178
+ ProviderManager,
179
+ MCP_ENDPOINT_PATH,
180
+ isMcpEndpointEnabled,
181
+ createMcpAccessGuard
139
182
  };
@@ -1,3 +1,8 @@
1
+ import {
2
+ claimHotDisposable,
3
+ isHotReloadRuntime
4
+ } from "./chunk-DCYKSYAT.js";
5
+
1
6
  // src/broadcasting/channels/Channel.ts
2
7
  var Channel = class {
3
8
  constructor(name, driver) {
@@ -884,6 +889,28 @@ data: ${JSON.stringify(data)}
884
889
  getChannelClients(channel) {
885
890
  return this.getClients().filter((client) => client.channels.has(channel));
886
891
  }
892
+ /**
893
+ * Close every SSE connection this manager is holding.
894
+ *
895
+ * Each connection owns a ping timer that is only cleared when the stream is
896
+ * cancelled or the request aborts. `Bun.serve().stop()` without forcing waits
897
+ * for in-flight requests instead of cutting them, and an SSE response never
898
+ * finishes — so on a hot reload those connections outlive the manager, and
899
+ * their timers go on pinging a stream nobody reads.
900
+ *
901
+ * `getClients()` returns a snapshot. A `Map` iterator does tolerate an entry
902
+ * deleting itself, which is all `cleanup()` does today — but not a `close()`
903
+ * that reaches another client, which would drop that one from the iteration
904
+ * unvisited and leave its timer running.
905
+ */
906
+ disconnectAll() {
907
+ for (const client of this.getClients()) {
908
+ try {
909
+ client.close();
910
+ } catch {
911
+ }
912
+ }
913
+ }
887
914
  /**
888
915
  * Generate a unique client ID.
889
916
  */
@@ -904,7 +931,14 @@ function getBroadcastManager() {
904
931
  return globalBroadcastManager;
905
932
  }
906
933
  function createBroadcastManager(options) {
907
- return new BroadcastManager(options);
934
+ const manager = new BroadcastManager(options);
935
+ claimHotDisposable(
936
+ "broadcast-manager",
937
+ isHotReloadRuntime() ? new Error().stack : void 0,
938
+ options?.default ?? "memory",
939
+ () => manager.disconnectAll()
940
+ );
941
+ return manager;
908
942
  }
909
943
 
910
944
  // src/broadcasting/typed.ts
@@ -32,6 +32,13 @@ interface RateLimitStore {
32
32
  */
33
33
  declare abstract class BaseMemoryStore implements RateLimitStore {
34
34
  protected cleanupInterval?: ReturnType<typeof setInterval>;
35
+ /**
36
+ * This store's claim on its hot-reload slot, if it holds one.
37
+ *
38
+ * Unlike the cache sweep, this interval is not `unref()`ed, so a leaked one
39
+ * both duplicates work and keeps the process alive on its own.
40
+ */
41
+ private readonly hotReloadClaim;
35
42
  constructor(cleanupIntervalMs?: number);
36
43
  abstract get(key: string): Promise<RateLimitEntry | null>;
37
44
  abstract increment(key: string, windowMs: number): Promise<RateLimitEntry>;
@@ -1,4 +1,4 @@
1
- import { A as Authenticatable, U as UserProvider } from './api-token-CB12xnVg.js';
1
+ import { A as Authenticatable, U as UserProvider } from './api-token-COQHXyM_.js';
2
2
 
3
3
  /**
4
4
  * Hash a token using SHA-256 or SHA-512.