@guren/server 2.26.0 → 2.28.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 (69) hide show
  1. package/dist/{DocsViewerServiceProvider-CIRNHQ2I.js → DocsViewerServiceProvider-BMbcTYVw.js} +1 -1
  2. package/dist/{Gate-BL_zW82W.js → Gate-CYfoGQqh.js} +13 -2
  3. package/dist/{McpServiceProvider-B-LioPSz.js → McpServiceProvider-PGFPlYTy.js} +1 -1
  4. package/dist/{Resource-gki0_2B6.js → Resource-BhOua2OB.js} +26 -20
  5. package/dist/{ServiceProvider-DDW3MqQJ.js → ServiceProvider-G0YclITd.js} +60 -8
  6. package/dist/agent/dispatch.d.ts +4 -4
  7. package/dist/agent/public.js +1 -1
  8. package/dist/agent-request-Caj6bnbj.js +18 -0
  9. package/dist/auth/AuthManager.d.ts +4 -0
  10. package/dist/auth/email-verification.d.ts +2 -1
  11. package/dist/auth/index.js +1 -1
  12. package/dist/auth/password/describe-hasher.d.ts +11 -0
  13. package/dist/{auth-DiyWALZT.js → auth-DIugW0O-.js} +70 -4
  14. package/dist/authorization/Gate.d.ts +3 -2
  15. package/dist/authorization/index.js +2 -2
  16. package/dist/authorization/middleware.d.ts +8 -0
  17. package/dist/{authorization-E6X6Y-B6.js → authorization-CKOLYWvi.js} +17 -2
  18. package/dist/broadcasting/BroadcastManager.d.ts +23 -6
  19. package/dist/broadcasting/index.d.ts +1 -1
  20. package/dist/broadcasting/index.js +1 -1
  21. package/dist/broadcasting/types.d.ts +13 -1
  22. package/dist/{broadcasting-D0vMkKcq.js → broadcasting-N4cRV42s.js} +204 -33
  23. package/dist/cache/CacheManager.d.ts +5 -0
  24. package/dist/cache/TaggedCache.d.ts +2 -0
  25. package/dist/cache/index.js +1 -1
  26. package/dist/cache/pending-computations.d.ts +22 -0
  27. package/dist/cache/stores/FileStore.d.ts +1 -1
  28. package/dist/cache/stores/file-lock.d.ts +1 -0
  29. package/dist/{cache-DcnRufMe.js → cache-BlXopnH1.js} +179 -39
  30. package/dist/container/ServiceProvider.d.ts +27 -2
  31. package/dist/container/defineModule.d.ts +4 -5
  32. package/dist/container/definePlugin.d.ts +2 -0
  33. package/dist/dev-banner-bekDeLgL.js +51 -0
  34. package/dist/{dispatch-BAwzftws.js → dispatch-ENWpBxbE.js} +26 -4
  35. package/dist/driver-map-CkQc52j-.js +12 -0
  36. package/dist/host-port-t6wQFaRu.js +15 -0
  37. package/dist/hot-reload/testing.d.ts +2 -1
  38. package/dist/http/Application.d.ts +19 -1
  39. package/dist/http/dev-banner.d.ts +0 -8
  40. package/dist/http/host-port.d.ts +8 -0
  41. package/dist/http/middleware/force-https.d.ts +2 -1
  42. package/dist/http/middleware/index.d.ts +1 -0
  43. package/dist/http/middleware/session-manager.d.ts +5 -0
  44. package/dist/http/middleware/websocket-origin.d.ts +22 -0
  45. package/dist/http/public-assets.d.ts +6 -1
  46. package/dist/index.d.ts +5 -3
  47. package/dist/index.js +695 -235
  48. package/dist/internal/agent-request.d.ts +18 -0
  49. package/dist/internal/dispatched-request.d.ts +4 -0
  50. package/dist/internal/testing.js +2 -2
  51. package/dist/internal/zod-json-schema.js +1 -1
  52. package/dist/introspection/driver-map.d.ts +3 -0
  53. package/dist/introspection/flag.d.ts +12 -0
  54. package/dist/introspection/manifest.d.ts +17 -0
  55. package/dist/introspection/plain-json.d.ts +7 -0
  56. package/dist/introspection/types.d.ts +167 -0
  57. package/dist/mcp/index.js +1 -1
  58. package/dist/mvc/Controller.d.ts +3 -2
  59. package/dist/mvc/Router.d.ts +33 -0
  60. package/dist/providers/ConfigServiceProvider.d.ts +7 -0
  61. package/dist/queue/QueueManager.d.ts +3 -0
  62. package/dist/queue/index.js +1 -1
  63. package/dist/{queue-Bo4Q857L.js → queue-C8s3buYz.js} +5 -0
  64. package/dist/runtime/index.js +15 -2
  65. package/dist/storage/StorageManager.d.ts +5 -0
  66. package/dist/storage/index.js +1 -1
  67. package/dist/{storage-wFsUJHZW.js → storage-IlUesK2t.js} +13 -1
  68. package/dist/{vite-manifest-DlU94f3Z.js → vite-manifest-wPxfAzjW.js} +1 -57
  69. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import type { WebSocketOriginOptions } from '../http/middleware/websocket-origin.js';
