@sdflc/backend-helpers 1.0.112 → 1.0.114

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 (214) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +586 -33
  5. package/build/BaseCore.js +821 -127
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/IpRateLimiter.d.ts +105 -0
  19. package/build/IpRateLimiter.js +104 -0
  20. package/build/RedisDataLoader.d.ts +144 -21
  21. package/build/RedisDataLoader.js +178 -49
  22. package/build/apiContext.d.ts +0 -8
  23. package/build/apiContext.js +30 -32
  24. package/build/checkItHelpers.d.ts +32 -0
  25. package/build/checkItHelpers.js +73 -7
  26. package/build/commonValidators.d.ts +107 -16
  27. package/build/commonValidators.js +211 -106
  28. package/build/configBuilder.d.ts +23 -0
  29. package/build/configBuilder.js +73 -0
  30. package/build/constants.d.ts +134 -17
  31. package/build/constants.js +95 -15
  32. package/build/dbHelpers.d.ts +89 -29
  33. package/build/dbHelpers.js +175 -86
  34. package/build/dbSeeder.d.ts +10 -1
  35. package/build/dbSeeder.js +80 -15
  36. package/build/dbTableHelpers.d.ts +122 -5
  37. package/build/dbTableHelpers.js +151 -13
  38. package/build/downloadHelpers.d.ts +24 -1
  39. package/build/downloadHelpers.js +51 -21
  40. package/build/esm/BaseController.d.ts +20 -0
  41. package/build/esm/BaseController.js +58 -0
  42. package/build/esm/BaseCore.d.ts +586 -33
  43. package/build/esm/BaseCore.js +812 -118
  44. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  45. package/build/esm/BaseExternalApiGateway.js +48 -0
  46. package/build/esm/BaseGateway.d.ts +455 -17
  47. package/build/esm/BaseGateway.js +503 -57
  48. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  49. package/build/esm/BaseRestApiCrudController.js +131 -0
  50. package/build/esm/DataCache.d.ts +116 -5
  51. package/build/esm/DataCache.js +142 -20
  52. package/build/esm/Database.d.ts +165 -4
  53. package/build/esm/Database.js +224 -51
  54. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  55. package/build/esm/DbMigratorAndSeeder.js +184 -71
  56. package/build/esm/IpRateLimiter.d.ts +105 -0
  57. package/build/esm/IpRateLimiter.js +100 -0
  58. package/build/esm/RedisDataLoader.d.ts +144 -21
  59. package/build/esm/RedisDataLoader.js +179 -50
  60. package/build/esm/apiContext.d.ts +0 -8
  61. package/build/esm/apiContext.js +30 -32
  62. package/build/esm/checkItHelpers.d.ts +32 -0
  63. package/build/esm/checkItHelpers.js +73 -7
  64. package/build/esm/commonValidators.d.ts +107 -16
  65. package/build/esm/commonValidators.js +209 -105
  66. package/build/esm/configBuilder.d.ts +23 -0
  67. package/build/esm/configBuilder.js +69 -0
  68. package/build/esm/constants.d.ts +134 -17
  69. package/build/esm/constants.js +94 -14
  70. package/build/esm/dbHelpers.d.ts +89 -29
  71. package/build/esm/dbHelpers.js +171 -81
  72. package/build/esm/dbSeeder.d.ts +10 -1
  73. package/build/esm/dbSeeder.js +81 -16
  74. package/build/esm/dbTableHelpers.d.ts +122 -5
  75. package/build/esm/dbTableHelpers.js +152 -14
  76. package/build/esm/downloadHelpers.d.ts +24 -1
  77. package/build/esm/downloadHelpers.js +51 -21
  78. package/build/esm/index.d.ts +6 -2
  79. package/build/esm/index.js +6 -2
  80. package/build/esm/interfaces/ApiContext.d.ts +33 -3
  81. package/build/esm/interfaces/ApiContext.js +1 -0
  82. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  83. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  84. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  85. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  86. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  87. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +146 -9
  88. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  89. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  90. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  91. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  92. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  93. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  94. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  95. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  96. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  97. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  98. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  99. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  100. package/build/esm/interfaces/CacheInterface.js +1 -0
  101. package/build/esm/interfaces/CoreActionInterface.d.ts +60 -0
  102. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  103. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  104. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  105. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  106. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  107. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  108. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  109. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  110. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  111. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  112. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  113. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  114. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  115. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  116. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  117. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  118. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  119. package/build/esm/interfaces/LoaderInterface.js +1 -0
  120. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  121. package/build/esm/interfaces/UserTokenParams.js +1 -0
  122. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  123. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  124. package/build/esm/interfaces/index.d.ts +4 -0
  125. package/build/esm/interfaces/index.js +4 -0
  126. package/build/esm/knexConfigBuilder.d.ts +25 -0
  127. package/build/esm/knexConfigBuilder.js +100 -36
  128. package/build/esm/parseIds.d.ts +6 -0
  129. package/build/esm/parseIds.js +13 -0
  130. package/build/esm/passwordHelpers.d.ts +22 -0
  131. package/build/esm/passwordHelpers.js +40 -8
  132. package/build/esm/redisClient.d.ts +57 -4
  133. package/build/esm/redisClient.js +40 -54
  134. package/build/esm/resolveClientIp.d.ts +15 -0
  135. package/build/esm/resolveClientIp.js +34 -0
  136. package/build/esm/resolversHelpers.d.ts +21 -1
  137. package/build/esm/resolversHelpers.js +48 -26
  138. package/build/esm/userToken.d.ts +50 -1
  139. package/build/esm/userToken.js +85 -20
  140. package/build/esm/utils.d.ts +20 -2
  141. package/build/esm/utils.js +23 -13
  142. package/build/index.d.ts +6 -2
  143. package/build/index.js +6 -2
  144. package/build/interfaces/ApiContext.d.ts +33 -3
  145. package/build/interfaces/ApiContext.js +1 -0
  146. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  147. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  148. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  149. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  150. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  151. package/build/interfaces/BaseCorePropsInterface.d.ts +146 -9
  152. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  153. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  154. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  155. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  156. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  157. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  158. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  159. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  160. package/build/interfaces/BuildConfigOptions.js +1 -0
  161. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  162. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  163. package/build/interfaces/CacheInterface.d.ts +18 -1
  164. package/build/interfaces/CacheInterface.js +1 -0
  165. package/build/interfaces/CoreActionInterface.d.ts +60 -0
  166. package/build/interfaces/CoreActionInterface.js +1 -0
  167. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  168. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  169. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  170. package/build/interfaces/DataCachePropsInterface.js +3 -0
  171. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  172. package/build/interfaces/DatabaseOptions.js +1 -0
  173. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  174. package/build/interfaces/DatabaseReadInterface.js +1 -0
  175. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  176. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  177. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  178. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  179. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  180. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  181. package/build/interfaces/ListArgsInterface.js +1 -0
  182. package/build/interfaces/LoaderInterface.d.ts +36 -1
  183. package/build/interfaces/LoaderInterface.js +1 -0
  184. package/build/interfaces/UserTokenParams.d.ts +23 -5
  185. package/build/interfaces/UserTokenParams.js +1 -0
  186. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  187. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  188. package/build/interfaces/index.d.ts +4 -0
  189. package/build/interfaces/index.js +4 -0
  190. package/build/knexConfigBuilder.d.ts +25 -0
  191. package/build/knexConfigBuilder.js +99 -35
  192. package/build/parseIds.d.ts +6 -0
  193. package/build/parseIds.js +17 -0
  194. package/build/passwordHelpers.d.ts +22 -0
  195. package/build/passwordHelpers.js +40 -8
  196. package/build/redisClient.d.ts +57 -4
  197. package/build/redisClient.js +40 -54
  198. package/build/resolveClientIp.d.ts +15 -0
  199. package/build/resolveClientIp.js +38 -0
  200. package/build/resolversHelpers.d.ts +21 -1
  201. package/build/resolversHelpers.js +48 -26
  202. package/build/userToken.d.ts +50 -1
  203. package/build/userToken.js +85 -20
  204. package/build/utils.d.ts +20 -2
  205. package/build/utils.js +24 -16
  206. package/package.json +19 -18
  207. package/build/baseController.d.ts +0 -17
  208. package/build/baseController.js +0 -64
  209. package/build/configBulder.d.ts +0 -2
  210. package/build/configBulder.js +0 -36
  211. package/build/esm/baseController.d.ts +0 -17
  212. package/build/esm/baseController.js +0 -58
  213. package/build/esm/configBulder.d.ts +0 -2
  214. package/build/esm/configBulder.js +0 -32
