@forklaunch/core 1.5.2 → 1.5.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 (264) hide show
  1. package/lib/cache/{index.d.mts → cacheKey.d.ts} +2 -6
  2. package/lib/cache/cacheKey.d.ts.map +1 -0
  3. package/lib/cache/index.d.ts +4 -15
  4. package/lib/cache/index.d.ts.map +1 -0
  5. package/lib/{ttlCache.interface-B3xaLT00.d.ts → cache/interfaces/ttlCache.interface.d.ts} +3 -5
  6. package/lib/cache/interfaces/ttlCache.interface.d.ts.map +1 -0
  7. package/lib/{ttlCacheRecord.types-oX0ti5SP.d.mts → cache/types/ttlCacheRecord.types.d.ts} +3 -4
  8. package/lib/cache/types/ttlCacheRecord.types.d.ts.map +1 -0
  9. package/lib/controllers/index.d.ts +2 -13
  10. package/lib/controllers/index.d.ts.map +1 -0
  11. package/lib/controllers/{index.d.mts → interfaces/controller.interface.d.ts} +2 -3
  12. package/lib/controllers/interfaces/controller.interface.d.ts.map +1 -0
  13. package/lib/environment/index.d.ts +2 -28
  14. package/lib/environment/index.d.ts.map +1 -0
  15. package/lib/environment/{index.d.mts → loadCascadingEnv.d.ts} +4 -5
  16. package/lib/environment/loadCascadingEnv.d.ts.map +1 -0
  17. package/lib/http/application/expressLikeApplication.d.ts +34 -0
  18. package/lib/http/application/expressLikeApplication.d.ts.map +1 -0
  19. package/lib/http/bootstrap/listen.d.ts +2 -0
  20. package/lib/http/bootstrap/listen.d.ts.map +1 -0
  21. package/lib/http/cluster/cluster.types.d.ts +17 -0
  22. package/lib/http/cluster/cluster.types.d.ts.map +1 -0
  23. package/lib/http/cluster/isPortBound.d.ts +2 -0
  24. package/lib/http/cluster/isPortBound.d.ts.map +1 -0
  25. package/lib/http/createHmacToken.d.ts +19 -0
  26. package/lib/http/createHmacToken.d.ts.map +1 -0
  27. package/lib/http/discriminateAuthMethod.d.ts +85 -0
  28. package/lib/http/discriminateAuthMethod.d.ts.map +1 -0
  29. package/lib/http/generateHmacAuthHeaders.d.ts +31 -0
  30. package/lib/http/generateHmacAuthHeaders.d.ts.map +1 -0
  31. package/lib/http/guards/hasFeatureChecks.d.ts +2 -0
  32. package/lib/http/guards/hasFeatureChecks.d.ts.map +1 -0
  33. package/lib/http/guards/hasPermissionChecks.d.ts +2 -0
  34. package/lib/http/guards/hasPermissionChecks.d.ts.map +1 -0
  35. package/lib/http/guards/hasRoleChecks.d.ts +2 -0
  36. package/lib/http/guards/hasRoleChecks.d.ts.map +1 -0
  37. package/lib/http/guards/hasScopeChecks.d.ts +2 -0
  38. package/lib/http/guards/hasScopeChecks.d.ts.map +1 -0
  39. package/lib/http/guards/hasSend.d.ts +17 -0
  40. package/lib/http/guards/hasSend.d.ts.map +1 -0
  41. package/lib/http/guards/hasSubscriptionChecks.d.ts +2 -0
  42. package/lib/http/guards/hasSubscriptionChecks.d.ts.map +1 -0
  43. package/lib/http/guards/hasVersionedSchema.d.ts +2 -0
  44. package/lib/http/guards/hasVersionedSchema.d.ts.map +1 -0
  45. package/lib/http/guards/isBasicAuthMethod.d.ts +3 -0
  46. package/lib/http/guards/isBasicAuthMethod.d.ts.map +1 -0
  47. package/lib/http/guards/isConstrainedForklaunchRouter.d.ts +21 -0
  48. package/lib/http/guards/isConstrainedForklaunchRouter.d.ts.map +1 -0
  49. package/lib/http/guards/isExpressLikeSchemaHandler.d.ts +32 -0
  50. package/lib/http/guards/isExpressLikeSchemaHandler.d.ts.map +1 -0
  51. package/lib/http/guards/isForklaunchExpressLikeRouter.d.ts +28 -0
  52. package/lib/http/guards/isForklaunchExpressLikeRouter.d.ts.map +1 -0
  53. package/lib/http/guards/isForklaunchRequest.d.ts +26 -0
  54. package/lib/http/guards/isForklaunchRequest.d.ts.map +1 -0
  55. package/lib/http/guards/isForklaunchResponse.d.ts +23 -0
  56. package/lib/http/guards/isForklaunchResponse.d.ts.map +1 -0
  57. package/lib/http/guards/isForklaunchRouter.d.ts +21 -0
  58. package/lib/http/guards/isForklaunchRouter.d.ts.map +1 -0
  59. package/lib/http/guards/isHmacMethod.d.ts +9 -0
  60. package/lib/http/guards/isHmacMethod.d.ts.map +1 -0
  61. package/lib/http/guards/isHttpContractDetails.d.ts +29 -0
  62. package/lib/http/guards/isHttpContractDetails.d.ts.map +1 -0
  63. package/lib/http/guards/isJwtAuthMethod.d.ts +3 -0
  64. package/lib/http/guards/isJwtAuthMethod.d.ts.map +1 -0
  65. package/lib/http/guards/isLoggerMeta.d.ts +3 -0
  66. package/lib/http/guards/isLoggerMeta.d.ts.map +1 -0
  67. package/lib/http/guards/isPath.d.ts +2 -0
  68. package/lib/http/guards/isPath.d.ts.map +1 -0
  69. package/lib/http/guards/isPathParamContractDetails.d.ts +4 -0
  70. package/lib/http/guards/isPathParamContractDetails.d.ts.map +1 -0
  71. package/lib/http/guards/isRequestShape.d.ts +3 -0
  72. package/lib/http/guards/isRequestShape.d.ts.map +1 -0
  73. package/lib/http/guards/isResponseCompiledSchema.d.ts +3 -0
  74. package/lib/http/guards/isResponseCompiledSchema.d.ts.map +1 -0
  75. package/lib/http/guards/isSdkHandler.d.ts +9 -0
  76. package/lib/http/guards/isSdkHandler.d.ts.map +1 -0
  77. package/lib/http/guards/isSdkRouter.d.ts +9 -0
  78. package/lib/http/guards/isSdkRouter.d.ts.map +1 -0
  79. package/lib/http/guards/isTypedHandler.d.ts +5 -0
  80. package/lib/http/guards/isTypedHandler.d.ts.map +1 -0
  81. package/lib/http/guards/isVersionedInputSchema.d.ts +3 -0
  82. package/lib/http/guards/isVersionedInputSchema.d.ts.map +1 -0
  83. package/lib/http/handlers/delete.d.ts +5 -0
  84. package/lib/http/handlers/delete.d.ts.map +1 -0
  85. package/lib/http/handlers/get.d.ts +5 -0
  86. package/lib/http/handlers/get.d.ts.map +1 -0
  87. package/lib/http/handlers/head.d.ts +5 -0
  88. package/lib/http/handlers/head.d.ts.map +1 -0
  89. package/lib/http/handlers/middleware.d.ts +10 -0
  90. package/lib/http/handlers/middleware.d.ts.map +1 -0
  91. package/lib/http/handlers/options.d.ts +5 -0
  92. package/lib/http/handlers/options.d.ts.map +1 -0
  93. package/lib/http/handlers/patch.d.ts +5 -0
  94. package/lib/http/handlers/patch.d.ts.map +1 -0
  95. package/lib/http/handlers/post.d.ts +5 -0
  96. package/lib/http/handlers/post.d.ts.map +1 -0
  97. package/lib/http/handlers/put.d.ts +5 -0
  98. package/lib/http/handlers/put.d.ts.map +1 -0
  99. package/lib/http/handlers/trace.d.ts +5 -0
  100. package/lib/http/handlers/trace.d.ts.map +1 -0
  101. package/lib/http/handlers/typedAuthHandler.d.ts +5 -0
  102. package/lib/http/handlers/typedAuthHandler.d.ts.map +1 -0
  103. package/lib/http/handlers/typedHandler.d.ts +14 -0
  104. package/lib/http/handlers/typedHandler.d.ts.map +1 -0
  105. package/lib/http/httpStatusCodes.d.ts +75 -0
  106. package/lib/http/httpStatusCodes.d.ts.map +1 -0
  107. package/lib/http/index.d.ts +47 -1244
  108. package/lib/http/index.d.ts.map +1 -0
  109. package/lib/http/index.js +445 -410
  110. package/lib/http/index.js.map +1 -1
  111. package/lib/http/index.mjs +439 -407
  112. package/lib/http/index.mjs.map +1 -1
  113. package/lib/http/interfaces/expressLikeRouter.interface.d.ts +25 -0
  114. package/lib/http/interfaces/expressLikeRouter.interface.d.ts.map +1 -0
  115. package/lib/http/mcpGenerator/mcpGenerator.d.ts +17 -0
  116. package/lib/http/mcpGenerator/mcpGenerator.d.ts.map +1 -0
  117. package/lib/http/middleware/request/auth.middleware.d.ts +16 -0
  118. package/lib/http/middleware/request/auth.middleware.d.ts.map +1 -0
  119. package/lib/http/middleware/request/cors.middleware.d.ts +13 -0
  120. package/lib/http/middleware/request/cors.middleware.d.ts.map +1 -0
  121. package/lib/http/middleware/request/createContext.middleware.d.ts +15 -0
  122. package/lib/http/middleware/request/createContext.middleware.d.ts.map +1 -0
  123. package/lib/http/middleware/request/enrichDetails.middleware.d.ts +18 -0
  124. package/lib/http/middleware/request/enrichDetails.middleware.d.ts.map +1 -0
  125. package/lib/http/middleware/request/parse.middleware.d.ts +17 -0
  126. package/lib/http/middleware/request/parse.middleware.d.ts.map +1 -0
  127. package/lib/http/middleware/request/tenantContext.middleware.d.ts +41 -0
  128. package/lib/http/middleware/request/tenantContext.middleware.d.ts.map +1 -0
  129. package/lib/http/middleware/response/enrichExpressLikeSend.middleware.d.ts +32 -0
  130. package/lib/http/middleware/response/enrichExpressLikeSend.middleware.d.ts.map +1 -0
  131. package/lib/http/middleware/response/parse.middleware.d.ts +31 -0
  132. package/lib/http/middleware/response/parse.middleware.d.ts.map +1 -0
  133. package/lib/http/openApiV3Generator/openApiV3Generator.d.ts +17 -0
  134. package/lib/http/openApiV3Generator/openApiV3Generator.d.ts.map +1 -0
  135. package/lib/http/rateLimit/index.d.ts +2 -0
  136. package/lib/http/rateLimit/index.d.ts.map +1 -0
  137. package/lib/http/rateLimit/rateLimiter.d.ts +66 -0
  138. package/lib/http/rateLimit/rateLimiter.d.ts.map +1 -0
  139. package/lib/http/router/discriminateBody.d.ts +43 -0
  140. package/lib/http/router/discriminateBody.d.ts.map +1 -0
  141. package/lib/http/router/expressLikeRouter.d.ts +240 -0
  142. package/lib/http/router/expressLikeRouter.d.ts.map +1 -0
  143. package/lib/http/router/routerSharedLogic.d.ts +50 -0
  144. package/lib/http/router/routerSharedLogic.d.ts.map +1 -0
  145. package/lib/http/router/unpackRouters.d.ts +7 -0
  146. package/lib/http/router/unpackRouters.d.ts.map +1 -0
  147. package/lib/http/telemetry/auditLogger.d.ts +21 -0
  148. package/lib/http/telemetry/auditLogger.d.ts.map +1 -0
  149. package/lib/http/telemetry/constants.d.ts +6 -0
  150. package/lib/http/telemetry/constants.d.ts.map +1 -0
  151. package/lib/http/telemetry/evaluateTelemetryOptions.d.ts +11 -0
  152. package/lib/http/telemetry/evaluateTelemetryOptions.d.ts.map +1 -0
  153. package/lib/http/telemetry/metricsDefinition.d.ts +3 -0
  154. package/lib/http/telemetry/metricsDefinition.d.ts.map +1 -0
  155. package/lib/http/telemetry/openTelemetryCollector.d.ts +53 -0
  156. package/lib/http/telemetry/openTelemetryCollector.d.ts.map +1 -0
  157. package/lib/http/telemetry/pinoLogger.d.ts +20 -0
  158. package/lib/http/telemetry/pinoLogger.d.ts.map +1 -0
  159. package/lib/http/telemetry/recordMetric.d.ts +5 -0
  160. package/lib/http/telemetry/recordMetric.d.ts.map +1 -0
  161. package/lib/http/types/apiDefinition.types.d.ts +471 -0
  162. package/lib/http/types/apiDefinition.types.d.ts.map +1 -0
  163. package/lib/http/types/contractDetails.types.d.ts +404 -0
  164. package/lib/http/types/contractDetails.types.d.ts.map +1 -0
  165. package/lib/http/types/docsConfiguration.types.d.ts +7 -0
  166. package/lib/http/types/docsConfiguration.types.d.ts.map +1 -0
  167. package/lib/http/types/expressLikeOptions.d.ts +224 -0
  168. package/lib/http/types/expressLikeOptions.d.ts.map +1 -0
  169. package/lib/http/types/expressLikeRouter.types.d.ts +127 -0
  170. package/lib/http/types/expressLikeRouter.types.d.ts.map +1 -0
  171. package/lib/http/types/openTelemetryCollector.types.d.ts +21 -0
  172. package/lib/http/types/openTelemetryCollector.types.d.ts.map +1 -0
  173. package/lib/http/types/router.types.d.ts +52 -0
  174. package/lib/http/types/router.types.d.ts.map +1 -0
  175. package/lib/http/types/sdk.types.d.ts +259 -0
  176. package/lib/http/types/sdk.types.d.ts.map +1 -0
  177. package/lib/http/types/typedHandler.types.d.ts +18 -0
  178. package/lib/http/types/typedHandler.types.d.ts.map +1 -0
  179. package/lib/mappers/guards/isSchemaResolutionFunction.d.ts +10 -0
  180. package/lib/mappers/guards/isSchemaResolutionFunction.d.ts.map +1 -0
  181. package/lib/mappers/index.d.ts +3 -68
  182. package/lib/mappers/index.d.ts.map +1 -0
  183. package/lib/mappers/mapServiceSchemas.d.ts +33 -0
  184. package/lib/mappers/mapServiceSchemas.d.ts.map +1 -0
  185. package/lib/mappers/mapper.d.ts +26 -0
  186. package/lib/mappers/mapper.d.ts.map +1 -0
  187. package/lib/mappers/types/schemaResolution.types.d.ts +9 -0
  188. package/lib/mappers/types/schemaResolution.types.d.ts.map +1 -0
  189. package/lib/objectstore/index.d.ts +3 -71
  190. package/lib/objectstore/index.d.ts.map +1 -0
  191. package/lib/objectstore/{index.d.mts → interfaces/objectstore.interface.d.ts} +3 -16
  192. package/lib/objectstore/interfaces/objectstore.interface.d.ts.map +1 -0
  193. package/lib/objectstore/objectstoreKey.d.ts +11 -0
  194. package/lib/objectstore/objectstoreKey.d.ts.map +1 -0
  195. package/lib/persistence/complianceEventSubscriber.d.ts +13 -0
  196. package/lib/persistence/complianceEventSubscriber.d.ts.map +1 -0
  197. package/lib/persistence/compliancePropertyBuilder.d.ts +26 -0
  198. package/lib/persistence/compliancePropertyBuilder.d.ts.map +1 -0
  199. package/lib/persistence/complianceTypes.d.ts +64 -0
  200. package/lib/persistence/complianceTypes.d.ts.map +1 -0
  201. package/lib/persistence/defineComplianceEntity.d.ts +19 -0
  202. package/lib/persistence/defineComplianceEntity.d.ts.map +1 -0
  203. package/lib/persistence/encryptedType.d.ts +85 -0
  204. package/lib/persistence/encryptedType.d.ts.map +1 -0
  205. package/lib/persistence/fieldEncryptor.d.ts +48 -0
  206. package/lib/persistence/fieldEncryptor.d.ts.map +1 -0
  207. package/lib/persistence/index.d.ts +10 -403
  208. package/lib/persistence/index.d.ts.map +1 -0
  209. package/lib/persistence/index.js.map +1 -1
  210. package/lib/persistence/index.mjs.map +1 -1
  211. package/lib/persistence/rls.d.ts +56 -0
  212. package/lib/persistence/rls.d.ts.map +1 -0
  213. package/lib/persistence/tenantEm.d.ts +60 -0
  214. package/lib/persistence/tenantEm.d.ts.map +1 -0
  215. package/lib/persistence/tenantFilter.d.ts +47 -0
  216. package/lib/persistence/tenantFilter.d.ts.map +1 -0
  217. package/lib/secrets/index.d.ts +2 -0
  218. package/lib/secrets/index.d.ts.map +1 -0
  219. package/lib/secrets/secretsAccessor.d.ts +17 -0
  220. package/lib/secrets/secretsAccessor.d.ts.map +1 -0
  221. package/lib/services/complianceDataService.d.ts +47 -0
  222. package/lib/services/complianceDataService.d.ts.map +1 -0
  223. package/lib/services/configInjector.d.ts +43 -0
  224. package/lib/services/configInjector.d.ts.map +1 -0
  225. package/lib/services/guards/isConstructed.d.ts +3 -0
  226. package/lib/services/guards/isConstructed.d.ts.map +1 -0
  227. package/lib/services/guards/isConstructedSingleton.d.ts +3 -0
  228. package/lib/services/guards/isConstructedSingleton.d.ts.map +1 -0
  229. package/lib/services/guards/isConstructor.d.ts +3 -0
  230. package/lib/services/guards/isConstructor.d.ts.map +1 -0
  231. package/lib/services/index.d.ts +10 -184
  232. package/lib/services/index.d.ts.map +1 -0
  233. package/lib/services/retentionService.d.ts +31 -0
  234. package/lib/services/retentionService.d.ts.map +1 -0
  235. package/lib/services/runRetentionEnforcement.d.ts +19 -0
  236. package/lib/services/runRetentionEnforcement.d.ts.map +1 -0
  237. package/lib/services/types/configInjector.types.d.ts +39 -0
  238. package/lib/services/types/configInjector.types.d.ts.map +1 -0
  239. package/lib/services/types/entityManager.types.d.ts +4 -0
  240. package/lib/services/types/entityManager.types.d.ts.map +1 -0
  241. package/lib/services/types/service.types.d.ts +5 -0
  242. package/lib/services/types/service.types.d.ts.map +1 -0
  243. package/lib/ws/asyncApiV3Generator/asyncApiV3Generator.d.ts +12 -0
  244. package/lib/ws/asyncApiV3Generator/asyncApiV3Generator.d.ts.map +1 -0
  245. package/lib/ws/index.d.ts +4 -67
  246. package/lib/ws/index.d.ts.map +1 -0
  247. package/lib/ws/index.js.map +1 -1
  248. package/lib/ws/index.mjs.map +1 -1
  249. package/lib/ws/types/eventSchema.types.d.ts +28 -0
  250. package/lib/ws/types/eventSchema.types.d.ts.map +1 -0
  251. package/lib/ws/webSocketLike.d.ts +18 -0
  252. package/lib/ws/webSocketLike.d.ts.map +1 -0
  253. package/package.json +33 -33
  254. package/lib/apiDefinition.types-DF_crhB0.d.mts +0 -1092
  255. package/lib/apiDefinition.types-DW4lfZqy.d.ts +0 -1092
  256. package/lib/http/index.d.mts +0 -1244
  257. package/lib/mappers/index.d.mts +0 -68
  258. package/lib/openTelemetryCollector-BS-ej09T.d.mts +0 -70
  259. package/lib/openTelemetryCollector-BS-ej09T.d.ts +0 -70
  260. package/lib/persistence/index.d.mts +0 -403
  261. package/lib/services/index.d.mts +0 -185
  262. package/lib/ttlCache.interface-CEOkrt8d.d.mts +0 -77
  263. package/lib/ttlCacheRecord.types-oX0ti5SP.d.ts +0 -25
  264. package/lib/ws/index.d.mts +0 -67