1
2
  export interface BroadcastEvent {
2
3
  channel: string;
3
4
  event: string;
@@ -59,11 +60,22 @@ export interface SSEMiddlewareOptions {
59
60
  retry?: number;
60
61
  /**
61
62
  * Resolves the user from the request context, which authorizes channels
62
- * requested via the `?channels=` query parameter.
63
+ * requested via the `?channels=` query parameter. Defaults to the session
64
+ * user, from the auth context under `AUTH_CONTEXT_KEY`.
65
+ */
66
+ getUser?: (ctx: unknown) => unknown | Promise<unknown>;
67
+ }
68
+ /** `allowedOrigins` is the `createWebSocketOriginGuard()` option; any other browser `Origin` gets 403. */
69
+ export interface WebSocketMiddlewareOptions extends WebSocketOriginOptions {
70
+ /**
71
+ * Resolves the user from the upgrade request. That one user authorizes the
72
+ * `?channels=` query and every `subscribe` message for the socket's lifetime.
73
+ * Defaults to the session user from the auth context.
63
74
  */
64
75
  getUser?: (ctx: unknown) => unknown | Promise<unknown>;
65
76
  }
66
77
  export interface AuthMiddlewareOptions {
78
+ /** Resolves the requesting user. Defaults to the session user from the auth context. */
67
79
  getUser?: (ctx: unknown) => unknown | Promise<unknown>;
68
80
  }
69
81
  /** Implemented by Event classes that broadcast. */
@@ -1,7 +1,47 @@
1
- import { a as parseRequestPayload } from "./request-CLOYytGP.js";
1
+ import { a as parseRequestPayload, t as asRecord } from "./request-CLOYytGP.js";
2
2
  import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-DWwscxfW.js";
3
+ import { r as getAuthContext } from "./context-af2n5abO.js";
3
4
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
4
5
  import { c as randomHex } from "./Random-S0OvCuR8.js";
6
+ //#region src/http/middleware/websocket-origin.ts
7
+ function toOrigin(value) {
8
+ let url;
9
+ try {
10
+ url = new URL(value);
11
+ } catch {
12
+ url = void 0;
13
+ }
14
+ if (url?.protocol !== "http:" && url?.protocol !== "https:") throw new Error(`allowedOrigins entry "${value}" is not an http(s) origin such as https://app.example.com`);
15
+ return url.origin;
16
+ }
17
+ /**
18
+ * Hosts are compared, not schemes: TLS usually ends at a proxy, so the app sees
19
+ * `http:`. No `Origin` is not a browser and carries no ambient cookies; `null`
20
+ * (sandboxed frames, file://) fails to parse and is refused.
21
+ */
22
+ function webSocketOriginCheck(allowedOrigins = []) {
23
+ const allowed = new Set(allowedOrigins.map(toOrigin));
24
+ return (ctx) => {
25
+ const origin = ctx.req.header("origin");
26
+ if (origin === void 0) return true;
27
+ let parsed;
28
+ try {
29
+ parsed = new URL(origin);
30
+ } catch {
31
+ return false;
32
+ }
33
+ return allowed.has(parsed.origin) || parsed.host === new URL(ctx.req.url).host;
34
+ };
35
+ }
36
+ /** Refuses, with 403, a request whose `Origin` is neither the app's own host nor listed. */
37
+ function createWebSocketOriginGuard(options = {}) {
38
+ const isAllowed = webSocketOriginCheck(options.allowedOrigins);
39
+ return async (ctx, next) => {
40
+ if (!isAllowed(ctx)) return ctx.json({ message: "Forbidden: cross-origin WebSocket upgrade" }, 403);
41
+ await next();
42
+ };
43
+ }
44
+ //#endregion
5
45
  //#region src/broadcasting/channels/Channel.ts
6
46
  var Channel = class {
7
47
  name;
@@ -323,6 +363,48 @@ function resolveClientUserId(user) {
323
363
  candidate.userId
324
364
  ]) if (typeof value === "string" || typeof value === "number") return value;
325
365
  }
