@geekmidas/services 1.0.3 → 1.0.4

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 (47) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +24 -0
  3. package/dist/{ServiceDiscovery-ykolgkIj.d.mts → ServiceDiscovery-CadEgTKz.d.mts} +2 -2
  4. package/dist/{ServiceDiscovery-ykolgkIj.d.mts.map → ServiceDiscovery-CadEgTKz.d.mts.map} +1 -1
  5. package/dist/{ServiceDiscovery-C5x1wcN1.cjs → ServiceDiscovery-Cxus7ber.cjs} +2 -2
  6. package/dist/{ServiceDiscovery-C5x1wcN1.cjs.map → ServiceDiscovery-Cxus7ber.cjs.map} +1 -1
  7. package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts → ServiceDiscovery-DF4OKEZp.d.cts} +2 -2
  8. package/dist/{ServiceDiscovery-Dvqa-Q1_.d.cts.map → ServiceDiscovery-DF4OKEZp.d.cts.map} +1 -1
  9. package/dist/{ServiceDiscovery-tZ6VKHIZ.mjs → ServiceDiscovery-SujDuYHr.mjs} +2 -2
  10. package/dist/{ServiceDiscovery-tZ6VKHIZ.mjs.map → ServiceDiscovery-SujDuYHr.mjs.map} +1 -1
  11. package/dist/ServiceDiscovery.cjs +2 -2
  12. package/dist/ServiceDiscovery.d.cts +2 -2
  13. package/dist/ServiceDiscovery.d.mts +2 -2
  14. package/dist/ServiceDiscovery.mjs +2 -2
  15. package/dist/{context-BpYagzpr.mjs → context-BojeLlxs.mjs} +61 -4
  16. package/dist/context-BojeLlxs.mjs.map +1 -0
  17. package/dist/{context-CoyHq8lH.cjs → context-CkCPt2Fe.cjs} +61 -4
  18. package/dist/context-CkCPt2Fe.cjs.map +1 -0
  19. package/dist/{context-CaeISj3o.d.cts → context-D5pIUGkm.d.cts} +2 -2
  20. package/dist/context-D5pIUGkm.d.cts.map +1 -0
  21. package/dist/{context-HGC2PJzv.d.mts → context-OmKid3Mr.d.mts} +2 -2
  22. package/dist/context-OmKid3Mr.d.mts.map +1 -0
  23. package/dist/context.cjs +1 -1
  24. package/dist/context.d.cts +2 -2
  25. package/dist/context.d.mts +2 -2
  26. package/dist/context.mjs +1 -1
  27. package/dist/index.cjs +2 -2
  28. package/dist/index.d.cts +3 -3
  29. package/dist/index.d.mts +3 -3
  30. package/dist/index.mjs +2 -2
  31. package/dist/{types-CcHmCx_U.d.mts → types-B99KrvXR.d.mts} +8 -1
  32. package/dist/types-B99KrvXR.d.mts.map +1 -0
  33. package/dist/{types-D7d_yeU5.d.cts → types-BY9yrY6Y.d.cts} +8 -1
  34. package/dist/types-BY9yrY6Y.d.cts.map +1 -0
  35. package/dist/types.d.cts +1 -1
  36. package/dist/types.d.mts +1 -1
  37. package/docs/request-scoped-logging.md +153 -0
  38. package/package.json +1 -1
  39. package/src/__tests__/context.spec.ts +180 -4
  40. package/src/context.ts +102 -8
  41. package/src/types.ts +7 -0
  42. package/dist/context-BpYagzpr.mjs.map +0 -1
  43. package/dist/context-CaeISj3o.d.cts.map +0 -1
  44. package/dist/context-CoyHq8lH.cjs.map +0 -1
  45. package/dist/context-HGC2PJzv.d.mts.map +0 -1
  46. package/dist/types-CcHmCx_U.d.mts.map +0 -1
  47. package/dist/types-D7d_yeU5.d.cts.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @geekmidas/services
2
2
 
3
+ ## 1.0.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 🐛 [#3](https://github.com/geekmidas/toolbox/pull/3) [`42fda53`](https://github.com/geekmidas/toolbox/commit/42fda532bdf4489a3352f6a684f5f30beafccedd) Thanks [@geekmidas](https://github.com/geekmidas)! - Fix stale logger from service initialization
8
+
3
9
  ## 1.0.3
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -286,6 +286,30 @@ const db3 = await serviceDiscovery.discover(databaseService);
286
286
  console.log(db1 === db2 && db2 === db3); // true
