@geekmidas/services 10.0.0-alpha.9 → 10.0.0-alpha.90
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.
- package/dist/{ServiceDiscovery-WHikQSQv.mjs → ServiceDiscovery-5LlW7BgD.mjs} +5 -5
- package/dist/ServiceDiscovery-5LlW7BgD.mjs.map +1 -0
- package/dist/{ServiceDiscovery-BrCUabG_.cjs → ServiceDiscovery-C1bAv6vY.cjs} +9 -9
- package/dist/ServiceDiscovery-C1bAv6vY.cjs.map +1 -0
- package/dist/{ServiceDiscovery-BO8W-RY8.d.cts → ServiceDiscovery-I7GKGDgi.d.mts} +5 -8
- package/dist/ServiceDiscovery-I7GKGDgi.d.mts.map +1 -0
- package/dist/{ServiceDiscovery-CRq_bGbi.d.mts → ServiceDiscovery-YbZxbSHi.d.cts} +5 -8
- package/dist/ServiceDiscovery-YbZxbSHi.d.cts.map +1 -0
- package/dist/context.cjs +156 -5
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +74 -3
- package/dist/context.d.cts.map +1 -0
- package/dist/context.d.mts +74 -3
- package/dist/context.d.mts.map +1 -0
- package/dist/context.mjs +152 -2
- package/dist/context.mjs.map +1 -0
- package/dist/index.cjs +5 -4
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -4
- package/dist/middy.cjs +4 -4
- package/dist/middy.cjs.map +1 -1
- package/dist/middy.d.cts +9 -13
- package/dist/middy.d.cts.map +1 -1
- package/dist/middy.d.mts +9 -13
- package/dist/middy.d.mts.map +1 -1
- package/dist/middy.mjs +3 -4
- package/dist/middy.mjs.map +1 -1
- package/dist/trpc.cjs +7 -7
- package/dist/trpc.cjs.map +1 -1
- package/dist/trpc.d.cts +8 -11
- package/dist/trpc.d.cts.map +1 -1
- package/dist/trpc.d.mts +8 -11
- package/dist/trpc.d.mts.map +1 -1
- package/dist/trpc.mjs +5 -6
- package/dist/trpc.mjs.map +1 -1
- package/dist/{types-Bgk-0NOO.d.cts → types-DDxt5Kcu.d.cts} +2 -5
- package/dist/types-DDxt5Kcu.d.cts.map +1 -0
- package/dist/{types-BoyOCa57.d.mts → types-DDxt5Kcu.d.mts} +2 -5
- package/dist/types-DDxt5Kcu.d.mts.map +1 -0
- package/package.json +7 -6
- package/dist/ServiceDiscovery-BO8W-RY8.d.cts.map +0 -1
- package/dist/ServiceDiscovery-BrCUabG_.cjs.map +0 -1
- package/dist/ServiceDiscovery-CRq_bGbi.d.mts.map +0 -1
- package/dist/ServiceDiscovery-WHikQSQv.mjs.map +0 -1
- package/dist/context-1ROj3zvL.cjs +0 -197
- package/dist/context-1ROj3zvL.cjs.map +0 -1
- package/dist/context-CH2c0ftq.mjs +0 -145
- package/dist/context-CH2c0ftq.mjs.map +0 -1
- package/dist/context-CU-87vsM.d.mts +0 -64
- package/dist/context-CU-87vsM.d.mts.map +0 -1
- package/dist/context-D2owD3ac.d.cts +0 -64
- package/dist/context-D2owD3ac.d.cts.map +0 -1
- package/dist/types-Bgk-0NOO.d.cts.map +0 -1
- package/dist/types-BoyOCa57.d.mts.map +0 -1
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { serviceContext } from "./context
|
|
2
|
-
|
|
1
|
+
import { serviceContext } from "./context.mjs";
|
|
3
2
|
//#region src/ServiceDiscovery.ts
|
|
4
3
|
/**
|
|
5
4
|
* Service discovery container that manages service registration and retrieval.
|
|
@@ -32,6 +31,7 @@ import { serviceContext } from "./context-CH2c0ftq.mjs";
|
|
|
32
31
|
* ```
|
|
33
32
|
*/
|
|
34
33
|
var ServiceDiscovery = class ServiceDiscovery {
|
|
34
|
+
envParser;
|
|
35
35
|
/** Singleton instance of ServiceDiscovery */
|
|
36
36
|
static _instance;
|
|
37
37
|
/** Map of registered service definitions */
|
|
@@ -187,7 +187,7 @@ var ServiceDiscovery = class ServiceDiscovery {
|
|
|
187
187
|
return this.services.has(service.serviceName);
|
|
188
188
|
}
|
|
189
189
|
};
|
|
190
|
-
|
|
191
190
|
//#endregion
|
|
192
|
-
export { ServiceDiscovery };
|
|
193
|
-
|
|
191
|
+
export { ServiceDiscovery as t };
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=ServiceDiscovery-5LlW7BgD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-5LlW7BgD.mjs","names":[],"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;CAkDxD;;CAhDrB,OAAe;;CAEf,2BAAmB,IAAI,IAAqB;;CAE5C,4BAAoB,IAAI,IAAiD;;;;;;;;;;;;;;CAezE,OAAO,YACN,WACsB;EACtB,IAAI,CAAC,iBAAiB,WACrB,iBAAiB,YAAY,IAAI,iBAAoB,SAAS;EAE/D,OAAO,iBAAiB;CACzB;;;;;;;;;;;;;CAcA,OAAO,QAAc;EACpB,iBAAiB,YAAY,KAAA;CAC9B;;;;;CAMA,YAAY,WAA2C;EAAlC,KAAA,YAAA;CAAmC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BxD,MAAM,SAA8B,UAAwC;EAC3E,MAAM,qBAAqB,CAAC;EAC5B,KAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;GACrB,IAAI,KAAK,UAAU,IAAI,IAAI,GAAG;IAC7B,mBAA4B,QAAQ,KAAK,UAAU,IAClD,IACD;IACA;GACD;GAGA,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAAS;GACV,CAAC;GAED,KAAK,UAAU,IAAI,MAAM,QAAsC;GAC/D,mBAA4B,QAC3B;EACF;EAEA,OAAO;CACR;;;;;;;;;;;;;;;;CAiBA,IAAwC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,IAAI;EAEtC,IAAI,CAAC,SACJ,MAAM,IAAI,MAAM,YAAY,KAAK,iCAAiC;EAGnE,OAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAAS;EACV,CAAC;CACF;;;;;;;;;;;;;;;;;;CAkBA,MAAM,QACL,OAC8C;EAC9C,MAAM,SAAS,CAAC;EAEhB,KAAK,MAAM,QAAQ,OAClB,OAAO,QAAQ,MAAM,KAAK,IAAI,IAAI;EAGnC,OAAO;CACR;;;;;;;;;;;;;;;;;;;;CAqBA,IAAI,SAAoC;EACvC,IAAI,OAAO,YAAY,UACtB,OAAO,KAAK,SAAS,IAAI,OAAO;EAGjC,OAAO,KAAK,SAAS,IAAI,QAAQ,WAAW;CAC7C;AACD"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
const require_context = require(
|
|
2
|
-
|
|
1
|
+
const require_context = require("./context.cjs");
|
|
3
2
|
//#region src/ServiceDiscovery.ts
|
|
4
3
|
/**
|
|
5
4
|
* Service discovery container that manages service registration and retrieval.
|
|
@@ -32,6 +31,7 @@ const require_context = require('./context-1ROj3zvL.cjs');
|
|
|
32
31
|
* ```
|
|
33
32
|
*/
|
|
34
33
|
var ServiceDiscovery = class ServiceDiscovery {
|
|
34
|
+
envParser;
|
|
35
35
|
/** Singleton instance of ServiceDiscovery */
|
|
36
36
|
static _instance;
|
|
37
37
|
/** Map of registered service definitions */
|
|
@@ -187,12 +187,12 @@ var ServiceDiscovery = class ServiceDiscovery {
|
|
|
187
187
|
return this.services.has(service.serviceName);
|
|
188
188
|
}
|
|
189
189
|
};
|
|
190
|
-
|
|
191
190
|
//#endregion
|
|
192
|
-
Object.defineProperty(exports,
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
191
|
+
Object.defineProperty(exports, "ServiceDiscovery", {
|
|
192
|
+
enumerable: true,
|
|
193
|
+
get: function() {
|
|
194
|
+
return ServiceDiscovery;
|
|
195
|
+
}
|
|
197
196
|
});
|
|
198
|
-
|
|
197
|
+
|
|
198
|
+
//# sourceMappingURL=ServiceDiscovery-C1bAv6vY.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-C1bAv6vY.cjs","names":["serviceContext"],"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;CAkDxD;;CAhDrB,OAAe;;CAEf,2BAAmB,IAAI,IAAqB;;CAE5C,4BAAoB,IAAI,IAAiD;;;;;;;;;;;;;;CAezE,OAAO,YACN,WACsB;EACtB,IAAI,CAAC,iBAAiB,WACrB,iBAAiB,YAAY,IAAI,iBAAoB,SAAS;EAE/D,OAAO,iBAAiB;CACzB;;;;;;;;;;;;;CAcA,OAAO,QAAc;EACpB,iBAAiB,YAAY,KAAA;CAC9B;;;;;CAMA,YAAY,WAA2C;EAAlC,KAAA,YAAA;CAAmC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BxD,MAAM,SAA8B,UAAwC;EAC3E,MAAM,qBAAqB,CAAC;EAC5B,KAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;GACrB,IAAI,KAAK,UAAU,IAAI,IAAI,GAAG;IAC7B,mBAA4B,QAAQ,KAAK,UAAU,IAClD,IACD;IACA;GACD;GAGA,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAASA,gBAAAA;GACV,CAAC;GAED,KAAK,UAAU,IAAI,MAAM,QAAsC;GAC/D,mBAA4B,QAC3B;EACF;EAEA,OAAO;CACR;;;;;;;;;;;;;;;;CAiBA,IAAwC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,IAAI;EAEtC,IAAI,CAAC,SACJ,MAAM,IAAI,MAAM,YAAY,KAAK,iCAAiC;EAGnE,OAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAASA,gBAAAA;EACV,CAAC;CACF;;;;;;;;;;;;;;;;;;CAkBA,MAAM,QACL,OAC8C;EAC9C,MAAM,SAAS,CAAC;EAEhB,KAAK,MAAM,QAAQ,OAClB,OAAO,QAAQ,MAAM,KAAK,IAAI,IAAI;EAGnC,OAAO;CACR;;;;;;;;;;;;;;;;;;;;CAqBA,IAAI,SAAoC;EACvC,IAAI,OAAO,YAAY,UACtB,OAAO,KAAK,SAAS,IAAI,OAAO;EAGjC,OAAO,KAAK,SAAS,IAAI,QAAQ,WAAW;CAC7C;AACD"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { Service } from "./types-
|
|
1
|
+
import { t as Service } from "./types-DDxt5Kcu.mjs";
|
|
2
2
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
3
|
-
|
|
4
3
|
//#region src/ServiceDiscovery.d.ts
|
|
5
|
-
|
|
6
4
|
/**
|
|
7
5
|
* Service discovery container that manages service registration and retrieval.
|
|
8
6
|
* Implements a singleton pattern with lazy initialization of services.
|
|
@@ -131,7 +129,7 @@ declare class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {
|
|
|
131
129
|
* ]);
|
|
132
130
|
* ```
|
|
133
131
|
*/
|
|
134
|
-
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P] }>;
|
|
132
|
+
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P]; }>;
|
|
135
133
|
/**
|
|
136
134
|
* Check if a service exists in the service discovery.
|
|
137
135
|
* Can check by service name or service instance.
|
|
@@ -180,8 +178,7 @@ type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];
|
|
|
180
178
|
* // }
|
|
181
179
|
* ```
|
|
182
180
|
*/
|
|
183
|
-
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never };
|
|
184
|
-
//# sourceMappingURL=ServiceDiscovery.d.ts.map
|
|
181
|
+
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never; };
|
|
185
182
|
//#endregion
|
|
186
|
-
export {
|
|
187
|
-
//# sourceMappingURL=ServiceDiscovery-
|
|
183
|
+
export { ServiceDiscovery as n, ServiceRecord as r, ExtractServiceNames as t };
|
|
184
|
+
//# sourceMappingURL=ServiceDiscovery-I7GKGDgi.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-I7GKGDgi.d.mts","names":[],"sources":["../src/ServiceDiscovery.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCa,iBAAiB,kBAAkB;WAkD1B,WAAW;;iBAhDjB;;UAEP;;UAEA;;;;;;;;;;;;;;SAeD,YAAY,UAAU,4BAC5B,WAAW,wBACT,iBAAiB;;;;;;;;;;;;;SAmBb;;;;;EAQP,YAAqB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;EA0B1B,SAAS,UAAU,WAAW,UAAU,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;EAwCxE,IAAI,gBAAgB,oBAAoB,MAAM,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;EA6B9D,QAAQ,iBAAiB,uBAC9B,WAAW,KACT,WAAW,KAAK,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;EA6BzC,IAAI,kBAAkB;;;;;;;;;;;;;KAoBX,oBAAoB,UAAU,aAAa;;;;;;;;;;;;;;;;KAiB3C,cAAc,UAAU,gBAClC,KAAK,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { Service } from "./types-
|
|
1
|
+
import { t as Service } from "./types-DDxt5Kcu.cjs";
|
|
2
2
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
3
|
-
|
|
4
3
|
//#region src/ServiceDiscovery.d.ts
|
|
5
|
-
|
|
6
4
|
/**
|
|
7
5
|
* Service discovery container that manages service registration and retrieval.
|
|
8
6
|
* Implements a singleton pattern with lazy initialization of services.
|
|
@@ -131,7 +129,7 @@ declare class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {
|
|
|
131
129
|
* ]);
|
|
132
130
|
* ```
|
|
133
131
|
*/
|
|
134
|
-
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P] }>;
|
|
132
|
+
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P]; }>;
|
|
135
133
|
/**
|
|
136
134
|
* Check if a service exists in the service discovery.
|
|
137
135
|
* Can check by service name or service instance.
|
|
@@ -180,8 +178,7 @@ type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];
|
|
|
180
178
|
* // }
|
|
181
179
|
* ```
|
|
182
180
|
*/
|
|
183
|
-
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never };
|
|
184
|
-
//# sourceMappingURL=ServiceDiscovery.d.ts.map
|
|
181
|
+
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never; };
|
|
185
182
|
//#endregion
|
|
186
|
-
export {
|
|
187
|
-
//# sourceMappingURL=ServiceDiscovery-
|
|
183
|
+
export { ServiceDiscovery as n, ServiceRecord as r, ExtractServiceNames as t };
|
|
184
|
+
//# sourceMappingURL=ServiceDiscovery-YbZxbSHi.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-YbZxbSHi.d.cts","names":[],"sources":["../src/ServiceDiscovery.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCa,iBAAiB,kBAAkB;WAkD1B,WAAW;;iBAhDjB;;UAEP;;UAEA;;;;;;;;;;;;;;SAeD,YAAY,UAAU,4BAC5B,WAAW,wBACT,iBAAiB;;;;;;;;;;;;;SAmBb;;;;;EAQP,YAAqB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;EA0B1B,SAAS,UAAU,WAAW,UAAU,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;EAwCxE,IAAI,gBAAgB,oBAAoB,MAAM,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;EA6B9D,QAAQ,iBAAiB,uBAC9B,WAAW,KACT,WAAW,KAAK,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;EA6BzC,IAAI,kBAAkB;;;;;;;;;;;;;KAoBX,oBAAoB,UAAU,aAAa;;;;;;;;;;;;;;;;KAiB3C,cAAc,UAAU,gBAClC,KAAK,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
|
package/dist/context.cjs
CHANGED
|
@@ -1,6 +1,157 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/context.ts
|
|
3
|
+
/**
|
|
4
|
+
* Internal AsyncLocalStorage instance for request context.
|
|
5
|
+
* Not exported - use runWithRequestContext() to establish context
|
|
6
|
+
* and serviceContext to access it.
|
|
7
|
+
*/
|
|
8
|
+
const requestContextStorage = new (require("node:async_hooks")).AsyncLocalStorage();
|
|
9
|
+
/**
|
|
10
|
+
* Resolve the logger for the current request, or throw if there is none.
|
|
11
|
+
*/
|
|
12
|
+
function resolveRequestLogger() {
|
|
13
|
+
const store = requestContextStorage.getStore();
|
|
14
|
+
if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
15
|
+
return store.logger;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Create a Logger that re-resolves its underlying logger on every call instead
|
|
19
|
+
* of capturing it once.
|
|
20
|
+
*
|
|
21
|
+
* This is what makes it safe for a **singleton** service to grab the logger a
|
|
22
|
+
* single time (e.g. during `register()`, which `ServiceDiscovery` only runs
|
|
23
|
+
* once and then caches) and reuse that reference for every request: each log
|
|
24
|
+
* call resolves the *current* request's logger from `AsyncLocalStorage`, so
|
|
25
|
+
* requests no longer inherit the first request's logger (and its `requestId`,
|
|
26
|
+
* user bindings, etc.).
|
|
27
|
+
*
|
|
28
|
+
* Implemented as a `Proxy` rather than a fixed list of methods so it forwards
|
|
29
|
+
* the *entire* surface of whatever logger is supplied — including members
|
|
30
|
+
* beyond the base `Logger` interface (e.g. a richer pino-backed logger's
|
|
31
|
+
* `flush()` or `level`) and any methods added to `Logger` in the future.
|
|
32
|
+
*
|
|
33
|
+
* @param bindings - `child()` bindings applied, in order, on top of the
|
|
34
|
+
* resolved logger before each call.
|
|
35
|
+
*/
|
|
36
|
+
function createRequestScopedLogger(bindings = []) {
|
|
37
|
+
let cachedBase;
|
|
38
|
+
let cachedResolved;
|
|
39
|
+
const resolve = () => {
|
|
40
|
+
const base = resolveRequestLogger();
|
|
41
|
+
if (base !== cachedBase) {
|
|
42
|
+
cachedBase = base;
|
|
43
|
+
cachedResolved = bindings.reduce((log, obj) => log.child(obj), base);
|
|
44
|
+
}
|
|
45
|
+
return cachedResolved;
|
|
46
|
+
};
|
|
47
|
+
return new Proxy({}, {
|
|
48
|
+
get(_target, prop) {
|
|
49
|
+
if (prop === "child") return (obj) => createRequestScopedLogger([...bindings, obj]);
|
|
50
|
+
if (prop === "then" || typeof prop === "symbol") return;
|
|
51
|
+
const value = resolve()[prop];
|
|
52
|
+
return typeof value === "function" ? (...args) => {
|
|
53
|
+
const resolved = resolve();
|
|
54
|
+
return resolved[prop].apply(resolved, args);
|
|
55
|
+
} : value;
|
|
56
|
+
},
|
|
57
|
+
has(_target, prop) {
|
|
58
|
+
if (prop === "child") return true;
|
|
59
|
+
if (prop === "then" || typeof prop === "symbol") return false;
|
|
60
|
+
return prop in resolve();
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Stable, process-wide request-scoped logger proxy. Shared across requests on
|
|
66
|
+
* purpose — it carries no request state itself, delegating to the current
|
|
67
|
+
* `AsyncLocalStorage` store on each call.
|
|
68
|
+
*/
|
|
69
|
+
const requestScopedLogger = createRequestScopedLogger();
|
|
70
|
+
/**
|
|
71
|
+
* ServiceContext implementation.
|
|
72
|
+
* Singleton that reads from AsyncLocalStorage.
|
|
73
|
+
* Methods throw if called outside a request context (catches bugs early).
|
|
74
|
+
*/
|
|
75
|
+
const serviceContext = {
|
|
76
|
+
getLogger() {
|
|
77
|
+
resolveRequestLogger();
|
|
78
|
+
return requestScopedLogger;
|
|
79
|
+
},
|
|
80
|
+
getRequestId() {
|
|
81
|
+
const store = requestContextStorage.getStore();
|
|
82
|
+
if (!store) throw new Error("ServiceContext.getRequestId() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
83
|
+
return store.requestId;
|
|
84
|
+
},
|
|
85
|
+
getRequestStartTime() {
|
|
86
|
+
const store = requestContextStorage.getStore();
|
|
87
|
+
if (!store) throw new Error("ServiceContext.getRequestStartTime() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
88
|
+
return store.startTime;
|
|
89
|
+
},
|
|
90
|
+
hasContext() {
|
|
91
|
+
return requestContextStorage.getStore() !== void 0;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* The current request's context, or undefined outside one.
|
|
96
|
+
*
|
|
97
|
+
* For code that annotates work when there is a request and carries on when
|
|
98
|
+
* there is not — tagging a query, say — where {@link serviceContext}'s
|
|
99
|
+
* accessors would throw.
|
|
100
|
+
*/
|
|
101
|
+
function currentRequestContext() {
|
|
102
|
+
return requestContextStorage.getStore();
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Run a function with request context.
|
|
106
|
+
* Used by endpoint/function/subscriber adaptors.
|
|
107
|
+
*
|
|
108
|
+
* @param data - Request context data (logger, requestId, startTime)
|
|
109
|
+
* @param fn - Function to run with context
|
|
110
|
+
* @returns Result of the function
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* const result = await runWithRequestContext(
|
|
115
|
+
* { logger, requestId, startTime: Date.now() },
|
|
116
|
+
* async () => {
|
|
117
|
+
* // Inside here, serviceContext.getLogger() returns `logger`
|
|
118
|
+
* // serviceContext.getRequestId() returns `requestId`
|
|
119
|
+
* return await handleRequest();
|
|
120
|
+
* }
|
|
121
|
+
* );
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
function runWithRequestContext(data, fn) {
|
|
125
|
+
return requestContextStorage.run(data, fn);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Mutate the current async task's store so that subsequent code in this task
|
|
129
|
+
* (and any descendants) sees the supplied request context.
|
|
130
|
+
*
|
|
131
|
+
* Unlike `runWithRequestContext`, this does not scope the context to a
|
|
132
|
+
* callback — useful when the caller can't wrap a function, for example in a
|
|
133
|
+
* Vitest fixture that suspends on `use()` and yields control to the test
|
|
134
|
+
* runner before the test body executes.
|
|
135
|
+
*
|
|
136
|
+
* **Test setup only.** In production handlers, prefer `runWithRequestContext`
|
|
137
|
+
* so the frame is automatically cleaned up.
|
|
138
|
+
*/
|
|
139
|
+
function enterRequestContext(data) {
|
|
140
|
+
requestContextStorage.enterWith(data);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Clear the request context for the current async task. Pairs with
|
|
144
|
+
* `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
|
|
145
|
+
* false for the remainder of the current async resource.
|
|
146
|
+
*/
|
|
147
|
+
function exitRequestContext() {
|
|
148
|
+
requestContextStorage.enterWith(void 0);
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
exports.currentRequestContext = currentRequestContext;
|
|
152
|
+
exports.enterRequestContext = enterRequestContext;
|
|
153
|
+
exports.exitRequestContext = exitRequestContext;
|
|
154
|
+
exports.runWithRequestContext = runWithRequestContext;
|
|
155
|
+
exports.serviceContext = serviceContext;
|
|
2
156
|
|
|
3
|
-
|
|
4
|
-
exports.exitRequestContext = require_context.exitRequestContext;
|
|
5
|
-
exports.runWithRequestContext = require_context.runWithRequestContext;
|
|
6
|
-
exports.serviceContext = require_context.serviceContext;
|
|
157
|
+
//# sourceMappingURL=context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["AsyncLocalStorage"],"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\t/**\n\t * What is running: `POST /orders`, `queue Emails`, `cron rate(1 day)`.\n\t * Carried so that work done on the request's behalf — a database query —\n\t * can say what it was done for.\n\t */\n\toperation?: string;\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 unknown 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// Re-resolve at call time so detached references target the\n\t\t\t\t\t\t// current request's logger, and invoke with that logger as\n\t\t\t\t\t\t// `this`: pino's log methods read internal state off the\n\t\t\t\t\t\t// receiver (`this[Symbol(pino.msgPrefix)]`), so calling them\n\t\t\t\t\t\t// unbound throws \"Cannot read properties of undefined\".\n\t\t\t\t\t\tconst resolved = resolve();\n\t\t\t\t\t\tconst fn = (resolved as unknown as Record<string, unknown>)[\n\t\t\t\t\t\t\tprop\n\t\t\t\t\t\t] as (...a: unknown[]) => unknown;\n\t\t\t\t\t\treturn fn.apply(resolved, args);\n\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 * The current request's context, or undefined outside one.\n *\n * For code that annotates work when there is a request and carries on when\n * there is not — tagging a query, say — where {@link serviceContext}'s\n * accessors would throw.\n */\nexport function currentRequestContext():\n\t| Readonly<RequestContextData>\n\t| undefined {\n\treturn requestContextStorage.getStore();\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":";;;;;;;AAyBA,MAAM,wBAAwB,+BAAIA,EAAAA,CAAAA,kBAAsC;;;;AAKxE,SAAS,uBAA+B;CACvC,MAAM,QAAQ,sBAAsB,SAAS;CAC7C,IAAI,CAAC,OACJ,MAAM,IAAI,MACT,6GAED;CAED,OAAO,MAAM;AACd;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,0BAA0B,WAAqB,CAAC,GAAW;CAKnE,IAAI;CACJ,IAAI;CAEJ,MAAM,gBAAwB;EAC7B,MAAM,OAAO,qBAAqB;EAClC,IAAI,SAAS,YAAY;GACxB,aAAa;GACb,iBAAiB,SAAS,QACxB,KAAK,QAAQ,IAAI,MAAM,GAAG,GAC3B,IACD;EACD;EACA,OAAO;CACR;CAEA,OAAO,IAAI,MAAM,CAAC,GAAa;EAC9B,IAAI,SAAS,MAAM;GAIlB,IAAI,SAAS,SACZ,QAAQ,QAAgB,0BAA0B,CAAC,GAAG,UAAU,GAAG,CAAC;GAIrE,IAAI,SAAS,UAAU,OAAO,SAAS,UACtC;GAED,MAAM,QAAS,QAAQ,CAAC,CAAwC;GAKhE,OAAO,OAAO,UAAU,cACpB,GAAG,SAAoB;IAMxB,MAAM,WAAW,QAAQ;IAIzB,OAHY,SACX,KAEQ,CAAC,MAAM,UAAU,IAAI;GAC/B,IACC;EACJ;EAGA,IAAI,SAAS,MAAM;GAClB,IAAI,SAAS,SAAS,OAAO;GAC7B,IAAI,SAAS,UAAU,OAAO,SAAS,UAAU,OAAO;GACxD,OAAO,QAAS,QAAQ;EACzB;CACD,CAAC;AACF;;;;;;AAOA,MAAM,sBAAsB,0BAA0B;;;;;;AAOtD,MAAa,iBAAiC;CAC7C,YAAY;EAGX,qBAAqB;EAIrB,OAAO;CACR;CAEA,eAAe;EACd,MAAM,QAAQ,sBAAsB,SAAS;EAC7C,IAAI,CAAC,OACJ,MAAM,IAAI,MACT,gHAED;EAED,OAAO,MAAM;CACd;CAEA,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,SAAS;EAC7C,IAAI,CAAC,OACJ,MAAM,IAAI,MACT,uHAED;EAED,OAAO,MAAM;CACd;CAEA,aAAa;EACZ,OAAO,sBAAsB,SAAS,MAAM,KAAA;CAC7C;AACD;;;;;;;;AASA,SAAgB,wBAEH;CACZ,OAAO,sBAAsB,SAAS;AACvC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,sBACf,MACA,IACiB;CACjB,OAAO,sBAAsB,IAAI,MAAM,EAAE;AAC1C;;;;;;;;;;;;;AAcA,SAAgB,oBAAoB,MAAgC;CACnE,sBAAsB,UAAU,IAAI;AACrC;;;;;;AAOA,SAAgB,qBAA2B;CAG1C,sBAAiE,UAChE,KAAA,CACD;AACD"}
|
package/dist/context.d.cts
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
import "./types-
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { n as ServiceContext } from "./types-DDxt5Kcu.cjs";
|
|
2
|
+
import { Logger } from "@geekmidas/logger";
|
|
3
|
+
//#region src/context.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Internal storage for request context data.
|
|
6
|
+
* Not exported - services use ServiceContext interface.
|
|
7
|
+
*/
|
|
8
|
+
export interface RequestContextData {
|
|
9
|
+
logger: Logger;
|
|
10
|
+
requestId: string;
|
|
11
|
+
startTime: number;
|
|
12
|
+
/**
|
|
13
|
+
* What is running: `POST /orders`, `queue Emails`, `cron rate(1 day)`.
|
|
14
|
+
* Carried so that work done on the request's behalf — a database query —
|
|
15
|
+
* can say what it was done for.
|
|
16
|
+
*/
|
|
17
|
+
operation?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* ServiceContext implementation.
|
|
21
|
+
* Singleton that reads from AsyncLocalStorage.
|
|
22
|
+
* Methods throw if called outside a request context (catches bugs early).
|
|
23
|
+
*/
|
|
24
|
+
export declare const serviceContext: ServiceContext;
|
|
25
|
+
/**
|
|
26
|
+
* The current request's context, or undefined outside one.
|
|
27
|
+
*
|
|
28
|
+
* For code that annotates work when there is a request and carries on when
|
|
29
|
+
* there is not — tagging a query, say — where {@link serviceContext}'s
|
|
30
|
+
* accessors would throw.
|
|
31
|
+
*/
|
|
32
|
+
export declare function currentRequestContext(): Readonly<RequestContextData> | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Run a function with request context.
|
|
35
|
+
* Used by endpoint/function/subscriber adaptors.
|
|
36
|
+
*
|
|
37
|
+
* @param data - Request context data (logger, requestId, startTime)
|
|
38
|
+
* @param fn - Function to run with context
|
|
39
|
+
* @returns Result of the function
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```typescript
|
|
43
|
+
* const result = await runWithRequestContext(
|
|
44
|
+
* { logger, requestId, startTime: Date.now() },
|
|
45
|
+
* async () => {
|
|
46
|
+
* // Inside here, serviceContext.getLogger() returns `logger`
|
|
47
|
+
* // serviceContext.getRequestId() returns `requestId`
|
|
48
|
+
* return await handleRequest();
|
|
49
|
+
* }
|
|
50
|
+
* );
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare function runWithRequestContext<T>(data: RequestContextData, fn: () => T | Promise<T>): T | Promise<T>;
|
|
54
|
+
/**
|
|
55
|
+
* Mutate the current async task's store so that subsequent code in this task
|
|
56
|
+
* (and any descendants) sees the supplied request context.
|
|
57
|
+
*
|
|
58
|
+
* Unlike `runWithRequestContext`, this does not scope the context to a
|
|
59
|
+
* callback — useful when the caller can't wrap a function, for example in a
|
|
60
|
+
* Vitest fixture that suspends on `use()` and yields control to the test
|
|
61
|
+
* runner before the test body executes.
|
|
62
|
+
*
|
|
63
|
+
* **Test setup only.** In production handlers, prefer `runWithRequestContext`
|
|
64
|
+
* so the frame is automatically cleaned up.
|
|
65
|
+
*/
|
|
66
|
+
export declare function enterRequestContext(data: RequestContextData): void;
|
|
67
|
+
/**
|
|
68
|
+
* Clear the request context for the current async task. Pairs with
|
|
69
|
+
* `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
|
|
70
|
+
* false for the remainder of the current async resource.
|
|
71
|
+
*/
|
|
72
|
+
export declare function exitRequestContext(): void;
|
|
73
|
+
//#endregion
|
|
74
|
+
//# sourceMappingURL=context.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.cts","names":[],"sources":["../src/context.ts"],"mappings":";;;;;;;iBAQiB;EAChB,QAAQ;EACR;EACA;;;;;;EAMA;;;;;;;qBAsHY,gBAAgB;;;;;;;;wBA6Cb,yBACb,SAAS;;;;;;;;;;;;;;;;;;;;;wBAyBI,sBAAsB,GACrC,MAAM,oBACN,UAAU,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;wBAgBC,oBAAoB,MAAM;;;;;;wBAS1B"}
|
package/dist/context.d.mts
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
import "./types-
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { n as ServiceContext } from "./types-DDxt5Kcu.mjs";
|
|
2
|
+
import { Logger } from "@geekmidas/logger";
|
|
3
|
+
//#region src/context.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Internal storage for request context data.
|
|
6
|
+
* Not exported - services use ServiceContext interface.
|
|
7
|
+
*/
|
|
8
|
+
export interface RequestContextData {
|
|
9
|
+
logger: Logger;
|
|
10
|
+
requestId: string;
|
|
11
|
+
startTime: number;
|
|
12
|
+
/**
|
|
13
|
+
* What is running: `POST /orders`, `queue Emails`, `cron rate(1 day)`.
|
|
14
|
+
* Carried so that work done on the request's behalf — a database query —
|
|
15
|
+
* can say what it was done for.
|
|
16
|
+
*/
|
|
17
|
+
operation?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* ServiceContext implementation.
|
|
21
|
+
* Singleton that reads from AsyncLocalStorage.
|
|
22
|
+
* Methods throw if called outside a request context (catches bugs early).
|
|
23
|
+
*/
|
|
24
|
+
export declare const serviceContext: ServiceContext;
|
|
25
|
+
/**
|
|
26
|
+
* The current request's context, or undefined outside one.
|
|
27
|
+
*
|
|
28
|
+
* For code that annotates work when there is a request and carries on when
|
|
29
|
+
* there is not — tagging a query, say — where {@link serviceContext}'s
|
|
30
|
+
* accessors would throw.
|
|
31
|
+
*/
|
|
32
|
+
export declare function currentRequestContext(): Readonly<RequestContextData> | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Run a function with request context.
|
|
35
|
+
* Used by endpoint/function/subscriber adaptors.
|
|
36
|
+
*
|
|
37
|
+
* @param data - Request context data (logger, requestId, startTime)
|
|
38
|
+
* @param fn - Function to run with context
|
|
39
|
+
* @returns Result of the function
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```typescript
|
|
43
|
+
* const result = await runWithRequestContext(
|
|
44
|
+
* { logger, requestId, startTime: Date.now() },
|
|
45
|
+
* async () => {
|
|
46
|
+
* // Inside here, serviceContext.getLogger() returns `logger`
|
|
47
|
+
* // serviceContext.getRequestId() returns `requestId`
|
|
48
|
+
* return await handleRequest();
|
|
49
|
+
* }
|
|
50
|
+
* );
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare function runWithRequestContext<T>(data: RequestContextData, fn: () => T | Promise<T>): T | Promise<T>;
|
|
54
|
+
/**
|
|
55
|
+
* Mutate the current async task's store so that subsequent code in this task
|
|
56
|
+
* (and any descendants) sees the supplied request context.
|
|
57
|
+
*
|
|
58
|
+
* Unlike `runWithRequestContext`, this does not scope the context to a
|
|
59
|
+
* callback — useful when the caller can't wrap a function, for example in a
|
|
60
|
+
* Vitest fixture that suspends on `use()` and yields control to the test
|
|
61
|
+
* runner before the test body executes.
|
|
62
|
+
*
|
|
63
|
+
* **Test setup only.** In production handlers, prefer `runWithRequestContext`
|
|
64
|
+
* so the frame is automatically cleaned up.
|
|
65
|
+
*/
|
|
66
|
+
export declare function enterRequestContext(data: RequestContextData): void;
|
|
67
|
+
/**
|
|
68
|
+
* Clear the request context for the current async task. Pairs with
|
|
69
|
+
* `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
|
|
70
|
+
* false for the remainder of the current async resource.
|
|
71
|
+
*/
|
|
72
|
+
export declare function exitRequestContext(): void;
|
|
73
|
+
//#endregion
|
|
74
|
+
//# sourceMappingURL=context.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.mts","names":[],"sources":["../src/context.ts"],"mappings":";;;;;;;iBAQiB;EAChB,QAAQ;EACR;EACA;;;;;;EAMA;;;;;;;qBAsHY,gBAAgB;;;;;;;;wBA6Cb,yBACb,SAAS;;;;;;;;;;;;;;;;;;;;;wBAyBI,sBAAsB,GACrC,MAAM,oBACN,UAAU,IAAI,QAAQ,KACpB,IAAI,QAAQ;;;;;;;;;;;;;wBAgBC,oBAAoB,MAAM;;;;;;wBAS1B"}
|