366
+ /**
367
+ * The user a connection or auth request is authorized as: the app's `getUser`,
368
+ * else the session user from the auth context. A guest is `undefined` either
369
+ * way, which is what an unowned stream and a refused private channel key on.
370
+ */
371
+ async function resolveRequestUser(ctx, getUser) {
372
+ if (getUser) return getUser(ctx);
373
+ return await getAuthContext(ctx)?.user() ?? void 0;
374
+ }
375
+ /** The channels a connection asks for up front, as `?channels=a,b`, each once. */
376
+ function requestedChannels(ctx) {
377
+ const channels = (ctx.req.query("channels") ?? "").split(",").map((value) => value.trim());
378
+ return [...new Set(channels.filter(Boolean))];
379
+ }
380
+ /**
381
+ * Whether the request came through a server that can upgrade it: `{ server }`
382
+ * from `Application.listen()`, or the server itself when an app passes
383
+ * `app.fetch` to `Bun.serve`. Mirrors `getBunServer()`, which cannot be asked:
384
+ * `hono/bun` reads the `Bun` global at load, and this check is what answers 501 off Bun.
385
+ */
386
+ function canUpgrade(ctx) {
387
+ const env = ctx.env;
388
+ if (typeof env !== "object" || env === null) return false;
389
+ return typeof ("server" in env ? env.server : env)?.upgrade === "function";
390
+ }
391
+ const MAX_WEBSOCKET_MESSAGE_LENGTH = 4096;
392
+ const MAX_PENDING_WEBSOCKET_MESSAGES = 32;
393
+ function parseWebSocketClientMessage(data) {
394
+ if (typeof data !== "string" || data.length > MAX_WEBSOCKET_MESSAGE_LENGTH) return void 0;
395
+ let parsed;
396
+ try {
397
+ parsed = JSON.parse(data);
398
+ } catch {
399
+ return;
400
+ }
401
+ const { action, channel } = asRecord(parsed);
402
+ if (action !== "subscribe" && action !== "unsubscribe" || typeof channel !== "string" || channel === "") return;
403
+ return {
404
+ action,
405
+ channel
406
+ };
407
+ }
326
408
  /** Broadcast manager for real-time event broadcasting. */
327
409
  var BroadcastManager = class {
328
410
  defaultDriver = "memory";
@@ -403,6 +485,14 @@ var BroadcastManager = class {
403
485
  }
404
486
  return await registration.authorizer(channelName, user) === true;
405
487
  }
488
+ async filterAuthorizedChannels(channels, user) {
489
+ const authorized = [];
490
+ for (const channelName of channels) {
491
+ const authResult = await this.authorize(channelName, user);
492
+ if (authResult !== false && authResult !== null) authorized.push(channelName);
493
+ }
494
+ return authorized;
495
+ }
406
496
  findChannelRegistration(channelName) {
407
497
  return this.channelRegistrations.find((reg) => this.matchPattern(reg.pattern, channelName));
408
498
  }
@@ -416,13 +506,8 @@ var BroadcastManager = class {
416
506
  return async (ctx) => {
417
507
  const clientId = this.generateClientId();
418
508
  const encoder = new TextEncoder();
419
- const requestedChannels = (ctx.req.query("channels") ?? "").split(",").map((value) => value.trim()).filter(Boolean);
420
- const user = options.getUser ? await options.getUser(ctx) : void 0;
421
- const authorizedChannels = [];
422
- for (const channelName of requestedChannels) {
423
- const authResult = await this.authorize(channelName, user);
424
- if (authResult !== false && authResult !== null) authorizedChannels.push(channelName);
425
- }
509
+ const user = await resolveRequestUser(ctx, options.getUser);
510
+ const authorizedChannels = await this.filterAuthorizedChannels(requestedChannels(ctx), user);
426
511
  const clientUserId = resolveClientUserId(user);
427
512
  let controller = null;
428
513
  let client = null;
@@ -488,9 +573,103 @@ var BroadcastManager = class {
488
573
  } });