@@ -2,87 +2,640 @@ import { OpResult } from '@sdflc/api-helpers';
2
2
  import { Logger, MeasureTool } from '@sdflc/utils';
3
3
  import { ID_TYPES } from './constants';
4
4
  import { Database } from './Database';
5
- import { BaseCorePropsInterface, BaseCoreActionsInterface, CoreActionInterface, JwtTokenSecretAndSettings, ApiContext, ExtractCredentialsArgs, ListArgsInterface } from './interfaces';
5
+ import { BaseCorePropsInterface, BaseCoreActionsInterface, CoreActionInterface, BaseCoreValidatorsInterface, JwtTokenSecretAndSettings, ApiContext, ExtractCredentialsArgs, ListArgsInterface } from './interfaces';
6
+ /**
7
+ * BaseCore is the foundation for all business-logic core classes.
8
+ *
9
+ * A core sits between the transport layer (GraphQL resolvers, REST controllers)
10
+ * and the data layer (gateways). It is responsible for:
11
+ * - Authentication and authorisation (via `runAction`)
12
+ * - Input validation (via validator functions)
13
+ * - Database transaction management
14
+ * - Calling gateway methods and transforming results
15
+ * - Consistent error handling and OpResult wrapping
16
+ * - Optional IP-based rate limiting (via `checkRateLimit`)
17
+ *
18
+ * Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
19
+ * including the ApiContext, db, logger, auth config, and optional rate-limit config.
20
+ *
21
+ * Rate limiting runs two independent tiers, both must pass:
22
+ *
23
+ * Global tier — context.globalRateLimit, set once at app startup.
24
+ * Always counted when present; cannot be opted out.
25
+ * Guards the whole service from a flood regardless of
26
+ * which action the IP targets.
27
+ *
28
+ * Core-or-action tier — mutually exclusive; action rule replaces core rule:
29
+ * 1. CoreActionInterface.rateLimit (per-call override)
30
+ * 2. rateLimitOnAction[actionName] (per-action props)
31
+ * 3. config.rateLimit (core-level default)
32
+ * false at step 1 or 2 disables this tier for that
33
+ * action (only global applies). Raising an action limit
34
+ * above the core default works correctly because the
35
+ * core counter is not also running.
36
+ *
37
+ * To wire up: create one IpRateLimiter at app startup, set it on context.rateLimiter.
38
+ * To use a custom limiter: pass `rateLimiter` (any RateLimiterInterface).
39
+ * To disable: pass `rateLimiter: null`.
40
+ *
41
+ * Rule resolution order (first match wins):
42
+ * CoreActionInterface.rateLimit
43
+ * → BaseCorePropsInterface.rateLimitOnAction[actionName]
44
+ * → BaseCorePropsInterface.rateLimit
45
+ * → no limiting
46
+ *
47
+ * Subclasses typically override:
48
+ * - `getValidators()` — to provide custom validation per action
49
+ * - `before*` / `after*` — to transform inputs/outputs per action
50
+ * - `processItemOnIn()` — to normalise inbound data
51
+ * - `processItemOnOut()` — to shape outbound data
52
+ * - `authenticate()` — to implement custom auth strategies
53
+ * - `getJwtTokenSecretAndSettings()` — to resolve JWT config per space/tenant
54
+ * - `onException()` — to customise exception messages
55
+ * - `getFilterToSetOrderNo()` — to scope orderNo sequences to a parent entity
56
+ */
6
57
  declare class BaseCore {
7
58
  protected measureTool: MeasureTool;
8
59
  protected config: BaseCorePropsInterface;
9
60
  protected logger: Logger;
10
61
  constructor(props: BaseCorePropsInterface);
62
+ /**
63
+ * Returns the ID type this core operates with (UUID, integer, etc.).
64
+ * Defaults to ID_TYPES.UNKNOWN if not configured.
65
+ * Used by consumers that need to validate or coerce ID formats.
66
+ */
11
67
  getIdType(): ID_TYPES;
68
+ /**
69
+ * Returns the Database instance from config.
70
+ * Used for transaction management and raw query access.
71
+ */
12
72
  getDb(): Database;
73
+ /**
74
+ * Returns the requestId from the current ApiContext.
75
+ * Used to detect same-request calls (see `sameRequest` logic in runAction).
76
+ */
13
77
  getRequestId(): string;
78
+ /**
79
+ * Returns the full ApiContext for this request.
80
+ * Contains userId, spaceId, gateways, cores, headers, etc.
81
+ */
14
82
  getContext(): ApiContext;
15
- getGateways(): any;
83
+ /**
84
+ * Returns all gateway instances from the current request context.
85
+ * Returns an empty object if context or gateways are not available.
86
+ */
87
+ getGateways(): Record<string, any>;
88
+ /**
89
+ * Returns a single gateway by name.
90
+ * Falls back to `config.gatewayName` if no name is provided.
91
+ * Returns undefined if the gateway does not exist in context.
92
+ */
16
93
  getGateway(name?: string): any;
17
- getValidators(): any;
94
+ /**
95
+ * Returns the validator map for this core.
96
+ * Override in subclasses to provide custom validators per action.
97
+ *
98
+ * Each validator is a function (or async function) that receives
99
+ * `(args, actionOpt)` and returns `[result, validatedItems]` where:
100
+ * - result === true means validation passed
101
+ * - result is a validation error object if validation failed
102
+ * - validatedItems is an optional object of pre-fetched/validated data
103
+ * that will be merged into actionOpt for the action handler
104
+ */
105
+ getValidators(): BaseCoreValidatorsInterface;
106
+ /**
107
+ * Wraps data in a successful OpResult and returns its plain JS representation.
108
+ *
109
+ * Always returns data as an array — single objects are wrapped in `[data]`.
110
+ * Empty/null data returns an empty array with OK status.
111
+ *
112
+ * @param data The data to include in the result
113
+ * @param code Optional result code (defaults to OP_RESULT_CODES.OK)
114
+ */
18
115
  success(data: any, code?: number): any;
116
+ /**
117
+ * Creates a failed OpResult with a single error message.
118
+ *
119
+ * @param code Result code (e.g. OP_RESULT_CODES.NOT_FOUND)
120
+ * @param errorMsg Human-readable error description
121
+ * @param data Optional data payload to include alongside the error
122
+ */
19
123
  failure(code: number, errorMsg: string, data?: any): any;
124
+ /**
125
+ * Creates a validation-failed OpResult from a validation error object.
126
+ *
127
+ * Handles two cases:
128
+ * - If `ex` is already an OpResult, returns a plain VALIDATION_FAILED result
129
+ * (the original OpResult's errors are not re-wrapped to avoid duplication)
130
+ * - Otherwise, iterates `ex.errors` (checkit library format) and adds each
131
+ * field's error messages individually, supporting both single and multiple
132
+ * rule failures per field
133
+ */
20
134
  validationFailure(ex: OpResult | any): any;
135
+ /**
136
+ * Creates an exception-failed OpResult from a caught error.
137
+ *
138
+ * Distinguishes between database errors (returned to the client with the
139
+ * DB-level message) and application errors (logged internally, generic
140
+ * message returned to the client to avoid leaking implementation details).
141
+ *
142
+ * Note: uses `isExOpResult` instead of `isOpResult` to avoid shadowing
143
+ * the imported `isOpResult` utility function.
144
+ *
145
+ * @param ex The caught exception
146
+ * @param doingWhat Description of the operation that failed (for logging)
147
+ * @param data Optional data payload to include in the result
148
+ */
21
149
  exceptionFailure(ex: any, doingWhat: string, data?: any): any;
150
+ /**
151
+ * Commits or rolls back the active database transaction based on the action result.
152
+ *
153
+ * Called at the end of every `runAction()` flow, including in the catch block.
154
+ * Does nothing if `hasTransaction` is false or if `sameRequest` is true
155
+ * (same-request calls share their caller's transaction).
156
+ *
157
+ * `skipCheckResult` forces a commit regardless of result code — useful for
158
+ * operations where the caller has already verified correctness and just needs
159
+ * the transaction closed (e.g. after a manual rollback-and-retry pattern).
160
+ */
22
161
  checkResult(args: any): Promise<void>;
162
+ /**
163
+ * Returns the active rate-limiter for this request.
164
+ *
165
+ * Resolution order (first defined value wins):
166
+ * 1. config.rateLimiter — per-core override; null explicitly disables
167
+ * 2. context.rateLimiter — app-level singleton set at startup
168
+ * 3. null — no limiting
169
+ *
170
+ * The app-level instance on context is created once at startup (e.g. in
171
+ * your context factory alongside spaceGw, globalRateLimit, etc.) and shared
172
+ * across all cores in all requests. This avoids creating a new limiter
173
+ * object on every request while still allowing individual cores to swap
174
+ * in a custom implementation or disable limiting entirely via config.
175
+ */
176
+ private getRateLimiter;
177
+ /**
178
+ * Collects the rate-limit rules that apply to a single runAction call.
179
+ *
180
+ * Returns at most two entries: one for the global tier and one for the
181
+ * core-or-action tier. Both tiers are independent — each gets its own
182
+ * Redis counter and the request must pass both to proceed.
183
+ *
184
+ * ── Global tier ─────────────────────────────────────────────────────────
185
+ * Sourced from context.globalRateLimit. Always included when present —
186
+ * it cannot be opted out by core or action configuration. This is the
187
+ * service-wide flood guard: no single IP can saturate the service
188
+ * regardless of which action it targets.
189
+ *
190
+ * ── Core-or-action tier (mutually exclusive) ────────────────────────────
191
+ * Core and action rules are NOT additive. If an action-level rule exists
192
+ * it completely replaces the core rule for that action. This makes
193
+ * loosening or tightening a single action meaningful: raising the action
194
+ * limit actually raises it (the core counter will not block first), and
195
+ * lowering it tightens that specific action without affecting others.
196
+ *
197
+ * Resolution for the core-or-action tier (first defined value wins):
198
+ * 1. callOverride (CoreActionInterface.rateLimit)
199
+ * 2. rateLimitOnAction[actionName]
200
+ * 3. config.rateLimit (core-level default)
201
+ * 4. nothing — tier omitted
202
+ *
203
+ * false at step 1 or 2 explicitly disables this tier for the action
204
+ * so only the global counter applies. false never suppresses global.
205
+ *
206
+ * @param actionName Stable action key used for per-action lookup and as
207
+ * the Redis key segment when rule.action is not set.
208
+ * @param callOverride The rateLimit value passed directly to runAction().
209
+ */
210
+ private collectRateLimitRules;
211
+ /**
212
+ * Checks applicable rate-limit counters for the current request.
213
+ *
214
+ * Called at the very start of runAction(), before the DB transaction is
215
+ * opened and before any authentication, so auth endpoints are protected
216
+ * from brute-force without any DB or session overhead.
217
+ *
218
+ * Runs up to two independent counters in parallel (global + core-or-action).
219
+ * The request is blocked if either counter is exceeded.
220
+ *
221
+ * Returns an OpResult with code TOO_MANY_REQUESTS (429) on the first block
222
+ * found, or null when the request may proceed.
223
+ *
224
+ * Never throws — any error from the limiter is treated as "allow" to ensure
225
+ * Redis unavailability cannot take down an endpoint.
226
+ *
227
+ * Skipped entirely when:
228
+ * - No rules are collected for this action (collectRateLimitRules returns [])
229
+ * - No limiter is available (no context.rateLimiter, no config.rateLimiter)
230
+ * - sameRequest is true (nested calls within the same request are not
231
+ * re-counted — the outer call has already consumed the slot)
232
+ *
233
+ * Redis key format per tier:
234
+ * rl:{spaceId}:{scope}:{actionKey}:{ip}
235
+ * The scope segment ('global' or 'core-action') keeps the two counters in
236
+ * separate keys so they never interfere with each other.
237
+ *
238
+ * @param actionName Stable action identifier used as the Redis key segment
239
+ * and for per-action rule lookup.
240
+ * @param callOverride The rateLimit value passed to the current runAction call.
241
+ * @param doingWhat Human-readable description used in log messages.
242
+ */
243
+ private checkRateLimit;
244
+ /**
245
+ * Core action runner. All public CRUD methods delegate to this.
246
+ *
247
+ * Execution flow:
248
+ * 1. Detect same-request calls (skip transaction + auth + rate limiting for
249
+ * nested calls within the same request, identified by matching requestId)
250
+ * 2. Check IP rate limits if configured — all applicable counters (global,
251
+ * core, action) are checked in parallel; blocked if any is exceeded
252
+ * 3. Start DB transaction if `hasTransaction` is true
253
+ * 4. Authenticate the request (if `doAuth` is true) OR verify the space
254
+ * (if `requireSpace` is not false) — space verification is a lighter
255
+ * alternative to full auth for public-but-space-scoped operations
256
+ * 5. Check role-based access if `roles` array is provided
257
+ * 6. Run the validator function if provided — validator returns
258
+ * `[true, validatedItems]` on success or `[errorObj, {}]` on failure
259
+ * 7. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
260
+ * 8. Commit or rollback the transaction via `checkResult()`
261
+ * 9. On any exception: rollback, call `onException()` and the caller's
262
+ * `onException` hook, then return an exceptionFailure result
263
+ *
264
+ * Same-request detection:
265
+ * When a core method calls another core method on the same request
266
+ * (e.g. create calling list to re-fetch results), it can pass
267
+ * `args.requestId = context.requestId`. The inner call detects this,
268
+ * skips starting a new transaction, skips auth, skips rate limiting,
269
+ * and skips committing — the outer call owns the transaction lifecycle.
270
+ *
271
+ * Rate limiting:
272
+ * Resolved via collectRateLimitRules() and checked via checkRateLimit().
273
+ * See BaseCorePropsInterface for the full rule resolution chain.
274
+ * Entirely skipped if no rateLimiter is configured.
275
+ *
276
+ * @param opt CoreActionInterface with all action configuration
277
+ */
23
278
  runAction(opt: CoreActionInterface): Promise<any>;
279
+ /**
280
+ * Lists records via the configured gateway.
281
+ *
282
+ * Calls `beforeList()` to transform filter args, then `afterList()` on results.
283
+ * Auth is controlled by `doAuthOnAction.list`.
284
+ * Does not use a DB transaction — list is a read-only operation.
285
+ */
24
286
  list(args: ListArgsInterface): Promise<any>;
287
+ /**
288
+ * Fetches a single record by id via the configured gateway.
289
+ *
290
+ * Calls `beforeGet()` to transform/validate the args object (which should
291
+ * contain an `id` field). Returns NOT_FOUND if:
292
+ * - beforeGet returns null/undefined id
293
+ * - the gateway returns no record for that id
294
+ *
295
+ * Does not use a DB transaction.
296
+ */
25
297
  get(args: any): Promise<any>;
298
+ /**
299
+ * Fetches multiple records by their ids via the configured gateway.
300
+ *
301
+ * Calls `beforeGetMany()` to transform the args object (which should
302
+ * contain an `ids` array). Returns NOT_FOUND if `ids` is not an array
303
+ * after the before-hook.
304
+ *
305
+ * Results are returned in DataLoader order (same order as input ids,
306
+ * with null entries for missing records). Does not use a DB transaction.
307
+ */
26
308
  getMany(args: any): Promise<any>;
309
+ /**
310
+ * Returns the gateway instance used for orderNo calculation.
311
+ * Override in subclasses to use a different gateway than the default one.
312
+ */
27
313
  getGatewayToSetOrerNo(): any;
28
- getFilterToSetOrderNo(args: any): {};
314
+ /**
315
+ * Returns the filter object used when querying for the last orderNo value.
316
+ * Override in subclasses to scope orderNo sequences to a parent entity
317
+ * (e.g. return `{ categoryId: params.categoryId }` to have per-category ordering).
318
+ */
319
+ getFilterToSetOrderNo(_args: any): Record<string, any>;
320
+ /**
321
+ * Creates a single record via the configured gateway.
322
+ *
323
+ * If `config.hasOrderNo` is true, auto-calculates the next orderNo value
324
+ * before calling `beforeCreate()`. Uses a DB transaction.
325
+ */
29
326
  create(args: any): Promise<any>;
327
+ /**
328
+ * Creates multiple records in a single gateway call.
329
+ *
330
+ * Calls `beforeCreateMany()` which maps each item through `processItemOnIn()`
331
+ * using `Promise.all` to correctly resolve async transforms.
332
+ * Uses a DB transaction.
333
+ */
30
334
  createMany(args: any): Promise<any>;
335
+ /**
336
+ * Updates a single record matching the `where` filter.
337
+ *
338
+ * `args` should contain `{ where, params }`:
339
+ * - `where` carries the filter (id, optional version for optimistic locking)
340
+ * - `params` carries the fields to update
341
+ *
342
+ * Returns NOT_FOUND if the gateway reports 0 affected records.
343
+ * Uses a DB transaction.
344
+ */
31
345
  update(args: any): Promise<any>;
346
+ /**
347
+ * Updates multiple records, each with its own where/params pair.
348
+ *
349
+ * `args.params` should be an array of `{ where, params }` objects.
350
+ * Each is processed sequentially by the gateway's `updateMany()`.
351
+ * Uses a DB transaction.
352
+ */
32
353
  updateMany(args: any): Promise<any>;
354
+ /**
355
+ * Upserts one or more records via the gateway's `set()` method
356
+ * (INSERT ... ON CONFLICT ... MERGE).
357
+ *
358
+ * `args.params` can be a single object or array. Each item is passed
359
+ * through `processItemOnIn()` via `beforeSet()`.
360
+ * Uses a DB transaction.
361
+ */
33
362
  set(args: any): Promise<any>;
363
+ /**
364
+ * Soft- or hard-deletes a single record matching `args.where`.
365
+ *
366
+ * The actual delete behaviour (hard vs soft) is determined by gateway config.
367
+ * Returns NOT_FOUND if the gateway reports 0 affected records.
368
+ * Does not use a DB transaction (remove is typically a single atomic operation).
369
+ */
34
370
  remove(args: any): Promise<any>;
371
+ /**
372
+ * Removes multiple records matching `args.where`.
373
+ *
374
+ * Delegates to the gateway's `remove()` method (not `removeMany`) —
375
+ * the gateway's `onRemoveFilter` handles the multi-id WHERE clause.
376
+ * Does not use a DB transaction.
377
+ */
35
378
  removeMany(args: any): Promise<any>;
36
- defaultAfterAndBefore(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
37
379
  /**
38
- * Used to transform an object before sending it in the response
39
- * @param {any} item An object coming from the database
40
- * @param {BaseCoreActionsInterface} opt Options
41
- * @returns {any} transformed object
380
+ * Default identity transform used by all before/after hooks that have
381
+ * no specific logic. Simply returns the params unchanged.
382
+ * Override to add cross-cutting transforms that apply to all actions.
383
+ */
384
+ defaultAfterAndBefore(params: any, _opt?: BaseCoreActionsInterface): Promise<any>;
385
+ /**
386
+ * Transforms an outbound record (from DB to caller).
387
+ * Override to rename fields, attach computed properties, or strip sensitive data.
388
+ * Called by all after-* hooks via their Promise.all map loops.
42
389
  */
43
390
  processItemOnOut(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
44
391
  /**
45
- * Used to transform an object before processing it on the request
46
- * @param {any} item An object coming from the outside
47
- * @param {BaseCoreActionsInterface} opt Options
48
- * @returns {any} transformed object
392
+ * Transforms an inbound record (from caller to DB).
393
+ * Override to normalise fields, enforce defaults, or coerce types before writes.
394
+ * Called by all before-* mutation hooks via their Promise.all map loops.
49
395
  */
50
396
  processItemOnIn(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
397
+ /**
398
+ * Transforms the args object before a get() call.
399
+ * The returned object should contain an `id` field.
400
+ * If it returns an OpResult, `get()` will return that OpResult directly.
401
+ */
51
402
  beforeGet(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
403
+ /**
404
+ * Transforms the args object before a getMany() call.
405
+ * The returned object should contain an `ids` array.
406
+ * If it returns an OpResult, `getMany()` will return that OpResult directly.
407
+ */
52
408
  beforeGetMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
409
+ /**
410
+ * Transforms the filter/args object before a list() call.
411
+ * Override to inject default filters, enforce scope restrictions, etc.
412
+ * If it returns an OpResult, `list()` will return that OpResult directly.
413
+ */
53
414
  beforeList(filter: any, opt?: BaseCoreActionsInterface): Promise<any>;
415
+ /**
416
+ * Transforms a single fetched record after get().
417
+ * Delegates to `processItemOnOut()`.
418
+ */
54
419
  afterGet(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
55
- afterGetMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
56
- afterList(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
420
+ /**
421
+ * Transforms fetched records after getMany().
422
+ * Maps each item through `processItemOnOut()` using Promise.all
423
+ * to correctly handle async transforms.
424
+ */
425
+ afterGetMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
426
+ /**
427
+ * Transforms fetched records after list().
428
+ * Maps each item through `processItemOnOut()` using Promise.all.
429
+ */
430
+ afterList(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
431
+ /**
432
+ * Transforms a single record before create().
433
+ * Delegates to `processItemOnIn()`.
434
+ */
57
435
  beforeCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
58
- afterCreate(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
59
- beforeCreateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
60
- afterCreateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
436
+ /**
437
+ * Transforms created records after create().
438
+ * Maps each item through `processItemOnOut()` using Promise.all.
439
+ */
440
+ afterCreate(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
441
+ /**
442
+ * Transforms an array of records before createMany().
443
+ * Maps each item through `processItemOnIn()` using Promise.all
444
+ * to correctly resolve async transforms.
445
+ *
446
+ * Fix: was using .map() without Promise.all, returning Promise[]
447
+ * instead of resolved values.
448
+ */
449
+ beforeCreateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
450
+ /**
451
+ * Transforms created records after createMany().
452
+ * Maps each item through `processItemOnOut()` using Promise.all.
453
+ */
454
+ afterCreateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
455
+ /**
456
+ * Transforms a single record before update().
457
+ * Delegates to `processItemOnIn()`.
458
+ */
61
459
  beforeUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
62
- afterUpdate(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
63
- beforeUpdateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
64
- afterUpdateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
460
+ /**
461
+ * Transforms updated records after update().
462
+ * Maps each item through `processItemOnOut()` using Promise.all.
463
+ */
464
+ afterUpdate(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
465
+ /**
466
+ * Transforms an array of { where, params } objects before updateMany().
467
+ * Maps each item's `params` through `processItemOnIn()` while preserving
468
+ * the `where` filter unchanged.
469
+ *
470
+ * Fix: was using .map() without Promise.all, returning Promise[]
471
+ * instead of resolved values.
472
+ */
473
+ beforeUpdateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
474
+ /**
475
+ * Transforms updated records after updateMany().
476
+ * Maps each item through `processItemOnOut()` using Promise.all.
477
+ */
478
+ afterUpdateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
479
+ /**
480
+ * Transforms params before set() (upsert).
481
+ * Normalises params to an array via castArray, then maps each item
482
+ * through `processItemOnIn()` using Promise.all.
483
+ *
484
+ * Fix: was using .map() without Promise.all, returning Promise[]
485
+ * instead of resolved values.
486
+ */
65
487
  beforeSet(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
66
- afterSet(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
488
+ /**
489
+ * Transforms upserted records after set().
490
+ * Maps each item through `processItemOnOut()` using Promise.all.
491
+ */
492
+ afterSet(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
493
+ /**
494
+ * Transforms the where filter before remove().
495
+ * Override to add ownership checks or enrich the filter before deletion.
496
+ * If it returns an OpResult, `remove()` returns that OpResult directly.
497
+ */
67
498
  beforeRemove(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
68
- afterRemove(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
499
+ /**
500
+ * Transforms removed records after remove().
501
+ * Maps each item through `processItemOnOut()` using Promise.all.
502
+ */
503
+ afterRemove(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
504
+ /**
505
+ * Transforms the where filter before removeMany().
506
+ * Same contract as beforeRemove() but for bulk removal.
507
+ */
69
508
  beforeRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
70
- afterRemoveMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
71
- onException(params: any, opt?: BaseCoreActionsInterface): Promise<string | null | undefined>;
72
509
  /**
73
- * Returns JWT secret and its settings to verify received JWT token
74
- * @param params Object of parameters passed to the authenticate method
75
- * @returns Object with the jwtSecret and verifyTokenArgs
510
+ * Transforms removed records after removeMany().
511
+ * Maps each item through `processItemOnOut()` using Promise.all.
512
+ */
513
+ afterRemoveMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
514
+ /**
515
+ * Called when `runAction()` catches an unhandled exception.
516
+ * Override to return a custom human-readable error message for specific
517
+ * exception types, or to trigger side effects (e.g. alert notifications).
518
+ *
519
+ * Return an empty string or null to let the default error handling apply.
520
+ * The caller's `onException` hook (passed to runAction) is called after this.
521
+ */
522
+ onException(_params: any, _opt?: BaseCoreActionsInterface): Promise<string | null | undefined>;
523
+ /**
524
+ * Returns the JWT secret and verification settings for the current request.
525
+ * Called by `authenticate()` to resolve auth config per space/tenant.
526
+ *
527
+ * Override to implement per-space token secrets, custom algorithms,
528
+ * or audience/issuer values derived from the request context.
529
+ *
530
+ * @param _params The args object passed to the action being authenticated
531
+ */
532
+ getJwtTokenSecretAndSettings(_params: any): Promise<JwtTokenSecretAndSettings>;
533
+ /**
534
+ * Resolves the current space from context or via the spaceGw gateway.
535
+ *
536
+ * Returns `[true, space]` on success, `[false, errorMessage]` on failure.
537
+ *
538
+ * Resolution order:
539
+ * 1. If `context.space` is already populated, return it immediately
540
+ * (avoids a redundant DB lookup on subsequent calls within the same request)
541
+ * 2. If `spaceGw` is configured, look up the space by `context.spaceId`
542
+ * 3. If no `spaceGw` is configured, return `[true, null]` —
543
+ * callers must handle the null space case
544
+ *
545
+ * Side effect: on successful lookup, `context.space` is populated for
546
+ * future calls within the same request.
76
547
  */
77
- getJwtTokenSecretAndSettings(params: any): Promise<JwtTokenSecretAndSettings>;
78
548
  findSpace(): Promise<any[]>;
549
+ /**
550
+ * Extracts the authentication token and fingerprint from the request.
551
+ * Called by `authenticate()` before token verification.
552
+ *
553
+ * Token resolution order:
554
+ * 1. Cookie named `space.cookieName`
555
+ * 2. Authorization header
556
+ * 3. `authorization` from context (passed explicitly, e.g. from API gateway)
557
+ *
558
+ * Fingerprint resolution order:
559
+ * 1. Cookie named `space.fingerprintCookieName`
560
+ * 2. X-Fingerprint header
561
+ * 3. `args.fingerprint` passed to the function
562
+ *
563
+ * Override to support additional token sources (e.g. query string tokens
564
+ * for WebSocket connections, or custom header schemes).
565
+ */
79
566
  extractCredentials(args: ExtractCredentialsArgs): Promise<{
80
- token: any;
81
- fingerprint: any;
567
+ token: string;
568
+ fingerprint: string;
82
569
  }>;
83
- authenticate(params: any, opt?: BaseCoreActionsInterface): Promise<any[]>;
570
+ /**
571
+ * Authenticates the current request.
572
+ * Called by `runAction()` when `doAuth` is true.
573
+ *
574
+ * Returns `[true, '']` on success, `[false, errorMessage]` on failure.
575
+ *
576
+ * Authentication flow:
577
+ * 1. Resolve the current space via `findSpace()`
578
+ * 2. Extract token + fingerprint via `extractCredentials()`
579
+ * 3. Resolve JWT secret via `getJwtTokenSecretAndSettings()`
580
+ * 4. If a token and secret are present, verify the JWT:
581
+ * - On success: populate context with accountId, roleId, userId,
582
+ * isSuperAdmin, spaceId, lang from token payload
583
+ * - On failure: return the verification error
584
+ * 5. If no token was present, fall back to API key auth:
585
+ * - Interservice API key (config.interserviceApiKey) for service-to-service calls
586
+ * - Space API key (space.apiKey) for public API access
587
+ * - If neither matches: return 'No authentication provided'
588
+ *
589
+ * Note: context.spaceId is only set from the token if not already present
590
+ * in context (header value takes precedence). context.lang defaults to
591
+ * empty string if neither requestedLang nor tokenData.lang is available.
592
+ *
593
+ * Override to add MFA checks, session validation, or custom token formats.
594
+ */
595
+ authenticate(params: any, _opt?: BaseCoreActionsInterface): Promise<any[]>;
596
+ /**
597
+ * Strips the removal suffix from a soft-deleted record's id.
598
+ *
599
+ * When a record is soft-deleted with `hasLang`, the gateway appends
600
+ * a timestamp to the id (e.g. "my-slug_en-20240101T120000+0000") to free
601
+ * the original key for re-use. This method extracts the original id
602
+ * by splitting at '~'.
603
+ */
84
604
  processRemovedRecord(record: any): any;
85
- addRemovedModifierToFields(fields: string | string[]): any;
605
+ /**
606
+ * Builds a partial update object that appends a removal suffix to the
607
+ * specified fields using a raw DB expression.
608
+ *
609
+ * Used to "tombstone" unique fields (slugs, emails, etc.) when soft-deleting,
610
+ * freeing them for re-use on new records. The suffix includes a UUID to
611
+ * ensure uniqueness even if the same record is deleted multiple times.
612
+ *
613
+ * Example: `{ slug: db.raw("slug || '~removed~' || uuid_generate_v4()") }`
614
+ *
615
+ * @param fields A single field name or array of field names to tombstone
616
+ */
617
+ addRemovedModifierToFields(fields: string | string[]): Record<string, any>;
618
+ /**
619
+ * Calculates and sets the next `orderNo` value on `params` before a create.
620
+ * Called by `create()` when `config.hasOrderNo` is true.
621
+ *
622
+ * Queries the gateway for the last record (sorted by orderNo DESC, limit 1)
623
+ * using the provided filter, then increments by `DEFAULT_ORDER_NO_STEP`.
624
+ *
625
+ * Supports two ordering strategies via `config.orderNoAsDecimal`:
626
+ * - `true` — numeric ordering (e.g. 10, 20, 30)
627
+ * - `false` — lexicographic string ordering via StrOrderHelpers
628
+ * (e.g. "a", "b", "c" — useful for reordering without renumbering)
629
+ *
630
+ * Does nothing if `params.orderNo` is already set (non-null).
631
+ *
632
+ * Fix: changed `!params.orderNo` to `params.orderNo == null` to correctly
633
+ * handle the case where `orderNo` is explicitly set to `0`.
634
+ *
635
+ * @param args.params The params object to mutate with the orderNo value
636
+ * @param args.filter Filter to scope the orderNo sequence (e.g. by parentId)
637
+ * @param args.gateway Gateway instance to query for the current max orderNo
638
+ */
86
639
  setOrderNo(args: any): Promise<void>;
87
640
  }
88
641
  export { BaseCore };