@guren/server 2.34.0 → 2.36.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 (63) hide show
  1. package/dist/{DocsViewerServiceProvider-BVPZjwQp.js → DocsViewerServiceProvider-DzrxQoYh.js} +15 -4
  2. package/dist/Event-COT3f5Xd.js +28 -0
  3. package/dist/{Gate-C252SwRR.js → Gate-BHyDcDKo.js} +45 -5
  4. package/dist/{HttpException-BlQ2yEmT.js → HttpException-2tfZGamp.js} +8 -2
  5. package/dist/{McpServiceProvider-CXOokGax.js → McpServiceProvider-BOeQyt7u.js} +2 -0
  6. package/dist/PrivateChannel-1krGz028.js +187 -0
  7. package/dist/{Resource-BBKaFgXf.js → Resource-PhnO_wNO.js} +116 -15
  8. package/dist/agent/derive.d.ts +23 -1
  9. package/dist/agent/dispatch.d.ts +12 -1
  10. package/dist/agent/pipeline.d.ts +6 -0
  11. package/dist/agent/public.d.ts +1 -1
  12. package/dist/agent/public.js +1 -1
  13. package/dist/{api-token-DJcqSybf.js → api-token-Cs1myxf6.js} +16 -2
  14. package/dist/auth/index.js +2 -2
  15. package/dist/{auth-Bj9uEHuC.js → auth-DYWBlmpS.js} +2 -2
  16. package/dist/authorization/Gate.d.ts +4 -1
  17. package/dist/authorization/index.js +2 -2
  18. package/dist/{authorization-C81TXOWD.js → authorization-rxx6aprN.js} +1 -1
  19. package/dist/broadcasting/BroadcastManager.d.ts +19 -5
  20. package/dist/broadcasting/event-target.d.ts +9 -0
  21. package/dist/broadcasting/index.d.ts +3 -1
  22. package/dist/broadcasting/index.js +3 -2
  23. package/dist/broadcasting/sender-envelope.d.ts +26 -0
  24. package/dist/broadcasting/types.d.ts +27 -2
  25. package/dist/{broadcasting-3pvO94xV.js → broadcasting-Bh6QoMpy.js} +51 -96
  26. package/dist/{contained-path-BkNSBljW.js → contained-path-DOVauNQC.js} +1 -22
  27. package/dist/{context-af2n5abO.js → context--l2HdOhy.js} +1 -1
  28. package/dist/{dev-banner-B_QaY29h.js → dev-banner-DGxB3HGY.js} +8 -4
  29. package/dist/{dispatch-ENWpBxbE.js → dispatch-CDNqcB3Q.js} +51 -12
  30. package/dist/errors/ExceptionHandler.d.ts +5 -1
  31. package/dist/errors/HttpException.d.ts +6 -0
  32. package/dist/errors/exceptions/NotFoundHttpException.d.ts +2 -0
  33. package/dist/errors/wants-html.d.ts +7 -0
  34. package/dist/{errors-JpkcCjjn.js → errors-C8neC8go.js} +1 -1
  35. package/dist/events/index.js +2 -1
  36. package/dist/{events-B6gfJkCH.js → events-DW197Nur.js} +2 -28
  37. package/dist/http/dev-banner.d.ts +6 -1
  38. package/dist/http/middleware/csrf.d.ts +1 -1
  39. package/dist/http/middleware/redirect-safety.d.ts +8 -0
  40. package/dist/http/vite-dev-server.d.ts +18 -1
  41. package/dist/http/vite-manifest.d.ts +4 -1
  42. package/dist/index.d.ts +7 -7
  43. package/dist/index.js +305 -161
  44. package/dist/internal/agent-principal.d.ts +8 -0
  45. package/dist/internal/testing.d.ts +1 -0
  46. package/dist/internal/testing.js +4 -4
  47. package/dist/mcp/index.js +1 -1
  48. package/dist/mvc/Router.d.ts +13 -0
  49. package/dist/mvc/inertia/InertiaEngine.d.ts +3 -0
  50. package/dist/mvc/inertia/props.d.ts +54 -3
  51. package/dist/providers/InertiaServiceProvider.d.ts +7 -0
  52. package/dist/runtime/index.js +5 -3
  53. package/dist/storage/index.js +1 -1
  54. package/dist/{storage-YPbsV9ju.js → storage-ziIKgHON.js} +2 -1
  55. package/dist/trim-slashes-BLY9hKAa.js +22 -0
  56. package/dist/vite/index.d.ts +2 -0
  57. package/dist/vite/index.js +283 -1
  58. package/dist/vite/mcp-app.d.ts +59 -0
  59. package/dist/vite/plugin.d.ts +12 -0
  60. package/dist/{vite-manifest-DO0pU1vm.js → vite-dev-server-Ag90otai.js} +25 -114
  61. package/dist/vite-manifest-BdXRybeq.js +129 -0
  62. package/package.json +1 -1
  63. package/dist/host-port-t6wQFaRu.js +0 -15