489
574
  };
490
575
  }
576
+ /**
577
+ * A route that upgrades to a WebSocket carrying broadcast events, the socket
578
+ * counterpart of `sseMiddleware()`; it needs `Application.listen()` on Bun.
579
+ * Frames are JSON. The server sends `{ event, data }`, first `connected` with
580
+ * `{ clientId, channels }`; the client sends `{ action: 'subscribe' | 'unsubscribe',
581
+ * channel }`, answered by a `subscription` event, and anything else is ignored.
582
+ */
583
+ webSocketMiddleware(options = {}) {
584
+ const isAllowedOrigin = webSocketOriginCheck(options.allowedOrigins);
585
+ return async (ctx) => {
586
+ if (!isAllowedOrigin(ctx)) return ctx.json({ message: "Forbidden: cross-origin WebSocket upgrade" }, 403);
587
+ if (ctx.req.header("upgrade")?.toLowerCase() !== "websocket") return ctx.json({ message: "Expected a WebSocket upgrade request" }, 426, { Upgrade: "websocket" });
588
+ if (!canUpgrade(ctx)) return ctx.json({ message: "This runtime cannot upgrade to a WebSocket. Serve the app with Application.listen() on Bun." }, 501);
589
+ if (!ctx.req.header("sec-websocket-key")) return ctx.json({ message: "Invalid WebSocket handshake" }, 400);
590
+ const user = await resolveRequestUser(ctx, options.getUser);
591
+ const authorizedChannels = await this.filterAuthorizedChannels(requestedChannels(ctx), user);
592
+ const userId = resolveClientUserId(user);
593
+ let clientId;
594
+ let handled = Promise.resolve();
595
+ let pending = 0;
596
+ const { upgradeWebSocket } = await import("hono/bun");
597
+ return await upgradeWebSocket(() => ({
598
+ onOpen: (_event, ws) => {
599
+ const send = (event, data) => ws.send(JSON.stringify({
600
+ event,
601
+ data
602
+ }));
603
+ clientId = this.registerWebSocketClient({
604
+ userId,
605
+ send,
606
+ close: () => ws.close()
607
+ });
608
+ send("connected", {
609
+ clientId,
610
+ channels: authorizedChannels
611
+ });
612
+ for (const channelName of authorizedChannels) this.subscribeWebSocketClient(clientId, channelName);
613
+ },
614
+ onMessage: (event, ws) => {
615
+ const message = parseWebSocketClientMessage(event.data);
616
+ const id = clientId;
617
+ if (!id || !message) return;
618
+ if (pending >= MAX_PENDING_WEBSOCKET_MESSAGES) {
619
+ ws.close(1008, "Too many pending messages");
620
+ return;
621
+ }
622
+ pending += 1;
623
+ handled = handled.then(() => this.handleWebSocketMessage(id, message, user)).catch((error) => {
624
+ console.error("Error handling broadcast WebSocket message:", error);
625
+ }).finally(() => {
626
+ pending -= 1;
627
+ });
628
+ },
629
+ onClose: () => {
630
+ if (clientId) this.removeWebSocketClient(clientId);
631
+ }
632
+ }))(ctx, async () => {}) ?? ctx.json({ message: "Invalid WebSocket handshake" }, 400);
633
+ };
634
+ }
635
+ async handleWebSocketMessage(clientId, message, user) {
636
+ const client = this.wsClients.get(clientId);
637
+ if (!client) return;
638
+ const { channel } = message;
639
+ if (message.action === "unsubscribe") {
640
+ this.unsubscribeWebSocketClient(clientId, channel);
641
+ await client.send("subscription", {
642
+ channel,
643
+ subscribed: false
644
+ });
645
+ return;
646
+ }
647
+ const result = await this.authorizeAndAttach(channel, user, clientId).catch((error) => {
648
+ console.error(`Error authorizing broadcast channel "${channel}":`, error);
649
+ return { authorized: false };
650
+ });
651
+ await client.send("subscription", {
652
+ channel,
653
+ ...result
654
+ });
655
+ }
656
+ /** The one answer `POST /broadcasting/auth` and a socket's `subscribe` both give. */
657
+ async authorizeAndAttach(channel, user, clientId) {
658
+ const authResult = await this.authorize(channel, user);
659
+ if (authResult === false || authResult === null) return { authorized: false };
660
+ const subscribed = clientId !== void 0 && (this.subscribeClient(clientId, channel) || this.subscribeWebSocketClient(clientId, channel));
661
+ return authResult === true ? {
662
+ authorized: true,
663
+ subscribed
664
+ } : {
665
+ authorized: true,
666
+ subscribed,
667
+ member: authResult
668
+ };
669
+ }
491
670
  authMiddleware(options = {}) {
492
671
  return async (ctx) => {
493
- const user = await (options.getUser ?? ((c) => c.auth?.user))(ctx);
672
+ const user = await resolveRequestUser(ctx, options.getUser);
494
673
  const payload = await parseRequestPayload(ctx);
495
674
  const channel = typeof payload.channel === "string" ? payload.channel : void 0;
496
675
  const channels = Array.isArray(payload.channels) ? payload.channels.filter((value) => typeof value === "string") : typeof payload.channels === "string" ? [payload.channels] : channel ? [channel] : [];
@@ -498,25 +677,9 @@ var BroadcastManager = class {
498
677
  const clientId = typeof payload.clientId === "string" ? payload.clientId : void 0;
499
678
  const results = {};
500
679
  const requesterId = resolveClientUserId(user);
501
- const target = clientId ? this.sseClients.get(clientId) : void 0;
680
+ const target = clientId ? this.sseClients.get(clientId) ?? this.wsClients.get(clientId) : void 0;
502
681
  const attachTo = target && (target.userId === void 0 || target.userId === requesterId) ? target : void 0;
503
- for (const ch of channels) {
504
- const authResult = await this.authorize(ch, user);
505
- if (authResult === false || authResult === null) {
506
- results[ch] = { authorized: false };
507
- continue;
508
- }
509
- const subscribed = attachTo ? this.subscribeClient(attachTo.id, ch) : false;
510
- if (authResult === true) results[ch] = {
511
- authorized: true,
512
- subscribed
513
- };
514
- else results[ch] = {
515
- authorized: true,
516
- subscribed,
517
- member: authResult
518
- };
519
- }
682
+ for (const ch of channels) results[ch] = await this.authorizeAndAttach(ch, user, attachTo?.id);
520
683
  return ctx.json(results);
521
684
  };
522
685
  }
@@ -583,6 +746,11 @@ var BroadcastManager = class {
583
746
  client.close();
584
747
  return true;
585
748
  }
749
+ /**
750
+ * Subscribes without authorizing, like `subscribeClient()`: for a channel the
751
+ * server chose. Put a channel the client named through `authorize()` first,
752
+ * as `webSocketMiddleware()` and `authMiddleware()` do.
753
+ */
586
754
  subscribeWebSocketClient(clientId, channel) {
587
755
  const client = this.wsClients.get(clientId);
588
756
  if (!client) return false;
@@ -622,16 +790,19 @@ var BroadcastManager = class {
622
790
  return this.getClients().filter((client) => client.channels.has(channel));
623
791
  }
624
792
  /**
625
- * Close every SSE connection this manager holds. Each owns a ping timer that
626
- * is only cleared on stream cancel or request abort, and `Bun.serve().stop()`
627
- * waits for in-flight requests while an SSE response never finishes — so on a
628
- * hot reload the timers would go on pinging. `getClients()` is a snapshot: a
629
- * `close()` reaching another client would drop it from a live iteration.
793
+ * Close every SSE and WebSocket connection this manager holds. Each SSE stream
794
+ * owns a ping timer that is only cleared on stream cancel or request abort, and
795
+ * `Bun.serve().stop()` waits for in-flight requests while an SSE response never
796
+ * finishes — so on a hot reload the timers would go on pinging. Both lists are
797
+ * snapshots: a `close()` reaching another client would drop it mid-iteration.
630
798
  */
631
799
  disconnectAll() {
632
800
  for (const client of this.getClients()) try {
633
801
  client.close();
634
802
  } catch {}
803
+ for (const client of this.getWebSocketClients()) try {
804
+ this.removeWebSocketClient(client.id);
805
+ } catch {}
635
806
  }
636
807
  generateClientId(prefix = "sse") {
637
808
  return `${prefix}_${randomHex(16)}`;
@@ -696,4 +867,4 @@ function wrapChannel(name, channel) {
696
867
  };
697
868
  }
698
869
  //#endregion
699
- export { setBroadcastManager as a, PresenceChannel as c, getBroadcastManager as i, PrivateChannel as l, BroadcastManager as n, RedisDriver as o, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t, Channel as u };
870
+ 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 };
@@ -1,9 +1,12 @@
1
1
  import type { CacheStore, TaggableCacheStore, CacheStoreFactory, CacheConfig } from './types.js';
2
+ import type { DriverMapEntry } from '../introspection/types.js';
2
3
  /** Cache manager for handling multiple cache stores. */
3
4
  export declare class CacheManager {
4
5
  private readonly defaultStoreName;
5
6
  private readonly storeFactories;
6
7
  private readonly resolvedStores;
8
+ /** The configured driver per store, keyed like `storeFactories`; null for a bare `registerStore()` factory. */
9
+ private readonly storeDrivers;
7
10
  /**
8
11
  * Where this manager was built, for identifying its stores across hot reloads.
9
12
  * Captured here rather than in `store()` because stores resolve lazily, from
@@ -29,5 +32,7 @@ export declare class CacheManager {
29
32
  hasStore(name: string): boolean;
30
33
  getDefaultStoreName(): string;
31
34
  getStoreNames(): string[];
35
+ /** The declared stores and the default, building none of them (RFC 0026 §1). */
36
+ describe(): DriverMapEntry;
32
37
  }
33
38
  export declare function createCacheManager(config?: CacheConfig): CacheManager;
@@ -4,6 +4,7 @@ export declare class TaggedCache implements TaggedCacheStore {
4
4
  private readonly store;
5
5
  private readonly tags;
6
6
  private readonly tagSetPrefix;
7
+ private readonly pending;
7
8
  constructor(store: CacheStore, tags: string[], tagSetPrefix?: string);
8
9
  private getTagNamespace;
9
10
  private generateNamespace;
@@ -18,6 +19,7 @@ export declare class TaggedCache implements TaggedCacheStore {
18
19
  decrement(key: string, value?: number): Promise<number>;
19
20
  remember<T>(key: string, ttl: number, callback: () => Promise<T>): Promise<T>;
20
21
  rememberForever<T>(key: string, callback: () => Promise<T>): Promise<T>;
22
+ private rememberAt;
21
23
  getMany<T>(keys: string[]): Promise<Map<string, T | null>>;
22
24
  setMany<T>(items: Map<string, T>, ttl?: number): Promise<void>;
23
25
  deleteMany(keys: string[]): Promise<number>;
@@ -1,2 +1,2 @@
1
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-DcnRufMe.js";
1
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-BlXopnH1.js";
2
2
  export { CacheManager, FileStore, MemoryStore, RedisStore, TaggedCache, createCacheManager };
@@ -0,0 +1,22 @@
1
+ import type { CacheStore } from './types.js';
2
+ /**
3
+ * Callers do not join a computation this old: a callback that never settles
4
+ * would otherwise hold every later caller for the key until restart. The
5
+ * callers already waiting stay attached. Mirrored in the cache guide.
6
+ */
7
+ export declare const PENDING_JOIN_WINDOW_MS = 10000;
8
+ /**
9
+ * One running computation per key and TTL, shared by the callers that ask
10
+ * while it runs. The TTL is part of the match because it is what the
11
+ * computation stores: a caller asking for 60 seconds must not get a forever entry.
12
+ */
13
+ export declare class PendingComputations {
14
+ private readonly now;
15
+ private readonly pending;
16
+ constructor(now?: () => number);
17
+ run<T>(key: string, ttl: number | undefined, compute: () => Promise<T>): Promise<T>;
18
+ private start;
19
+ forget(key: string): void;
20
+ forgetAll(): void;
21
+ }
22
+ export declare function pendingComputationsFor(store: CacheStore): PendingComputations;
@@ -9,7 +9,7 @@ export declare class FileStore implements CacheStore {
9
9
  private ensureDirectory;
10
10
  private readCacheFile;
11
11
  private writeCacheFile;
12
- private withFileLock;
12
+ private locked;
13
13
  private deleteCacheFile;
14
14
  private isExpired;
15
15
  get<T>(key: string): Promise<T | null>;
@@ -0,0 +1 @@
1
+ export declare function withFileLock<T>(lockPath: string, timeoutMs: number, callback: () => Promise<T>): Promise<T>;