287
287
  ```
288
288
 
289
+ ### Request-Scoped Logging
290
+
291
+ Because services are singletons, `register()` runs **once** while the per-request
292
+ logger changes on every request. `serviceContext.getLogger()` returns a
293
+ **request-scoped proxy** that re-resolves the current request's logger on each call,
294
+ so a service can safely capture the logger once during `register()` and still log
295
+ against the correct request:
296
+
297
+ ```typescript
298
+ register({ context }) {
299
+ const logger = context.getLogger().child({ svc: 'db' }); // ✅ safe to capture
300
+
301
+ return {
302
+ async query(sql: string) {
303
+ logger.debug({ sql }, 'Executing query'); // logs to the CURRENT request
304
+ },
305
+ };
306
+ }
307
+ ```
308
+
309
+ See [docs/request-scoped-logging.md](./docs/request-scoped-logging.md) for the full
310
+ problem description (and the bug it prevents: a captured logger freezing the first
311
+ request's `requestId` for every later request).
312
+
289
313
  ## Error Handling
290
314
 
291
315
  Handle service initialization errors gracefully:
@@ -1,4 +1,4 @@
1
- import { Service } from "./types-CcHmCx_U.mjs";
1
+ import { Service } from "./types-B99KrvXR.mjs";
2
2
  import { EnvironmentParser } from "@geekmidas/envkit";
3
3
 
4
4
  //#region src/ServiceDiscovery.d.ts
@@ -184,4 +184,4 @@ type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]
184
184
  //# sourceMappingURL=ServiceDiscovery.d.ts.map
185
185
  //#endregion
186
186
  export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
187
- //# sourceMappingURL=ServiceDiscovery-ykolgkIj.d.mts.map
187
+ //# sourceMappingURL=ServiceDiscovery-CadEgTKz.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceDiscovery-ykolgkIj.d.mts","names":[],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;AAgL8B;AAoB9B;AAA+B,cApMlB,gBAoMkB,CAAA,kBApMiB,MAoMjB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAA,SAAW,SAAA,EAlJT,iBAkJS,CAAA,CAAA,CAAA,CAAA;EAAO;EAAO,eAAA,SAAA;EAiB5C;EAAa,QAAA,QAAA;EAAA;EAAkB,QACpC,SAAA;EAAC;;;;;;AACG;;;;;;;+BAlMmB,uCACjB,wBACT,iBAAiB;;;;;;;;;;;;;;;;;;yBA2BY;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BP,qBAAqB,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;sBAwCpD,0BAA0B,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;2BA6BrC,kCACnB,KACT,gBAAgB,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;wBA6BnB;;;;;;;;;;;;;KAoBX,8BAA8B,aAAa;;;;;;;;;;;;;;;;KAiB3C,wBAAwB,qBAC7B,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
1
+ {"version":3,"file":"ServiceDiscovery-CadEgTKz.d.mts","names":[],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;AAgL8B;AAoB9B;AAA+B,cApMlB,gBAoMkB,CAAA,kBApMiB,MAoMjB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAA,SAAW,SAAA,EAlJT,iBAkJS,CAAA,CAAA,CAAA,CAAA;EAAO;EAAO,eAAA,SAAA;EAiB5C;EAAa,QAAA,QAAA;EAAA;EAAkB,QACpC,SAAA;EAAC;;;;;;AACG;;;;;;;+BAlMmB,uCACjB,wBACT,iBAAiB;;;;;;;;;;;;;;;;;;yBA2BY;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BP,qBAAqB,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;sBAwCpD,0BAA0B,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;2BA6BrC,kCACnB,KACT,gBAAgB,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;wBA6BnB;;;;;;;;;;;;;KAoBX,8BAA8B,aAAa;;;;;;;;;;;;;;;;KAiB3C,wBAAwB,qBAC7B,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
@@ -1,4 +1,4 @@
1
- const require_context = require('./context-CoyHq8lH.cjs');
1
+ const require_context = require('./context-CkCPt2Fe.cjs');
2
2
 
3
3
  //#region src/ServiceDiscovery.ts
4
4
  /**
@@ -195,4 +195,4 @@ Object.defineProperty(exports, 'ServiceDiscovery', {
195
195
  return ServiceDiscovery;
196
196
  }
197
197
  });
198
- //# sourceMappingURL=ServiceDiscovery-C5x1wcN1.cjs.map
198
+ //# sourceMappingURL=ServiceDiscovery-Cxus7ber.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceDiscovery-C5x1wcN1.cjs","names":["envParser: EnvironmentParser<{}>","services: T","serviceContext","name: K","names: [...K]","service: string | Service"],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { serviceContext } from './context';\nimport type { Service } from './types';\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);\n *\n * // Register services\n * await discovery.register([\n * databaseService,\n * cacheService,\n * authService\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {\n\t/** Singleton instance of ServiceDiscovery */\n\tprivate static _instance: ServiceDiscovery<any>;\n\t/** Map of registered service definitions */\n\tprivate services = new Map<string, Service>();\n\t/** Map of instantiated service instances */\n\tprivate instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n\t/**\n\t * Gets the singleton instance of ServiceDiscovery.\n\t * Creates a new instance if one doesn't exist.\n\t *\n\t * @template T - Record type mapping service names to their instance types\n\t * @param envParser - Environment parser for service configuration\n\t * @returns The ServiceDiscovery singleton instance\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = ServiceDiscovery.getInstance<MyServices>(envParser);\n\t * ```\n\t */\n\tstatic getInstance<T extends Record<any, unknown> = any>(\n\t\tenvParser: EnvironmentParser<{}>,\n\t): ServiceDiscovery<T> {\n\t\tif (!ServiceDiscovery._instance) {\n\t\t\tServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);\n\t\t}\n\t\treturn ServiceDiscovery._instance as ServiceDiscovery<T>;\n\t}\n\n\t/**\n\t * Resets the singleton instance. Use only for testing purposes.\n\t * This clears all cached services and allows a fresh instance to be created.\n\t *\n\t * @example\n\t * ```typescript\n\t * // In test teardown\n\t * afterEach(() => {\n\t * ServiceDiscovery.reset();\n\t * });\n\t * ```\n\t */\n\tstatic reset(): void {\n\t\tServiceDiscovery._instance = undefined as any;\n\t}\n\n\t/**\n\t *\n\t * @param envParser - Environment parser for service configuration\n\t */\n\tconstructor(readonly envParser: EnvironmentParser<{}>) {}\n\n\t/**\n\t * Register multiple services with the service discovery.\n\t * Services are instantiated lazily on first access.\n\t * Already instantiated services are returned from cache.\n\t *\n\t * @template T - Array type of services to register\n\t * @param services - Array of services to register\n\t * @returns Promise resolving to a record of service names to instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = await discovery.register([\n\t * databaseService,\n\t * cacheService,\n\t * authService\n\t * ]);\n\t *\n\t * // services = {\n\t * // database: Database instance,\n\t * // cache: CacheService instance,\n\t * // auth: AuthService instance\n\t * // }\n\t * ```\n\t */\n\tasync register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n\t\tconst registeredServices = {} as ServiceRecord<T>;\n\t\tfor (const service of services) {\n\t\t\tconst name = service.serviceName as T[number]['serviceName'];\n\t\t\tif (this.instances.has(name)) {\n\t\t\t\t(registeredServices as any)[name] = this.instances.get(\n\t\t\t\t\tname,\n\t\t\t\t) as TServices[keyof TServices];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Pass both envParser and context to service\n\t\t\tconst instance = await service.register({\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\tcontext: serviceContext,\n\t\t\t});\n\n\t\t\tthis.instances.set(name, instance as TServices[keyof TServices]);\n\t\t\t(registeredServices as any)[name] =\n\t\t\t\tinstance as TServices[keyof TServices];\n\t\t}\n\n\t\treturn registeredServices;\n\t}\n\n\t/**\n\t * Get a service from the service discovery.\n\t * Services are instantiated on first access if not already cached.\n\t *\n\t * @template K - The service name key\n\t * @param name - The name of the service to get\n\t * @returns Promise resolving to the service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * const database = await discovery.get('database');\n\t * const users = await database.query('SELECT * FROM users');\n\t * ```\n\t */\n\tget<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n\t\tconst service = this.services.get(name);\n\n\t\tif (!service) {\n\t\t\tthrow new Error(`Service '${name}' not found in service discovery`);\n\t\t}\n\n\t\treturn service.register({\n\t\t\tenvParser: this.envParser,\n\t\t\tcontext: serviceContext,\n\t\t}) as Promise<TServices[K]>;\n\t}\n\t/**\n\t * Get multiple services from the service discovery.\n\t * Useful for retrieving multiple dependencies at once.\n\t *\n\t * @template K - Array of service name keys\n\t * @param names - Array of service names to retrieve\n\t * @returns Promise resolving to an object containing the service instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const { database, cache, auth } = await discovery.getMany([\n\t * 'database',\n\t * 'cache',\n\t * 'auth'\n\t * ]);\n\t * ```\n\t */\n\tasync getMany<K extends (keyof TServices & string)[]>(\n\t\tnames: [...K],\n\t): Promise<{ [P in K[number]]: TServices[P] }> {\n\t\tconst result = {} as { [P in K[number]]: TServices[P] };\n\n\t\tfor (const name of names) {\n\t\t\tresult[name] = await this.get(name);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check if a service exists in the service discovery.\n\t * Can check by service name or service instance.\n\t *\n\t * @param service - The service name or service instance to check\n\t * @returns True if the service exists, false otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (discovery.has('database')) {\n\t * const db = await discovery.get('database');\n\t * }\n\t *\n\t * // Or check with service instance\n\t * if (!discovery.has(databaseService)) {\n\t * await discovery.register([databaseService]);\n\t * }\n\t * ```\n\t */\n\thas(service: string | Service): boolean {\n\t\tif (typeof service === 'string') {\n\t\t\treturn this.services.has(service);\n\t\t}\n\n\t\treturn this.services.has(service.serviceName);\n\t}\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;\n * // type MyServiceRecord = {\n * // database: DatabaseInstance;\n * // cache: CacheInstance;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n\t[K in T[number] as K['serviceName']]: K extends Service\n\t\t? Awaited<ReturnType<K['register']>>\n\t\t: never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,mBAAb,MAAa,iBAAiE;;CAE7E,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;CAexB,OAAO,YACNA,WACsB;AACtB,OAAK,iBAAiB,UACrB,kBAAiB,YAAY,IAAI,iBAAoB;AAEtD,SAAO,iBAAiB;CACxB;;;;;;;;;;;;;CAcD,OAAO,QAAc;AACpB,mBAAiB;CACjB;;;;;CAMD,YAAqBA,WAAkC;EAAlC;CAAoC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BzD,MAAM,SAA8BC,UAAwC;EAC3E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC7B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IAClD,KACA;AACD;GACA;GAGD,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAASC;GACT,EAAC;AAEF,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC3B;EACD;AAED,SAAO;CACP;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACJ,OAAM,IAAI,OAAO,WAAW,KAAK;AAGlC,SAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAASD;EACT,EAAC;CACF;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACLE,OAC8C;EAC9C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MAClB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGpC,SAAO;CACP;;;;;;;;;;;;;;;;;;;;CAqBD,IAAIC,SAAoC;AACvC,aAAW,YAAY,SACtB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGlC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC7C;AACD"}
1
+ {"version":3,"file":"ServiceDiscovery-Cxus7ber.cjs","names":["envParser: EnvironmentParser<{}>","services: T","serviceContext","name: K","names: [...K]","service: string | Service"],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { serviceContext } from './context';\nimport type { Service } from './types';\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);\n *\n * // Register services\n * await discovery.register([\n * databaseService,\n * cacheService,\n * authService\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {\n\t/** Singleton instance of ServiceDiscovery */\n\tprivate static _instance: ServiceDiscovery<any>;\n\t/** Map of registered service definitions */\n\tprivate services = new Map<string, Service>();\n\t/** Map of instantiated service instances */\n\tprivate instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n\t/**\n\t * Gets the singleton instance of ServiceDiscovery.\n\t * Creates a new instance if one doesn't exist.\n\t *\n\t * @template T - Record type mapping service names to their instance types\n\t * @param envParser - Environment parser for service configuration\n\t * @returns The ServiceDiscovery singleton instance\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = ServiceDiscovery.getInstance<MyServices>(envParser);\n\t * ```\n\t */\n\tstatic getInstance<T extends Record<any, unknown> = any>(\n\t\tenvParser: EnvironmentParser<{}>,\n\t): ServiceDiscovery<T> {\n\t\tif (!ServiceDiscovery._instance) {\n\t\t\tServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);\n\t\t}\n\t\treturn ServiceDiscovery._instance as ServiceDiscovery<T>;\n\t}\n\n\t/**\n\t * Resets the singleton instance. Use only for testing purposes.\n\t * This clears all cached services and allows a fresh instance to be created.\n\t *\n\t * @example\n\t * ```typescript\n\t * // In test teardown\n\t * afterEach(() => {\n\t * ServiceDiscovery.reset();\n\t * });\n\t * ```\n\t */\n\tstatic reset(): void {\n\t\tServiceDiscovery._instance = undefined as any;\n\t}\n\n\t/**\n\t *\n\t * @param envParser - Environment parser for service configuration\n\t */\n\tconstructor(readonly envParser: EnvironmentParser<{}>) {}\n\n\t/**\n\t * Register multiple services with the service discovery.\n\t * Services are instantiated lazily on first access.\n\t * Already instantiated services are returned from cache.\n\t *\n\t * @template T - Array type of services to register\n\t * @param services - Array of services to register\n\t * @returns Promise resolving to a record of service names to instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = await discovery.register([\n\t * databaseService,\n\t * cacheService,\n\t * authService\n\t * ]);\n\t *\n\t * // services = {\n\t * // database: Database instance,\n\t * // cache: CacheService instance,\n\t * // auth: AuthService instance\n\t * // }\n\t * ```\n\t */\n\tasync register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n\t\tconst registeredServices = {} as ServiceRecord<T>;\n\t\tfor (const service of services) {\n\t\t\tconst name = service.serviceName as T[number]['serviceName'];\n\t\t\tif (this.instances.has(name)) {\n\t\t\t\t(registeredServices as any)[name] = this.instances.get(\n\t\t\t\t\tname,\n\t\t\t\t) as TServices[keyof TServices];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Pass both envParser and context to service\n\t\t\tconst instance = await service.register({\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\tcontext: serviceContext,\n\t\t\t});\n\n\t\t\tthis.instances.set(name, instance as TServices[keyof TServices]);\n\t\t\t(registeredServices as any)[name] =\n\t\t\t\tinstance as TServices[keyof TServices];\n\t\t}\n\n\t\treturn registeredServices;\n\t}\n\n\t/**\n\t * Get a service from the service discovery.\n\t * Services are instantiated on first access if not already cached.\n\t *\n\t * @template K - The service name key\n\t * @param name - The name of the service to get\n\t * @returns Promise resolving to the service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * const database = await discovery.get('database');\n\t * const users = await database.query('SELECT * FROM users');\n\t * ```\n\t */\n\tget<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n\t\tconst service = this.services.get(name);\n\n\t\tif (!service) {\n\t\t\tthrow new Error(`Service '${name}' not found in service discovery`);\n\t\t}\n\n\t\treturn service.register({\n\t\t\tenvParser: this.envParser,\n\t\t\tcontext: serviceContext,\n\t\t}) as Promise<TServices[K]>;\n\t}\n\t/**\n\t * Get multiple services from the service discovery.\n\t * Useful for retrieving multiple dependencies at once.\n\t *\n\t * @template K - Array of service name keys\n\t * @param names - Array of service names to retrieve\n\t * @returns Promise resolving to an object containing the service instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const { database, cache, auth } = await discovery.getMany([\n\t * 'database',\n\t * 'cache',\n\t * 'auth'\n\t * ]);\n\t * ```\n\t */\n\tasync getMany<K extends (keyof TServices & string)[]>(\n\t\tnames: [...K],\n\t): Promise<{ [P in K[number]]: TServices[P] }> {\n\t\tconst result = {} as { [P in K[number]]: TServices[P] };\n\n\t\tfor (const name of names) {\n\t\t\tresult[name] = await this.get(name);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check if a service exists in the service discovery.\n\t * Can check by service name or service instance.\n\t *\n\t * @param service - The service name or service instance to check\n\t * @returns True if the service exists, false otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (discovery.has('database')) {\n\t * const db = await discovery.get('database');\n\t * }\n\t *\n\t * // Or check with service instance\n\t * if (!discovery.has(databaseService)) {\n\t * await discovery.register([databaseService]);\n\t * }\n\t * ```\n\t */\n\thas(service: string | Service): boolean {\n\t\tif (typeof service === 'string') {\n\t\t\treturn this.services.has(service);\n\t\t}\n\n\t\treturn this.services.has(service.serviceName);\n\t}\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;\n * // type MyServiceRecord = {\n * // database: DatabaseInstance;\n * // cache: CacheInstance;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n\t[K in T[number] as K['serviceName']]: K extends Service\n\t\t? Awaited<ReturnType<K['register']>>\n\t\t: never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,mBAAb,MAAa,iBAAiE;;CAE7E,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;CAexB,OAAO,YACNA,WACsB;AACtB,OAAK,iBAAiB,UACrB,kBAAiB,YAAY,IAAI,iBAAoB;AAEtD,SAAO,iBAAiB;CACxB;;;;;;;;;;;;;CAcD,OAAO,QAAc;AACpB,mBAAiB;CACjB;;;;;CAMD,YAAqBA,WAAkC;EAAlC;CAAoC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BzD,MAAM,SAA8BC,UAAwC;EAC3E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC7B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IAClD,KACA;AACD;GACA;GAGD,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAASC;GACT,EAAC;AAEF,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC3B;EACD;AAED,SAAO;CACP;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACJ,OAAM,IAAI,OAAO,WAAW,KAAK;AAGlC,SAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAASD;EACT,EAAC;CACF;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACLE,OAC8C;EAC9C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MAClB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGpC,SAAO;CACP;;;;;;;;;;;;;;;;;;;;CAqBD,IAAIC,SAAoC;AACvC,aAAW,YAAY,SACtB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGlC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC7C;AACD"}
@@ -1,4 +1,4 @@
1
- import { Service } from "./types-D7d_yeU5.cjs";
1
+ import { Service } from "./types-BY9yrY6Y.cjs";
2
2
  import { EnvironmentParser } from "@geekmidas/envkit";
3
3
 
4
4
  //#region src/ServiceDiscovery.d.ts
@@ -184,4 +184,4 @@ type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]
184
184
  //# sourceMappingURL=ServiceDiscovery.d.ts.map
185
185
  //#endregion
186
186
  export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
187
- //# sourceMappingURL=ServiceDiscovery-Dvqa-Q1_.d.cts.map
187
+ //# sourceMappingURL=ServiceDiscovery-DF4OKEZp.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceDiscovery-Dvqa-Q1_.d.cts","names":[],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;AAgL8B;AAoB9B;AAA+B,cApMlB,gBAoMkB,CAAA,kBApMiB,MAoMjB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAA,SAAW,SAAA,EAlJT,iBAkJS,CAAA,CAAA,CAAA,CAAA;EAAO;EAAO,eAAA,SAAA;EAiB5C;EAAa,QAAA,QAAA;EAAA;EAAkB,QACpC,SAAA;EAAC;;;;;;AACG;;;;;;;+BAlMmB,uCACjB,wBACT,iBAAiB;;;;;;;;;;;;;;;;;;yBA2BY;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BP,qBAAqB,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;sBAwCpD,0BAA0B,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;2BA6BrC,kCACnB,KACT,gBAAgB,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;wBA6BnB;;;;;;;;;;;;;KAoBX,8BAA8B,aAAa;;;;;;;;;;;;;;;;KAiB3C,wBAAwB,qBAC7B,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
1
+ {"version":3,"file":"ServiceDiscovery-DF4OKEZp.d.cts","names":[],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;AAgL8B;AAoB9B;AAA+B,cApMlB,gBAoMkB,CAAA,kBApMiB,MAoMjB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAA,SAAW,SAAA,EAlJT,iBAkJS,CAAA,CAAA,CAAA,CAAA;EAAO;EAAO,eAAA,SAAA;EAiB5C;EAAa,QAAA,QAAA;EAAA;EAAkB,QACpC,SAAA;EAAC;;;;;;AACG;;;;;;;+BAlMmB,uCACjB,wBACT,iBAAiB;;;;;;;;;;;;;;;;;;yBA2BY;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BP,qBAAqB,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;sBAwCpD,0BAA0B,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;2BA6BrC,kCACnB,KACT,gBAAgB,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;wBA6BnB;;;;;;;;;;;;;KAoBX,8BAA8B,aAAa;;;;;;;;;;;;;;;;KAiB3C,wBAAwB,qBAC7B,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
@@ -1,4 +1,4 @@
1
- import { serviceContext } from "./context-BpYagzpr.mjs";
1
+ import { serviceContext } from "./context-BojeLlxs.mjs";
2
2
 
3
3
  //#region src/ServiceDiscovery.ts
4
4
  /**
@@ -190,4 +190,4 @@ var ServiceDiscovery = class ServiceDiscovery {
190
190
 
191
191
  //#endregion
192
192
  export { ServiceDiscovery };
193
- //# sourceMappingURL=ServiceDiscovery-tZ6VKHIZ.mjs.map
193
+ //# sourceMappingURL=ServiceDiscovery-SujDuYHr.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceDiscovery-tZ6VKHIZ.mjs","names":["envParser: EnvironmentParser<{}>","services: T","name: K","names: [...K]","service: string | Service"],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { serviceContext } from './context';\nimport type { Service } from './types';\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);\n *\n * // Register services\n * await discovery.register([\n * databaseService,\n * cacheService,\n * authService\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {\n\t/** Singleton instance of ServiceDiscovery */\n\tprivate static _instance: ServiceDiscovery<any>;\n\t/** Map of registered service definitions */\n\tprivate services = new Map<string, Service>();\n\t/** Map of instantiated service instances */\n\tprivate instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n\t/**\n\t * Gets the singleton instance of ServiceDiscovery.\n\t * Creates a new instance if one doesn't exist.\n\t *\n\t * @template T - Record type mapping service names to their instance types\n\t * @param envParser - Environment parser for service configuration\n\t * @returns The ServiceDiscovery singleton instance\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = ServiceDiscovery.getInstance<MyServices>(envParser);\n\t * ```\n\t */\n\tstatic getInstance<T extends Record<any, unknown> = any>(\n\t\tenvParser: EnvironmentParser<{}>,\n\t): ServiceDiscovery<T> {\n\t\tif (!ServiceDiscovery._instance) {\n\t\t\tServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);\n\t\t}\n\t\treturn ServiceDiscovery._instance as ServiceDiscovery<T>;\n\t}\n\n\t/**\n\t * Resets the singleton instance. Use only for testing purposes.\n\t * This clears all cached services and allows a fresh instance to be created.\n\t *\n\t * @example\n\t * ```typescript\n\t * // In test teardown\n\t * afterEach(() => {\n\t * ServiceDiscovery.reset();\n\t * });\n\t * ```\n\t */\n\tstatic reset(): void {\n\t\tServiceDiscovery._instance = undefined as any;\n\t}\n\n\t/**\n\t *\n\t * @param envParser - Environment parser for service configuration\n\t */\n\tconstructor(readonly envParser: EnvironmentParser<{}>) {}\n\n\t/**\n\t * Register multiple services with the service discovery.\n\t * Services are instantiated lazily on first access.\n\t * Already instantiated services are returned from cache.\n\t *\n\t * @template T - Array type of services to register\n\t * @param services - Array of services to register\n\t * @returns Promise resolving to a record of service names to instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = await discovery.register([\n\t * databaseService,\n\t * cacheService,\n\t * authService\n\t * ]);\n\t *\n\t * // services = {\n\t * // database: Database instance,\n\t * // cache: CacheService instance,\n\t * // auth: AuthService instance\n\t * // }\n\t * ```\n\t */\n\tasync register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n\t\tconst registeredServices = {} as ServiceRecord<T>;\n\t\tfor (const service of services) {\n\t\t\tconst name = service.serviceName as T[number]['serviceName'];\n\t\t\tif (this.instances.has(name)) {\n\t\t\t\t(registeredServices as any)[name] = this.instances.get(\n\t\t\t\t\tname,\n\t\t\t\t) as TServices[keyof TServices];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Pass both envParser and context to service\n\t\t\tconst instance = await service.register({\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\tcontext: serviceContext,\n\t\t\t});\n\n\t\t\tthis.instances.set(name, instance as TServices[keyof TServices]);\n\t\t\t(registeredServices as any)[name] =\n\t\t\t\tinstance as TServices[keyof TServices];\n\t\t}\n\n\t\treturn registeredServices;\n\t}\n\n\t/**\n\t * Get a service from the service discovery.\n\t * Services are instantiated on first access if not already cached.\n\t *\n\t * @template K - The service name key\n\t * @param name - The name of the service to get\n\t * @returns Promise resolving to the service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * const database = await discovery.get('database');\n\t * const users = await database.query('SELECT * FROM users');\n\t * ```\n\t */\n\tget<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n\t\tconst service = this.services.get(name);\n\n\t\tif (!service) {\n\t\t\tthrow new Error(`Service '${name}' not found in service discovery`);\n\t\t}\n\n\t\treturn service.register({\n\t\t\tenvParser: this.envParser,\n\t\t\tcontext: serviceContext,\n\t\t}) as Promise<TServices[K]>;\n\t}\n\t/**\n\t * Get multiple services from the service discovery.\n\t * Useful for retrieving multiple dependencies at once.\n\t *\n\t * @template K - Array of service name keys\n\t * @param names - Array of service names to retrieve\n\t * @returns Promise resolving to an object containing the service instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const { database, cache, auth } = await discovery.getMany([\n\t * 'database',\n\t * 'cache',\n\t * 'auth'\n\t * ]);\n\t * ```\n\t */\n\tasync getMany<K extends (keyof TServices & string)[]>(\n\t\tnames: [...K],\n\t): Promise<{ [P in K[number]]: TServices[P] }> {\n\t\tconst result = {} as { [P in K[number]]: TServices[P] };\n\n\t\tfor (const name of names) {\n\t\t\tresult[name] = await this.get(name);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check if a service exists in the service discovery.\n\t * Can check by service name or service instance.\n\t *\n\t * @param service - The service name or service instance to check\n\t * @returns True if the service exists, false otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (discovery.has('database')) {\n\t * const db = await discovery.get('database');\n\t * }\n\t *\n\t * // Or check with service instance\n\t * if (!discovery.has(databaseService)) {\n\t * await discovery.register([databaseService]);\n\t * }\n\t * ```\n\t */\n\thas(service: string | Service): boolean {\n\t\tif (typeof service === 'string') {\n\t\t\treturn this.services.has(service);\n\t\t}\n\n\t\treturn this.services.has(service.serviceName);\n\t}\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;\n * // type MyServiceRecord = {\n * // database: DatabaseInstance;\n * // cache: CacheInstance;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n\t[K in T[number] as K['serviceName']]: K extends Service\n\t\t? Awaited<ReturnType<K['register']>>\n\t\t: never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,mBAAb,MAAa,iBAAiE;;CAE7E,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;CAexB,OAAO,YACNA,WACsB;AACtB,OAAK,iBAAiB,UACrB,kBAAiB,YAAY,IAAI,iBAAoB;AAEtD,SAAO,iBAAiB;CACxB;;;;;;;;;;;;;CAcD,OAAO,QAAc;AACpB,mBAAiB;CACjB;;;;;CAMD,YAAqBA,WAAkC;EAAlC;CAAoC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BzD,MAAM,SAA8BC,UAAwC;EAC3E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC7B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IAClD,KACA;AACD;GACA;GAGD,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAAS;GACT,EAAC;AAEF,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC3B;EACD;AAED,SAAO;CACP;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACJ,OAAM,IAAI,OAAO,WAAW,KAAK;AAGlC,SAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAAS;EACT,EAAC;CACF;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACLC,OAC8C;EAC9C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MAClB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGpC,SAAO;CACP;;;;;;;;;;;;;;;;;;;;CAqBD,IAAIC,SAAoC;AACvC,aAAW,YAAY,SACtB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGlC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC7C;AACD"}
1
+ {"version":3,"file":"ServiceDiscovery-SujDuYHr.mjs","names":["envParser: EnvironmentParser<{}>","services: T","name: K","names: [...K]","service: string | Service"],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { serviceContext } from './context';\nimport type { Service } from './types';\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);\n *\n * // Register services\n * await discovery.register([\n * databaseService,\n * cacheService,\n * authService\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {\n\t/** Singleton instance of ServiceDiscovery */\n\tprivate static _instance: ServiceDiscovery<any>;\n\t/** Map of registered service definitions */\n\tprivate services = new Map<string, Service>();\n\t/** Map of instantiated service instances */\n\tprivate instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n\t/**\n\t * Gets the singleton instance of ServiceDiscovery.\n\t * Creates a new instance if one doesn't exist.\n\t *\n\t * @template T - Record type mapping service names to their instance types\n\t * @param envParser - Environment parser for service configuration\n\t * @returns The ServiceDiscovery singleton instance\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = ServiceDiscovery.getInstance<MyServices>(envParser);\n\t * ```\n\t */\n\tstatic getInstance<T extends Record<any, unknown> = any>(\n\t\tenvParser: EnvironmentParser<{}>,\n\t): ServiceDiscovery<T> {\n\t\tif (!ServiceDiscovery._instance) {\n\t\t\tServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);\n\t\t}\n\t\treturn ServiceDiscovery._instance as ServiceDiscovery<T>;\n\t}\n\n\t/**\n\t * Resets the singleton instance. Use only for testing purposes.\n\t * This clears all cached services and allows a fresh instance to be created.\n\t *\n\t * @example\n\t * ```typescript\n\t * // In test teardown\n\t * afterEach(() => {\n\t * ServiceDiscovery.reset();\n\t * });\n\t * ```\n\t */\n\tstatic reset(): void {\n\t\tServiceDiscovery._instance = undefined as any;\n\t}\n\n\t/**\n\t *\n\t * @param envParser - Environment parser for service configuration\n\t */\n\tconstructor(readonly envParser: EnvironmentParser<{}>) {}\n\n\t/**\n\t * Register multiple services with the service discovery.\n\t * Services are instantiated lazily on first access.\n\t * Already instantiated services are returned from cache.\n\t *\n\t * @template T - Array type of services to register\n\t * @param services - Array of services to register\n\t * @returns Promise resolving to a record of service names to instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = await discovery.register([\n\t * databaseService,\n\t * cacheService,\n\t * authService\n\t * ]);\n\t *\n\t * // services = {\n\t * // database: Database instance,\n\t * // cache: CacheService instance,\n\t * // auth: AuthService instance\n\t * // }\n\t * ```\n\t */\n\tasync register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n\t\tconst registeredServices = {} as ServiceRecord<T>;\n\t\tfor (const service of services) {\n\t\t\tconst name = service.serviceName as T[number]['serviceName'];\n\t\t\tif (this.instances.has(name)) {\n\t\t\t\t(registeredServices as any)[name] = this.instances.get(\n\t\t\t\t\tname,\n\t\t\t\t) as TServices[keyof TServices];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Pass both envParser and context to service\n\t\t\tconst instance = await service.register({\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\tcontext: serviceContext,\n\t\t\t});\n\n\t\t\tthis.instances.set(name, instance as TServices[keyof TServices]);\n\t\t\t(registeredServices as any)[name] =\n\t\t\t\tinstance as TServices[keyof TServices];\n\t\t}\n\n\t\treturn registeredServices;\n\t}\n\n\t/**\n\t * Get a service from the service discovery.\n\t * Services are instantiated on first access if not already cached.\n\t *\n\t * @template K - The service name key\n\t * @param name - The name of the service to get\n\t * @returns Promise resolving to the service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * const database = await discovery.get('database');\n\t * const users = await database.query('SELECT * FROM users');\n\t * ```\n\t */\n\tget<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n\t\tconst service = this.services.get(name);\n\n\t\tif (!service) {\n\t\t\tthrow new Error(`Service '${name}' not found in service discovery`);\n\t\t}\n\n\t\treturn service.register({\n\t\t\tenvParser: this.envParser,\n\t\t\tcontext: serviceContext,\n\t\t}) as Promise<TServices[K]>;\n\t}\n\t/**\n\t * Get multiple services from the service discovery.\n\t * Useful for retrieving multiple dependencies at once.\n\t *\n\t * @template K - Array of service name keys\n\t * @param names - Array of service names to retrieve\n\t * @returns Promise resolving to an object containing the service instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const { database, cache, auth } = await discovery.getMany([\n\t * 'database',\n\t * 'cache',\n\t * 'auth'\n\t * ]);\n\t * ```\n\t */\n\tasync getMany<K extends (keyof TServices & string)[]>(\n\t\tnames: [...K],\n\t): Promise<{ [P in K[number]]: TServices[P] }> {\n\t\tconst result = {} as { [P in K[number]]: TServices[P] };\n\n\t\tfor (const name of names) {\n\t\t\tresult[name] = await this.get(name);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check if a service exists in the service discovery.\n\t * Can check by service name or service instance.\n\t *\n\t * @param service - The service name or service instance to check\n\t * @returns True if the service exists, false otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (discovery.has('database')) {\n\t * const db = await discovery.get('database');\n\t * }\n\t *\n\t * // Or check with service instance\n\t * if (!discovery.has(databaseService)) {\n\t * await discovery.register([databaseService]);\n\t * }\n\t * ```\n\t */\n\thas(service: string | Service): boolean {\n\t\tif (typeof service === 'string') {\n\t\t\treturn this.services.has(service);\n\t\t}\n\n\t\treturn this.services.has(service.serviceName);\n\t}\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;\n * // type MyServiceRecord = {\n * // database: DatabaseInstance;\n * // cache: CacheInstance;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n\t[K in T[number] as K['serviceName']]: K extends Service\n\t\t? Awaited<ReturnType<K['register']>>\n\t\t: never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,mBAAb,MAAa,iBAAiE;;CAE7E,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;CAexB,OAAO,YACNA,WACsB;AACtB,OAAK,iBAAiB,UACrB,kBAAiB,YAAY,IAAI,iBAAoB;AAEtD,SAAO,iBAAiB;CACxB;;;;;;;;;;;;;CAcD,OAAO,QAAc;AACpB,mBAAiB;CACjB;;;;;CAMD,YAAqBA,WAAkC;EAAlC;CAAoC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BzD,MAAM,SAA8BC,UAAwC;EAC3E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC7B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IAClD,KACA;AACD;GACA;GAGD,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAAS;GACT,EAAC;AAEF,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC3B;EACD;AAED,SAAO;CACP;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACJ,OAAM,IAAI,OAAO,WAAW,KAAK;AAGlC,SAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAAS;EACT,EAAC;CACF;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACLC,OAC8C;EAC9C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MAClB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGpC,SAAO;CACP;;;;;;;;;;;;;;;;;;;;CAqBD,IAAIC,SAAoC;AACvC,aAAW,YAAY,SACtB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGlC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC7C;AACD"}
@@ -1,4 +1,4 @@
1
- require('./context-CoyHq8lH.cjs');
2
- const require_ServiceDiscovery = require('./ServiceDiscovery-C5x1wcN1.cjs');
1
+ require('./context-CkCPt2Fe.cjs');
2
+ const require_ServiceDiscovery = require('./ServiceDiscovery-Cxus7ber.cjs');
3
3
 
4
4
  exports.ServiceDiscovery = require_ServiceDiscovery.ServiceDiscovery;
@@ -1,3 +1,3 @@
1
- import "./types-D7d_yeU5.cjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-Dvqa-Q1_.cjs";
1
+ import "./types-BY9yrY6Y.cjs";
2
+ import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-DF4OKEZp.cjs";
3
3
  export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
@@ -1,3 +1,3 @@
1
- import "./types-CcHmCx_U.mjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-ykolgkIj.mjs";
1
+ import "./types-B99KrvXR.mjs";
2
+ import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-CadEgTKz.mjs";
3
3
  export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
@@ -1,4 +1,4 @@
1
- import "./context-BpYagzpr.mjs";
2
- import { ServiceDiscovery } from "./ServiceDiscovery-tZ6VKHIZ.mjs";
1
+ import "./context-BojeLlxs.mjs";
2
+ import { ServiceDiscovery } from "./ServiceDiscovery-SujDuYHr.mjs";
3
3
 
4
4
  export { ServiceDiscovery };
@@ -8,15 +8,72 @@ import { AsyncLocalStorage } from "node:async_hooks";
8
8
  */
9
9
  const requestContextStorage = new AsyncLocalStorage();
10
10
  /**
11
+ * Resolve the logger for the current request, or throw if there is none.
12
+ */
13
+ function resolveRequestLogger() {
14
+ const store = requestContextStorage.getStore();
15
+ if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
16
+ return store.logger;
17
+ }
18
+ /**
19
+ * Create a Logger that re-resolves its underlying logger on every call instead
20
+ * of capturing it once.
21
+ *
22
+ * This is what makes it safe for a **singleton** service to grab the logger a
23
+ * single time (e.g. during `register()`, which `ServiceDiscovery` only runs
24
+ * once and then caches) and reuse that reference for every request: each log
25
+ * call resolves the *current* request's logger from `AsyncLocalStorage`, so
26
+ * requests no longer inherit the first request's logger (and its `requestId`,
27
+ * user bindings, etc.).
28
+ *
29
+ * Implemented as a `Proxy` rather than a fixed list of methods so it forwards
30
+ * the *entire* surface of whatever logger is supplied — including members
31
+ * beyond the base `Logger` interface (e.g. a richer pino-backed logger's
32
+ * `flush()` or `level`) and any methods added to `Logger` in the future.
33
+ *
34
+ * @param bindings - `child()` bindings applied, in order, on top of the
35
+ * resolved logger before each call.
36
+ */
37
+ function createRequestScopedLogger(bindings = []) {
38
+ let cachedBase;
39
+ let cachedResolved;
40
+ const resolve = () => {
41
+ const base = resolveRequestLogger();
42
+ if (base !== cachedBase) {
43
+ cachedBase = base;
44
+ cachedResolved = bindings.reduce((log, obj) => log.child(obj), base);
45
+ }
46
+ return cachedResolved;
47
+ };
48
+ return new Proxy({}, {
49
+ get(_target, prop) {
50
+ if (prop === "child") return (obj) => createRequestScopedLogger([...bindings, obj]);
51
+ if (prop === "then" || typeof prop === "symbol") return void 0;
52
+ const value = resolve()[prop];
53
+ return typeof value === "function" ? (...args) => resolve()[prop](...args) : value;
54
+ },
55
+ has(_target, prop) {
56
+ if (prop === "child") return true;
57
+ if (prop === "then" || typeof prop === "symbol") return false;
58
+ return prop in resolve();
59
+ }
60
+ });
61
+ }
62
+ /**
63
+ * Stable, process-wide request-scoped logger proxy. Shared across requests on
64
+ * purpose — it carries no request state itself, delegating to the current
65
+ * `AsyncLocalStorage` store on each call.
66
+ */
67
+ const requestScopedLogger = createRequestScopedLogger();
68
+ /**
11
69
  * ServiceContext implementation.
12
70
  * Singleton that reads from AsyncLocalStorage.
13
71
  * Methods throw if called outside a request context (catches bugs early).
14
72
  */
15
73
  const serviceContext = {
16
74
  getLogger() {
17
- const store = requestContextStorage.getStore();
18
- if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
19
- return store.logger;
75
+ resolveRequestLogger();
76
+ return requestScopedLogger;
20
77
  },
21
78
  getRequestId() {
22
79
  const store = requestContextStorage.getStore();
@@ -81,4 +138,4 @@ function exitRequestContext() {
81
138
 
82
139
  //#endregion
83
140
  export { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
84
- //# sourceMappingURL=context-BpYagzpr.mjs.map
141
+ //# sourceMappingURL=context-BojeLlxs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-BojeLlxs.mjs","names":["bindings: object[]","cachedBase: Logger | undefined","cachedResolved: Logger | undefined","obj: object","serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * Resolve the logger for the current request, or throw if there is none.\n */\nfunction resolveRequestLogger(): Logger {\n\tconst store = requestContextStorage.getStore();\n\tif (!store) {\n\t\tthrow new Error(\n\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t);\n\t}\n\treturn store.logger;\n}\n\n/**\n * Create a Logger that re-resolves its underlying logger on every call instead\n * of capturing it once.\n *\n * This is what makes it safe for a **singleton** service to grab the logger a\n * single time (e.g. during `register()`, which `ServiceDiscovery` only runs\n * once and then caches) and reuse that reference for every request: each log\n * call resolves the *current* request's logger from `AsyncLocalStorage`, so\n * requests no longer inherit the first request's logger (and its `requestId`,\n * user bindings, etc.).\n *\n * Implemented as a `Proxy` rather than a fixed list of methods so it forwards\n * the *entire* surface of whatever logger is supplied — including members\n * beyond the base `Logger` interface (e.g. a richer pino-backed logger's\n * `flush()` or `level`) and any methods added to `Logger` in the future.\n *\n * @param bindings - `child()` bindings applied, in order, on top of the\n * resolved logger before each call.\n */\nfunction createRequestScopedLogger(bindings: object[] = []): Logger {\n\t// Memoise the resolved (optionally child) logger per underlying base logger\n\t// so we don't rebuild the child chain on every access within a request.\n\t// Recomputed whenever the current request's logger changes — there is no\n\t// await between the check and use, so this is safe under concurrency.\n\tlet cachedBase: Logger | undefined;\n\tlet cachedResolved: Logger | undefined;\n\n\tconst resolve = (): Logger => {\n\t\tconst base = resolveRequestLogger();\n\t\tif (base !== cachedBase) {\n\t\t\tcachedBase = base;\n\t\t\tcachedResolved = bindings.reduce<Logger>(\n\t\t\t\t(log, obj) => log.child(obj),\n\t\t\t\tbase,\n\t\t\t);\n\t\t}\n\t\treturn cachedResolved as Logger;\n\t};\n\n\treturn new Proxy({} as Logger, {\n\t\tget(_target, prop) {\n\t\t\t// `child()` must stay request-scoped: return a new proxy carrying the\n\t\t\t// extra binding, NOT the underlying logger's child (which would freeze\n\t\t\t// to the current request).\n\t\t\tif (prop === 'child') {\n\t\t\t\treturn (obj: object) => createRequestScopedLogger([...bindings, obj]);\n\t\t\t}\n\t\t\t// Never look like a thenable, and don't answer symbol/inspection probes\n\t\t\t// (util.inspect, Symbol.toPrimitive, etc.) with bound functions.\n\t\t\tif (prop === 'then' || typeof prop === 'symbol') {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst value = (resolve() as Record<string, unknown>)[prop];\n\t\t\t// Functions are re-resolved at *call* time so detached references\n\t\t\t// (`const info = logger.info`) still target the current request's\n\t\t\t// logger. Non-function members (e.g. `level`) forward as their live\n\t\t\t// value on the current request's logger.\n\t\t\treturn typeof value === 'function'\n\t\t\t\t? (...args: unknown[]) =>\n\t\t\t\t\t\t(resolve() as Record<string, (...a: unknown[]) => unknown>)[prop](\n\t\t\t\t\t\t\t...args,\n\t\t\t\t\t\t)\n\t\t\t\t: value;\n\t\t},\n\t\t// Keep `'prop' in logger` / hasOwnProperty truthful against the underlying\n\t\t// logger so feature-detection works.\n\t\thas(_target, prop) {\n\t\t\tif (prop === 'child') return true;\n\t\t\tif (prop === 'then' || typeof prop === 'symbol') return false;\n\t\t\treturn prop in (resolve() as object);\n\t\t},\n\t});\n}\n\n/**\n * Stable, process-wide request-scoped logger proxy. Shared across requests on\n * purpose — it carries no request state itself, delegating to the current\n * `AsyncLocalStorage` store on each call.\n */\nconst requestScopedLogger = createRequestScopedLogger();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\t// Throw eagerly if there is no context, preserving the \"catch bugs early\"\n\t\t// contract for callers that read the logger at an unexpected time.\n\t\tresolveRequestLogger();\n\t\t// Return the shared proxy rather than the raw `store.logger`. A service\n\t\t// that captures this once still logs against the correct per-request\n\t\t// logger because the proxy re-resolves on every call.\n\t\treturn requestScopedLogger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,wBAAwB,IAAI;;;;AAKlC,SAAS,uBAA+B;CACvC,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,MAAK,MACJ,OAAM,IAAI,MACT;AAIF,QAAO,MAAM;AACb;;;;;;;;;;;;;;;;;;;;AAqBD,SAAS,0BAA0BA,WAAqB,CAAE,GAAU;CAKnE,IAAIC;CACJ,IAAIC;CAEJ,MAAM,UAAU,MAAc;EAC7B,MAAM,OAAO,sBAAsB;AACnC,MAAI,SAAS,YAAY;AACxB,gBAAa;AACb,oBAAiB,SAAS,OACzB,CAAC,KAAK,QAAQ,IAAI,MAAM,IAAI,EAC5B,KACA;EACD;AACD,SAAO;CACP;AAED,QAAO,IAAI,MAAM,CAAE,GAAY;EAC9B,IAAI,SAAS,MAAM;AAIlB,OAAI,SAAS,QACZ,QAAO,CAACC,QAAgB,0BAA0B,CAAC,GAAG,UAAU,GAAI,EAAC;AAItE,OAAI,SAAS,iBAAiB,SAAS,SACtC;GAED,MAAM,QAAS,SAAS,CAA6B;AAKrD,iBAAc,UAAU,aACrB,CAAC,GAAG,SACJ,AAAC,SAAS,CAAkD,MAC3D,GAAG,KACH,GACD;EACH;EAGD,IAAI,SAAS,MAAM;AAClB,OAAI,SAAS,QAAS,QAAO;AAC7B,OAAI,SAAS,iBAAiB,SAAS,SAAU,QAAO;AACxD,UAAO,QAAS,SAAS;EACzB;CACD;AACD;;;;;;AAOD,MAAM,sBAAsB,2BAA2B;;;;;;AAOvD,MAAaC,iBAAiC;CAC7C,YAAY;AAGX,wBAAsB;AAItB,SAAO;CACP;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
@@ -31,15 +31,72 @@ const node_async_hooks = __toESM(require("node:async_hooks"));
31
31
  */
32
32
  const requestContextStorage = new node_async_hooks.AsyncLocalStorage();
33
33
  /**
34
+ * Resolve the logger for the current request, or throw if there is none.
35
+ */
36
+ function resolveRequestLogger() {
37
+ const store = requestContextStorage.getStore();
38
+ if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
39
+ return store.logger;
40
+ }
41
+ /**
42
+ * Create a Logger that re-resolves its underlying logger on every call instead
43
+ * of capturing it once.
44
+ *
45
+ * This is what makes it safe for a **singleton** service to grab the logger a
46
+ * single time (e.g. during `register()`, which `ServiceDiscovery` only runs
47
+ * once and then caches) and reuse that reference for every request: each log
48
+ * call resolves the *current* request's logger from `AsyncLocalStorage`, so
49
+ * requests no longer inherit the first request's logger (and its `requestId`,
50
+ * user bindings, etc.).
51
+ *
52
+ * Implemented as a `Proxy` rather than a fixed list of methods so it forwards
53
+ * the *entire* surface of whatever logger is supplied — including members
54
+ * beyond the base `Logger` interface (e.g. a richer pino-backed logger's
55
+ * `flush()` or `level`) and any methods added to `Logger` in the future.
56
+ *
57
+ * @param bindings - `child()` bindings applied, in order, on top of the
58
+ * resolved logger before each call.
59
+ */
60
+ function createRequestScopedLogger(bindings = []) {
61
+ let cachedBase;
62
+ let cachedResolved;
63
+ const resolve = () => {
64
+ const base = resolveRequestLogger();
65
+ if (base !== cachedBase) {
66
+ cachedBase = base;
67
+ cachedResolved = bindings.reduce((log, obj) => log.child(obj), base);
68
+ }
69
+ return cachedResolved;
70
+ };
71
+ return new Proxy({}, {
72
+ get(_target, prop) {
73
+ if (prop === "child") return (obj) => createRequestScopedLogger([...bindings, obj]);
74
+ if (prop === "then" || typeof prop === "symbol") return void 0;
75
+ const value = resolve()[prop];
76
+ return typeof value === "function" ? (...args) => resolve()[prop](...args) : value;
77
+ },
78
+ has(_target, prop) {
79
+ if (prop === "child") return true;
80
+ if (prop === "then" || typeof prop === "symbol") return false;
81
+ return prop in resolve();
82
+ }
83
+ });
84
+ }
85
+ /**
86
+ * Stable, process-wide request-scoped logger proxy. Shared across requests on
87
+ * purpose — it carries no request state itself, delegating to the current
88
+ * `AsyncLocalStorage` store on each call.
89
+ */
90
+ const requestScopedLogger = createRequestScopedLogger();
91
+ /**
34
92
  * ServiceContext implementation.
35
93
  * Singleton that reads from AsyncLocalStorage.
36
94
  * Methods throw if called outside a request context (catches bugs early).
37
95
  */
38
96
  const serviceContext = {
39
97
  getLogger() {
40
- const store = requestContextStorage.getStore();
41
- if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
42
- return store.logger;
98
+ resolveRequestLogger();
99
+ return requestScopedLogger;
43
100
  },
44
101
  getRequestId() {
45
102
  const store = requestContextStorage.getStore();
@@ -127,4 +184,4 @@ Object.defineProperty(exports, 'serviceContext', {
127
184
  return serviceContext;
128
185
  }
129
186
  });
130
- //# sourceMappingURL=context-CoyHq8lH.cjs.map
187
+ //# sourceMappingURL=context-CkCPt2Fe.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-CkCPt2Fe.cjs","names":["AsyncLocalStorage","bindings: object[]","cachedBase: Logger | undefined","cachedResolved: Logger | undefined","obj: object","serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * Resolve the logger for the current request, or throw if there is none.\n */\nfunction resolveRequestLogger(): Logger {\n\tconst store = requestContextStorage.getStore();\n\tif (!store) {\n\t\tthrow new Error(\n\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t);\n\t}\n\treturn store.logger;\n}\n\n/**\n * Create a Logger that re-resolves its underlying logger on every call instead\n * of capturing it once.\n *\n * This is what makes it safe for a **singleton** service to grab the logger a\n * single time (e.g. during `register()`, which `ServiceDiscovery` only runs\n * once and then caches) and reuse that reference for every request: each log\n * call resolves the *current* request's logger from `AsyncLocalStorage`, so\n * requests no longer inherit the first request's logger (and its `requestId`,\n * user bindings, etc.).\n *\n * Implemented as a `Proxy` rather than a fixed list of methods so it forwards\n * the *entire* surface of whatever logger is supplied — including members\n * beyond the base `Logger` interface (e.g. a richer pino-backed logger's\n * `flush()` or `level`) and any methods added to `Logger` in the future.\n *\n * @param bindings - `child()` bindings applied, in order, on top of the\n * resolved logger before each call.\n */\nfunction createRequestScopedLogger(bindings: object[] = []): Logger {\n\t// Memoise the resolved (optionally child) logger per underlying base logger\n\t// so we don't rebuild the child chain on every access within a request.\n\t// Recomputed whenever the current request's logger changes — there is no\n\t// await between the check and use, so this is safe under concurrency.\n\tlet cachedBase: Logger | undefined;\n\tlet cachedResolved: Logger | undefined;\n\n\tconst resolve = (): Logger => {\n\t\tconst base = resolveRequestLogger();\n\t\tif (base !== cachedBase) {\n\t\t\tcachedBase = base;\n\t\t\tcachedResolved = bindings.reduce<Logger>(\n\t\t\t\t(log, obj) => log.child(obj),\n\t\t\t\tbase,\n\t\t\t);\n\t\t}\n\t\treturn cachedResolved as Logger;\n\t};\n\n\treturn new Proxy({} as Logger, {\n\t\tget(_target, prop) {\n\t\t\t// `child()` must stay request-scoped: return a new proxy carrying the\n\t\t\t// extra binding, NOT the underlying logger's child (which would freeze\n\t\t\t// to the current request).\n\t\t\tif (prop === 'child') {\n\t\t\t\treturn (obj: object) => createRequestScopedLogger([...bindings, obj]);\n\t\t\t}\n\t\t\t// Never look like a thenable, and don't answer symbol/inspection probes\n\t\t\t// (util.inspect, Symbol.toPrimitive, etc.) with bound functions.\n\t\t\tif (prop === 'then' || typeof prop === 'symbol') {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst value = (resolve() as Record<string, unknown>)[prop];\n\t\t\t// Functions are re-resolved at *call* time so detached references\n\t\t\t// (`const info = logger.info`) still target the current request's\n\t\t\t// logger. Non-function members (e.g. `level`) forward as their live\n\t\t\t// value on the current request's logger.\n\t\t\treturn typeof value === 'function'\n\t\t\t\t? (...args: unknown[]) =>\n\t\t\t\t\t\t(resolve() as Record<string, (...a: unknown[]) => unknown>)[prop](\n\t\t\t\t\t\t\t...args,\n\t\t\t\t\t\t)\n\t\t\t\t: value;\n\t\t},\n\t\t// Keep `'prop' in logger` / hasOwnProperty truthful against the underlying\n\t\t// logger so feature-detection works.\n\t\thas(_target, prop) {\n\t\t\tif (prop === 'child') return true;\n\t\t\tif (prop === 'then' || typeof prop === 'symbol') return false;\n\t\t\treturn prop in (resolve() as object);\n\t\t},\n\t});\n}\n\n/**\n * Stable, process-wide request-scoped logger proxy. Shared across requests on\n * purpose — it carries no request state itself, delegating to the current\n * `AsyncLocalStorage` store on each call.\n */\nconst requestScopedLogger = createRequestScopedLogger();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\t// Throw eagerly if there is no context, preserving the \"catch bugs early\"\n\t\t// contract for callers that read the logger at an unexpected time.\n\t\tresolveRequestLogger();\n\t\t// Return the shared proxy rather than the raw `store.logger`. A service\n\t\t// that captures this once still logs against the correct per-request\n\t\t// logger because the proxy re-resolves on every call.\n\t\treturn requestScopedLogger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,wBAAwB,IAAIA;;;;AAKlC,SAAS,uBAA+B;CACvC,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,MAAK,MACJ,OAAM,IAAI,MACT;AAIF,QAAO,MAAM;AACb;;;;;;;;;;;;;;;;;;;;AAqBD,SAAS,0BAA0BC,WAAqB,CAAE,GAAU;CAKnE,IAAIC;CACJ,IAAIC;CAEJ,MAAM,UAAU,MAAc;EAC7B,MAAM,OAAO,sBAAsB;AACnC,MAAI,SAAS,YAAY;AACxB,gBAAa;AACb,oBAAiB,SAAS,OACzB,CAAC,KAAK,QAAQ,IAAI,MAAM,IAAI,EAC5B,KACA;EACD;AACD,SAAO;CACP;AAED,QAAO,IAAI,MAAM,CAAE,GAAY;EAC9B,IAAI,SAAS,MAAM;AAIlB,OAAI,SAAS,QACZ,QAAO,CAACC,QAAgB,0BAA0B,CAAC,GAAG,UAAU,GAAI,EAAC;AAItE,OAAI,SAAS,iBAAiB,SAAS,SACtC;GAED,MAAM,QAAS,SAAS,CAA6B;AAKrD,iBAAc,UAAU,aACrB,CAAC,GAAG,SACJ,AAAC,SAAS,CAAkD,MAC3D,GAAG,KACH,GACD;EACH;EAGD,IAAI,SAAS,MAAM;AAClB,OAAI,SAAS,QAAS,QAAO;AAC7B,OAAI,SAAS,iBAAiB,SAAS,SAAU,QAAO;AACxD,UAAO,QAAS,SAAS;EACzB;CACD;AACD;;;;;;AAOD,MAAM,sBAAsB,2BAA2B;;;;;;AAOvD,MAAaC,iBAAiC;CAC7C,YAAY;AAGX,wBAAsB;AAItB,SAAO;CACP;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
@@ -1,4 +1,4 @@
1
- import { ServiceContext } from "./types-D7d_yeU5.cjs";
1
+ import { ServiceContext } from "./types-BY9yrY6Y.cjs";
2
2
  import { Logger } from "@geekmidas/logger";
3
3
 
4
4
  //#region src/context.d.ts
@@ -61,4 +61,4 @@ declare function exitRequestContext(): void;
61
61
  //# sourceMappingURL=context.d.ts.map
62
62
  //#endregion
63
63
  export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
64
- //# sourceMappingURL=context-CaeISj3o.d.cts.map
64
+ //# sourceMappingURL=context-D5pIUGkm.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-D5pIUGkm.d.cts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAiHA;AA0DgB,UA3KC,kBAAA,CA2KoB;EAAA,MAAA,EA1K5B,MA0K4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;AAgBE,cA7EH,cA6EsB,EA7EN,cA6Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
@@ -1,4 +1,4 @@
1
- import { ServiceContext } from "./types-CcHmCx_U.mjs";
1
+ import { ServiceContext } from "./types-B99KrvXR.mjs";
2
2
  import { Logger } from "@geekmidas/logger";
3
3
 
4
4
  //#region src/context.d.ts
@@ -61,4 +61,4 @@ declare function exitRequestContext(): void;
61
61
  //# sourceMappingURL=context.d.ts.map
62
62
  //#endregion
63
63
  export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
64
- //# sourceMappingURL=context-HGC2PJzv.d.mts.map
64
+ //# sourceMappingURL=context-OmKid3Mr.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-OmKid3Mr.d.mts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAiHA;AA0DgB,UA3KC,kBAAA,CA2KoB;EAAA,MAAA,EA1K5B,MA0K4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;AAgBE,cA7EH,cA6EsB,EA7EN,cA6Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
package/dist/context.cjs CHANGED
@@ -1,4 +1,4 @@
1
- const require_context = require('./context-CoyHq8lH.cjs');
1
+ const require_context = require('./context-CkCPt2Fe.cjs');
2
2
 
3
3
  exports.enterRequestContext = require_context.enterRequestContext;
4
4
  exports.exitRequestContext = require_context.exitRequestContext;
@@ -1,3 +1,3 @@
1
- import "./types-D7d_yeU5.cjs";
2
- import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-CaeISj3o.cjs";
1
+ import "./types-BY9yrY6Y.cjs";
2
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-D5pIUGkm.cjs";
3
3
  export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
@@ -1,3 +1,3 @@
1
- import "./types-CcHmCx_U.mjs";
2
- import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-HGC2PJzv.mjs";
1
+ import "./types-B99KrvXR.mjs";
2
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-OmKid3Mr.mjs";
3
3
  export { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/context.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-BpYagzpr.mjs";
1
+ import { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-BojeLlxs.mjs";
2
2
 
3
3
  export { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- const require_context = require('./context-CoyHq8lH.cjs');
2
- const require_ServiceDiscovery = require('./ServiceDiscovery-C5x1wcN1.cjs');
1
+ const require_context = require('./context-CkCPt2Fe.cjs');
2
+ const require_ServiceDiscovery = require('./ServiceDiscovery-Cxus7ber.cjs');
3
3
 
4
4
  exports.ServiceDiscovery = require_ServiceDiscovery.ServiceDiscovery;
5
5
  exports.enterRequestContext = require_context.enterRequestContext;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-D7d_yeU5.cjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-Dvqa-Q1_.cjs";
3
- import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-CaeISj3o.cjs";
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-BY9yrY6Y.cjs";
2
+ import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-DF4OKEZp.cjs";
3
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-D5pIUGkm.cjs";
4
4
  export { ExtractServiceNames, RequestContextData, Service, ServiceContext, ServiceDiscovery, ServiceRecord, ServiceRegisterOptions, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-CcHmCx_U.mjs";
2
- import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-ykolgkIj.mjs";
3
- import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-HGC2PJzv.mjs";
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-B99KrvXR.mjs";
2
+ import { ExtractServiceNames, ServiceDiscovery, ServiceRecord } from "./ServiceDiscovery-CadEgTKz.mjs";
3
+ import { RequestContextData, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-OmKid3Mr.mjs";
4
4
  export { ExtractServiceNames, RequestContextData, Service, ServiceContext, ServiceDiscovery, ServiceRecord, ServiceRegisterOptions, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-BpYagzpr.mjs";
2
- import { ServiceDiscovery } from "./ServiceDiscovery-tZ6VKHIZ.mjs";
1
+ import { enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext } from "./context-BojeLlxs.mjs";
2
+ import { ServiceDiscovery } from "./ServiceDiscovery-SujDuYHr.mjs";
3
3
 
4
4
  export { ServiceDiscovery, enterRequestContext, exitRequestContext, runWithRequestContext, serviceContext };
@@ -11,6 +11,13 @@ import { Logger } from "@geekmidas/logger";
11
11
  interface ServiceContext {
12
12
  /**
13
13
  * Get the current request's logger.
14
+ *
15
+ * Returns a **request-scoped proxy** that re-resolves the underlying logger
16
+ * from AsyncLocalStorage on every call. This makes it safe for a singleton
17
+ * service to capture the logger once (e.g. during `register()`) and reuse it
18
+ * across requests — each log call routes to the current request's logger
19
+ * instead of freezing the first request's logger.
20
+ *
14
21
  * @throws Error if called outside a request context
15
22
  */
16
23
  getLogger(): Logger;
@@ -83,4 +90,4 @@ interface Service<TName extends string = string, TInstance = unknown> {
83
90
  //# sourceMappingURL=types.d.ts.map
84
91
  //#endregion
85
92
  export { Service, ServiceContext, ServiceRegisterOptions };
86
- //# sourceMappingURL=types-CcHmCx_U.d.mts.map
93
+ //# sourceMappingURL=types-B99KrvXR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-B99KrvXR.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAqCA;;AAEY,UAvCK,cAAA,CAuCL;EAAiB;AAEL;AA8BxB;;;;;;;AAW+D;;eAtEjD;;;;;;;;;;;;;;;;;;;;;UAyBG,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
@@ -11,6 +11,13 @@ import { Logger } from "@geekmidas/logger";
11
11
  interface ServiceContext {
12
12
  /**
13
13
  * Get the current request's logger.
14
+ *
15
+ * Returns a **request-scoped proxy** that re-resolves the underlying logger
16
+ * from AsyncLocalStorage on every call. This makes it safe for a singleton
17
+ * service to capture the logger once (e.g. during `register()`) and reuse it
18
+ * across requests — each log call routes to the current request's logger
19
+ * instead of freezing the first request's logger.
20
+ *
14
21
  * @throws Error if called outside a request context
15
22
  */
16
23
  getLogger(): Logger;
@@ -83,4 +90,4 @@ interface Service<TName extends string = string, TInstance = unknown> {
83
90
  //# sourceMappingURL=types.d.ts.map
84
91
  //#endregion
85
92
  export { Service, ServiceContext, ServiceRegisterOptions };
86
- //# sourceMappingURL=types-D7d_yeU5.d.cts.map
93
+ //# sourceMappingURL=types-BY9yrY6Y.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BY9yrY6Y.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAqCA;;AAEY,UAvCK,cAAA,CAuCL;EAAiB;AAEL;AA8BxB;;;;;;;AAW+D;;eAtEjD;;;;;;;;;;;;;;;;;;;;;UAyBG,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
package/dist/types.d.cts CHANGED
@@ -1,2 +1,2 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-D7d_yeU5.cjs";
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-BY9yrY6Y.cjs";
2
2
  export { Service, ServiceContext, ServiceRegisterOptions };
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { Service, ServiceContext, ServiceRegisterOptions } from "./types-CcHmCx_U.mjs";
1
+ import { Service, ServiceContext, ServiceRegisterOptions } from "./types-B99KrvXR.mjs";
2
2
  export { Service, ServiceContext, ServiceRegisterOptions };
@@ -0,0 +1,153 @@
1
+ # Request-Scoped Logging in Singleton Services
2
+
3
+ ## Problem
4
+
5
+ Services in `@geekmidas/services` are **singletons**. `ServiceDiscovery.register()`
6
+ (and `get()`) instantiates a service **once**, caches the instance in an internal
7
+ `Map`, and returns that same instance for every subsequent request:
8
+
9
+ ```ts
10
+ // ServiceDiscovery.register()
11
+ if (this.instances.has(name)) {
12
+ return this.instances.get(name); // cached — register() does NOT run again
13
+ }
14
+ const instance = await service.register({ envParser, context: serviceContext });
15
+ this.instances.set(name, instance);
16
+ ```
17
+
18
+ The per-request logger, on the other hand, is **not** a singleton. On every request
19
+ an adaptor builds a fresh child logger with request-specific bindings and stores it
20
+ in `AsyncLocalStorage` via `runWithRequestContext`:
21
+
22
+ ```ts
23
+ // e.g. HonoEndpointAdaptor
24
+ const logger = endpoint.logger.child({
25
+ requestId, // unique per request
26
+ endpoint, route, host, method, path,
27
+ });
28
+
29
+ return runWithRequestContext({ logger, requestId, startTime }, async () => {
30
+ const services = await serviceDiscovery.register(endpoint.services);
31
+ // ...handle request...
32
+ });
33
+ ```
34
+
35
+ ### The bug
36
+
37
+ `service.register()` runs **inside the first request's context**. If a service reads
38
+ the logger **at registration time** and stores the concrete reference:
39
+
40
+ ```ts
41
+ const databaseService = {
42
+ serviceName: 'database' as const,
43
+ register({ context }) {
44
+ const logger = context.getLogger(); // ❌ resolved ONCE, during request #1
45
+
46
+ return {
47
+ async query(sql: string) {
48
+ logger.debug({ sql }, 'Executing query'); // always request #1's logger
49
+ },
50
+ };
51
+ },
52
+ } satisfies Service<'database', Database>;
53
+ ```
54
+
55
+ …then `logger` is frozen to the **first** request's logger forever, because
56
+ `register()` never runs again. Every later request reuses the cached service
57
+ instance, so its logs carry the **first** request's `requestId` (and any user/session
58
+ bindings).
59
+
60
+ **Symptom:** logs make it look like the user who made the *first* request after a
61
+ cold start is responsible for actions actually performed by *other* users on later
62
+ requests. Request correlation, per-user log filtering, and audit trails are all
63
+ silently wrong.
64
+
65
+ This is an easy mistake to make because `register()` is handed a `context` object,
66
+ and "grab the logger once and reuse it" looks reasonable — but it is incompatible
67
+ with the singleton lifecycle.
68
+
69
+ ## Solution
70
+
71
+ `serviceContext.getLogger()` returns a **stable, request-scoped proxy logger**
72
+ instead of the raw logger. The proxy holds no logger of its own — on **every** log
73
+ call it re-resolves the current request's logger from `AsyncLocalStorage`:
74
+
75
+ ```
76
+ proxy.info('x') → asyncLocalStorage.getStore().logger.info('x') // resolved at call time
77
+ ```
78
+
79
+ Because resolution happens per call (not at capture time), capturing the logger once
80
+ during `register()` is now **safe**: the single captured reference routes each call
81
+ to whichever request is currently executing.
82
+
83
+ ```ts
84
+ register({ context }) {
85
+ const logger = context.getLogger(); // ✅ now safe to capture — it's a live proxy
86
+
87
+ return {
88
+ async query(sql: string) {
89
+ logger.debug({ sql }, 'Executing query'); // logs to the CURRENT request
90
+ },
91
+ };
92
+ }
93
+ ```
94
+
95
+ ### Child loggers compose correctly too
96
+
97
+ `proxy.child(bindings)` returns **another** proxy carrying the bindings, applied lazily
98
+ on top of the current request's logger at call time:
99
+
100
+ ```ts
101
+ register({ context }) {
102
+ // Captured once. `{ svc: 'db' }` is the static part; the per-request bindings
103
+ // (requestId, user, ...) come from whichever base logger is current.
104
+ const logger = context.getLogger().child({ svc: 'db' });
105
+
106
+ return {
107
+ async query(sql: string) {
108
+ // request A → loggerA.child({ svc: 'db' }).debug(...)
109
+ // request B → loggerB.child({ svc: 'db' }).debug(...)
110
+ logger.debug({ sql }, 'Executing query');
111
+ },
112
+ };
113
+ }
114
+ ```
115
+
116
+ ### Implementation
117
+
118
+ See `createRequestScopedLogger` in
119
+ [`src/context.ts`](../src/context.ts):
120
+
121
+ - `getLogger()` still **throws eagerly** if called with no active request context,
122
+ preserving the "catch bugs early" contract.
123
+ - The returned object is a shared, process-wide proxy. It carries no request state,
124
+ so sharing it across requests is safe — `AsyncLocalStorage` provides correct
125
+ per-async-context isolation, and each resolve/log call is synchronous (no `await`
126
+ between resolving and using the logger), so it is concurrency-safe.
127
+ - Each `child()` call returns a new proxy that remembers its bindings and rebuilds
128
+ the child chain off the current base logger, memoised per underlying logger to
129
+ avoid rebuilding the chain on every log line.
130
+
131
+ ## Guidance for service authors
132
+
133
+ - ✅ You **may** capture `context.getLogger()` (or a `.child()` of it) once in
134
+ `register()` and reuse it — it stays correct per request.
135
+ - ✅ You **may** also call `context.getLogger()` inside each method; behaviour is
136
+ identical.
137
+ - ⚠️ Do **not** wrap the proxy in something that snapshots a concrete logger, e.g.
138
+ `const real = someConcreteLogger; ...` outside the proxy. Resolution only stays
139
+ live while you go through the proxy returned by `getLogger()`/`.child()`.
140
+ - ⚠️ Calling a log method outside any request context throws
141
+ (`called outside request context`). Guard background work with
142
+ `serviceContext.hasContext()` if it may run detached from a request.
143
+
144
+ ## Tests
145
+
146
+ Regression coverage lives in
147
+ [`src/__tests__/context.spec.ts`](../src/__tests__/context.spec.ts):
148
+
149
+ - `captured-once logger follows each request (singleton service fix)` — a logger
150
+ captured during the first request still logs to the second request's logger.
151
+ - `child loggers also follow the current request` — the same guarantee for
152
+ `.child()` proxies.
153
+ - `should delegate to the current request logger` — basic delegation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/services",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,7 +1,40 @@
1
+ import type { Logger } from '@geekmidas/logger';
1
2
  import { ConsoleLogger } from '@geekmidas/logger/console';
2
- import { describe, expect, it } from 'vitest';
3
+ import { describe, expect, it, vi } from 'vitest';
3
4
  import { runWithRequestContext, serviceContext } from '../context';
4
5
 
6
+ /** Minimal spy logger whose `child()` returns itself for easy assertions. */
7
+ function makeSpyLogger(): Logger {
8
+ const logger: Logger = {
9
+ trace: vi.fn(),
10
+ debug: vi.fn(),
11
+ info: vi.fn(),
12
+ warn: vi.fn(),
13
+ error: vi.fn(),
14
+ fatal: vi.fn(),
15
+ child: vi.fn(() => logger),
16
+ };
17
+ return logger;
18
+ }
19
+
20
+ /**
21
+ * A logger that carries MORE than the base `Logger` interface: an extra method
22
+ * (`flush`) and a data property (`level`). Models a richer real-world logger
23
+ * (e.g. pino) so we can assert the request-scoped proxy forwards the full
24
+ * surface, not just the known log methods.
25
+ */
26
+ type ExtendedLogger = Logger & {
27
+ flush: ReturnType<typeof vi.fn>;
28
+ level: string;
29
+ };
30
+
31
+ function makeExtendedSpyLogger(level = 'info'): ExtendedLogger {
32
+ const logger = makeSpyLogger() as ExtendedLogger;
33
+ logger.flush = vi.fn();
34
+ logger.level = level;
35
+ return logger;
36
+ }
37
+
5
38
  describe('Request Context', () => {
6
39
  const logger = new ConsoleLogger({ app: 'test' });
7
40
 
@@ -28,13 +61,156 @@ describe('Request Context', () => {
28
61
  );
29
62
  });
30
63
 
31
- it('should return logger inside request context', async () => {
64
+ it('should delegate to the current request logger', async () => {
65
+ const requestLogger = makeSpyLogger();
32
66
  await runWithRequestContext(
33
- { logger, requestId: 'test-id', startTime: Date.now() },
67
+ {
68
+ logger: requestLogger,
69
+ requestId: 'test-id',
70
+ startTime: Date.now(),
71
+ },
34
72
  async () => {
35
- expect(serviceContext.getLogger()).toBe(logger);
73
+ serviceContext.getLogger().info('hello');
36
74
  },
37
75
  );
76
+ expect(requestLogger.info).toHaveBeenCalledWith('hello');
77
+ });
78
+
79
+ it('captured-once logger follows each request (singleton service fix)', async () => {
80
+ // Mimic a singleton service that grabs the logger ONCE (during its
81
+ // one-time register) and reuses that reference for every request.
82
+ let captured: Logger | undefined;
83
+ const handle = (requestLogger: Logger) =>
84
+ runWithRequestContext(
85
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
86
+ async () => {
87
+ captured ??= serviceContext.getLogger();
88
+ captured.info('handled');
89
+ },
90
+ );
91
+
92
+ const first = makeSpyLogger();
93
+ const second = makeSpyLogger();
94
+ await handle(first);
95
+ await handle(second);
96
+
97
+ // Before the fix, the captured logger stayed bound to `first`, so
98
+ // `second` never saw the call.
99
+ expect(first.info).toHaveBeenCalledTimes(1);
100
+ expect(second.info).toHaveBeenCalledTimes(1);
101
+ });
102
+
103
+ it('child loggers also follow the current request', async () => {
104
+ let capturedChild: Logger | undefined;
105
+ const handle = (requestLogger: Logger) =>
106
+ runWithRequestContext(
107
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
108
+ async () => {
109
+ capturedChild ??= serviceContext
110
+ .getLogger()
111
+ .child({ scope: 'svc' });
112
+ capturedChild.info('scoped');
113
+ },
114
+ );
115
+
116
+ const first = makeSpyLogger();
117
+ const second = makeSpyLogger();
118
+ await handle(first);
119
+ await handle(second);
120
+
121
+ expect(first.child).toHaveBeenCalledWith({ scope: 'svc' });
122
+ expect(second.child).toHaveBeenCalledWith({ scope: 'svc' });
123
+ expect(first.info).toHaveBeenCalledWith('scoped');
124
+ expect(second.info).toHaveBeenCalledWith('scoped');
125
+ });
126
+
127
+ describe('forwards the full logger surface (logger with more)', () => {
128
+ it('forwards an extra method beyond the Logger interface', async () => {
129
+ const requestLogger = makeExtendedSpyLogger();
130
+ await runWithRequestContext(
131
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
132
+ async () => {
133
+ (serviceContext.getLogger() as ExtendedLogger).flush();
134
+ },
135
+ );
136
+ expect(requestLogger.flush).toHaveBeenCalledTimes(1);
137
+ });
138
+
139
+ it('re-resolves an extra method per request when captured once', async () => {
140
+ let captured: ExtendedLogger | undefined;
141
+ const handle = (requestLogger: Logger) =>
142
+ runWithRequestContext(
143
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
144
+ async () => {
145
+ captured ??= serviceContext.getLogger() as ExtendedLogger;
146
+ captured.flush();
147
+ },
148
+ );
149
+
150
+ const first = makeExtendedSpyLogger();
151
+ const second = makeExtendedSpyLogger();
152
+ await handle(first);
153
+ await handle(second);
154
+
155
+ expect(first.flush).toHaveBeenCalledTimes(1);
156
+ expect(second.flush).toHaveBeenCalledTimes(1);
157
+ });
158
+
159
+ it('forwards a data property as the current request logger value', async () => {
160
+ const captureLevel = (requestLogger: Logger) =>
161
+ runWithRequestContext(
162
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
163
+ async () => (serviceContext.getLogger() as ExtendedLogger).level,
164
+ );
165
+
166
+ const debugLogger = makeExtendedSpyLogger('debug');
167
+ const warnLogger = makeExtendedSpyLogger('warn');
168
+
169
+ expect(await captureLevel(debugLogger)).toBe('debug');
170
+ expect(await captureLevel(warnLogger)).toBe('warn');
171
+ });
172
+
173
+ it('detached method reference still targets the current request', async () => {
174
+ const requestLogger = makeExtendedSpyLogger();
175
+ await runWithRequestContext(
176
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
177
+ async () => {
178
+ const { info } = serviceContext.getLogger();
179
+ info('detached');
180
+ },
181
+ );
182
+ expect(requestLogger.info).toHaveBeenCalledWith('detached');
183
+ });
184
+
185
+ it('reflects underlying membership via the `in` operator', async () => {
186
+ const requestLogger = makeExtendedSpyLogger();
187
+ await runWithRequestContext(
188
+ { logger: requestLogger, requestId: 'r', startTime: Date.now() },
189
+ async () => {
190
+ const proxy = serviceContext.getLogger();
191
+ expect('flush' in proxy).toBe(true);
192
+ expect('child' in proxy).toBe(true);
193
+ expect('nope' in proxy).toBe(false);
194
+ },
195
+ );
196
+ });
197
+
198
+ it('is not thenable (safe to return from async / await)', async () => {
199
+ await runWithRequestContext(
200
+ {
201
+ logger: makeExtendedSpyLogger(),
202
+ requestId: 'r',
203
+ startTime: Date.now(),
204
+ },
205
+ async () => {
206
+ const proxy = serviceContext.getLogger();
207
+ expect((proxy as { then?: unknown }).then).toBeUndefined();
208
+ // Awaiting a non-thenable yields the value itself rather than
209
+ // hanging or invoking a spurious `then`.
210
+ expect(await proxy).toBe(proxy);
211
+ },
212
+ );
213
+ });
38
214
  });
39
215
  });
40
216
 
package/src/context.ts CHANGED
@@ -19,6 +19,101 @@ export interface RequestContextData {
19
19
  */
20
20
  const requestContextStorage = new AsyncLocalStorage<RequestContextData>();
21
21
 
22
+ /**
23
+ * Resolve the logger for the current request, or throw if there is none.
24
+ */
25
+ function resolveRequestLogger(): Logger {
26
+ const store = requestContextStorage.getStore();
27
+ if (!store) {
28
+ throw new Error(
29
+ 'ServiceContext.getLogger() called outside request context. ' +
30
+ 'Ensure code runs within runWithRequestContext().',
31
+ );
32
+ }
33
+ return store.logger;
34
+ }
35
+
36
+ /**
37
+ * Create a Logger that re-resolves its underlying logger on every call instead
38
+ * of capturing it once.
39
+ *
40
+ * This is what makes it safe for a **singleton** service to grab the logger a
41
+ * single time (e.g. during `register()`, which `ServiceDiscovery` only runs
42
+ * once and then caches) and reuse that reference for every request: each log
43
+ * call resolves the *current* request's logger from `AsyncLocalStorage`, so
44
+ * requests no longer inherit the first request's logger (and its `requestId`,
45
+ * user bindings, etc.).
46
+ *
47
+ * Implemented as a `Proxy` rather than a fixed list of methods so it forwards
48
+ * the *entire* surface of whatever logger is supplied — including members
49
+ * beyond the base `Logger` interface (e.g. a richer pino-backed logger's
50
+ * `flush()` or `level`) and any methods added to `Logger` in the future.
51
+ *
52
+ * @param bindings - `child()` bindings applied, in order, on top of the
53
+ * resolved logger before each call.
54
+ */
55
+ function createRequestScopedLogger(bindings: object[] = []): Logger {
56
+ // Memoise the resolved (optionally child) logger per underlying base logger
57
+ // so we don't rebuild the child chain on every access within a request.
58
+ // Recomputed whenever the current request's logger changes — there is no
59
+ // await between the check and use, so this is safe under concurrency.
60
+ let cachedBase: Logger | undefined;
61
+ let cachedResolved: Logger | undefined;
62
+
63
+ const resolve = (): Logger => {
64
+ const base = resolveRequestLogger();
65
+ if (base !== cachedBase) {
66
+ cachedBase = base;
67
+ cachedResolved = bindings.reduce<Logger>(
68
+ (log, obj) => log.child(obj),
69
+ base,
70
+ );
71
+ }
72
+ return cachedResolved as Logger;
73
+ };
74
+
75
+ return new Proxy({} as Logger, {
76
+ get(_target, prop) {
77
+ // `child()` must stay request-scoped: return a new proxy carrying the
78
+ // extra binding, NOT the underlying logger's child (which would freeze
79
+ // to the current request).
80
+ if (prop === 'child') {
81
+ return (obj: object) => createRequestScopedLogger([...bindings, obj]);
82
+ }
83
+ // Never look like a thenable, and don't answer symbol/inspection probes
84
+ // (util.inspect, Symbol.toPrimitive, etc.) with bound functions.
85
+ if (prop === 'then' || typeof prop === 'symbol') {
86
+ return undefined;
87
+ }
88
+ const value = (resolve() as Record<string, unknown>)[prop];
89
+ // Functions are re-resolved at *call* time so detached references
90
+ // (`const info = logger.info`) still target the current request's
91
+ // logger. Non-function members (e.g. `level`) forward as their live
92
+ // value on the current request's logger.
93
+ return typeof value === 'function'
94
+ ? (...args: unknown[]) =>
95
+ (resolve() as Record<string, (...a: unknown[]) => unknown>)[prop](
96
+ ...args,
97
+ )
98
+ : value;
99
+ },
100
+ // Keep `'prop' in logger` / hasOwnProperty truthful against the underlying
101
+ // logger so feature-detection works.
102
+ has(_target, prop) {
103
+ if (prop === 'child') return true;
104
+ if (prop === 'then' || typeof prop === 'symbol') return false;
105
+ return prop in (resolve() as object);
106
+ },
107
+ });
108
+ }
109
+
110
+ /**
111
+ * Stable, process-wide request-scoped logger proxy. Shared across requests on
112
+ * purpose — it carries no request state itself, delegating to the current
113
+ * `AsyncLocalStorage` store on each call.
114
+ */
115
+ const requestScopedLogger = createRequestScopedLogger();
116
+
22
117
  /**
23
118
  * ServiceContext implementation.
24
119
  * Singleton that reads from AsyncLocalStorage.
@@ -26,14 +121,13 @@ const requestContextStorage = new AsyncLocalStorage<RequestContextData>();
26
121
  */
27
122
  export const serviceContext: ServiceContext = {
28
123
  getLogger() {
29
- const store = requestContextStorage.getStore();
30
- if (!store) {
31
- throw new Error(
32
- 'ServiceContext.getLogger() called outside request context. ' +
33
- 'Ensure code runs within runWithRequestContext().',
34
- );
35
- }
36
- return store.logger;
124
+ // Throw eagerly if there is no context, preserving the "catch bugs early"
125
+ // contract for callers that read the logger at an unexpected time.
126
+ resolveRequestLogger();
127
+ // Return the shared proxy rather than the raw `store.logger`. A service
128
+ // that captures this once still logs against the correct per-request
129
+ // logger because the proxy re-resolves on every call.
130
+ return requestScopedLogger;
37
131
  },
38
132
 
39
133
  getRequestId() {
package/src/types.ts CHANGED
@@ -9,6 +9,13 @@ import type { Logger } from '@geekmidas/logger';
9
9
  export interface ServiceContext {
10
10
  /**
11
11
  * Get the current request's logger.
12
+ *
13
+ * Returns a **request-scoped proxy** that re-resolves the underlying logger
14
+ * from AsyncLocalStorage on every call. This makes it safe for a singleton
15
+ * service to capture the logger once (e.g. during `register()`) and reuse it
16
+ * across requests — each log call routes to the current request's logger
17
+ * instead of freezing the first request's logger.
18
+ *
12
19
  * @throws Error if called outside a request context
13
20
  */
14
21
  getLogger(): Logger;
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-BpYagzpr.mjs","names":["serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.logger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,wBAAwB,IAAI;;;;;;AAOlC,MAAaA,iBAAiC;CAC7C,YAAY;EACX,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-CaeISj3o.d.cts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAkBA;AA2DgB,UA7EC,kBAAA,CA6EoB;EAAA,MAAA,EA5E5B,MA4E4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;AAgBE,cA9EH,cA8EsB,EA9EN,cA8Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-CoyHq8lH.cjs","names":["AsyncLocalStorage","serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.logger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,wBAAwB,IAAIA;;;;;;AAOlC,MAAaC,iBAAiC;CAC7C,YAAY;EACX,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-HGC2PJzv.d.mts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AAkBA;AA2DgB,UA7EC,kBAAA,CA6EoB;EAAA,MAAA,EA5E5B,MA4E4B;EAAA,SAC9B,EAAA,MAAA;EAAkB,SACd,EAAA,MAAA;;;;;;AACG;AAgBE,cA9EH,cA8EsB,EA9EN,cA8Ea;AAS1C;;;;;;;;;;;;;;;;;;;;iBA5BgB,+BACT,8BACI,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;iBAgBC,mBAAA,OAA0B;;;;;;iBAS1B,kBAAA,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-CcHmCx_U.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AA8BA;;AAEY,UAhCK,cAAA,CAgCL;EAAiB;AAEL;AA8BxB;;EAAwB,SAIV,EAAA,EA/DA,MA+DA;EAAK;;;;EAO4C,YAAA,EAAA,EAAA,MAAA;;;;;;;;;;;;;;;;UA7C9C,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-D7d_yeU5.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AA8BA;;AAEY,UAhCK,cAAA,CAgCL;EAAiB;AAEL;AA8BxB;;EAAwB,SAIV,EAAA,EA/DA,MA+DA;EAAK;;;;EAO4C,YAAA,EAAA,EAAA,MAAA;;;;;;;;;;;;;;;;UA7C9C,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}