@guren/server 2.10.0 → 2.11.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 (91) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/encryption/index.js +5 -96
  21. package/dist/encryption-fOWQaKqX.js +250 -0
  22. package/dist/endpoint-D-20PiHY.js +46 -0
  23. package/dist/endpoint-D6GIqOpe.js +31 -0
  24. package/dist/errors-quJOkkCn.js +81 -0
  25. package/dist/events/index.js +2 -28
  26. package/dist/events-aIH_bWRx.js +410 -0
  27. package/dist/health/index.js +2 -24
  28. package/dist/health-VWdWXRwh.js +345 -0
  29. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  30. package/dist/hot-reload/testing.d.ts +1 -1
  31. package/dist/http/resources/Resource.d.ts +23 -3
  32. package/dist/i18n/index.js +2 -30
  33. package/dist/i18n-mcWi7LCd.js +617 -0
  34. package/dist/index.js +7515 -7276
  35. package/dist/lambda/index.js +114 -71
  36. package/dist/logging/index.js +2 -24
  37. package/dist/logging-CPaRMuPP.js +518 -0
  38. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  39. package/dist/mail/index.js +2 -27
  40. package/dist/mail-DfEfSQEr.js +699 -0
  41. package/dist/mcp/index.js +2 -10
  42. package/dist/notifications/index.js +2 -33
  43. package/dist/notifications-BGqmUNZ8.js +759 -0
  44. package/dist/queue/index.js +3 -42
  45. package/dist/queue-CXrRK85G.js +948 -0
  46. package/dist/redis/index.js +672 -642
  47. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  48. package/dist/runtime/index.js +472 -616
  49. package/dist/scheduling/index.js +2 -29
  50. package/dist/scheduling-CPiEdtQd.js +839 -0
  51. package/dist/storage/index.js +2 -15
  52. package/dist/storage-tWHMv2H_.js +841 -0
  53. package/dist/support/expiry.js +69 -12
  54. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  55. package/dist/vite/index.js +118 -181
  56. package/dist/vite/plugin.d.ts +1 -1
  57. package/dist/vite-dev-server-BSJkduhZ.js +131 -0
  58. package/package.json +6 -5
  59. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  60. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  61. package/dist/chunk-2SC566CD.js +0 -376
  62. package/dist/chunk-2V3YID4H.js +0 -20
  63. package/dist/chunk-3KV5X2FL.js +0 -31
  64. package/dist/chunk-63SKW5PS.js +0 -457
  65. package/dist/chunk-6J6B5KOB.js +0 -425
  66. package/dist/chunk-A5JJ7XTH.js +0 -24
  67. package/dist/chunk-AZOYI43J.js +0 -18
  68. package/dist/chunk-B5E5VBDI.js +0 -115
  69. package/dist/chunk-DAQKYKLH.js +0 -182
  70. package/dist/chunk-DRNPVBAA.js +0 -1002
  71. package/dist/chunk-EI5GYMAT.js +0 -853
  72. package/dist/chunk-H3B23O6T.js +0 -271
  73. package/dist/chunk-HPET6XY5.js +0 -853
  74. package/dist/chunk-HR2KZ3WL.js +0 -616
  75. package/dist/chunk-IOTWFHZU.js +0 -558
  76. package/dist/chunk-K6CUBJX6.js +0 -642
  77. package/dist/chunk-KTNJG7R7.js +0 -911
  78. package/dist/chunk-LAJQCSSF.js +0 -355
  79. package/dist/chunk-LHR6OHI7.js +0 -189
  80. package/dist/chunk-N7PLD7MB.js +0 -729
  81. package/dist/chunk-Q2P6YLRR.js +0 -24
  82. package/dist/chunk-QQKTH5KX.js +0 -114
  83. package/dist/chunk-SFQP6O52.js +0 -126
  84. package/dist/chunk-SQR7277M.js +0 -911
  85. package/dist/chunk-T2FFUU6J.js +0 -484
  86. package/dist/chunk-TVV5YNEC.js +0 -1842
  87. package/dist/chunk-UY3AZSYL.js +0 -14
  88. package/dist/chunk-V4DNC2ER.js +0 -114
  89. package/dist/chunk-VSA3QY5Q.js +0 -274
  90. package/dist/chunk-YSOJKAAU.js +0 -427
  91. package/dist/errors-PUNHAFL2.js +0 -34