@@ -1,68 +0,0 @@
1
- import { Prettify } from '@forklaunch/common';
2
- import { AnySchemaValidator, IdiomaticSchema, Schema } from '@forklaunch/validator';
3
- import { EntitySchema, InferEntity } from '@mikro-orm/core';
4
-
5
- declare function requestMapper<SV extends AnySchemaValidator, DomainSchema extends IdiomaticSchema<SV>, Entity extends EntitySchema, AdditionalArgs extends unknown[] = []>({ schemaValidator, schema, entity, mapperDefinition }: {
6
- schemaValidator: SV;
7
- schema: DomainSchema;
8
- entity: Entity;
9
- mapperDefinition: {
10
- toEntity: (dto: Schema<DomainSchema, SV>, ...args: AdditionalArgs) => Promise<InferEntity<Entity>>;
11
- };
12
- }): {
13
- entity: Entity;
14
- schema: DomainSchema;
15
- } & typeof mapperDefinition;
16
- declare function responseMapper<SV extends AnySchemaValidator, DomainSchema extends IdiomaticSchema<SV>, Entity extends EntitySchema, AdditionalArgs extends unknown[] = []>({ schemaValidator, schema, entity, mapperDefinition }: {
17
- schemaValidator: SV;
18
- schema: DomainSchema;
19
- entity: Entity;
20
- mapperDefinition: {
21
- toDto: (entity: InferEntity<Entity>, ...args: AdditionalArgs) => Promise<Schema<DomainSchema, SV>>;
22
- };
23
- }): Prettify<{
24
- entity: Entity;
25
- schema: DomainSchema;
26
- } & typeof mapperDefinition>;
27
-
28
- /**
29
- * A function type that, given an options object, returns a schema or schema-like object.
30
- *
31
- * @template Args - The type of the options object, typically an object with configuration or dependencies.
32
- * @param {Args} options - The options to use for schema resolution (e.g., validator, uuidId, etc.).
33
- * @returns {unknown} The resolved schema or schema-like object.
34
- */
35
- type SchemaResolutionFunction<Args extends Record<string, unknown>> = (options: Args) => unknown;
36
-
37
- /**
38
- * Maps a set of service schema factories or pre-instantiated schemas to their resolved schemas using the provided arguments.
39
- *
40
- * This utility allows you to provide an object whose values are either:
41
- * - Schema factory functions (SchemaResolutionFunction) that accept an options object (Args) and return a schema or schema group.
42
- * - Already-instantiated schemas (IdiomaticSchema).
43
- *
44
- * Each factory function will be called with the provided `args` object, and the result will be included in the returned mapping.
45
- * If a value is already a schema (not a function), it is returned as-is.
46
- *
47
- * @template SV - The schema validator type.
48
- * @template T - An object whose values are either schema factory functions or instantiated schemas.
49
- * @template Args - The type of the options object passed to each factory function (e.g., { validator, uuidId, ... }).
50
- *
51
- * @param {T} schemas - An object mapping schema names to either factory functions (SchemaResolutionFunction) or instantiated schemas (IdiomaticSchema).
52
- * @param {Args} args - The options object to be passed to each schema factory function.
53
- * @returns {{ [K in keyof T]: T[K] extends SchemaResolutionFunction<Args> ? ReturnType<T[K]> : T[K] }} An object mapping each schema name to its resolved schema.
54
- *
55
- * @example
56
- * const schemas = {
57
- * UserSchemas: (opts) => createUserSchemas(opts),
58
- * ProductSchemas: (opts) => createProductSchemas(opts),
59
- * AlreadyInstantiated: someSchemaObject
60
- * };
61
- * const mapped = mapServiceSchemas(schemas, { validator: myValidator });
62
- * // mapped.UserSchemas and mapped.ProductSchemas are instantiated, mapped.AlreadyInstantiated is passed through
63
- */
64
- declare function mapServiceSchemas<SV extends AnySchemaValidator, T extends Record<string, SchemaResolutionFunction<Args> | IdiomaticSchema<SV>>, Args extends Record<string, unknown>>(schemas: T, args: Args): {
65
- [K in keyof T]: T[K] extends SchemaResolutionFunction<Args> ? ReturnType<T[K]> : T[K];
66
- };
67
-
68
- export { mapServiceSchemas, requestMapper, responseMapper };
@@ -1,70 +0,0 @@
1
- import { Counter, Gauge, Histogram, UpDownCounter, ObservableCounter, ObservableGauge, ObservableUpDownCounter } from '@opentelemetry/api';
2
- import pino, { LevelWithSilentOrString, Logger, LevelWithSilent } from 'pino';
3
- import { AnyValueMap } from '@opentelemetry/api-logs';
4
-
5
- type MetricType<T extends string> = T extends 'counter' ? Counter : T extends 'gauge' ? Gauge : T extends 'histogram' ? Histogram : T extends 'upDownCounter' ? UpDownCounter : T extends 'observableCounter' ? ObservableCounter : T extends 'observableGauge' ? ObservableGauge : T extends 'observableUpDownCounter' ? ObservableUpDownCounter : undefined;
6
- type MetricsDefinition = Record<string, 'counter' | 'gauge' | 'histogram' | 'upDownCounter' | 'observableCounter' | 'observableGauge' | 'observableUpDownCounter'>;
7
- type LoggerMeta = Record<string, unknown> & {
8
- _meta: true;
9
- };
10
- interface LogFn {
11
- <T extends object>(obj: T | LoggerMeta, msg?: string | LoggerMeta, ...args: unknown[]): void;
12
- (obj: unknown | LoggerMeta, msg?: string | LoggerMeta, ...args: unknown[]): void;
13
- (msg: string | LoggerMeta, ...args: unknown[]): void;
14
- }
15
- interface TelemetryOptions {
16
- enabled: boolean | {
17
- metrics?: boolean;
18
- tracing?: boolean;
19
- logging?: boolean;
20
- };
21
- level: LevelWithSilentOrString;
22
- }
23
-
24
- declare function meta(meta: Record<string, unknown>): LoggerMeta;
25
- declare class PinoLogger {
26
- _pinoLogger: Logger;
27
- _meta: AnyValueMap;
28
- constructor(level: LevelWithSilentOrString, meta?: AnyValueMap);
29
- log(level: LevelWithSilent, ...args: (string | unknown | LoggerMeta)[]): void;
30
- error: LogFn;
31
- info: LogFn;
32
- debug: LogFn;
33
- warn: LogFn;
34
- trace: LogFn;
35
- child(meta?: AnyValueMap): PinoLogger;
36
- getBaseLogger(): pino.Logger;
37
- }
38
- declare function logger(level: LevelWithSilentOrString, meta?: AnyValueMap): PinoLogger;
39
-
40
- declare class OpenTelemetryCollector<AppliedMetricsDefinition extends MetricsDefinition> {
41
- _logger: PinoLogger;
42
- _serviceName: string;
43
- _metrics: Record<keyof AppliedMetricsDefinition, Counter | Gauge | Histogram | UpDownCounter | ObservableCounter | ObservableGauge | ObservableUpDownCounter>;
44
- constructor(serviceName: string, level?: LevelWithSilentOrString, metricDefinitions?: AppliedMetricsDefinition);
45
- log(level: LevelWithSilent, ...args: (string | unknown | LoggerMeta)[]): void;
46
- info: LogFn;
47
- error: LogFn;
48
- warn: LogFn;
49
- debug: LogFn;
50
- trace: LogFn;
51
- getMetric<T extends keyof AppliedMetricsDefinition>(metricId: T): MetricType<AppliedMetricsDefinition[T]>;
52
- }
53
- declare const httpRequestsTotalCounter: Counter<{
54
- "service.name": string;
55
- application_id?: string;
56
- "api.name": string;
57
- "http.request.method": string;
58
- "http.route": string;
59
- "http.response.status_code": number;
60
- }>;
61
- declare const httpServerDurationHistogram: Histogram<{
62
- "service.name": string;
63
- application_id?: string;
64
- "api.name": string;
65
- "http.request.method": string;
66
- "http.route": string;
67
- "http.response.status_code": number;
68
- }>;
69
-
70
- export { type LogFn as L, type MetricsDefinition as M, OpenTelemetryCollector as O, PinoLogger as P, type TelemetryOptions as T, type LoggerMeta as a, type MetricType as b, httpServerDurationHistogram as c, httpRequestsTotalCounter as h, logger as l, meta as m };
@@ -1,70 +0,0 @@
1
- import { Counter, Gauge, Histogram, UpDownCounter, ObservableCounter, ObservableGauge, ObservableUpDownCounter } from '@opentelemetry/api';
2
- import pino, { LevelWithSilentOrString, Logger, LevelWithSilent } from 'pino';
3
- import { AnyValueMap } from '@opentelemetry/api-logs';
4
-
5
- type MetricType<T extends string> = T extends 'counter' ? Counter : T extends 'gauge' ? Gauge : T extends 'histogram' ? Histogram : T extends 'upDownCounter' ? UpDownCounter : T extends 'observableCounter' ? ObservableCounter : T extends 'observableGauge' ? ObservableGauge : T extends 'observableUpDownCounter' ? ObservableUpDownCounter : undefined;
6
- type MetricsDefinition = Record<string, 'counter' | 'gauge' | 'histogram' | 'upDownCounter' | 'observableCounter' | 'observableGauge' | 'observableUpDownCounter'>;
7
- type LoggerMeta = Record<string, unknown> & {
8
- _meta: true;
9
- };
10
- interface LogFn {
11
- <T extends object>(obj: T | LoggerMeta, msg?: string | LoggerMeta, ...args: unknown[]): void;
12
- (obj: unknown | LoggerMeta, msg?: string | LoggerMeta, ...args: unknown[]): void;
13
- (msg: string | LoggerMeta, ...args: unknown[]): void;
14
- }
15
- interface TelemetryOptions {
16
- enabled: boolean | {
17
- metrics?: boolean;
18
- tracing?: boolean;
19
- logging?: boolean;
20
- };
21
- level: LevelWithSilentOrString;
22
- }
23
-
24
- declare function meta(meta: Record<string, unknown>): LoggerMeta;
25
- declare class PinoLogger {
26
- _pinoLogger: Logger;
27
- _meta: AnyValueMap;
28
- constructor(level: LevelWithSilentOrString, meta?: AnyValueMap);
29
- log(level: LevelWithSilent, ...args: (string | unknown | LoggerMeta)[]): void;
30
- error: LogFn;
31
- info: LogFn;
32
- debug: LogFn;
33
- warn: LogFn;
34
- trace: LogFn;
35
- child(meta?: AnyValueMap): PinoLogger;
36
- getBaseLogger(): pino.Logger;
37
- }
38
- declare function logger(level: LevelWithSilentOrString, meta?: AnyValueMap): PinoLogger;
39
-
40
- declare class OpenTelemetryCollector<AppliedMetricsDefinition extends MetricsDefinition> {
41
- _logger: PinoLogger;
42
- _serviceName: string;
43
- _metrics: Record<keyof AppliedMetricsDefinition, Counter | Gauge | Histogram | UpDownCounter | ObservableCounter | ObservableGauge | ObservableUpDownCounter>;
44
- constructor(serviceName: string, level?: LevelWithSilentOrString, metricDefinitions?: AppliedMetricsDefinition);
45
- log(level: LevelWithSilent, ...args: (string | unknown | LoggerMeta)[]): void;
46
- info: LogFn;
47
- error: LogFn;
48
- warn: LogFn;
49
- debug: LogFn;
50
- trace: LogFn;
51
- getMetric<T extends keyof AppliedMetricsDefinition>(metricId: T): MetricType<AppliedMetricsDefinition[T]>;
52
- }
53
- declare const httpRequestsTotalCounter: Counter<{
54
- "service.name": string;
55
- application_id?: string;
56
- "api.name": string;
57
- "http.request.method": string;
58
- "http.route": string;
59
- "http.response.status_code": number;
60
- }>;
61
- declare const httpServerDurationHistogram: Histogram<{
62
- "service.name": string;
63
- application_id?: string;
64
- "api.name": string;
65
- "http.request.method": string;
66
- "http.route": string;
67
- "http.response.status_code": number;
68
- }>;
69
-
70
- export { type LogFn as L, type MetricsDefinition as M, OpenTelemetryCollector as O, PinoLogger as P, type TelemetryOptions as T, type LoggerMeta as a, type MetricType as b, httpServerDurationHistogram as c, httpRequestsTotalCounter as h, logger as l, meta as m };
@@ -1,403 +0,0 @@
1
- import { PropertyBuilders, EntityMetadataWithProperties, EntitySchemaWithMeta, InferEntityFromProperties, Type, Platform, TransformContext, FilterDef, EntityManager, EventSubscriber, MikroORM } from '@mikro-orm/core';
2
-
3
- declare const ComplianceLevel: {
4
- readonly pii: "pii";
5
- readonly phi: "phi";
6
- readonly pci: "pci";
7
- readonly none: "none";
8
- };
9
- type ComplianceLevel = (typeof ComplianceLevel)[keyof typeof ComplianceLevel];
10
- declare function getComplianceMetadata(entityName: string, fieldName: string): ComplianceLevel;
11
- declare function getEntityComplianceFields(entityName: string): Map<string, ComplianceLevel> | undefined;
12
- declare function entityHasEncryptedFields(entityName: string): boolean;
13
- declare const RetentionAction: {
14
- readonly delete: "delete";
15
- readonly anonymize: "anonymize";
16
- };
17
- type RetentionAction = (typeof RetentionAction)[keyof typeof RetentionAction];
18
- interface RetentionPolicy {
19
- duration: string;
20
- action: RetentionAction;
21
- }
22
- declare const RetentionDuration: {
23
- readonly days: (n: number) => string;
24
- readonly months: (n: number) => string;
25
- readonly years: (n: number) => string;
26
- };
27
- interface ParsedDuration {
28
- years: number;
29
- months: number;
30
- days: number;
31
- }
32
- /**
33
- * Parse an ISO 8601 duration string into calendar units.
34
- * Returns structured units to enable calendar-aware date arithmetic.
35
- */
36
- declare function parseDuration(iso: string): ParsedDuration;
37
- /**
38
- * Subtract a parsed duration from a date using calendar-aware arithmetic.
39
- * Handles month-end clamping and leap years correctly.
40
- */
41
- declare function subtractDuration(from: Date, duration: ParsedDuration): Date;
42
- declare function getEntityUserIdField(entityName: string): string;
43
- declare function getAllUserIdFields(): ReadonlyMap<string, string>;
44
- declare function getEntityRetention(entityName: string): RetentionPolicy | undefined;
45
- declare function getAllRetentionPolicies(): ReadonlyMap<string, RetentionPolicy>;
46
- /**
47
- * Adds `compliance` to PropertyOptions, which flows into IncludeKeys
48
- * for all scalar/enum/embedded builders (PropertyOptions is extended by
49
- * EnumOptions and EmbeddedOptions). Relation builders use ReferenceOptions
50
- * instead, so they don't get .compliance() — which is what we want.
51
- */
52
- declare module '@mikro-orm/core' {
53
- interface PropertyOptions<Owner> {
54
- compliance?: ComplianceLevel;
55
- }
56
- interface UniversalPropertyOptionsBuilder<Value, Options, IncludeKeys> {
57
- compliance(level: ComplianceLevel): Pick<UniversalPropertyOptionsBuilder<Value, Options & {
58
- readonly '~c': true;
59
- }, IncludeKeys>, IncludeKeys & keyof UniversalPropertyOptionsBuilder<never, never, never>>;
60
- }
61
- }
62
-
63
- /**
64
- * ForkLaunch property builder. Drop-in replacement for MikroORM's `p`
65
- * that adds `.compliance(level)` to every scalar property builder
66
- * and auto-classifies relation builders as 'none'.
67
- *
68
- * - Scalar fields: `fp.string().compliance('pii')` — must call `.compliance()`
69
- * - Relation fields: `fp.manyToOne(Target)` — auto-classified, no `.compliance()` needed
70
- *
71
- * @example
72
- * ```typescript
73
- * import { defineComplianceEntity, fp } from '@forklaunch/core/persistence';
74
- *
75
- * const User = defineComplianceEntity({
76
- * name: 'User',
77
- * properties: {
78
- * id: fp.uuid().primary().compliance('none'),
79
- * email: fp.string().unique().compliance('pii'),
80
- * medicalRecord: fp.string().nullable().compliance('phi'),
81
- * organization: () => fp.manyToOne(Organization).nullable(),
82
- * }
83
- * });
84
- * ```
85
- */
86
- declare const fp: PropertyBuilders;
87
-
88
- type ValidateProperties<T> = {
89
- [K in keyof T]: T[K] extends {
90
- '~options': {
91
- readonly '~c': true;
92
- };
93
- } | ((...args: never[]) => unknown) ? T[K] : {
94
- '~options': {
95
- readonly '~c': true;
96
- };
97
- };
98
- };
99
- declare function defineComplianceEntity<const TName extends string, const TTableName extends string, const TProperties extends Record<string, unknown>, const TPK extends (keyof TProperties)[] | undefined = undefined, const TBase = never, const TRepository = never, const TForceObject extends boolean = false>(meta: EntityMetadataWithProperties<TName, TTableName, TProperties & ValidateProperties<TProperties>, TPK, TBase, TRepository, TForceObject> & {
100
- retention?: RetentionPolicy;
101
- userIdField?: string;
102
- }): EntitySchemaWithMeta<TName, TTableName, InferEntityFromProperties<TProperties, TPK, TBase, TRepository, TForceObject>, TBase, TProperties>;
103
-
104
- /**
105
- * Wraps an EntityManager to block `nativeInsert`, `nativeUpdate`, and
106
- * `nativeDelete` on entities that have PII, PHI, or PCI compliance fields.
107
- *
108
- * This prevents bypassing the EncryptedType's encryption by using raw
109
- * queries. Call this in the tenant context middleware when creating the
110
- * request-scoped EM.
111
- *
112
- * @returns A Proxy-wrapped EntityManager that throws on native query
113
- * operations targeting compliance entities.
114
- */
115
- declare function wrapEmWithNativeQueryBlocking<T extends object>(em: T): T;
116
-
117
- declare class MissingEncryptionKeyError extends Error {
118
- readonly name: "MissingEncryptionKeyError";
119
- constructor(message?: string);
120
- }
121
- declare class DecryptionError extends Error {
122
- readonly name: "DecryptionError";
123
- constructor(message?: string);
124
- }
125
- declare class EncryptionRequiredError extends Error {
126
- readonly name: "EncryptionRequiredError";
127
- constructor(message?: string);
128
- }
129
- declare class FieldEncryptor {
130
- private readonly masterKey;
131
- constructor(masterKey: string);
132
- /**
133
- * Derive a per-tenant 32-byte key using HKDF-SHA256.
134
- * The master key is used as input key material and the tenantId as info context.
135
- */
136
- deriveKey(tenantId: string): Buffer;
137
- /**
138
- * Derive a deterministic IV from the key and plaintext using HMAC-SHA256,
139
- * truncated to IV_BYTES. Same plaintext + same key → same IV → same
140
- * ciphertext. This enables WHERE clause matching on encrypted columns
141
- * while maintaining AES-256-GCM authenticated encryption.
142
- *
143
- * Meets SOC 2, HIPAA, PCI DSS, GDPR requirements for encryption at rest.
144
- */
145
- private deriveDeterministicIv;
146
- /**
147
- * Encrypt a plaintext string.
148
- *
149
- * Uses deterministic encryption (HMAC-derived IV) so the same plaintext
150
- * always produces the same ciphertext. This enables database WHERE clause
151
- * matching and UNIQUE constraints on encrypted columns.
152
- *
153
- * @returns Format: `v2:{base64(iv)}:{base64(authTag)}:{base64(ciphertext)}`
154
- */
155
- encrypt(plaintext: string | null): string | null;
156
- encrypt(plaintext: string | null, tenantId: string): string | null;
157
- /**
158
- * Decrypt a ciphertext string produced by {@link encrypt}.
159
- * Supports both v1 (random IV) and v2 (deterministic IV) formats.
160
- */
161
- decrypt(ciphertext: string | null): string | null;
162
- decrypt(ciphertext: string | null, tenantId: string): string | null;
163
- }
164
-
165
- /**
166
- * Register the FieldEncryptor instance for use by EncryptedType.
167
- * Call this once at application bootstrap (e.g., in mikro-orm.config.ts).
168
- */
169
- declare function registerEncryptor(encryptor: FieldEncryptor): void;
170
- /**
171
- * Set the encryption tenant ID for the current async context.
172
- *
173
- * IMPORTANT: this uses `AsyncLocalStorage.enterWith`, which mutates the
174
- * current async resource's store. It does NOT reliably propagate through
175
- * `pg` connection pool callback async resources — pooled connections are
176
- * long-lived async resources created at pool init, and resumption
177
- * callbacks run in the pool's resource, not the caller's. As a result,
178
- * MikroORM hydration of encrypted columns can read an empty / wrong
179
- * tenant id from `getCurrentTenantId()` even when this was called
180
- * correctly at the start of the request.
181
- *
182
- * Prefer `withEncryptionContext(tenantId, fn)` (or the
183
- * `wrapEmWithTenantContext` helper) for any code path that hits the
184
- * database. `setEncryptionTenantId` remains useful as a best-effort seed
185
- * for purely synchronous code paths.
186
- */
187
- declare function setEncryptionTenantId(tenantId: string): void;
188
- /**
189
- * Run `fn` inside a fresh AsyncLocalStorage scope bound to `tenantId`.
190
- *
191
- * Unlike `setEncryptionTenantId`, this uses `AsyncLocalStorage.run`, which
192
- * creates a new async resource bound to the store. Node's promise hooks
193
- * propagate the store forward through pool callback async resources, so
194
- * MikroORM hydration of encrypted columns inside `fn` (even after multiple
195
- * awaits and a pg pool roundtrip) sees the correct tenant id.
196
- *
197
- * Most application code should not call this directly — use
198
- * `wrapEmWithTenantContext(em, tenantId)` in your DI EntityManager
199
- * factory and every method on the returned EM will be wrapped
200
- * automatically.
201
- */
202
- declare function withEncryptionContext<T>(tenantId: string, fn: () => T): T;
203
- /**
204
- * Get the current tenant ID. Returns empty string when no context is set
205
- * (startup, seeders, better-auth, background jobs).
206
- */
207
- declare function getCurrentTenantId(): string;
208
- /**
209
- * MikroORM custom Type that transparently encrypts/decrypts values.
210
- *
211
- * Works with any JS type. Non-string values are serialized before
212
- * encryption and hydrated after decryption using the original Type's
213
- * runtimeType for correct JS type reconstruction.
214
- *
215
- * DB column is always `text` — the encrypted ciphertext is a string
216
- * regardless of the original JS type.
217
- *
218
- * For array container types, the element type is tracked separately
219
- * so each element is hydrated individually after decryption.
220
- */
221
- declare class EncryptedType extends Type<unknown, string | null> {
222
- readonly _elementRuntimeType: string;
223
- readonly _isArray: boolean;
224
- readonly _enumValues: unknown[] | undefined;
225
- /**
226
- * @param elementRuntimeType - The runtimeType of the (element) type,
227
- * e.g. 'string', 'number', 'Date', 'bigint', 'Buffer', 'any'.
228
- * @param isArray - Whether this is an array container type.
229
- * @param enumValues - Optional list of allowed enum values for app-level
230
- * validation (used when an enum field has encrypted compliance).
231
- */
232
- constructor(elementRuntimeType?: string, isArray?: boolean, enumValues?: unknown[]);
233
- convertToDatabaseValue(value: unknown, _platform: Platform, _context?: TransformContext): string | null;
234
- convertToJSValue(value: string | null, _platform: Platform): unknown;
235
- getColumnType(): string;
236
- get runtimeType(): string;
237
- ensureComparable(): boolean;
238
- private serialize;
239
- private deserialize;
240
- private tryJsonParse;
241
- }
242
-
243
- /**
244
- * The name used to register the tenant isolation filter.
245
- */
246
- declare const TENANT_FILTER_NAME = "tenant";
247
- /**
248
- * Creates the tenant filter definition.
249
- *
250
- * The filter adds `WHERE <column> = :tenantId` to all queries
251
- * on entities that have the configured tenant column (or its relation).
252
- * Entities without the property are unaffected (empty condition).
253
- *
254
- * @param column - The entity property name used for tenant isolation.
255
- * Defaults to `'organizationId'`. The relation name
256
- * (without `Id` suffix) is also checked.
257
- */
258
- declare function createTenantFilterDef(column?: string, relationName?: string): FilterDef;
259
- /**
260
- * Registers the global tenant isolation filter on the ORM's entity manager.
261
- * Call this once at application bootstrap after `MikroORM.init()`.
262
- *
263
- * After calling this, every fork of the EM will inherit the filter.
264
- * Set the tenant ID per-request via:
265
- *
266
- * ```ts
267
- * em.setFilterParams('tenant', { tenantId: 'org-123' });
268
- * ```
269
- */
270
- declare function setupTenantFilter(orm: {
271
- em: Pick<EntityManager, 'addFilter'>;
272
- }, config?: {
273
- /** Entity property name used for tenant isolation. Defaults to `'organizationId'`. */
274
- column?: string;
275
- /** Relation property name if different from column without 'Id' suffix. E.g., if column is 'orgId' but relation is 'parentOrg'. */
276
- relation?: string;
277
- logger?: {
278
- info: (msg: string, ...args: unknown[]) => void;
279
- };
280
- }): void;
281
- /**
282
- * Returns a forked EntityManager with the tenant filter disabled.
283
- *
284
- * Use this only from code paths that have verified super-admin permissions.
285
- * Queries executed through the returned EM will return cross-tenant data.
286
- */
287
- declare function getSuperAdminContext(em: Pick<EntityManager, 'fork'>): ReturnType<EntityManager['fork']>;
288
-
289
- /**
290
- * Structural subset of {@link TransactionEventArgs} used by
291
- * `RlsEventSubscriber` so that callers (and tests) only need to provide
292
- * the properties the subscriber actually reads.
293
- */
294
- interface RlsTransactionEventArgs {
295
- em: {
296
- getFilterParams: EntityManager['getFilterParams'];
297
- getConnection(): {
298
- execute(query: string, params?: unknown[], method?: 'all' | 'get' | 'run', ctx?: unknown): Promise<unknown>;
299
- };
300
- };
301
- transaction?: unknown;
302
- }
303
- interface RlsConfig {
304
- /**
305
- * Whether to enable PostgreSQL Row-Level Security.
306
- * Defaults to `true` when the driver is PostgreSQL, `false` otherwise.
307
- * Set to `false` to opt out even on PostgreSQL.
308
- */
309
- enabled?: boolean;
310
- /** Optional logger for compliance messages. Falls back to console. */
311
- logger?: {
312
- info: (msg: string, ...args: unknown[]) => void;
313
- warn: (msg: string, ...args: unknown[]) => void;
314
- };
315
- }
316
- /**
317
- * MikroORM EventSubscriber that executes `SET LOCAL app.tenant_id = :tenantId`
318
- * at the start of every transaction when PostgreSQL RLS is enabled.
319
- *
320
- * This ensures that even if the MikroORM global filter is somehow bypassed,
321
- * the database-level RLS policy enforces tenant isolation.
322
- *
323
- * The tenant ID is read from the EntityManager's filter parameters
324
- * (set by the tenant context middleware).
325
- */
326
- declare class RlsEventSubscriber implements EventSubscriber {
327
- afterTransactionStart(args: RlsTransactionEventArgs): Promise<void>;
328
- private getTenantId;
329
- }
330
- /**
331
- * Sets up PostgreSQL Row-Level Security integration.
332
- *
333
- * 1. Registers the `RlsEventSubscriber` to run `SET LOCAL app.tenant_id`
334
- * at the start of every transaction.
335
- * 2. Validates that RLS policies exist on tenant-scoped tables (warns if missing).
336
- *
337
- * Call this at application bootstrap after `MikroORM.init()` and `setupTenantFilter()`.
338
- *
339
- * @param orm - The initialized MikroORM instance
340
- * @param config - RLS configuration (enabled defaults to auto-detect PostgreSQL)
341
- */
342
- declare function setupRls(orm: MikroORM, config?: RlsConfig): void;
343
-
344
- /**
345
- * Wrap a tenant-scoped MikroORM `EntityManager` so that every operation on
346
- * it executes inside `withEncryptionContext(tenantId, …)`.
347
- *
348
- * # Why this exists
349
- *
350
- * `setEncryptionTenantId` (and other places that need to record the
351
- * current tenant for `EncryptedType` hydration) uses
352
- * `AsyncLocalStorage.enterWith`. `enterWith` mutates the *current* async
353
- * resource's store. That works for plain Promise chains, but it does NOT
354
- * propagate through `pg` connection pool callback async resources.
355
- *
356
- * Pooled connections are long-lived async resources created at pool init.
357
- * When MikroORM hydration runs in a connection's resolution callback,
358
- * `getCurrentTenantId()` reads whatever store was bound to that pool
359
- * resource at creation time (typically empty), not the request's value.
360
- * The result is intermittent decrypt failures on encrypted columns even
361
- * though the EM is "tenant-scoped" everywhere in app code, with no obvious
362
- * culprit at any single call site.
363
- *
364
- * `withEncryptionContext(tenantId, fn)` uses `als.run(...)` instead, which
365
- * creates a fresh async resource bound to the store. Node's promise hooks
366
- * then propagate the store forward through the pool callback boundary, so
367
- * `getCurrentTenantId()` returns the right value at hydration time
368
- * regardless of which pooled connection serviced the query.
369
- *
370
- * By proxying the EM, every `find / findOne / populate / flush / persist`
371
- * etc executes inside its own bound `als.run` callback. Single point of
372
- * truth for tenant scoping; call sites stay clean.
373
- *
374
- * # Usage
375
- *
376
- * Use this in your DI `EntityManager` factory:
377
- *
378
- * ```ts
379
- * EntityManager: {
380
- * lifetime: Lifetime.Scoped,
381
- * type: EntityManager,
382
- * factory: (
383
- * { Orm },
384
- * context?: { entityManagerOptions?: ForkOptions; tenantId?: string }
385
- * ) =>
386
- * wrapEmWithTenantContext(
387
- * Orm.em.fork(context?.entityManagerOptions),
388
- * context?.tenantId
389
- * )
390
- * }
391
- * ```
392
- *
393
- * If `tenantId` is `undefined` or empty, the original EM is returned
394
- * unwrapped — useful for super-admin / lookup paths that need an
395
- * unscoped query before they know the tenant.
396
- *
397
- * @param em a freshly forked `EntityManager` from `orm.em.fork(...)`
398
- * @param tenantId the org/tenant id to bind for filter params + ALS;
399
- * pass `undefined` to skip wrapping entirely
400
- */
401
- declare function wrapEmWithTenantContext(em: EntityManager, tenantId: string | undefined): EntityManager;
402
-
403
- export { ComplianceLevel, ComplianceLevel as ComplianceLevelType, DecryptionError, EncryptedType, EncryptionRequiredError, FieldEncryptor, MissingEncryptionKeyError, type ParsedDuration, RetentionAction, RetentionAction as RetentionActionType, RetentionDuration, type RetentionPolicy, type RlsConfig, RlsEventSubscriber, TENANT_FILTER_NAME, createTenantFilterDef, defineComplianceEntity, entityHasEncryptedFields, fp, getAllRetentionPolicies, getAllUserIdFields, getComplianceMetadata, getCurrentTenantId, getEntityComplianceFields, getEntityRetention, getEntityUserIdField, getSuperAdminContext, parseDuration, registerEncryptor, setEncryptionTenantId, setupRls, setupTenantFilter, subtractDuration, withEncryptionContext, wrapEmWithNativeQueryBlocking, wrapEmWithTenantContext };