@guren/server 2.22.0 → 2.23.1

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 (108) hide show
  1. package/dist/Job-BVvaY-7p.js +165 -0
  2. package/dist/auth/AuthManager.d.ts +29 -0
  3. package/dist/auth/AuthenticatableModel.d.ts +15 -0
  4. package/dist/auth/RequestAuthContext.d.ts +10 -1
  5. package/dist/auth/SessionGuard.d.ts +2 -0
  6. package/dist/auth/api-token.d.ts +6 -0
  7. package/dist/auth/context.d.ts +32 -0
  8. package/dist/auth/index.d.ts +7 -0
  9. package/dist/auth/index.js +2 -2
  10. package/dist/auth/model-capability.d.ts +8 -0
  11. package/dist/auth/oauth/index.d.ts +5 -0
  12. package/dist/auth/password/DefaultHasher.d.ts +17 -6
  13. package/dist/auth/password/configured-hasher.d.ts +23 -0
  14. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  15. package/dist/auth/providers/unconfigured-user-provider.d.ts +12 -0
  16. package/dist/auth/types.d.ts +9 -0
  17. package/dist/{auth-CjE2oO50.js → auth-D_W1cJp3.js} +279 -84
  18. package/dist/authorization/Gate.d.ts +12 -0
  19. package/dist/authorization/index.js +1 -1
  20. package/dist/{authorization-CdEWZZw3.js → authorization-0mCGUFoI.js} +58 -12
  21. package/dist/broadcasting/BroadcastManager.d.ts +10 -0
  22. package/dist/broadcasting/index.js +1 -1
  23. package/dist/{broadcasting-B5RzB0A2.js → broadcasting-BdJnaq1O.js} +17 -3
  24. package/dist/console/Command.d.ts +3 -3
  25. package/dist/console/ConsoleKernel.d.ts +2 -2
  26. package/dist/console/index.d.ts +1 -1
  27. package/dist/console/types.d.ts +9 -1
  28. package/dist/container/Container.d.ts +18 -1
  29. package/dist/container/bindings.d.ts +5 -0
  30. package/dist/container/index.d.ts +4 -2
  31. package/dist/container/resolve-optional.d.ts +10 -0
  32. package/dist/context-af2n5abO.js +91 -0
  33. package/dist/{Job-CvDwk2Gj.js → default-application-Chbrul_m.js} +126 -82
  34. package/dist/encryption/Encrypter.d.ts +10 -0
  35. package/dist/encryption/index.js +1 -1
  36. package/dist/{encryption-uwP3Di4D.js → encryption-BRjZnshr.js} +23 -5
  37. package/dist/errors/ExceptionHandler.d.ts +10 -0
  38. package/dist/events/Event.d.ts +18 -0
  39. package/dist/events/EventManager.d.ts +56 -4
  40. package/dist/events/index.d.ts +2 -1
  41. package/dist/events/index.js +2 -2
  42. package/dist/events/queued.d.ts +8 -0
  43. package/dist/events/serialize.d.ts +8 -0
  44. package/dist/events/types.d.ts +19 -2
  45. package/dist/events-CaJKZ2qk.js +428 -0
  46. package/dist/health/checks/CacheCheck.d.ts +3 -5
  47. package/dist/health/checks/StorageCheck.d.ts +3 -5
  48. package/dist/health/index.js +1 -1
  49. package/dist/{health-DQSvUplL.js → health-CB0oS_UE.js} +2 -2
  50. package/dist/http/Application.d.ts +28 -0
  51. package/dist/http/default-application.d.ts +33 -0
  52. package/dist/http/middleware/detect-locale.d.ts +2 -1
  53. package/dist/http/request-container.d.ts +25 -0
  54. package/dist/i18n/I18nManager.d.ts +16 -3
  55. package/dist/i18n/index.d.ts +1 -1
  56. package/dist/i18n/index.js +2 -2
  57. package/dist/{i18n-BZ2VrSud.js → i18n-DRo1g0AN.js} +34 -10
  58. package/dist/index.d.ts +14 -9
  59. package/dist/index.js +196 -87
  60. package/dist/lambda/index.js +1 -1
  61. package/dist/logging/LogManager.d.ts +9 -0
  62. package/dist/logging/index.js +1 -1
  63. package/dist/{logging-Dmzdb6mL.js → logging-CXotojgW.js} +16 -3
  64. package/dist/mail/Mail.d.ts +14 -1
  65. package/dist/mail/MailManager.d.ts +10 -2
  66. package/dist/mail/index.js +1 -1
  67. package/dist/{mail-9CrvJyBZ.js → mail-zMjQimaJ.js} +42 -11
  68. package/dist/mvc/Controller.d.ts +2 -2
  69. package/dist/mvc/Router.d.ts +16 -5
  70. package/dist/mvc/inertia/InertiaEngine.d.ts +18 -3
  71. package/dist/mvc/inertia/shared.d.ts +7 -0
  72. package/dist/notifications/NotificationManager.d.ts +15 -0
  73. package/dist/notifications/index.js +1 -1
  74. package/dist/{notifications-D0VXkFLF.js → notifications-BLid0Y6M.js} +24 -5
  75. package/dist/providers/AuthServiceProvider.d.ts +5 -4
  76. package/dist/providers/AuthorizationServiceProvider.d.ts +2 -2
  77. package/dist/providers/BroadcastServiceProvider.d.ts +4 -1
  78. package/dist/providers/EncryptionServiceProvider.d.ts +7 -1
  79. package/dist/providers/EventServiceProvider.d.ts +1 -0
  80. package/dist/providers/LogServiceProvider.d.ts +6 -1
  81. package/dist/providers/MailServiceProvider.d.ts +7 -1
  82. package/dist/providers/NotificationServiceProvider.d.ts +4 -1
  83. package/dist/queue/Job.d.ts +39 -0
  84. package/dist/queue/QueueManager.d.ts +14 -5
  85. package/dist/queue/Worker.d.ts +2 -1
  86. package/dist/queue/index.d.ts +1 -1
  87. package/dist/queue/index.js +3 -3
  88. package/dist/queue/types.d.ts +7 -0
  89. package/dist/{queue-zPPYZdif.js → queue-IdJjqbyJ.js} +24 -10
  90. package/dist/redis/RedisSchedulerLock.d.ts +17 -0
  91. package/dist/redis/index.d.ts +2 -0
  92. package/dist/redis/index.js +21 -1
  93. package/dist/runtime/index.js +1 -1
  94. package/dist/scheduling/MemorySchedulerLock.d.ts +16 -0
  95. package/dist/scheduling/ScheduledTask.d.ts +19 -2
  96. package/dist/scheduling/Scheduler.d.ts +25 -0
  97. package/dist/scheduling/index.d.ts +2 -1
  98. package/dist/scheduling/index.js +2 -2
  99. package/dist/scheduling/types.d.ts +26 -2
  100. package/dist/{scheduling-C6tcOtUl.js → scheduling-DudNXGnh.js} +178 -20
  101. package/dist/storage/index.js +1 -1
  102. package/dist/{storage-D_yNe54O.js → storage-6HLaUf9j.js} +2 -13
  103. package/dist/support/deprecate.d.ts +16 -0
  104. package/dist/{vite-manifest-D295_7-_.js → vite-manifest-QooqG8FE.js} +1 -1
  105. package/dist/warn-once-p-IlMjra.js +13 -0
  106. package/package.json +2 -2
  107. package/dist/context-CXk_umpT.js +0 -21
  108. package/dist/events-DOmAHDeP.js +0 -230