@@ -0,0 +1,1055 @@
1
+ import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-WsTX2ySN.js";
2
+ import { c as randomHex } from "./Random-DbIJ22KQ.js";
3
+ //#region src/http/request.ts
4
+ function isPlainObject(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ /**
8
+ * Parses the incoming request payload supporting both JSON bodies and form submissions.
9
+ * Falls back to an empty object if the payload cannot be parsed.
10
+ */
11
+ async function parseRequestPayload(ctx) {
12
+ if ((ctx.req.header("content-type") ?? "").includes("application/json")) {
13
+ const body = await ctx.req.json().catch(() => ({}));
14
+ return isPlainObject(body) ? body : {};
15
+ }
16
+ if (typeof ctx.req.parseBody === "function") {
17
+ const form = await ctx.req.parseBody();
18
+ return Object.fromEntries(Object.entries(form).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value]));
19
+ }
20
+ return {};
21
+ }
22
+ /**
23
+ * Collects query parameters preserving repeated keys as arrays while keeping
24
+ * single occurrences as plain strings (`?tag=a&tag=b` → `{ tag: ['a', 'b'] }`,
25
+ * `?page=2` → `{ page: '2' }`). Use this instead of `ctx.req.query()` when
26
+ * feeding query data into validation schemas.
27
+ */
28
+ function flattenRequestQueries(ctx) {
29
+ const queries = ctx.req.queries();
30
+ const flat = {};
31
+ for (const [key, values] of Object.entries(queries)) flat[key] = values.length === 1 ? values[0] : values;
32
+ return flat;
33
+ }
34
+ /**
35
+ * Converts a Zod-style validation error into a flat record usable by forms.
36
+ */
37
+ function formatValidationErrors(error, fallbackMessage = "The provided data is invalid.") {
38
+ const errors = {};
39
+ for (const issue of error.issues ?? []) {
40
+ const field = issue.path?.[0];
41
+ if (typeof field === "string" && !errors[field]) errors[field] = issue.message;
42
+ }
43
+ if (Object.keys(errors).length === 0) errors.message = fallbackMessage;
44
+ return errors;
45
+ }
46
+ //#endregion
47
+ //#region src/broadcasting/channels/Channel.ts
48
+ /**
49
+ * Base broadcast channel.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const channel = new Channel('notifications', driver)
54
+ * await channel.broadcast('NewMessage', { content: 'Hello!' })
55
+ * ```
56
+ */
57
+ var Channel = class {
58
+ name;
59
+ driver;
60
+ constructor(name, driver) {
61
+ this.name = name;
62
+ this.driver = driver;
63
+ }
64
+ /**
65
+ * Broadcast an event to this channel.
66
+ */
67
+ async broadcast(event, data) {
68
+ await this.driver.publish(this.name, event, data);
69
+ }
70
+ /**
71
+ * Subscribe to events on this channel.
72
+ * Returns an unsubscribe function.
73
+ */
74
+ subscribe(callback) {
75
+ return this.driver.subscribe(this.name, (e) => {
76
+ callback(e.event, e.data);
77
+ });
78
+ }
79
+ /**
80
+ * Get the full channel name for broadcasting.
81
+ */
82
+ getChannelName() {
83
+ return this.name;
84
+ }
85
+ };
86
+ //#endregion
87
+ //#region src/broadcasting/channels/PrivateChannel.ts
88
+ /**
89
+ * Private broadcast channel.
90
+ *
91
+ * Requires authentication to subscribe.
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const channel = new PrivateChannel('orders.123', driver)
96
+ * await channel.broadcast('OrderUpdated', { status: 'shipped' })
97
+ * ```
98
+ */
99
+ var PrivateChannel = class PrivateChannel extends Channel {
100
+ /**
101
+ * Channel name prefix.
102
+ */
103
+ static PREFIX = "private-";
104
+ constructor(name, driver) {
105
+ const channelName = name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
106
+ super(channelName, driver);
107
+ }
108
+ /**
109
+ * Get the channel name without the private prefix.
110
+ */
111
+ getBaseName() {
112
+ return this.name.startsWith(PrivateChannel.PREFIX) ? this.name.slice(PrivateChannel.PREFIX.length) : this.name;
113
+ }
114
+ /**
115
+ * Check if a channel name is a private channel.
116
+ */
117
+ static isPrivateChannel(name) {
118
+ return name.startsWith(PrivateChannel.PREFIX);
119
+ }
120
+ /**
121
+ * Normalize a channel name to include the private prefix.
122
+ */
123
+ static normalize(name) {
124
+ return name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
125
+ }
126
+ };
127
+ //#endregion
128
+ //#region src/broadcasting/channels/PresenceChannel.ts
129
+ /**
130
+ * Presence broadcast channel.
131
+ *
132
+ * Tracks members who have joined the channel.
133
+ *
134
+ * @example
135
+ * ```typescript
136
+ * const channel = new PresenceChannel('chat.1', driver)
137
+ *
138
+ * // Join channel
139
+ * await channel.join({ id: 1, info: { name: 'John' } })
140
+ *
141
+ * // Get members
142
+ * const members = channel.members()
143
+ *
144
+ * // Leave channel
145
+ * await channel.leave(1)
146
+ *
147
+ * // Broadcast
148
+ * await channel.broadcast('UserTyping', { userId: 1 })
149
+ * ```
150
+ */
151
+ var PresenceChannel = class PresenceChannel extends Channel {
152
+ /**
153
+ * Channel name prefix.
154
+ */
155
+ static PREFIX = "presence-";
156
+ presenceDriver;
157
+ constructor(name, driver) {
158
+ const channelName = name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
159
+ super(channelName, driver);
160
+ if (this.isPresenceDriver(driver)) this.presenceDriver = driver;
161
+ else throw new Error("Driver does not support presence channels. Ensure the driver implements PresenceBroadcastDriver interface.");
162
+ }
163
+ /**
164
+ * Check if a driver supports presence.
165
+ */
166
+ isPresenceDriver(driver) {
167
+ return "getMembers" in driver && "addMember" in driver && "removeMember" in driver;
168
+ }
169
+ /**
170
+ * Get members in this channel.
171
+ */
172
+ members() {
173
+ return this.presenceDriver.getMembers(this.name);
174
+ }
175
+ /**
176
+ * Join the channel.
177
+ */
178
+ async join(member) {
179
+ this.presenceDriver.addMember(this.name, member);
180
+ await this.broadcast("presence:joining", { member });
181
+ }
182
+ /**
183
+ * Leave the channel.
184
+ */
185
+ async leave(memberId) {
186
+ const member = this.members().find((m) => m.id === memberId);
187
+ this.presenceDriver.removeMember(this.name, memberId);
188
+ if (member) await this.broadcast("presence:leaving", { member });
189
+ }
190
+ /**
191
+ * Check if a member is in the channel.
192
+ */
193
+ hasMember(memberId) {
194
+ return this.members().some((m) => m.id === memberId);
195
+ }
196
+ /**
197
+ * Get member by ID.
198
+ */
199
+ getMember(memberId) {
200
+ return this.members().find((m) => m.id === memberId);
201
+ }
202
+ /**
203
+ * Get member count.
204
+ */
205
+ count() {
206
+ return this.members().length;
207
+ }
208
+ /**
209
+ * Get the channel name without the presence prefix.
210
+ */
211
+ getBaseName() {
212
+ return this.name.startsWith(PresenceChannel.PREFIX) ? this.name.slice(PresenceChannel.PREFIX.length) : this.name;
213
+ }
214
+ /**
215
+ * Check if a channel name is a presence channel.
216
+ */
217
+ static isPresenceChannel(name) {
218
+ return name.startsWith(PresenceChannel.PREFIX);
219
+ }
220
+ /**
221
+ * Normalize a channel name to include the presence prefix.
222
+ */
223
+ static normalize(name) {
224
+ return name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
225
+ }
226
+ };
227
+ //#endregion
228
+ //#region src/broadcasting/drivers/MemoryDriver.ts
229
+ /**
230
+ * Memory broadcast driver.
231
+ *
232
+ * Stores all subscriptions and presence data in memory.
233
+ * Useful for testing and single-server deployments.
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * const driver = new MemoryDriver()
238
+ *
239
+ * // Subscribe to a channel
240
+ * const unsubscribe = driver.subscribe('notifications', (event) => {
241
+ * console.log('Received:', event)
242
+ * })
243
+ *
244
+ * // Publish an event
245
+ * await driver.publish('notifications', 'NewMessage', { content: 'Hello!' })
246
+ *
247
+ * // Unsubscribe
248
+ * unsubscribe()
249
+ * ```
250
+ */
251
+ var MemoryDriver = class {
252
+ /**
253
+ * Channel subscribers.
254
+ */
255
+ subscribers = /* @__PURE__ */ new Map();
256
+ /**
257
+ * Presence channel members.
258
+ */
259
+ presenceMembers = /* @__PURE__ */ new Map();
260
+ /**
261
+ * Published events (for testing).
262
+ */
263
+ publishedEvents = [];
264
+ /**
265
+ * Publish an event to a channel.
266
+ */
267
+ async publish(channel, event, data) {
268
+ const broadcastEvent = {
269
+ channel,
270
+ event,
271
+ data,
272
+ timestamp: /* @__PURE__ */ new Date()
273
+ };
274
+ this.publishedEvents.push(broadcastEvent);
275
+ const callbacks = this.subscribers.get(channel);
276
+ if (callbacks) for (const callback of callbacks) try {
277
+ callback(broadcastEvent);
278
+ } catch (error) {
279
+ console.error(`Error in broadcast subscriber:`, error);
280
+ }
281
+ }
282
+ /**
283
+ * Subscribe to a channel.
284
+ */
285
+ subscribe(channel, callback) {
286
+ let callbacks = this.subscribers.get(channel);
287
+ if (!callbacks) {
288
+ callbacks = /* @__PURE__ */ new Set();
289
+ this.subscribers.set(channel, callbacks);
290
+ }
291
+ callbacks.add(callback);
292
+ return () => {
293
+ this.unsubscribe(channel, callback);
294
+ };
295
+ }
296
+ /**
297
+ * Unsubscribe from a channel.
298
+ */
299
+ unsubscribe(channel, callback) {
300
+ const callbacks = this.subscribers.get(channel);
301
+ if (callbacks) {
302
+ callbacks.delete(callback);
303
+ if (callbacks.size === 0) this.subscribers.delete(channel);
304
+ }
305
+ }
306
+ /**
307
+ * Get members of a presence channel.
308
+ */
309
+ getMembers(channel) {
310
+ const members = this.presenceMembers.get(channel);
311
+ return members ? Array.from(members.values()) : [];
312
+ }
313
+ /**
314
+ * Add a member to a presence channel.
315
+ */
316
+ addMember(channel, member) {
317
+ let members = this.presenceMembers.get(channel);
318
+ if (!members) {
319
+ members = /* @__PURE__ */ new Map();
320
+ this.presenceMembers.set(channel, members);
321
+ }
322
+ members.set(member.id, member);
323
+ }
324
+ /**
325
+ * Remove a member from a presence channel.
326
+ */
327
+ removeMember(channel, memberId) {
328
+ const members = this.presenceMembers.get(channel);
329
+ if (members) {
330
+ members.delete(memberId);
331
+ if (members.size === 0) this.presenceMembers.delete(channel);
332
+ }
333
+ }
334
+ /**
335
+ * Check if a channel has subscribers.
336
+ */
337
+ hasSubscribers(channel) {
338
+ const callbacks = this.subscribers.get(channel);
339
+ return callbacks !== void 0 && callbacks.size > 0;
340
+ }
341
+ /**
342
+ * Get subscriber count for a channel.
343
+ */
344
+ getSubscriberCount(channel) {
345
+ const callbacks = this.subscribers.get(channel);
346
+ return callbacks ? callbacks.size : 0;
347
+ }
348
+ /**
349
+ * Get all channels with subscribers.
350
+ */
351
+ getChannels() {
352
+ return Array.from(this.subscribers.keys());
353
+ }
354
+ /**
355
+ * Get all presence channels.
356
+ */
357
+ getPresenceChannels() {
358
+ return Array.from(this.presenceMembers.keys());
359
+ }
360
+ /**
361
+ * Get all published events (for testing).
362
+ */
363
+ getPublishedEvents() {
364
+ return [...this.publishedEvents];
365
+ }
366
+ /**
367
+ * Get published events for a specific channel.
368
+ */
369
+ getPublishedEventsFor(channel) {
370
+ return this.publishedEvents.filter((e) => e.channel === channel);
371
+ }
372
+ /**
373
+ * Clear all data (for testing).
374
+ */
375
+ clear() {
376
+ this.subscribers.clear();
377
+ this.presenceMembers.clear();
378
+ this.publishedEvents = [];
379
+ }
380
+ /**
381
+ * Clear published events only.
382
+ */
383
+ clearPublishedEvents() {
384
+ this.publishedEvents = [];
385
+ }
386
+ };
387
+ //#endregion
388
+ //#region src/broadcasting/drivers/RedisDriver.ts
389
+ /**
390
+ * Redis broadcast driver.
391
+ *
392
+ * Uses Redis pub/sub for multi-server deployments.
393
+ *
394
+ * @example
395
+ * ```typescript
396
+ * import Redis from 'ioredis'
397
+ *
398
+ * const redis = new Redis()
399
+ * const driver = new RedisDriver(redis)
400
+ *
401
+ * // Subscribe to a channel
402
+ * driver.subscribe('notifications', (event) => {
403
+ * console.log('Received:', event)
404
+ * })
405
+ *
406
+ * // Publish an event
407
+ * await driver.publish('notifications', 'NewMessage', { content: 'Hello!' })
408
+ * ```
409
+ */
410
+ var RedisDriver = class {
411
+ /**
412
+ * Publisher Redis client.
413
+ */
414
+ publisher;
415
+ /**
416
+ * Subscriber Redis client.
417
+ */
418
+ subscriber;
419
+ /**
420
+ * Local subscribers.
421
+ */
422
+ subscribers = /* @__PURE__ */ new Map();
423
+ /**
424
+ * Local presence members cache.
425
+ */
426
+ localPresence = /* @__PURE__ */ new Map();
427
+ /**
428
+ * Presence key prefix.
429
+ */
430
+ presencePrefix = "broadcasting:presence:";
431
+ /**
432
+ * Whether the driver is initialized.
433
+ */
434
+ initialized = false;
435
+ constructor(redis, options = {}) {
436
+ this.publisher = redis;
437
+ this.subscriber = redis.duplicate();
438
+ if (options.presencePrefix) this.presencePrefix = options.presencePrefix;
439
+ this.setupSubscriber();
440
+ }
441
+ /**
442
+ * Setup the subscriber client.
443
+ */
444
+ setupSubscriber() {
445
+ this.subscriber.on("message", (channel, message) => {
446
+ try {
447
+ const event = JSON.parse(message);
448
+ event.timestamp = new Date(event.timestamp);
449
+ const callbacks = this.subscribers.get(channel);
450
+ if (callbacks) for (const callback of callbacks) try {
451
+ callback(event);
452
+ } catch (error) {
453
+ console.error(`Error in broadcast subscriber:`, error);
454
+ }
455
+ } catch (error) {
456
+ console.error(`Error parsing broadcast message:`, error);
457
+ }
458
+ });
459
+ this.initialized = true;
460
+ }
461
+ /**
462
+ * Publish an event to a channel.
463
+ */
464
+ async publish(channel, event, data) {
465
+ const broadcastEvent = {
466
+ channel,
467
+ event,
468
+ data,
469
+ timestamp: /* @__PURE__ */ new Date()
470
+ };
471
+ await this.publisher.publish(channel, JSON.stringify(broadcastEvent));
472
+ }
473
+ /**
474
+ * Subscribe to a channel.
475
+ */
476
+ subscribe(channel, callback) {
477
+ let callbacks = this.subscribers.get(channel);
478
+ const isNew = !callbacks;
479
+ if (!callbacks) {
480
+ callbacks = /* @__PURE__ */ new Set();
481
+ this.subscribers.set(channel, callbacks);
482
+ }
483
+ callbacks.add(callback);
484
+ if (isNew) this.subscriber.subscribe(channel).catch((error) => {
485
+ console.error(`Error subscribing to Redis channel:`, error);
486
+ });
487
+ return () => {
488
+ this.unsubscribe(channel, callback);
489
+ };
490
+ }
491
+ /**
492
+ * Unsubscribe from a channel.
493
+ */
494
+ unsubscribe(channel, callback) {
495
+ const callbacks = this.subscribers.get(channel);
496
+ if (callbacks) {
497
+ callbacks.delete(callback);
498
+ if (callbacks.size === 0) {
499
+ this.subscribers.delete(channel);
500
+ this.subscriber.unsubscribe(channel).catch((error) => {
501
+ console.error(`Error unsubscribing from Redis channel:`, error);
502
+ });
503
+ }
504
+ }
505
+ }
506
+ /**
507
+ * Get members of a presence channel.
508
+ */
509
+ getMembers(channel) {
510
+ const members = this.localPresence.get(channel);
511
+ return members ? Array.from(members.values()) : [];
512
+ }
513
+ /**
514
+ * Get members asynchronously from Redis.
515
+ */
516
+ async getMembersAsync(channel) {
517
+ const key = `${this.presencePrefix}${channel}`;
518
+ const data = await this.publisher.hgetall(key);
519
+ const members = [];
520
+ for (const [_, value] of Object.entries(data)) try {
521
+ members.push(JSON.parse(value));
522
+ } catch {}
523
+ const localMembers = /* @__PURE__ */ new Map();
524
+ for (const member of members) localMembers.set(member.id, member);
525
+ this.localPresence.set(channel, localMembers);
526
+ return members;
527
+ }
528
+ /**
529
+ * Add a member to a presence channel.
530
+ */
531
+ addMember(channel, member) {
532
+ let members = this.localPresence.get(channel);
533
+ if (!members) {
534
+ members = /* @__PURE__ */ new Map();
535
+ this.localPresence.set(channel, members);
536
+ }
537
+ members.set(member.id, member);
538
+ const key = `${this.presencePrefix}${channel}`;
539
+ this.publisher.hset(key, String(member.id), JSON.stringify(member)).catch((error) => {
540
+ console.error(`Error adding presence member to Redis:`, error);
541
+ });
542
+ }
543
+ /**
544
+ * Remove a member from a presence channel.
545
+ */
546
+ removeMember(channel, memberId) {
547
+ const members = this.localPresence.get(channel);
548
+ if (members) {
549
+ members.delete(memberId);
550
+ if (members.size === 0) this.localPresence.delete(channel);
551
+ }
552
+ const key = `${this.presencePrefix}${channel}`;
553
+ this.publisher.hdel(key, String(memberId)).catch((error) => {
554
+ console.error(`Error removing presence member from Redis:`, error);
555
+ });
556
+ }
557
+ /**
558
+ * Check if a channel has subscribers.
559
+ */
560
+ hasSubscribers(channel) {
561
+ const callbacks = this.subscribers.get(channel);
562
+ return callbacks !== void 0 && callbacks.size > 0;
563
+ }
564
+ /**
565
+ * Get subscriber count for a channel.
566
+ */
567
+ getSubscriberCount(channel) {
568
+ const callbacks = this.subscribers.get(channel);
569
+ return callbacks ? callbacks.size : 0;
570
+ }
571
+ };
572
+ //#endregion
573
+ //#region src/broadcasting/BroadcastManager.ts
574
+ /**
575
+ * Best-effort identity for the user behind a connection.
576
+ *
577
+ * `getUser` is application-supplied and returns `unknown`, so this reads the
578
+ * conventional identity fields and gives up otherwise. Giving up yields
579
+ * `undefined`, which marks the stream unowned and therefore attachable — the
580
+ * permissive direction, chosen because a stream opened before sign-in has to
581
+ * stay attachable for authorize-after-login to work, and the two cases are
582
+ * indistinguishable from here.
583
+ *
584
+ * So the ownership check below is defence in depth, not the primary control:
585
+ * what actually stops an attach against someone else's stream is that client
586
+ * ids are unguessable. An app whose user objects carry none of these fields
587
+ * gets the unguessable id and no second layer.
588
+ */
589
+ function resolveClientUserId(user) {
590
+ if (typeof user !== "object" || user === null) return void 0;
591
+ const candidate = user;
592
+ for (const value of [
593
+ candidate.id,
594
+ candidate.sub,
595
+ candidate.userId
596
+ ]) if (typeof value === "string" || typeof value === "number") return value;
597
+ }
598
+ /**
599
+ * Broadcast manager for real-time event broadcasting.
600
+ *
601
+ * @example
602
+ * ```typescript
603
+ * const broadcast = new BroadcastManager({
604
+ * default: 'memory',
605
+ * drivers: {
606
+ * memory: () => new MemoryDriver(),
607
+ * redis: () => new RedisDriver(redis),
608
+ * },
609
+ * })
610
+ *
611
+ * // Register channel authorizers
612
+ * broadcast
613
+ * .channel('public.*', () => true)
614
+ * .privateChannel('orders.{orderId}', async (channel, user) => {
615
+ * const orderId = channel.split('.')[1]
616
+ * return order.userId === user.id
617
+ * })
618
+ * .presenceChannel('chat.{roomId}', async (channel, user) => {
619
+ * return { id: user.id, info: { name: user.name } }
620
+ * })
621
+ *
622
+ * // Broadcast events
623
+ * await broadcast.broadcast('notifications', 'NewMessage', { content: 'Hello!' })
624
+ *
625
+ * // Or use channel helpers
626
+ * await broadcast.toChannel('notifications').broadcast('NewMessage', data)
627
+ * await broadcast.toPrivate('orders.123').broadcast('OrderUpdated', data)
628
+ * await broadcast.toPresence('chat.1').broadcast('UserTyping', data)
629
+ * ```
630
+ */
631
+ var BroadcastManager = class {
632
+ /**
633
+ * Default driver name.
634
+ */
635
+ defaultDriver = "memory";
636
+ /**
637
+ * Driver factories.
638
+ */
639
+ driverFactories = /* @__PURE__ */ new Map();
640
+ /**
641
+ * Resolved drivers.
642
+ */
643
+ resolvedDrivers = /* @__PURE__ */ new Map();
644
+ /**
645
+ * Channel registrations.
646
+ */
647
+ channelRegistrations = [];
648
+ /**
649
+ * SSE clients.
650
+ */
651
+ sseClients = /* @__PURE__ */ new Map();
652
+ /**
653
+ * WebSocket clients.
654
+ */
655
+ wsClients = /* @__PURE__ */ new Map();
656
+ constructor(options = {}) {
657
+ if (options.default) this.defaultDriver = options.default;
658
+ if (options.drivers) for (const [name, factory] of Object.entries(options.drivers)) this.registerDriver(name, factory);
659
+ if (!this.driverFactories.has("memory")) this.registerDriver("memory", () => new MemoryDriver());
660
+ }
661
+ /**
662
+ * Register a driver factory.
663
+ */
664
+ registerDriver(name, factory) {
665
+ this.driverFactories.set(name, factory);
666
+ return this;
667
+ }
668
+ /**
669
+ * Get a driver by name.
670
+ */
671
+ driver(name) {
672
+ const driverName = name ?? this.defaultDriver;
673
+ const resolved = this.resolvedDrivers.get(driverName);
674
+ if (resolved) return resolved;
675
+ const factory = this.driverFactories.get(driverName);
676
+ if (!factory) throw new Error(`Broadcast driver "${driverName}" not found`);
677
+ const driver = factory();
678
+ this.resolvedDrivers.set(driverName, driver);
679
+ return driver;
680
+ }
681
+ /**
682
+ * Register a public channel authorizer.
683
+ */
684
+ channel(pattern, authorizer) {
685
+ this.channelRegistrations.push({
686
+ pattern,
687
+ type: "public",
688
+ authorizer
689
+ });
690
+ return this;
691
+ }
692
+ /**
693
+ * Register a private channel authorizer.
694
+ */
695
+ privateChannel(pattern, authorizer) {
696
+ this.channelRegistrations.push({
697
+ pattern: PrivateChannel.normalize(pattern),
698
+ type: "private",
699
+ authorizer
700
+ });
701
+ return this;
702
+ }
703
+ /**
704
+ * Register a presence channel authorizer.
705
+ */
706
+ presenceChannel(pattern, authorizer) {
707
+ this.channelRegistrations.push({
708
+ pattern: PresenceChannel.normalize(pattern),
709
+ type: "presence",
710
+ authorizer
711
+ });
712
+ return this;
713
+ }
714
+ /**
715
+ * Broadcast an event to a channel.
716
+ */
717
+ async broadcast(channelName, event, data) {
718
+ await this.driver().publish(channelName, event, data);
719
+ }
720
+ /**
721
+ * Get a public channel.
722
+ */
723
+ toChannel(name) {
724
+ return new Channel(name, this.driver());
725
+ }
726
+ /**
727
+ * Get a private channel.
728
+ */
729
+ toPrivate(name) {
730
+ return new PrivateChannel(name, this.driver());
731
+ }
732
+ /**
733
+ * Get a presence channel.
734
+ */
735
+ toPresence(name) {
736
+ return new PresenceChannel(name, this.driver());
737
+ }
738
+ /**
739
+ * Authorize a channel for a user.
740
+ */
741
+ async authorize(channelName, user) {
742
+ const registration = this.findChannelRegistration(channelName);
743
+ if (!registration) return !(channelName.startsWith("private-") || channelName.startsWith("presence-"));
744
+ if (registration.type === "presence") {
745
+ const presenceAuth = registration.authorizer;
746
+ const member = await presenceAuth(channelName, user);
747
+ return typeof member === "object" && member !== null ? member : false;
748
+ }
749
+ return await registration.authorizer(channelName, user) === true;
750
+ }
751
+ /**
752
+ * Find channel registration for a channel name.
753
+ */
754
+ findChannelRegistration(channelName) {
755
+ return this.channelRegistrations.find((reg) => this.matchPattern(reg.pattern, channelName));
756
+ }
757
+ /**
758
+ * Match a channel name against a pattern.
759
+ */
760
+ matchPattern(pattern, channelName) {
761
+ const regexPattern = pattern.replace(/\{[^}]+\}/g, "[^.]+").replace(/\*\*/g, ".+").replace(/\*/g, "[^.]+");
762
+ return new RegExp(`^${regexPattern}$`).test(channelName);
763
+ }
764
+ /**
765
+ * Create SSE middleware.
766
+ */
767
+ sseMiddleware(options = {}) {
768
+ const pingInterval = options.pingInterval ?? 3e4;
769
+ const retry = options.retry ?? 3e3;
770
+ return async (ctx) => {
771
+ const clientId = this.generateClientId();
772
+ const encoder = new TextEncoder();
773
+ const manager = this;
774
+ const requestedChannels = (ctx.req.query("channels") ?? "").split(",").map((value) => value.trim()).filter(Boolean);
775
+ const user = options.getUser ? await options.getUser(ctx) : void 0;
776
+ const authorizedChannels = [];
777
+ for (const channelName of requestedChannels) {
778
+ const authResult = await this.authorize(channelName, user);
779
+ if (authResult !== false && authResult !== null) authorizedChannels.push(channelName);
780
+ }
781
+ const clientUserId = resolveClientUserId(user);
782
+ let controller = null;
783
+ let client = null;
784
+ let pingTimer = null;
785
+ const sendRaw = (message) => {
786
+ if (!controller) return;
787
+ controller.enqueue(encoder.encode(message));
788
+ };
789
+ const cleanup = () => {
790
+ if (pingTimer) {
791
+ clearInterval(pingTimer);
792
+ pingTimer = null;
793
+ }
794
+ if (client) {
795
+ manager.sseClients.delete(client.id);
796
+ client = null;
797
+ }
798
+ if (controller) {
799
+ try {
800
+ controller.close();
801
+ } catch {}
802
+ controller = null;
803
+ }
804
+ };
805
+ const stream = new ReadableStream({
806
+ start(streamController) {
807
+ controller = streamController;
808
+ client = {
809
+ id: clientId,
810
+ userId: clientUserId,
811
+ channels: /* @__PURE__ */ new Set(),
812
+ send: (event, data) => {
813
+ const message = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
814
+ sendRaw(message);
815
+ },
816
+ close: cleanup
817
+ };
818
+ manager.sseClients.set(clientId, client);
819
+ sendRaw(`retry: ${retry}\n\n`);
820
+ client.send("connected", {
821
+ clientId,
822
+ channels: authorizedChannels
823
+ });
824
+ for (const channelName of authorizedChannels) manager.subscribeClient(clientId, channelName);
825
+ pingTimer = setInterval(() => {
826
+ try {
827
+ client?.send("ping", { time: Date.now() });
828
+ } catch {
829
+ cleanup();
830
+ }
831
+ }, pingInterval);
832
+ },
833
+ cancel() {
834
+ cleanup();
835
+ }
836
+ });
837
+ ctx.req.raw.signal.addEventListener("abort", cleanup, { once: true });
838
+ return new Response(stream, { headers: {
839
+ "Content-Type": "text/event-stream",
840
+ "Cache-Control": "no-cache",
841
+ Connection: "keep-alive"
842
+ } });
843
+ };
844
+ }
845
+ /**
846
+ * Create auth middleware for channel authorization.
847
+ */
848
+ authMiddleware(options = {}) {
849
+ return async (ctx) => {
850
+ const user = await (options.getUser ?? ((c) => c.auth?.user))(ctx);
851
+ const payload = await parseRequestPayload(ctx);
852
+ const channel = typeof payload.channel === "string" ? payload.channel : void 0;
853
+ const channels = Array.isArray(payload.channels) ? payload.channels.filter((value) => typeof value === "string") : typeof payload.channels === "string" ? [payload.channels] : channel ? [channel] : [];
854
+ if (channels.length === 0) return ctx.json({ error: "No channel specified" }, 400);
855
+ const clientId = typeof payload.clientId === "string" ? payload.clientId : void 0;
856
+ const results = {};
857
+ const requesterId = resolveClientUserId(user);
858
+ const target = clientId ? this.sseClients.get(clientId) : void 0;
859
+ const attachTo = target && (target.userId === void 0 || target.userId === requesterId) ? target : void 0;
860
+ for (const ch of channels) {
861
+ const authResult = await this.authorize(ch, user);
862
+ if (authResult === false || authResult === null) {
863
+ results[ch] = { authorized: false };
864
+ continue;
865
+ }
866
+ const subscribed = attachTo ? this.subscribeClient(attachTo.id, ch) : false;
867
+ if (authResult === true) results[ch] = {
868
+ authorized: true,
869
+ subscribed
870
+ };
871
+ else results[ch] = {
872
+ authorized: true,
873
+ subscribed,
874
+ member: authResult
875
+ };
876
+ }
877
+ return ctx.json(results);
878
+ };
879
+ }
880
+ /**
881
+ * Subscribe a client to a channel.
882
+ */
883
+ subscribeClient(clientId, channel) {
884
+ const client = this.sseClients.get(clientId);
885
+ if (!client) return false;
886
+ client.channels.add(channel);
887
+ this.driver().subscribe(channel, (event) => {
888
+ if (client.channels.has(channel)) client.send(event.event, event.data);
889
+ });
890
+ return true;
891
+ }
892
+ /**
893
+ * Register a WebSocket client and return its generated client ID.
894
+ */
895
+ registerWebSocketClient(client) {
896
+ const clientId = this.generateClientId("ws");
897
+ this.wsClients.set(clientId, {
898
+ ...client,
899
+ id: clientId,
900
+ channels: /* @__PURE__ */ new Set()
901
+ });
902
+ return clientId;
903
+ }
904
+ /**
905
+ * Remove a WebSocket client and close the underlying connection.
906
+ */
907
+ removeWebSocketClient(clientId) {
908
+ const client = this.wsClients.get(clientId);
909
+ if (!client) return false;
910
+ this.wsClients.delete(clientId);
911
+ client.close();
912
+ return true;
913
+ }
914
+ /**
915
+ * Subscribe a WebSocket client to a channel.
916
+ */
917
+ subscribeWebSocketClient(clientId, channel) {
918
+ const client = this.wsClients.get(clientId);
919
+ if (!client) return false;
920
+ client.channels.add(channel);
921
+ this.driver().subscribe(channel, async (event) => {
922
+ if (client.channels.has(channel)) await client.send(event.event, event.data);
923
+ });
924
+ return true;
925
+ }
926
+ /**
927
+ * Unsubscribe a WebSocket client from a channel.
928
+ */
929
+ unsubscribeWebSocketClient(clientId, channel) {
930
+ const client = this.wsClients.get(clientId);
931
+ if (!client) return false;
932
+ client.channels.delete(channel);
933
+ return true;
934
+ }
935
+ /**
936
+ * Get a WebSocket client by ID.
937
+ */
938
+ getWebSocketClient(clientId) {
939
+ return this.wsClients.get(clientId);
940
+ }
941
+ /**
942
+ * Get all WebSocket clients.
943
+ */
944
+ getWebSocketClients() {
945
+ return Array.from(this.wsClients.values());
946
+ }
947
+ /**
948
+ * Unsubscribe a client from a channel.
949
+ */
950
+ unsubscribeClient(clientId, channel) {
951
+ const client = this.sseClients.get(clientId);
952
+ if (!client) return false;
953
+ client.channels.delete(channel);
954
+ return true;
955
+ }
956
+ /**
957
+ * Get SSE client by ID.
958
+ */
959
+ getClient(clientId) {
960
+ return this.sseClients.get(clientId);
961
+ }
962
+ /**
963
+ * Get all SSE clients.
964
+ */
965
+ getClients() {
966
+ return Array.from(this.sseClients.values());
967
+ }
968
+ /**
969
+ * Get clients subscribed to a channel.
970
+ */
971
+ getChannelClients(channel) {
972
+ return this.getClients().filter((client) => client.channels.has(channel));
973
+ }
974
+ /**
975
+ * Close every SSE connection this manager is holding.
976
+ *
977
+ * Each connection owns a ping timer that is only cleared when the stream is
978
+ * cancelled or the request aborts. `Bun.serve().stop()` without forcing waits
979
+ * for in-flight requests instead of cutting them, and an SSE response never
980
+ * finishes — so on a hot reload those connections outlive the manager, and
981
+ * their timers go on pinging a stream nobody reads.
982
+ *
983
+ * `getClients()` returns a snapshot. A `Map` iterator does tolerate an entry
984
+ * deleting itself, which is all `cleanup()` does today — but not a `close()`
985
+ * that reaches another client, which would drop that one from the iteration
986
+ * unvisited and leave its timer running.
987
+ */
988
+ disconnectAll() {
989
+ for (const client of this.getClients()) try {
990
+ client.close();
991
+ } catch {}
992
+ }
993
+ /**
994
+ * Generate a unique client ID.
995
+ */
996
+ generateClientId(prefix = "sse") {
997
+ return `${prefix}_${randomHex(16)}`;
998
+ }
999
+ };
1000
+ let globalBroadcastManager = null;
1001
+ /**
1002
+ * Set the global broadcast manager.
1003
+ */
1004
+ function setBroadcastManager(manager) {
1005
+ globalBroadcastManager = manager;
1006
+ }
1007
+ /**
1008
+ * Get the global broadcast manager.
1009
+ */
1010
+ function getBroadcastManager() {
1011
+ if (!globalBroadcastManager) throw new Error("BroadcastManager not initialized. Call setBroadcastManager() first.");
1012
+ return globalBroadcastManager;
1013
+ }
1014
+ /**
1015
+ * Create a broadcast manager.
1016
+ *
1017
+ * Under `bun --hot`, the manager this one replaces has its SSE connections
1018
+ * closed first, so their ping timers stop with it. Registered from the factory
1019
+ * rather than the constructor because the factory is what application code
1020
+ * calls: frame 2 of the stack is the provider that built the manager, not this
1021
+ * file. A bare `new BroadcastManager()` is left alone.
1022
+ */
1023
+ function createBroadcastManager(options) {
1024
+ const manager = new BroadcastManager(options);
1025
+ claimHotDisposable("broadcast-manager", isHotReloadRuntime() ? (/* @__PURE__ */ new Error()).stack : void 0, options?.default ?? "memory", () => manager.disconnectAll());
1026
+ return manager;
1027
+ }
1028
+ //#endregion
1029
+ //#region src/broadcasting/typed.ts
1030
+ function createTypedBroadcaster(manager) {
1031
+ return {
1032
+ broadcast(channel, event, payload) {
1033
+ return manager.broadcast(channel, event, payload);
1034
+ },
1035
+ toChannel(channel) {
1036
+ return wrapChannel(channel, manager.toChannel(channel));
1037
+ },
1038
+ toPrivate(channel) {
1039
+ return wrapChannel(channel, manager.toPrivate(channel));
1040
+ },
1041
+ toPresence(channel) {
1042
+ return wrapChannel(channel, manager.toPresence(channel));
1043
+ }
1044
+ };
1045
+ }
1046
+ function wrapChannel(name, channel) {
1047
+ return {
1048
+ name,
1049
+ broadcast(event, payload) {
1050
+ return channel.broadcast(event, payload);
1051
+ }
1052
+ };
1053
+ }
1054
+ //#endregion
1055
+ export { setBroadcastManager as a, PresenceChannel as c, flattenRequestQueries as d, formatValidationErrors as f, getBroadcastManager as i, PrivateChannel as l, BroadcastManager as n, RedisDriver as o, parseRequestPayload as p, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t, Channel as u };