@@ -157,6 +157,12 @@ export interface AgentInvocationOptions {
157
157
  * so a route behind those refuses. Omitted, nothing is installed.
158
158
  */
159
159
  handoff?: 'seam';
160
+ /**
161
+ * The shared Inertia props the dispatched request may carry (RFC 0038 §6),
162
+ * installed on the request object so nothing on the wire can widen it.
163
+ * Undefined leaves them all.
164
+ */
165
+ sharedProps?: readonly string[];
160
166
  /** Forwarded to `app.fetch` — D1/R2 bindings on Workers (RFC 0016 §3.1). */
161
167
  env?: unknown;
162
168
  /** Forwarded to `app.fetch` — `waitUntil` on Workers. */
@@ -10,5 +10,5 @@
10
10
  */
11
11
  export { advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse, PREFLIGHT_ARGUMENT, } from './dispatch.js';
12
12
  export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, ToolRequestBuildFailure, } from './dispatch.js';
13
- export type { AgentToolInputSource, AgentToolSchema, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './derive.js';
13
+ export type { AgentToolInputSource, AgentToolSchema, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, DerivedAgentToolUi, } from './derive.js';
14
14
  export type { AgentSurface } from './events.js';
@@ -1,2 +1,2 @@
1
- import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-ENWpBxbE.js";
1
+ import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-CDNqcB3Q.js";
2
2
  export { PREFLIGHT_ARGUMENT, advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse };
@@ -1,4 +1,4 @@
1
- import { a as setResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.js";
1
+ import { a as setResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context--l2HdOhy.js";
2
2
  import { isOptionalExpiryPast } from "./support/expiry.js";
3
3
  import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
4
4
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
@@ -34,6 +34,20 @@ function markAgentDispatch(request) {
34
34
  function isAgentDispatch(request) {
35
35
  return dispatched.has(request);
36
36
  }
37
+ const sharedProps = /* @__PURE__ */ new WeakMap();
38
+ /**
39
+ * Mark `request` as allowed only the named shared Inertia props (RFC 0038 §6),
40
+ * returning that same object. A surface opts in through the pipeline's
41
+ * `sharedProps`; nothing on the wire can ask for it, and nothing can widen it.
42
+ */
43
+ function installAgentSharedProps(request, keys) {
44
+ sharedProps.set(request, new Set(keys));
45
+ return request;
46
+ }
47
+ /** The shared props this exact request may carry, or `undefined` for all of them. */
48
+ function readAgentSharedProps(request) {
49
+ return sharedProps.get(request);
50
+ }
37
51
  //#endregion
38
52
  //#region src/auth/utils.ts
39
53
  function hashToken(token, algorithm = "sha256") {
@@ -480,4 +494,4 @@ function getApiTokenOrFail(ctx) {
480
494
  return result;
481
495
  }
482
496
  //#endregion
483
- export { secureStringCompare as A, scopesAllowTool as C, hashToken as D, generateToken as E, markAgentDispatch as M, readAgentPrincipal as N, parseTokenUrl as O, parseToolScope as S, generateId as T, tokenCanAny as _, getApiToken as a, classifyRegistrationScope as b, hasBearerHeader as c, revokeAllApiTokens as d, revokeApiToken as f, tokenCanAll as g, tokenCan as h, createBearerTokenMiddleware as i, installAgentPrincipal as j, secureCompare as k, parseApiToken as l, tokenAuthenticatesRequest as m, MemoryApiTokenStore as n, getApiTokenOrFail as o, revokePresentedToken as p, createApiToken as r, getUserApiTokens as s, API_TOKEN_KEY as t, readBearerToken as u, verifyApiToken as v, buildTokenUrl as w, expandToolScopes as x, AGENT_TOOL_NAME_PATTERN as y };
497
+ export { secureStringCompare as A, scopesAllowTool as C, hashToken as D, generateToken as E, readAgentSharedProps as F, installAgentSharedProps as M, markAgentDispatch as N, parseTokenUrl as O, readAgentPrincipal as P, parseToolScope as S, generateId as T, tokenCanAny as _, getApiToken as a, classifyRegistrationScope as b, hasBearerHeader as c, revokeAllApiTokens as d, revokeApiToken as f, tokenCanAll as g, tokenCan as h, createBearerTokenMiddleware as i, installAgentPrincipal as j, secureCompare as k, parseApiToken as l, tokenAuthenticatesRequest as m, MemoryApiTokenStore as n, getApiTokenOrFail as o, revokePresentedToken as p, createApiToken as r, getUserApiTokens as s, API_TOKEN_KEY as t, readBearerToken as u, verifyApiToken as v, buildTokenUrl as w, expandToolScopes as x, AGENT_TOOL_NAME_PATTERN as y };
@@ -1,3 +1,3 @@
1
- import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as NodeHasher, I as AuthManager, O as parseOAuthRedirectUrl, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "../auth-Bj9uEHuC.js";
2
- import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, T as generateId, _ as tokenCanAny, a as getApiToken, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAll, h as tokenCan, i as createBearerTokenMiddleware, k as secureCompare, l as parseApiToken, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "../api-token-DJcqSybf.js";
1
+ import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as NodeHasher, I as AuthManager, O as parseOAuthRedirectUrl, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "../auth-DYWBlmpS.js";
2
+ import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, T as generateId, _ as tokenCanAny, a as getApiToken, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAll, h as tokenCan, i as createBearerTokenMiddleware, k as secureCompare, l as parseApiToken, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "../api-token-Cs1myxf6.js";
3
3
  export { API_TOKEN_KEY, ScryptHasher as Argon2Hasher, ScryptHasher, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };
@@ -1,7 +1,7 @@
1
1
  import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-DIUT1Yao.js";
2
2
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
3
- import { A as secureStringCompare, D as hashToken, E as generateToken, N as readAgentPrincipal, O as parseTokenUrl, T as generateId, c as hasBearerHeader, k as secureCompare, l as parseApiToken, m as tokenAuthenticatesRequest, p as revokePresentedToken, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "./api-token-DJcqSybf.js";
4
- import { a as setResolvedPrincipal, i as getResolvedPrincipal, o as AuthenticationException, r as getAuthContext } from "./context-af2n5abO.js";
3
+ import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, P as readAgentPrincipal, T as generateId, c as hasBearerHeader, k as secureCompare, l as parseApiToken, m as tokenAuthenticatesRequest, p as revokePresentedToken, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "./api-token-Cs1myxf6.js";
4
+ import { a as setResolvedPrincipal, i as getResolvedPrincipal, o as AuthenticationException, r as getAuthContext } from "./context--l2HdOhy.js";
5
5
  import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
6
6
  import { t as redactQueryParams } from "./redact-query-params-Ba-sAfcP.js";
7
7
  import { isExpired } from "./support/expiry.js";
@@ -4,7 +4,10 @@ import type { AuthUser, GateCallback, GateBeforeCallback, GateDefinition, GateOp
4
4
  export declare const Response: ResponseBuilder;
5
5
  /** Narrow a policy/gate return value to an `AuthorizationResponse`. */
6
6
  export declare function isAuthorizationResponse(value: unknown): value is AuthorizationResponse;
7
- /** Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404. */
7
+ /**
8
+ * Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404.
9
+ * A 404 is a `NotFoundHttpException`, so a renderer registered for missing records renders it too.
10
+ */
8
11
  export declare function denialToException(response: AuthorizationResponse): Error;
9
12
  /** Authorization gate for defining and checking abilities. */
10
13
  export declare class Gate {
@@ -1,3 +1,3 @@
1
- import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-C81TXOWD.js";
2
- import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-C252SwRR.js";
1
+ import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-rxx6aprN.js";
2
+ import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-BHyDcDKo.js";
3
3
  export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };
@@ -1,5 +1,5 @@
1
1
  import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
2
- import { c as denialToException, d as resolveGate, n as Response, p as AuthorizationException } from "./Gate-C252SwRR.js";
2
+ import { c as denialToException, d as resolveGate, n as Response, p as AuthorizationException } from "./Gate-BHyDcDKo.js";
3
3
  //#region src/http/middleware/capabilities.ts
4
4
  /**
5
5
  * Internal security-capability marker (RFC 0007): built-in middleware
@@ -1,4 +1,4 @@
1
- import type { BroadcastDriver, BroadcastDriverFactory, BroadcastManagerOptions, ChannelAuthorizer, PresenceChannelAuthorizer, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, SSEClient, WebSocketClient, BroadcastEvent } from './types.js';
1
+ import type { BroadcastDriver, BroadcastDriverFactory, BroadcastManagerOptions, ChannelAuthorizer, PresenceChannelAuthorizer, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, SSEClient, WebSocketClient, BroadcastEvent, BroadcastEventOptions, BroadcastableEvent } from './types.js';
2
2
  import { Channel, PrivateChannel, PresenceChannel } from './channels/index.js';
3
3
  import type { Middleware } from '../http/middleware/index.js';
4
4
  /** Broadcast manager for real-time event broadcasting. */
@@ -23,6 +23,20 @@ export declare class BroadcastManager {
23
23
  privateChannel(pattern: string, authorizer: ChannelAuthorizer): this;
24
24
  presenceChannel(pattern: string, authorizer: PresenceChannelAuthorizer): this;
25
25
  broadcast(channelName: string, event: string, data: unknown): Promise<void>;
26
+ /**
27
+ * Publishes `broadcastWith()` (else `{}`) as `broadcastNameOf(event)` on every
28
+ * channel `broadcastOn()` names: the name a `live()` prop listening for this
29
+ * event subscribes to.
30
+ */
31
+ broadcastEvent(event: BroadcastableEvent, options?: BroadcastEventOptions): Promise<void>;
32
+ /** A sender is only worth marking with a socket id this manager could have issued and a user to bind it to. */
33
+ private resolveSender;
34
+ /**
35
+ * What one client receives of a delivered event: nothing when it is the
36
+ * sender's own socket, else the payload without the reserved fields. The ids
37
+ * compare strictly, as `authMiddleware()` compares an owner: `7` is not `'7'`.
38
+ */
39
+ private deliveryFor;
26
40
  toChannel(name: string): Channel;
27
41
  toPrivate(name: string): PrivateChannel;
28
42
  toPresence(name: string): PresenceChannel;
@@ -37,9 +51,9 @@ export declare class BroadcastManager {
37
51
  /**
38
52
  * A route that upgrades to a WebSocket carrying broadcast events, the socket
39
53
  * counterpart of `sseMiddleware()`; it needs `Application.listen()` on Bun.
40
- * Frames are JSON. The server sends `{ event, data }`, first `connected` with
41
- * `{ clientId, channels }`; the client sends `{ action: 'subscribe' | 'unsubscribe',
42
- * channel }`, answered by a `subscription` event, and anything else is ignored.
54
+ * JSON frames: an event `{ event, channel, data }`, the server's own `{ event, data }`
55
+ * (first `connected` with `{ clientId, socketId, channels }`). The client sends
56
+ * `{ action: 'subscribe' | 'unsubscribe', channel }`, answered by `subscription`.
43
57
  */
44
58
  webSocketMiddleware(options?: WebSocketMiddlewareOptions): Middleware;
45
59
  private handleWebSocketMessage;
@@ -64,7 +78,7 @@ export declare class BroadcastManager {
64
78
  */
65
79
  protected releaseDriverSubscriptions(clientId: string): void;
66
80
  /** Returns the generated client ID. */
67
- registerWebSocketClient(client: Omit<WebSocketClient, 'id' | 'channels'> & {
81
+ registerWebSocketClient(client: Omit<WebSocketClient, 'id' | 'channels' | 'socketId'> & {
68
82
  userId?: string | number;
69
83
  }): string;
70
84
  removeWebSocketClient(clientId: string): boolean;
@@ -0,0 +1,9 @@
1
+ import type { BroadcastableEvent } from './types.js';
2
+ /** An event as `live()` and `broadcastEvent()` read it. `eventName` is `Event`'s own getter. */
3
+ export type BroadcastTarget = Pick<BroadcastableEvent, 'broadcastOn' | 'broadcastAs'> & {
4
+ readonly eventName?: string;
5
+ };
6
+ /** `broadcastAs()`, else the event's `eventName`, else its class name. */
7
+ export declare function broadcastNameOf(event: BroadcastTarget): string;
8
+ /** The wire names `broadcastOn()` returns, prefix included, verbatim. */
9
+ export declare function broadcastChannelsOf(event: BroadcastTarget): string[];
@@ -1,6 +1,8 @@
1
- export type { BroadcastEvent, BroadcastDriver, PresenceBroadcastDriver, ChannelAuthorizer, PresenceChannelAuthorizer, PresenceMember, SSEClient, WebSocketClient, BroadcastManagerOptions, BroadcastDriverFactory, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, BroadcastableEvent, } from './types.js';
1
+ export type { BroadcastEvent, BroadcastDriver, PresenceBroadcastDriver, ChannelAuthorizer, PresenceChannelAuthorizer, PresenceMember, SSEClient, WebSocketClient, BroadcastManagerOptions, BroadcastDriverFactory, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, BroadcastableEvent, BroadcastEventOptions, BroadcastSender, } from './types.js';
2
2
  export { BroadcastManager, setBroadcastManager, getBroadcastManager, createBroadcastManager, } from './BroadcastManager.js';
3
3
  export { createTypedBroadcaster, } from './typed.js';
4
+ export { broadcastChannelsOf, broadcastNameOf } from './event-target.js';
5
+ export type { BroadcastTarget } from './event-target.js';
4
6
  export type { TypedBroadcaster, TypedChannelHandle, TypedPrivateChannelHandle, TypedPresenceChannelHandle, } from './typed.js';
5
7
  export { Channel, PrivateChannel, PresenceChannel } from './channels/index.js';
6
8
  export { MemoryDriver, RedisDriver, type MemoryDriverOptions, type RedisClient, type RedisDriverOptions, } from './drivers/index.js';
@@ -1,2 +1,3 @@
1
- import { a as setBroadcastManager, c as PresenceChannel, 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-3pvO94xV.js";
2
- export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
1
+ import { l as broadcastChannelsOf, n as PresenceChannel, r as Channel, t as PrivateChannel, u as broadcastNameOf } from "../PrivateChannel-1krGz028.js";
2
+ import { a as setBroadcastManager, i as getBroadcastManager, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster } from "../broadcasting-Bh6QoMpy.js";
3
+ export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, broadcastChannelsOf, broadcastNameOf, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The sender of a broadcast, carried inside its payload (RFC 0037 §4) so every
3
+ * driver passes it across instances. `__inertia.socketId` and `__inertia.userId`
4
+ * are reserved: every manager publish path strips them from what the app passes
5
+ * before marking, so a relayed payload cannot forge a mark, and delivery strips
6
+ * them before any client sees the payload.
7
+ */
8
+ export interface BroadcastSenderMark {
9
+ readonly socketId: string;
10
+ readonly userId: string | number;
11
+ }
12
+ export declare function isSocketId(value: unknown): value is string;
13
+ /** A user id that survives JSON as itself: `NaN` and the infinities become `null` on the Redis driver. */
14
+ export declare function isSenderUserId(value: unknown): value is string | number;
15
+ /**
16
+ * The payload with the sender added. An object that is not plain (a class
17
+ * instance, one with `toJSON()`) is marked as the JSON a client would receive;
18
+ * an array or a primitive cannot carry a mark.
19
+ */
20
+ export declare function markSender(data: unknown, sender: BroadcastSenderMark): unknown;
21
+ export declare function readSender(data: unknown): BroadcastSenderMark | undefined;
22
+ /**
23
+ * The payload without the reserved fields, valid or not, and without the
24
+ * envelope once nothing else is in it.
25
+ */
26
+ export declare function stripSender(data: unknown): unknown;
@@ -31,16 +31,41 @@ export interface SSEClient {
31
31
  id: string;
32
32
  userId?: string | number;
33
33
  channels: Set<string>;
34
- send(event: string, data: unknown): void;
34
+ /** `channel` is the one an event arrived on; absent on control events (`connected`, `ping`). */
35
+ send(event: string, data: unknown, channel?: string): void;
35
36
  close(): void;
36
37
  }
37
38
  export interface WebSocketClient {
38
39
  id: string;
39
40
  userId?: string | number;
41
+ /**
42
+ * Issued by `registerWebSocketClient()` and sent in `connected`: the value a
43
+ * request names as `X-Socket-Id` to skip its own broadcast (RFC 0037 §4).
44
+ */
45
+ socketId?: string;
40
46
  channels: Set<string>;
41
- send(event: string, data: unknown): void | Promise<void>;
47
+ /** `channel` is the one an event arrived on; absent on control events (`connected`, `subscription`). */
48
+ send(event: string, data: unknown, channel?: string): void | Promise<void>;
42
49
  close(): void;
43
50
  }
51
+ /** Who sent a broadcast, so their own sockets can be skipped. */
52
+ export interface BroadcastSender {
53
+ /** The `X-Socket-Id` the request carried. */
54
+ readonly socketId?: string | null;
55
+ readonly user?: unknown;
56
+ }
57
+ export interface BroadcastEventOptions {
58
+ /**
59
+ * Skip the sender's own socket: the request's context (its `X-Socket-Id`
60
+ * header and signed-in user), or the two given by hand. Only a socket owned
61
+ * by that same user is skipped.
62
+ */
63
+ readonly except?: BroadcastSender | {
64
+ readonly req: {
65
+ header(name: string): string | undefined;
66
+ };
67
+ } | null;
68
+ }
44
69
  export interface BroadcastManagerOptions {
45
70
  default?: string;
46
71
  drivers?: Record<string, BroadcastDriverFactory>;
@@ -1,6 +1,7 @@
1
1
  import { a as parseRequestPayload, t as asRecord } from "./request-CLOYytGP.js";
2
2
  import { g as warnDeprecatedSetter, h as warnDeprecatedGetter, i as bindAmbient, n as ambientBinding } from "./default-application-s9SE-Er7.js";
3
- import { r as getAuthContext } from "./context-af2n5abO.js";
3
+ import { a as isSocketId, c as stripSender, i as isSenderUserId, l as broadcastChannelsOf, n as PresenceChannel, o as markSender, r as Channel, s as readSender, t as PrivateChannel, u as broadcastNameOf } from "./PrivateChannel-1krGz028.js";
4
+ import { r as getAuthContext } from "./context--l2HdOhy.js";
4
5
  import { t as redactQueryParams } from "./redact-query-params-Ba-sAfcP.js";
5
6
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
6
7
  import { c as randomHex } from "./Random-S0OvCuR8.js";
@@ -43,93 +44,6 @@ function createWebSocketOriginGuard(options = {}) {
43
44
  };
44
45
  }
45
46
  //#endregion
46
- //#region src/broadcasting/channels/Channel.ts
47
- var Channel = class {
48
- name;
49
- driver;
50
- constructor(name, driver) {
51
- this.name = name;
52
- this.driver = driver;
53
- }
54
- async broadcast(event, data) {
55
- await this.driver.publish(this.name, event, data);
56
- }
57
- /** Returns an unsubscribe function. */
58
- subscribe(callback) {
59
- return this.driver.subscribe(this.name, (e) => {
60
- callback(e.event, e.data);
61
- });
62
- }
63
- getChannelName() {
64
- return this.name;
65
- }
66
- };
67
- //#endregion
68
- //#region src/broadcasting/channels/PrivateChannel.ts
69
- /** Broadcast channel that requires authentication to subscribe. */
70
- var PrivateChannel = class PrivateChannel extends Channel {
71
- static PREFIX = "private-";
72
- constructor(name, driver) {
73
- const channelName = name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
74
- super(channelName, driver);
75
- }
76
- getBaseName() {
77
- return this.name.startsWith(PrivateChannel.PREFIX) ? this.name.slice(PrivateChannel.PREFIX.length) : this.name;
78
- }
79
- static isPrivateChannel(name) {
80
- return name.startsWith(PrivateChannel.PREFIX);
81
- }
82
- static normalize(name) {
83
- return name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
84
- }
85
- };
86
- //#endregion
87
- //#region src/broadcasting/channels/PresenceChannel.ts
88
- /** Broadcast channel that tracks the members who have joined it. */
89
- var PresenceChannel = class PresenceChannel extends Channel {
90
- static PREFIX = "presence-";
91
- presenceDriver;
92
- constructor(name, driver) {
93
- const channelName = name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
94
- super(channelName, driver);
95
- if (this.isPresenceDriver(driver)) this.presenceDriver = driver;
96
- else throw new Error("Driver does not support presence channels. Ensure the driver implements PresenceBroadcastDriver interface.");
97
- }
98
- isPresenceDriver(driver) {
99
- return "getMembers" in driver && "addMember" in driver && "removeMember" in driver;
100
- }
101
- members() {
102
- return this.presenceDriver.getMembers(this.name);
103
- }
104
- async join(member) {
105
- this.presenceDriver.addMember(this.name, member);
106
- await this.broadcast("presence:joining", { member });
107
- }
108
- async leave(memberId) {
109
- const member = this.members().find((m) => m.id === memberId);
110
- this.presenceDriver.removeMember(this.name, memberId);
111
- if (member) await this.broadcast("presence:leaving", { member });
112
- }
113
- hasMember(memberId) {
114
- return this.members().some((m) => m.id === memberId);
115
- }
116
- getMember(memberId) {
117
- return this.members().find((m) => m.id === memberId);
118
- }
119
- count() {
120
- return this.members().length;
121
- }
122
- getBaseName() {
123
- return this.name.startsWith(PresenceChannel.PREFIX) ? this.name.slice(PresenceChannel.PREFIX.length) : this.name;
124
- }
125
- static isPresenceChannel(name) {
126
- return name.startsWith(PresenceChannel.PREFIX);
127
- }
128
- static normalize(name) {
129
- return name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
130
- }
131
- };
132
- //#endregion
133
47
  //#region src/broadcasting/drivers/MemoryDriver.ts
134
48
  /**
135
49
  * Keeps subscriptions and presence data in memory — for testing and
@@ -465,7 +379,39 @@ var BroadcastManager = class {
465
379
  return this;
466
380
  }
467
381
  async broadcast(channelName, event, data) {
468
- await this.driver().publish(channelName, event, data);
382
+ await this.driver().publish(channelName, event, stripSender(data));
383
+ }
384
+ /**
385
+ * Publishes `broadcastWith()` (else `{}`) as `broadcastNameOf(event)` on every
386
+ * channel `broadcastOn()` names: the name a `live()` prop listening for this
387
+ * event subscribes to.
388
+ */
389
+ async broadcastEvent(event, options = {}) {
390
+ const name = broadcastNameOf(event);
391
+ const payload = stripSender(event.broadcastWith?.() ?? {});
392
+ const sender = options.except ? await this.resolveSender(options.except) : void 0;
393
+ const data = sender ? markSender(payload, sender) : payload;
394
+ for (const channel of broadcastChannelsOf(event)) await this.driver().publish(channel, name, data);
395
+ }
396
+ /** A sender is only worth marking with a socket id this manager could have issued and a user to bind it to. */
397
+ async resolveSender(except) {
398
+ const fromContext = "req" in except;
399
+ const socketId = fromContext ? except.req.header("X-Socket-Id") : except.socketId;
400
+ if (!isSocketId(socketId)) return void 0;
401
+ const userId = resolveClientUserId(fromContext ? await resolveRequestUser(except, void 0) : except.user);
402
+ return isSenderUserId(userId) ? {
403
+ socketId,
404
+ userId
405
+ } : void 0;
406
+ }
407
+ /**
408
+ * What one client receives of a delivered event: nothing when it is the
409
+ * sender's own socket, else the payload without the reserved fields. The ids
410
+ * compare strictly, as `authMiddleware()` compares an owner: `7` is not `'7'`.
411
+ */
412
+ deliveryFor(client, data) {
413
+ const sender = readSender(data);
414
+ return sender !== void 0 && "socketId" in client && client.socketId === sender.socketId && client.userId !== void 0 && client.userId === sender.userId ? void 0 : { data: stripSender(data) };
469
415
  }
470
416
  toChannel(name) {
471
417
  return new Channel(name, this.driver());
@@ -577,9 +523,9 @@ var BroadcastManager = class {
577
523
  /**
578
524
  * A route that upgrades to a WebSocket carrying broadcast events, the socket
579
525
  * counterpart of `sseMiddleware()`; it needs `Application.listen()` on Bun.
580
- * Frames are JSON. The server sends `{ event, data }`, first `connected` with
581
- * `{ clientId, channels }`; the client sends `{ action: 'subscribe' | 'unsubscribe',
582
- * channel }`, answered by a `subscription` event, and anything else is ignored.
526
+ * JSON frames: an event `{ event, channel, data }`, the server's own `{ event, data }`
527
+ * (first `connected` with `{ clientId, socketId, channels }`). The client sends
528
+ * `{ action: 'subscribe' | 'unsubscribe', channel }`, answered by `subscription`.
583
529
  */
584
530
  webSocketMiddleware(options = {}) {
585
531
  const isAllowedOrigin = webSocketOriginCheck(options.allowedOrigins);
@@ -597,8 +543,12 @@ var BroadcastManager = class {
597
543
  const { upgradeWebSocket } = await import("hono/bun");
598
544
  return await upgradeWebSocket(() => ({
599
545
  onOpen: (_event, ws) => {
600
- const send = (event, data) => ws.send(JSON.stringify({
546
+ const send = (event, data, channel) => ws.send(JSON.stringify(channel === void 0 ? {
547
+ event,
548
+ data
549
+ } : {
601
550
  event,
551
+ channel,
602
552
  data
603
553
  }));
604
554
  clientId = this.registerWebSocketClient({
@@ -606,8 +556,10 @@ var BroadcastManager = class {
606
556
  send,
607
557
  close: () => ws.close()
608
558
  });
559
+ const { socketId } = this.wsClients.get(clientId);
609
560
  send("connected", {
610
561
  clientId,
562
+ socketId,
611
563
  channels: authorizedChannels
612
564
  });
613
565
  for (const channelName of authorizedChannels) this.subscribeWebSocketClient(clientId, channelName);
@@ -689,7 +641,8 @@ var BroadcastManager = class {
689
641
  if (!client) return false;
690
642
  client.channels.add(channel);
691
643
  this.openDriverSubscription(clientId, channel, (event) => {
692
- if (client.channels.has(channel)) client.send(event.event, event.data);
644
+ const delivery = client.channels.has(channel) ? this.deliveryFor(client, event.data) : void 0;
645
+ if (delivery) client.send(event.event, delivery.data, channel);
693
646
  });
694
647
  return true;
695
648
  }
@@ -735,6 +688,7 @@ var BroadcastManager = class {
735
688
  this.wsClients.set(clientId, {
736
689
  ...client,
737
690
  id: clientId,
691
+ socketId: `s_${randomHex(16)}`,
738
692
  channels: /* @__PURE__ */ new Set()
739
693
  });
740
694
  return clientId;
@@ -757,7 +711,8 @@ var BroadcastManager = class {
757
711
  if (!client) return false;
758
712
  client.channels.add(channel);
759
713
  this.openDriverSubscription(clientId, channel, async (event) => {
760
- if (client.channels.has(channel)) await client.send(event.event, event.data);
714
+ const delivery = client.channels.has(channel) ? this.deliveryFor(client, event.data) : void 0;
715
+ if (delivery) await client.send(event.event, delivery.data, channel);
761
716
  });
762
717
  return true;
763
718
  }
@@ -868,4 +823,4 @@ function wrapChannel(name, channel) {
868
823
  };
869
824
  }
870
825
  //#endregion
871
- export { setBroadcastManager as a, PresenceChannel as c, createWebSocketOriginGuard as d, getBroadcastManager as i, PrivateChannel as l, BroadcastManager as n, RedisDriver as o, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t, Channel as u };
826
+ export { setBroadcastManager as a, createWebSocketOriginGuard as c, getBroadcastManager as i, BroadcastManager as n, RedisDriver as o, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t };
@@ -1,26 +1,5 @@
1
1
  import { basename, dirname, join, sep } from "node:path";
2
2
  import { realpath } from "node:fs/promises";
3
- //#region src/support/trim-slashes.ts
4
- /**
5
- * No regex: patterns like `/\/+$/` backtrack quadratically on long slash runs
6
- * mid-string, and several call sites feed request-derived paths.
7
- *
8
- * Twins that cannot import this module: `@guren/cli` (`src/utils.ts`) and
9
- * `@guren/plugin-cloudflare` (`src/storage/R2Driver.ts`) — keep them in step.
10
- */
11
- function trimTrailingSlashes(value) {
12
- let end = value.length;
13
- while (end > 0 && value[end - 1] === "/") end--;
14
- return value.slice(0, end);
15
- }
16
- function trimSlashes(value) {
17
- let start = 0;
18
- let end = value.length;
19
- while (start < end && value[start] === "/") start++;
20
- while (end > start && value[end - 1] === "/") end--;
21
- return value.slice(start, end);
22
- }
23
- //#endregion
24
3
  //#region src/support/contained-path.ts
25
4
  /**
26
5
  * Lexical containment. The trailing separator keeps out a sibling whose name
@@ -75,4 +54,4 @@ async function realPathOfNearestExisting(path) {
75
54
  }
76
55
  }
77
56
  //#endregion
78
- export { trimTrailingSlashes as a, trimSlashes as i, isRealPathWithin as n, realPathOfNearestExisting as r, isPathWithin as t };
57
+ export { isRealPathWithin as n, realPathOfNearestExisting as r, isPathWithin as t };
@@ -1,4 +1,4 @@
1
- import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
1
+ import { t as HttpException } from "./HttpException-2tfZGamp.js";
2
2
  //#region src/errors/exceptions/AuthenticationException.ts
3
3
  /** 401: the user is not authenticated, or the credentials were invalid. */
4
4
  var AuthenticationException = class AuthenticationException extends HttpException {
@@ -1,10 +1,10 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { n as isWildcardHost, t as formatHostPort } from "./host-port-t6wQFaRu.js";
2
+ import { d as formatHostPort, f as isWildcardHost, t as DEFAULT_DEV_SERVER_URL } from "./vite-manifest-BdXRybeq.js";
3
3
  import chalk from "chalk";
4
4
  import figlet from "figlet";
5
5
  import standard from "figlet/importable-fonts/Standard.js";
6
6
  //#region package.json
7
- var version = "2.34.0";
7
+ var version = "2.36.0";
8
8
  //#endregion
9
9
  //#region src/http/dev-banner.ts
10
10
  var dev_banner_exports = /* @__PURE__ */ __exportAll({
@@ -26,7 +26,11 @@ function generateAsciiArt(text) {
26
26
  }
27
27
  const GUREN_ASCII_ART = chalk.redBright.bold(generateAsciiArt("GUREN"));
28
28
  const GUREN_VERSION = version;
29
- function logDevServerBanner({ hostname, port, assetsUrl = "http://localhost:5173" }) {
29
+ const ASSET_SERVER_LABELS = {
30
+ managed: "Vite, started by Guren",
31
+ external: "not started by Guren, run it yourself"
32
+ };
33
+ function logDevServerBanner({ hostname, port, assetsUrl = DEFAULT_DEV_SERVER_URL, assetServer }) {
30
34
  const localUrl = `http://localhost:${port}`;
31
35
  const boundUrl = `http://${formatHostPort(hostname, port)}`;
32
36
  const boundLabel = isWildcardHost(hostname) ? " (all interfaces)" : "";
@@ -40,7 +44,7 @@ function logDevServerBanner({ hostname, port, assetsUrl = "http://localhost:5173
40
44
  ...header,
41
45
  detail("App URL", localUrl),
42
46
  detail("Bound address", `${boundUrl}${boundLabel}`),
43
- detail("Asset server", `${assetsUrl} (Vite)`),
47
+ detail("Asset server", `${assetsUrl} (${assetServer ? ASSET_SERVER_LABELS[assetServer] : "Vite"})`),
44
48
  "",
45
49
  chalk.yellowBright("Press Ctrl+C to douse the flames."),
46
50
  ""