@@ -1,5 +1,6 @@
1
1
  import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
2
- import { n as getAuthContext } from "./context-CXk_umpT.js";
2
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
3
+ import { r as getAuthContext } from "./context-af2n5abO.js";
3
4
  //#region src/http/middleware/capabilities.ts
4
5
  /**
5
6
  * Internal security-capability marker (RFC 0007): built-in middleware
@@ -45,6 +46,30 @@ function capabilitiesOf(handler) {
45
46
  return handler[CAPABILITIES];
46
47
  }
47
48
  //#endregion
49
+ //#region src/http/request-container.ts
50
+ /**
51
+ * Context variable the serving Application's container is stamped under
52
+ * (RFC 0023 §2). The stamp is the first middleware `Application` mounts, so
53
+ * nothing an app registers runs ahead of it. The one place a middleware
54
+ * reaches its app's container without holding the app.
55
+ */
56
+ const CONTAINER_CONTEXT_KEY = "guren.container";
57
+ /**
58
+ * The container of the Application serving `ctx`, or undefined off an
59
+ * Application (bare Hono). Judged by shape rather than `instanceof`: a test
60
+ * double answering every key must not pass as a container.
61
+ */
62
+ function tryGetRequestContainer(ctx) {
63
+ const container = ctx.get(CONTAINER_CONTEXT_KEY);
64
+ return typeof container?.makeOptional === "function" ? container : void 0;
65
+ }
66
+ /** The container of the Application serving `ctx`; throws off an Application (bare Hono). */
67
+ function getRequestContainer(ctx) {
68
+ const container = tryGetRequestContainer(ctx);
69
+ if (!container) throw new Error("No Application container on this request. The container is stamped by Application; a bare Hono app has none — pass the service explicitly there.");
70
+ return container;
71
+ }
72
+ //#endregion
48
73
  //#region src/errors/exceptions/AuthorizationException.ts
49
74
  /** 403: the user is authenticated but not allowed to perform the action. */
50
75
  var AuthorizationException = class AuthorizationException extends HttpException {
@@ -262,25 +287,42 @@ let globalGate = null;
262
287
  function createGate(options) {
263
288
  return new Gate(options);
264
289
  }
290
+ /**
291
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the gate on the
292
+ * app's container instead — `AuthorizationServiceProvider` already does, and a
293
+ * provider of your own reaches it as `this.container.instance('gate', gate)`.
294
+ */
265
295
  function setGate(gate) {
266
- globalGate = gate;
296
+ warnDeprecatedSetter("setGate");
297
+ globalGate = bindAmbient("gate", gate) ? null : gate;
267
298
  }
299
+ /**
300
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use `this.make('gate')`
301
+ * in a controller, `getRequestContainer(ctx).make('gate')` in middleware, or
302
+ * `defaultContainer().make('gate')`.
303
+ */
268
304
  function getGate() {
269
- if (!globalGate) throw new Error("Gate not initialized. Call setGate() first.");
270
- return globalGate;
305
+ warnDeprecatedGetter("getGate");
306
+ return resolveGate();
307
+ }
308
+ /** @internal The default application's `gate`, else the one `setGate()` installed, without the warning. */
309
+ function resolveGate() {
310
+ const gate = ambientBinding("gate") ?? globalGate;
311
+ if (!gate) throw new Error("Gate not initialized. Construct the app with createApp(), or call setGate() first.");
312
+ return gate;
271
313
  }
272
314
  /** Define a gate on the global instance. */
273
315
  function defineGate(ability, callback) {
274
- getGate().define(ability, callback);
316
+ resolveGate().define(ability, callback);
275
317
  }
276
318
  async function can(ability, ...args) {
277
- return getGate().allows(ability, ...args);
319
+ return resolveGate().allows(ability, ...args);
278
320
  }
279
321
  async function cannot(ability, ...args) {
280
- return getGate().denies(ability, ...args);
322
+ return resolveGate().denies(ability, ...args);
281
323
  }
282
324
  async function authorize(ability, ...args) {
283
- return getGate().authorize(ability, ...args);
325
+ return resolveGate().authorize(ability, ...args);
284
326
  }
285
327
  //#endregion
286
328
  //#region src/authorization/Policy.ts
@@ -333,6 +375,10 @@ function definePolicy(definition) {
333
375
  }
334
376
  //#endregion
335
377
  //#region src/authorization/middleware.ts
378
+ /** The gate of the app serving `ctx` (RFC 0023 §2); the ambient one on a bare Hono app. */
379
+ function gateFor(ctx) {
380
+ return tryGetRequestContainer(ctx)?.makeOptional("gate") ?? resolveGate();
381
+ }
336
382
  /**
337
383
  * Middleware to authorize an ability. An array argument is snapshotted at
338
384
  * creation, and a one-element array behaves exactly like the bare ability.
@@ -343,7 +389,7 @@ function authorizeMiddleware(ability, modelResolver, options = {}) {
343
389
  const abilities = Array.isArray(ability) ? [...ability] : [ability];
344
390
  const anyOf = abilities.length !== 1;
345
391
  return stampCapabilities(async (ctx, next) => {
346
- const gate = getGate();
392
+ const gate = gateFor(ctx);
347
393
  const user = await gate.resolveUser(ctx);
348
394
  const gateForUser = gate.forUser(user);
349
395
  const model = modelResolver ? await modelResolver(ctx) : void 0;
@@ -372,7 +418,7 @@ function authorizeAllMiddleware(input, modelResolver, options = {}) {
372
418
  const abilities = [...input];
373
419
  if (abilities.length === 0) throw new Error("authorizeAllMiddleware() requires at least one ability: an empty list authorizes every request while claiming to authorize.");
374
420
  return stampCapabilities(async (ctx, next) => {
375
- const gate = getGate();
421
+ const gate = gateFor(ctx);
376
422
  const user = await gate.resolveUser(ctx);
377
423
  const gateForUser = gate.forUser(user);
378
424
  const model = modelResolver ? await modelResolver(ctx) : void 0;
@@ -414,7 +460,7 @@ function authorizeResourceMiddleware(modelResolver, options = {}) {
414
460
  const method = ctx.req.method.toUpperCase();
415
461
  const ability = abilityFor?.(method) ?? resourceAbilityForMethod(method);
416
462
  if (ability === void 0) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
417
- const gate = getGate();
463
+ const gate = gateFor(ctx);
418
464
  const user = await gate.resolveUser(ctx);
419
465
  const gateForUser = gate.forUser(user);
420
466
  const model = await modelResolver(ctx);
@@ -449,4 +495,4 @@ function withAuthorization(gate) {
449
495
  };
450
496
  }
451
497
  //#endregion
452
- export { setGate as _, withAuthorization as a, mergeCapabilities as b, Gate as c, can as d, cannot as f, isAuthorizationResponse as g, getGate as h, resourceAbilityForMethod as i, Response as l, defineGate as m, authorizeMiddleware as n, Policy as o, createGate as p, authorizeResourceMiddleware as r, definePolicy as s, authorizeAllMiddleware as t, authorize as u, AuthorizationException as v, stampCapabilities as x, capabilitiesOf as y };
498
+ export { capabilitiesOf as C, tryGetRequestContainer as S, stampCapabilities as T, resolveGate as _, withAuthorization as a, CONTAINER_CONTEXT_KEY as b, Gate as c, can as d, cannot as f, isAuthorizationResponse as g, getGate as h, resourceAbilityForMethod as i, Response as l, defineGate as m, authorizeMiddleware as n, Policy as o, createGate as p, authorizeResourceMiddleware as r, definePolicy as s, authorizeAllMiddleware as t, authorize as u, setGate as v, mergeCapabilities as w, getRequestContainer as x, AuthorizationException as y };
@@ -74,7 +74,17 @@ export declare class BroadcastManager {
74
74
  disconnectAll(): void;
75
75
  protected generateClientId(prefix?: 'sse' | 'ws'): string;
76
76
  }
77
+ /**
78
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the manager on the
79
+ * app's container instead — `BroadcastServiceProvider` already does, and a
80
+ * provider of your own reaches it as `this.container.instance('broadcast', m)`.
81
+ */
77
82
  export declare function setBroadcastManager(manager: BroadcastManager): void;
83
+ /**
84
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use
85
+ * `this.make('broadcast')` in a controller, job or command, or
86
+ * `defaultContainer().make('broadcast')`.
87
+ */
78
88
  export declare function getBroadcastManager(): BroadcastManager;
79
89
  /**
80
90
  * Under `bun --hot`, the manager this one replaces has its SSE connections
@@ -1,2 +1,2 @@
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-B5RzB0A2.js";
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-BdJnaq1O.js";
2
2
  export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
@@ -1,4 +1,5 @@
1
1
  import { a as parseRequestPayload } from "./request-CLOYytGP.js";
2
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
2
3
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
3
4
  import { c as randomHex } from "./Random-S0OvCuR8.js";
4
5
  //#region src/broadcasting/channels/Channel.ts
@@ -637,12 +638,25 @@ var BroadcastManager = class {
637
638
  }
638
639
  };
639
640
  let globalBroadcastManager = null;
641
+ /**
642
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the manager on the
643
+ * app's container instead — `BroadcastServiceProvider` already does, and a
644
+ * provider of your own reaches it as `this.container.instance('broadcast', m)`.
645
+ */
640
646
  function setBroadcastManager(manager) {
641
- globalBroadcastManager = manager;
647
+ warnDeprecatedSetter("setBroadcastManager");
648
+ globalBroadcastManager = bindAmbient("broadcast", manager) ? null : manager;
642
649
  }
650
+ /**
651
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use
652
+ * `this.make('broadcast')` in a controller, job or command, or
653
+ * `defaultContainer().make('broadcast')`.
654
+ */
643
655
  function getBroadcastManager() {
644
- if (!globalBroadcastManager) throw new Error("BroadcastManager not initialized. Call setBroadcastManager() first.");
645
- return globalBroadcastManager;
656
+ warnDeprecatedGetter("getBroadcastManager");
657
+ const manager = ambientBinding("broadcast") ?? globalBroadcastManager;
658
+ if (!manager) throw new Error("BroadcastManager not initialized. Register BroadcastServiceProvider, or call setBroadcastManager() first.");
659
+ return manager;
646
660
  }
647
661
  /**
648
662
  * Under `bun --hot`, the manager this one replaces has its SSE connections
@@ -1,5 +1,5 @@
1
1
  import type { Container } from '../container/index.js';
2
- import type { OutputInterface, CommandInstance } from './types.js';
2
+ import type { OutputInterface, CommandInstance, ConsoleHandleOptions } from './types.js';
3
3
  import { Input } from './Input.js';
4
4
  import * as readline from 'readline';
5
5
  /** Base class for console commands. */
@@ -57,10 +57,10 @@ export declare abstract class Command implements CommandInstance {
57
57
  protected createReadline(): readline.Interface;
58
58
  withProgress<T>(items: T[], callback: (item: T, index: number) => Promise<void>): Promise<void>;
59
59
  protected kernel?: {
60
- handle(argv: string[]): Promise<number>;
60
+ handle(argv: string[], options?: ConsoleHandleOptions): Promise<number>;
61
61
  };
62
62
  setKernel(kernel: {
63
- handle(argv: string[]): Promise<number>;
63
+ handle(argv: string[], options?: ConsoleHandleOptions): Promise<number>;
64
64
  }): void;
65
65
  call(command: string, args?: string[]): Promise<number>;
66
66
  protected resolve<T>(key: string): T;
@@ -1,5 +1,5 @@
1
1
  import type { Container } from '../container/index.js';
2
- import type { CommandClass, ConsoleKernelOptions, OutputInterface } from './types.js';
2
+ import type { CommandClass, ConsoleHandleOptions, ConsoleKernelOptions, OutputInterface } from './types.js';
3
3
  /** Console kernel for managing and executing commands. */
4
4
  export declare class ConsoleKernel {
5
5
  protected commands: Map<string, CommandClass>;
@@ -13,7 +13,7 @@ export declare class ConsoleKernel {
13
13
  hasCommand(name: string): boolean;
14
14
  setOutput(output: OutputInterface): this;
15
15
  getOutput(): OutputInterface;
16
- handle(argv?: string[]): Promise<number>;
16
+ handle(argv?: string[], options?: ConsoleHandleOptions): Promise<number>;
17
17
  protected runCommand(CommandClass: CommandClass, args: string[]): Promise<number>;
18
18
  protected showHelp(): void;
19
19
  protected showCommandHelp(commandName: string): void;
@@ -1,4 +1,4 @@
1
- export type { ArgumentDefinition, OptionDefinition, ParsedSignature, CommandClass, CommandInstance, ConsoleKernelOptions, OutputInterface, InputInterface, ScheduledCommand, PromptInterface, ProgressInterface, } from './types.js';
1
+ export type { ArgumentDefinition, OptionDefinition, ParsedSignature, CommandClass, CommandInstance, ConsoleKernelOptions, ConsoleHandleOptions, OutputInterface, InputInterface, ScheduledCommand, PromptInterface, ProgressInterface, } from './types.js';
2
2
  export { Command } from './Command.js';
3
3
  export { Input, parseSignature } from './Input.js';
4
4
  export { Output, BufferedOutput } from './Output.js';
@@ -28,10 +28,18 @@ export interface CommandInstance {
28
28
  setInput(argv: string[]): void;
29
29
  setOutput(output: OutputInterface): void;
30
30
  setKernel(kernel: {
31
- handle(argv: string[]): Promise<number>;
31
+ handle(argv: string[], options?: ConsoleHandleOptions): Promise<number>;
32
32
  }): void;
33
33
  run(): Promise<number>;
34
34
  }
35
+ export interface ConsoleHandleOptions {
36
+ /**
37
+ * Whether `--help` / `-h` among the arguments prints the command's help instead of
38
+ * running it (default `true`). `call()` passes `false`: arguments assembled by code
39
+ * may carry either token as a value, and a silent call would report the skip as success.
40
+ */
41
+ helpFlags?: boolean;
42
+ }
35
43
  export interface OutputInterface {
36
44
  info(message: string): void;
37
45
  error(message: string): void;
@@ -61,6 +61,23 @@ export declare class Container {
61
61
  protected findContextualBinding(needs: string): ServiceFactory<unknown> | null;
62
62
  }
63
63
  export declare function createContainer(): Container;
64
+ /** @internal The ambient slot's write, without the deprecation warning `setContainer()` carries. */
65
+ export declare function installContainer(container: Container): void;
66
+ /** @internal The ambient container without the throw, for `defaultApplication()`'s ownership check. */
67
+ export declare function peekContainer(): Container | null;
68
+ /** @internal Empties the ambient slot; `resetDefaultApplication()` is the public seam. */
69
+ export declare function clearContainer(): void;
70
+ /** @internal The ambient container or the throw, without the deprecation warning `getContainer()` carries. */
71
+ export declare function requireContainer(): Container;
72
+ /**
73
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Choose the ambient
74
+ * application with `useAsDefaultApplication(app)`; every `Application`
75
+ * constructor already publishes its own container.
76
+ */
64
77
  export declare function setContainer(container: Container): void;
78
+ /**
79
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use `defaultContainer()`
80
+ * for the ambient one, `this.make(key)` in a controller, job or command, or
81
+ * `getRequestContainer(ctx)` in middleware.
82
+ */
65
83
  export declare function getContainer(): Container;
66
- export declare function resolve<T = unknown>(key: string): T;
@@ -18,6 +18,7 @@ import type { Scheduler } from '../scheduling/index.js';
18
18
  import type { Gate } from '../authorization/Gate.js';
19
19
  import type { ExceptionHandler } from '../errors/index.js';
20
20
  import type { SharedInertiaPropsRegistry } from '../mvc/inertia/shared.js';
21
+ import type { InertiaDocumentOptions, InertiaSsrRenderer } from '../mvc/inertia/InertiaEngine.js';
21
22
  import type { AgentAuditEmitter } from '../agent/audit-emitter.js';
22
23
  import type { SessionManager } from '../http/middleware/session-manager.js';
23
24
  /** Maps service keys to their concrete types, for `container.make('key')`. */
@@ -44,6 +45,10 @@ export interface ServiceBindings {
44
45
  gate: Gate;
45
46
  /** Bound lazily on the first `shareInertiaProps(fn, container)` call. */
46
47
  'inertia.sharedProps': SharedInertiaPropsRegistry;
48
+ /** `createApp({ inertia: { document } })`; read by the Inertia engine ahead of `setInertiaDocument()` (RFC 0023 §1). */
49
+ 'inertia.document': InertiaDocumentOptions;
50
+ /** `createApp({ inertia: { ssrRenderer } })`; per-call `ssr.render` still wins. */
51
+ 'inertia.ssrRenderer': InertiaSsrRenderer;
47
52
  /**
48
53
  * How an agent surface records what it did (RFC 0016 §5.2). Bound by
49
54
  * `@guren/plugin-mcp` at boot, absent without it; the *emitter*, not the sink,
@@ -1,6 +1,8 @@
1
- export type { ServiceFactory, ServiceClass, ServiceBinding, ContextualBindingBuilder, ContextualNeedsBuilder, ContextualBinding, ServiceProviderOptions, Provider, ServiceProviderClass, } from './types.js';
1
+ export type { ContainerLike, ServiceFactory, ServiceClass, ServiceBinding, ContextualBindingBuilder, ContextualNeedsBuilder, ContextualBinding, ServiceProviderOptions, Provider, ServiceProviderClass, } from './types.js';
2
2
  export type { ServiceBindings } from './bindings.js';
3
- export { Container, createContainer, setContainer, getContainer, resolve, } from './Container.js';
3
+ export { Container, createContainer, setContainer, getContainer, } from './Container.js';
4
+ export { resolve } from '../http/default-application.js';
5
+ export { resolveOptional } from './resolve-optional.js';
4
6
  export { ServiceProvider, ProviderManager } from './ServiceProvider.js';
5
7
  export { definePlugin } from './definePlugin.js';
6
8
  export type { PluginDefinition, PluginFactory } from './definePlugin.js';
@@ -0,0 +1,10 @@
1
+ import type { ServiceBindings } from './bindings.js';
2
+ import type { ContainerLike } from './types.js';
3
+ /**
4
+ * The binding `container` holds under `key`, undefined when it holds none.
5
+ * Prefers `makeOptional` where the container has it: `has()` sees neither a
6
+ * fake nor a deferred provider, so a consumer spelling `has()` itself answers
7
+ * differently from the same key resolved through the container (RFC 0023 §2).
8
+ */
9
+ export declare function resolveOptional<K extends keyof ServiceBindings>(container: ContainerLike | null | undefined, key: K): ServiceBindings[K] | undefined;
10
+ export declare function resolveOptional<T>(container: ContainerLike | null | undefined, key: string): T | undefined;
@@ -0,0 +1,91 @@
1
+ import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
2
+ //#region src/errors/exceptions/AuthenticationException.ts
3
+ /** 401: the user is not authenticated, or the credentials were invalid. */
4
+ var AuthenticationException = class AuthenticationException extends HttpException {
5
+ /** The guard that threw. */
6
+ guard;
7
+ redirectTo;
8
+ constructor(message = "Unauthenticated.", guard, redirectTo) {
9
+ super(401, message);
10
+ this.name = "AuthenticationException";
11
+ this.guard = guard;
12
+ this.redirectTo = redirectTo;
13
+ }
14
+ static withRedirect(redirectTo, message) {
15
+ return new AuthenticationException(message, void 0, redirectTo);
16
+ }
17
+ static forGuard(guard, message) {
18
+ return new AuthenticationException(message, guard);
19
+ }
20
+ };
21
+ //#endregion
22
+ //#region src/auth/context.ts
23
+ /**
24
+ * Context key the framework auth context is stored under.
25
+ *
26
+ * Lives here rather than in `http/middleware/auth` so that `auth/` modules can
27
+ * import it without reaching back into the middleware layer. The middleware
28
+ * re-exports it, and it stays a public root export.
29
+ */
30
+ const AUTH_CONTEXT_KEY = "guren:auth";
31
+ /**
32
+ * Context key the principal a middleware already resolved is stored under.
33
+ *
34
+ * The framework auth context answers from this slot before it reaches a guard,
35
+ * so a middleware that authenticates a request (the bearer-token middleware,
36
+ * or an app's own) reaches the Gate whatever order it is mounted in.
37
+ */
38
+ const RESOLVED_PRINCIPAL_KEY = "guren:resolved-principal";
39
+ /**
40
+ * Read the framework auth context off a request context. `ctx.get` returns
41
+ * arbitrary values for unknown keys, so the cast is a claim, not a check. A
42
+ * caller whose behavior turns on a real auth context probes the member it is
43
+ * about to call, as `Gate.resolveUser` does before its legacy `ctx.get('user')`
44
+ * fallback; probing here would reject contexts `requireAuthenticated` can use.
45
+ */
46
+ function getAuthContext(ctx) {
47
+ return ctx.get(AUTH_CONTEXT_KEY);
48
+ }
49
+ function getResolvedPrincipal(ctx) {
50
+ return ctx.get(RESOLVED_PRINCIPAL_KEY);
51
+ }
52
+ function setResolvedPrincipal(ctx, principal) {
53
+ ctx.set(RESOLVED_PRINCIPAL_KEY, principal);
54
+ }
55
+ /**
56
+ * The auth context a request carries when a middleware resolved a principal and
57
+ * nothing attached a framework context — a bearer-authenticated route on a
58
+ * plain Hono app. Credential flows throw rather than pretending to succeed;
59
+ * `logout()` revokes the presented credential.
60
+ */
61
+ function createPrincipalAuthContext(ctx) {
62
+ const unsupported = (method) => {
63
+ throw new Error(`${method}() is not available on a request with no auth context attached.`);
64
+ };
65
+ const principal = () => getResolvedPrincipal(ctx);
66
+ const user = async () => principal()?.user ?? null;
67
+ return {
68
+ check: async () => principal()?.user != null,
69
+ guest: async () => principal()?.user == null,
70
+ user,
71
+ userOrFail: async () => {
72
+ const resolved = await user();
73
+ if (resolved == null) throw new AuthenticationException();
74
+ return resolved;
75
+ },
76
+ id: async () => {
77
+ const resolved = principal();
78
+ return resolved?.user == null ? null : resolved.id;
79
+ },
80
+ login: async () => unsupported("login"),
81
+ attempt: async () => unsupported("attempt"),
82
+ logout: async () => {
83
+ await principal()?.revoke?.();
84
+ setResolvedPrincipal(ctx, void 0);
85
+ },
86
+ guard: () => unsupported("guard"),
87
+ session: () => void 0
88
+ };
89
+ }
90
+ //#endregion
91
+ export { setResolvedPrincipal as a, getResolvedPrincipal as i, createPrincipalAuthContext as n, AuthenticationException as o, getAuthContext as r, AUTH_CONTEXT_KEY as t };
@@ -1,4 +1,33 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { t as warnOnce } from "./warn-once-p-IlMjra.js";
2
+ //#region src/support/deprecate.ts
3
+ /** The release these shims were deprecated in, and the one that removes them (RFC 0023 Part 3). */
4
+ const SINCE = "2.23.0";
5
+ const REMOVED_IN = "3.0.0";
6
+ /** RFC 0023 §5: the module-level service slots, split by direction. */
7
+ const GLOBAL_SERVICE_SETTERS = "global-service-setters";
8
+ const GLOBAL_SERVICE_GETTERS = "global-service-getters";
9
+ const SETTER_REPLACEMENT = "Bind the service on the owning app's container instead — container.instance(key, value) from a service provider. createApp({ inertia }) covers the two Inertia options, and shareInertiaProps(fn, container) the shared props.";
10
+ const GETTER_REPLACEMENT = "Resolve from the container that owns the call — this.make(key) in a controller, job or command, getRequestContainer(ctx).make(key) in middleware, defaultContainer().make(key) elsewhere.";
11
+ /**
12
+ * @internal The deprecation policy's warning format
13
+ * (`contributing/deprecation-policy.md`), keyed per symbol so one deprecated
14
+ * call does not silence its siblings.
15
+ */
16
+ function warnDeprecated(id, symbol, replacement, versions = {
17
+ since: SINCE,
18
+ removedIn: REMOVED_IN
19
+ }) {
20
+ warnOnce(`${id}:${symbol}`, `[guren] Deprecation (${id}): ${symbol}() is deprecated\n since ${versions.since}, will be removed in ${versions.removedIn}.\n ${replacement}`);
21
+ }
22
+ /** @internal */
23
+ function warnDeprecatedSetter(symbol) {
24
+ warnDeprecated(GLOBAL_SERVICE_SETTERS, symbol, SETTER_REPLACEMENT);
25
+ }
26
+ /** @internal */
27
+ function warnDeprecatedGetter(symbol) {
28
+ warnDeprecated(GLOBAL_SERVICE_GETTERS, symbol, GETTER_REPLACEMENT);
29
+ }
30
+ //#endregion
2
31
  //#region src/container/Container.ts
3
32
  /**
4
33
  * Dependency injection container. Keys from `ServiceBindings` type `make()`
@@ -193,102 +222,117 @@ function createContainer() {
193
222
  return new Container();
194
223
  }
195
224
  let globalContainer = null;
196
- function setContainer(container) {
225
+ /** @internal The ambient slot's write, without the deprecation warning `setContainer()` carries. */
226
+ function installContainer(container) {
197
227
  globalContainer = container;
198
228
  }
199
- function getContainer() {
229
+ /** @internal The ambient container without the throw, for `defaultApplication()`'s ownership check. */
230
+ function peekContainer() {
231
+ return globalContainer;
232
+ }
233
+ /** @internal Empties the ambient slot; `resetDefaultApplication()` is the public seam. */
234
+ function clearContainer() {
235
+ globalContainer = null;
236
+ }
237
+ /** @internal The ambient container or the throw, without the deprecation warning `getContainer()` carries. */
238
+ function requireContainer() {
200
239
  if (!globalContainer) throw new Error("Container not initialized. Call setContainer() first.");
201
240
  return globalContainer;
202
241
  }
203
- function resolve(key) {
204
- return getContainer().make(key);
242
+ /**
243
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Choose the ambient
244
+ * application with `useAsDefaultApplication(app)`; every `Application`
245
+ * constructor already publishes its own container.
246
+ */
247
+ function setContainer(container) {
248
+ warnDeprecatedSetter("setContainer");
249
+ installContainer(container);
250
+ }
251
+ /**
252
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use `defaultContainer()`
253
+ * for the ambient one, `this.make(key)` in a controller, job or command, or
254
+ * `getRequestContainer(ctx)` in middleware.
255
+ */
256
+ function getContainer() {
257
+ warnDeprecatedGetter("getContainer");
258
+ return requireContainer();
205
259
  }
206
260
  //#endregion
207
- //#region src/queue/Job.ts
208
- let globalDriver = null;
209
- function setQueueDriver(driver) {
210
- globalDriver = driver;
261
+ //#region src/http/default-application.ts
262
+ /**
263
+ * The ambient Application (RFC 0023 §3), what a helper with no handle to pass
264
+ * (`encrypt()`, `t()`, `Job.dispatch()`, `resolve()`) resolves from.
265
+ * Last-constructed wins, which a sequential `bun test` process needs; a second
266
+ * construction beside a live default is the hazard, so it marks the choice
267
+ * ambiguous and the next ambient call warns once.
268
+ */
269
+ let current = null;
270
+ let ambiguous = false;
271
+ const AMBIGUOUS_WARNING = "[guren] Two Applications exist in this process, and an ambient helper resolved a service from the most recently constructed one. Call useAsDefaultApplication(app) to choose, or resolve explicitly: container.make(key), this.make(key) in a controller, job or command, or createFacades(container).";
272
+ /** @internal Application constructor only. Displacing a still-ambient app is what makes the choice ambiguous. */
273
+ function adoptDefaultApplication(app) {
274
+ const displaces = Boolean(current && current !== app && peekContainer() === current.container);
275
+ setDefault(app, ambiguous || displaces);
211
276
  }
212
- function getQueueDriver() {
213
- return globalDriver;
277
+ /** Opt-in override for a process that constructs several and wants the ambient one chosen, not last. */
278
+ function useAsDefaultApplication(app) {
279
+ setDefault(app, false);
214
280
  }
215
- function generateJobId() {
216
- return randomBytes(16).toString("hex");
281
+ /** @internal Test seam: empties the ambient slot and the ambiguity flag. */
282
+ function resetDefaultApplication() {
283
+ current = null;
284
+ ambiguous = false;
285
+ clearContainer();
286
+ }
287
+ function setDefault(app, nextAmbiguous) {
288
+ current = app;
289
+ ambiguous = nextAmbiguous;
290
+ installContainer(app.container);
217
291
  }
218
- var Job = class {
219
- /**
220
- * Stable wire name: queued messages record it and the worker resolves the
221
- * class back from it. Defaults to the class name, which breaks under
222
- * identifier mangling or a rename with messages still in flight.
223
- * @default the class name
224
- */
225
- static jobName;
226
- /** @default 'default' */
227
- static queue = "default";
228
- /** @default 3 */
229
- static maxAttempts = 3;
230
- /**
231
- * 'exponential' = 2^attempt * 1000ms, 'linear' = attempt * 1000ms, a number
232
- * is a fixed delay in milliseconds.
233
- * @default 'exponential'
234
- */
235
- static backoff = "exponential";
236
- make(key) {
237
- return getContainer().make(key);
238
- }
239
- static async dispatch(payload, options = {}) {
240
- const driver = globalDriver;
241
- if (!driver) throw new Error("Queue driver not configured. Call setQueueDriver() first.");
242
- const jobId = generateJobId();
243
- const now = /* @__PURE__ */ new Date();
244
- const delay = options.delay ?? 0;
245
- const job = {
246
- id: jobId,
247
- name: resolveJobName(this),
248
- payload,
249
- queue: options.queue ?? this.queue,
250
- attempts: 0,
251
- maxAttempts: options.maxAttempts ?? this.maxAttempts,
252
- availableAt: new Date(now.getTime() + delay),
253
- createdAt: now,
254
- reservedAt: null
255
- };
256
- await driver.push(job);
257
- return jobId;
258
- }
259
- static async dispatchAfter(delayMs, payload, options = {}) {
260
- return this.dispatch(payload, {
261
- ...options,
262
- delay: delayMs
263
- });
264
- }
265
- static calculateRetryDelay(attempts) {
266
- if (typeof this.backoff === "number") return this.backoff;
267
- if (this.backoff === "linear") return attempts * 1e3;
268
- return Math.pow(2, attempts) * 1e3;
269
- }
270
- };
271
292
  /**
272
- * Only an *own* `jobName` counts: statics are inherited, so reading the
273
- * prototype chain would make every subclass of a pinned job claim its
274
- * parent's identity and overwrite it in the registry.
293
+ * The most recently constructed Application; `null` before any exists, and
294
+ * `null` again once `setContainer()` handed the ambient slot a container that
295
+ * belongs to no Application.
275
296
  */
276
- function resolveJobName(jobClass) {
277
- return (Object.prototype.hasOwnProperty.call(jobClass, "jobName") ? jobClass.jobName : void 0) ?? jobClass.name;
297
+ function defaultApplication() {
298
+ warnIfAmbiguous();
299
+ if (!current || peekContainer() !== current.container) return null;
300
+ return current;
301
+ }
302
+ /** The default application's container; throws the same "not initialized" error the getters throw. */
303
+ function defaultContainer() {
304
+ warnIfAmbiguous();
305
+ return requireContainer();
306
+ }
307
+ /** `defaultContainer()` for a caller with a fallback of its own: null instead of the throw. */
308
+ function ambientContainer() {
309
+ warnIfAmbiguous();
310
+ return peekContainer();
278
311
  }
279
- const jobRegistry = /* @__PURE__ */ new Map();
280
- function registerJob(jobClass) {
281
- jobRegistry.set(resolveJobName(jobClass), jobClass);
312
+ /**
313
+ * The binding the default application holds under `key`, or undefined when
314
+ * there is no default application or it binds nothing there. Every functional
315
+ * helper reads through this before its module slot (RFC 0023 §3).
316
+ */
317
+ function ambientBinding(key) {
318
+ return ambientContainer()?.makeOptional(key);
282
319
  }
283
- function getJob(name) {
284
- return jobRegistry.get(name);
320
+ /**
321
+ * @internal A deprecated setter's write (RFC 0023 §5): the ambient container
322
+ * when one exists, else nothing. Answers whether it landed, so the caller can
323
+ * drop its module slot rather than leave a copy that outlives the app.
324
+ */
325
+ function bindAmbient(key, value) {
326
+ const container = ambientContainer();
327
+ container?.instance(key, value);
328
+ return container !== null;
285
329
  }
286
- function getRegisteredJobs() {
287
- return new Map(jobRegistry);
330
+ /** Resolve `key` from the default application's container. */
331
+ function resolve(key) {
332
+ return defaultContainer().make(key);
288
333
  }
289
- /** Testing only. */
290
- function clearJobRegistry() {
291
- jobRegistry.clear();
334
+ function warnIfAmbiguous() {
335
+ if (ambiguous) warnOnce("ambient-application-ambiguous", AMBIGUOUS_WARNING);
292
336
  }
293
337
  //#endregion
294
- export { getRegisteredJobs as a, setQueueDriver as c, getContainer as d, resolve as f, getQueueDriver as i, Container as l, clearJobRegistry as n, registerJob as o, setContainer as p, getJob as r, resolveJobName as s, Job as t, createContainer as u };
338
+ export { defaultApplication as a, resolve as c, createContainer as d, getContainer as f, warnDeprecatedSetter as h, bindAmbient as i, useAsDefaultApplication as l, warnDeprecatedGetter as m, ambientBinding as n, defaultContainer as o, setContainer as p, ambientContainer as r, resetDefaultApplication as s, adoptDefaultApplication as t, Container as u };