@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
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/ExtractCredentialsArgs.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,7 +1,25 @@
1
1
  import { PaginationAndSortingInterface } from '..';
2
2
  export interface ListArgsInterface {
3
+ /**
4
+ * Filter params passed to onListFilter() in the gateway.
5
+ * Shape is resource-specific — each gateway interprets it in onListFilter().
6
+ */
3
7
  filter: any;
8
+ /**
9
+ * Pagination and sorting config (pageSize, page, sortBy).
10
+ * Converted to limit/offset/orderBy by db.createLimitOffsetSortBy().
11
+ */
4
12
  params?: PaginationAndSortingInterface;
13
+ /**
14
+ * When explicitly set, overrides config.noCache for this call.
15
+ * When true: fetches only ids, hydrates via the loader.
16
+ * When false: fetches selectFields directly, bypasses loader.
17
+ * Defaults to !config.noCache if not provided.
18
+ */
5
19
  useCache?: boolean;
20
+ /**
21
+ * Reserved for core-level callers. Not used by BaseGateway.list() —
22
+ * authentication is the core's responsibility, not the gateway's.
23
+ */
6
24
  skipAuth?: boolean;
7
25
  }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/ListArgsInterface.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,7 +1,42 @@
1
+ /**
2
+ * Interface for batch-loading data by key with per-request caching.
3
+ * Implemented by DataCache (DataLoader-backed) and any custom loaders
4
+ * passed via BaseGatewayPropsInterface.loader.
5
+ *
6
+ * Follows DataLoader semantics:
7
+ * - load() and loadMany() batch all calls within the same tick
8
+ * - Results are cached for the duration of the instance's lifetime
9
+ * - clear() and clearAll() invalidate cached entries
10
+ * - prime() seeds the cache without a round-trip
11
+ */
1
12
  export interface LoaderInterface {
13
+ /**
14
+ * Loads a single record by id. Batches concurrent calls within the
15
+ * same tick into a single underlying query.
16
+ * Returns null if the record is not found.
17
+ */
2
18
  load(id: any): Promise<any>;
3
- loadMany(id: any): Promise<any[]>;
19
+ /**
20
+ * Loads multiple records by their ids in a single batched call.
21
+ * Returns results in the same order as the input ids array,
22
+ * with null entries for any ids that were not found.
23
+ */
24
+ loadMany(ids: any[]): Promise<any[]>;
25
+ /**
26
+ * Clears the cached value for one or more keys.
27
+ * Accepts either a single id or an array of ids.
28
+ * Returns `this` for chaining.
29
+ */
4
30
  clear(key: any | any[]): this;
31
+ /**
32
+ * Clears all cached values from this loader instance.
33
+ * Returns `this` for chaining.
34
+ */
5
35
  clearAll(): this;
36
+ /**
37
+ * Seeds the cache with a known value for the given key, avoiding
38
+ * a load() round-trip for recently written records.
39
+ * Returns `this` for chaining.
40
+ */
6
41
  prime(key: any, value: any): this;
7
42
  }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/LoaderInterface.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,8 +1,26 @@
1
1
  export interface UserTokenParams {
2
- spaceId: string;
3
- accountId: string;
4
- roleId: string;
2
+ /**
3
+ * The user's ID — used as the JWT `subject` claim. Required.
4
+ */
5
5
  userId: string;
6
- lang: string;
7
- [tokenProp: string]: string;
6
+ /**
7
+ * The space (tenant) ID the token is scoped to.
8
+ */
9
+ spaceId?: string;
10
+ /**
11
+ * The account ID associated with the user.
12
+ */
13
+ accountId?: string;
14
+ /**
15
+ * The role ID assigned to the user for this token.
16
+ */
17
+ roleId?: string;
18
+ /**
19
+ * The language preference for this session.
20
+ */
21
+ lang?: string;
22
+ /**
23
+ * Additional arbitrary string claims to include in the token payload.
24
+ */
25
+ [tokenProp: string]: string | undefined;
8
26
  }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/UserTokenParams.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,13 +1,53 @@
1
1
  export interface VerifyUserTokenArgs {
2
- algorithms?: any;
2
+ /**
3
+ * Accepted signing algorithms. Defaults to [defaultJwtAlgorithm] (HS256).
4
+ */
5
+ algorithms?: string[];
6
+ /**
7
+ * Expected audience claim. Must match the `aud` in the token.
8
+ */
3
9
  audience?: string | string[];
10
+ /**
11
+ * Expected issuer claim. Must match the `iss` in the token.
12
+ * Accepts a single string or array of accepted issuers.
13
+ */
4
14
  issuer?: string | string[];
15
+ /**
16
+ * When true, expired tokens are accepted without error.
17
+ * Use only in specific scenarios (e.g. token refresh flows).
18
+ */
5
19
  ignoreExpiration?: boolean;
20
+ /**
21
+ * When true, ignores the `nbf` (not-before) claim.
22
+ */
6
23
  ignoreNotBefore?: boolean;
24
+ /**
25
+ * Expected subject claim. Must match the `sub` in the token.
26
+ */
7
27
  subject?: string;
28
+ /**
29
+ * Allowed clock skew in seconds when validating `exp` and `nbf` claims.
30
+ * Useful for systems with slight clock drift between services.
31
+ */
8
32
  clockTolerance?: number;
9
- maxAge?: number;
33
+ /**
34
+ * Maximum allowed token age as seconds or a string duration (e.g. '2h').
35
+ * Tokens older than this are rejected even if `exp` has not been reached.
36
+ */
37
+ maxAge?: number | string;
38
+ /**
39
+ * Override the current timestamp (Unix seconds) used for claim validation.
40
+ * Useful in tests to simulate token verification at a specific point in time.
41
+ */
10
42
  clockTimestamp?: number;
43
+ /**
44
+ * Expected `nonce` claim for OpenID Connect ID tokens.
45
+ */
11
46
  nonce?: string;
47
+ /**
48
+ * Client-side fingerprint (from a secure cookie) to compare against the
49
+ * fingerprint embedded in the token payload.
50
+ * A mismatch results in UNAUTHORIZED — mitigates token theft.
51
+ */
12
52
  fingerprint?: string;
13
53
  }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/VerifyUserTokenArgs.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -26,3 +26,7 @@ export * from './ExtractCredentialsArgs';
26
26
  export * from './DownloadFileArgs';
27
27
  export * from './BuildListQueryArgsInterface';
28
28
  export * from './BaseCoreDoAuthOnActionInterface';
29
+ export * from './BaseControllerPropsInterface';
30
+ export * from './BaseRestApiCrudControllerPropsInterface';
31
+ export * from './BaseExternalApiGatewayPropsInterface';
32
+ export * from './DataCachePropsInterface';
@@ -41,3 +41,7 @@ __exportStar(require("./ExtractCredentialsArgs"), exports);
41
41
  __exportStar(require("./DownloadFileArgs"), exports);
42
42
  __exportStar(require("./BuildListQueryArgsInterface"), exports);
43
43
  __exportStar(require("./BaseCoreDoAuthOnActionInterface"), exports);
44
+ __exportStar(require("./BaseControllerPropsInterface"), exports);
45
+ __exportStar(require("./BaseRestApiCrudControllerPropsInterface"), exports);
46
+ __exportStar(require("./BaseExternalApiGatewayPropsInterface"), exports);
47
+ __exportStar(require("./DataCachePropsInterface"), exports);
@@ -1 +1,26 @@
1
+ /**
2
+ * Builds a Knex configuration object for the current environment.
3
+ *
4
+ * Reads connection and migration settings from `appConfig` (typically built
5
+ * by `buildConfig()`) and returns a fully configured Knex config object
6
+ * for the active `nodeEnv`. Falls back to the `development` config if
7
+ * `nodeEnv` does not match 'development' or 'production'.
8
+ *
9
+ * Built-in behaviours:
10
+ * - All query results are post-processed to camelCase via `camelResponse`
11
+ * - All identifiers are converted to snake_case via `wrapIdentifier`,
12
+ * with an optional override map for exceptions
13
+ * - Pool config can be provided as a full object (`dbPool`) or as
14
+ * individual min/max values (`dbPoolMin`, `dbPoolMax`)
15
+ * - Database port is coerced to a Number internally — no need to do this
16
+ * in the consuming app
17
+ * - MSSQL-specific connection options (encrypt, trustServerCertificate, etc.)
18
+ * are included automatically when `dbType === 'mssql'`
19
+ * - PostgreSQL searchPath is set automatically when `dbType === 'pg'`
20
+ * and `dbSchema` is provided
21
+ *
22
+ * @param dirName Absolute path to the directory containing migrations/seeds.
23
+ * Pass `__dirname` or `import.meta.dirname` from your entry point.
24
+ * @param appConfig Flat config object, typically from `buildConfig()`.
25
+ */
1
26
  export declare const buildKnexConfig: (dirName: string, appConfig: any) => any;
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/knexConfigBuilder.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -11,38 +12,77 @@ const defaultMigrationsTable = 'migrations';
11
12
  const defaultMigrationsFolder = 'migrations';
12
13
  const defaultMigrationsTemplateFileName = 'migrations-template.js';
13
14
  const defaultSeedsFolder = 'seeds';
15
+ /**
16
+ * Post-processes Knex query results by converting all keys to camelCase.
17
+ *
18
+ * Knex calls this with the already-processed result which is either:
19
+ * - An array of row objects (SELECT queries)
20
+ * - A non-array object (INSERT/UPDATE with RETURNING, aggregate queries, etc.)
21
+ *
22
+ * The `result.rows` guard handles edge cases where a raw pg-driver result
23
+ * shape leaks through — in that case we return it unchanged since Knex's
24
+ * own processing has not yet run.
25
+ *
26
+ * See: https://knexjs.org/guide/#post-process-response
27
+ */
14
28
  const camelResponse = (result) => {
15
29
  if (!result || result.rows) {
16
30
  return result;
17
31
  }
18
32
  return (0, utils_1.camelKeys)(result);
19
33
  };
34
+ /**
35
+ * Builds a Knex configuration object for the current environment.
36
+ *
37
+ * Reads connection and migration settings from `appConfig` (typically built
38
+ * by `buildConfig()`) and returns a fully configured Knex config object
39
+ * for the active `nodeEnv`. Falls back to the `development` config if
40
+ * `nodeEnv` does not match 'development' or 'production'.
41
+ *
42
+ * Built-in behaviours:
43
+ * - All query results are post-processed to camelCase via `camelResponse`
44
+ * - All identifiers are converted to snake_case via `wrapIdentifier`,
45
+ * with an optional override map for exceptions
46
+ * - Pool config can be provided as a full object (`dbPool`) or as
47
+ * individual min/max values (`dbPoolMin`, `dbPoolMax`)
48
+ * - Database port is coerced to a Number internally — no need to do this
49
+ * in the consuming app
50
+ * - MSSQL-specific connection options (encrypt, trustServerCertificate, etc.)
51
+ * are included automatically when `dbType === 'mssql'`
52
+ * - PostgreSQL searchPath is set automatically when `dbType === 'pg'`
53
+ * and `dbSchema` is provided
54
+ *
55
+ * @param dirName Absolute path to the directory containing migrations/seeds.
56
+ * Pass `__dirname` or `import.meta.dirname` from your entry point.
57
+ * @param appConfig Flat config object, typically from `buildConfig()`.
58
+ */
20
59
  const buildKnexConfig = (dirName, appConfig) => {
21
60
  const { dbType, dbHost, dbPort, dbName, dbSchema, dbUser, dbPassword, dbPoolMin, dbPoolMax, debug, nodeEnv, migrationsTemplateFileName, migrationsFolder, migrationsTable, useSchemaForMigrationsTable, seedsFolder, seedsFolderDev, seedsFolderProd, wrapIdentifierOverrideMap, dbPool, } = appConfig;
22
- const sharedConfig = {
23
- client: dbType || 'pg',
24
- postProcessResponse: camelResponse,
25
- wrapIdentifier: (value, origImpl) => {
26
- if (value === '*') {
27
- return origImpl(value);
28
- }
29
- const value2use = wrapIdentifierOverrideMap?.[value] || origImpl((0, lodash_1.snakeCase)(value));
30
- return value2use;
31
- },
32
- connection: {
33
- host: dbHost,
34
- port: dbPort,
35
- user: dbUser,
36
- password: dbPassword,
37
- database: dbName,
38
- //ssl: database.ssl,
39
- },
61
+ const resolvedDbType = dbType || 'pg';
62
+ // ─── Connection ──────────────────────────────────────────────────────────
63
+ const connection = {
64
+ host: dbHost,
65
+ // Fix: coerce port to Number here so consuming apps don't need to do it
66
+ port: dbPort != null ? Number(dbPort) : undefined,
67
+ user: dbUser,
68
+ password: dbPassword,
69
+ database: dbName,
70
+ connectionTimeout: 30000,
40
71
  };
41
- if (typeof dbPool === 'object') {
42
- sharedConfig.pool = dbPool;
72
+ // MSSQL-specific connection options — previously repeated in every project
73
+ if (resolvedDbType === 'mssql') {
74
+ connection.options = {
75
+ encrypt: true,
76
+ trustServerCertificate: false,
77
+ enableArithAbort: true,
78
+ requestTimeout: 30000,
79
+ connectionTimeout: 30000,
80
+ };
43
81
  }
44
- else {
45
- sharedConfig.pool = {
82
+ // ─── Pool ─────────────────────────────────────────────────────────────────
83
+ const pool = typeof dbPool === 'object'
84
+ ? dbPool
85
+ : {
46
86
  min: dbPoolMin != null && !isNaN(dbPoolMin) ? dbPoolMin : 0,
47
87
  max: dbPoolMax != null && !isNaN(dbPoolMax) ? dbPoolMax : 50,
48
88
  acquireTimeoutMillis: 30000,
@@ -53,17 +93,45 @@ const buildKnexConfig = (dirName, appConfig) => {
53
93
  createRetryIntervalMillis: 200,
54
94
  propagateCreateError: false,
55
95
  };
96
+ // ─── Shared config ────────────────────────────────────────────────────────
97
+ const sharedConfig = {
98
+ client: resolvedDbType,
99
+ postProcessResponse: camelResponse,
100
+ /**
101
+ * Converts camelCase JS identifiers to snake_case DB column names.
102
+ * '*' is passed through unchanged (Knex uses it for SELECT *).
103
+ * `wrapIdentifierOverrideMap` allows exceptions for identifiers that
104
+ * should not be snake_cased (e.g. already-snake_cased names, reserved words).
105
+ */
106
+ wrapIdentifier: (value, origImpl) => {
107
+ if (value === '*') {
108
+ return origImpl(value);
109
+ }
110
+ return wrapIdentifierOverrideMap?.[value] || origImpl((0, lodash_1.snakeCase)(value));
111
+ },
112
+ connection,
113
+ pool,
114
+ };
115
+ // pg searchPath — previously set in every project after buildKnexConfig()
116
+ if (resolvedDbType === 'pg' && dbSchema) {
117
+ sharedConfig.searchPath = [dbSchema, 'public'];
56
118
  }
119
+ // ─── Migration config ─────────────────────────────────────────────────────
120
+ const migrationsConfig = {
121
+ directory: path_1.default.join(dirName, migrationsFolder || defaultMigrationsFolder),
122
+ schemaName: useSchemaForMigrationsTable ? dbSchema : undefined,
123
+ tableName: migrationsTable || defaultMigrationsTable,
124
+ };
125
+ // ─── Environment configs ──────────────────────────────────────────────────
57
126
  const config = {
58
127
  development: {
59
128
  ...sharedConfig,
129
+ // debug defaults to false in production even if env var is set
60
130
  debug,
61
131
  migrations: {
62
- // https://knexjs.org/guide/migrations.html#migration-api
132
+ // stub is only needed in development (used by `knex migrate:make`)
63
133
  stub: path_1.default.join(dirName, migrationsTemplateFileName || defaultMigrationsTemplateFileName),
64
- directory: path_1.default.join(dirName, migrationsFolder || defaultMigrationsFolder),
65
- schemaName: useSchemaForMigrationsTable ? dbSchema : undefined,
66
- tableName: migrationsTable || defaultMigrationsTable,
134
+ ...migrationsConfig,
67
135
  },
68
136
  seeds: {
69
137
  directory: path_1.default.join(dirName, seedsFolderDev || seedsFolder || defaultSeedsFolder),
@@ -71,21 +139,17 @@ const buildKnexConfig = (dirName, appConfig) => {
71
139
  },
72
140
  production: {
73
141
  ...sharedConfig,
74
- debug,
142
+ debug: false, // never enable debug in production regardless of env var
75
143
  migrations: {
76
- directory: path_1.default.join(dirName, migrationsFolder || defaultMigrationsFolder),
77
- schemaName: useSchemaForMigrationsTable ? dbSchema : undefined,
78
- tableName: migrationsTable || defaultMigrationsTable,
144
+ ...migrationsConfig,
79
145
  },
80
146
  seeds: {
81
147
  directory: path_1.default.join(dirName, seedsFolderProd || seedsFolder || defaultSeedsFolder),
82
148
  },
83
149
  },
84
150
  };
85
- let config2use = (0, lodash_1.get)(config, nodeEnv);
86
- if (!config2use) {
87
- config2use = config.development;
88
- }
89
- return config2use;
151
+ // Fix: direct bracket access instead of lodash get() — avoids dot-notation
152
+ // path interpretation (e.g. 'development.migrations' would be misread)
153
+ return config[nodeEnv] ?? config.development;
90
154
  };
91
155
  exports.buildKnexConfig = buildKnexConfig;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Parses a raw :id route param into a single string or an array of strings.
3
+ * If the value contains commas, it is split, trimmed, and empty entries removed.
4
+ * Returns a tuple so callers can branch cleanly without re-checking.
5
+ */
6
+ export declare const parseIds: (raw: string) => [isSingle: boolean, ids: string[]];
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ // ./src/utils/parseIds.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.parseIds = void 0;
5
+ /**
6
+ * Parses a raw :id route param into a single string or an array of strings.
7
+ * If the value contains commas, it is split, trimmed, and empty entries removed.
8
+ * Returns a tuple so callers can branch cleanly without re-checking.
9
+ */
10
+ const parseIds = (raw) => {
11
+ const ids = raw
12
+ .split(',')
13
+ .map((id) => id.trim())
14
+ .filter(Boolean);
15
+ return [ids.length === 1, ids];
16
+ };
17
+ exports.parseIds = parseIds;
@@ -1,5 +1,27 @@
1
+ /**
2
+ * Generates a bcrypt salt and hashes the provided password.
3
+ *
4
+ * @param password The plaintext password to hash. Must be a non-empty string.
5
+ * @param saltRounds The bcrypt cost factor. Higher = slower but more secure.
6
+ * Defaults to 10 (OWASP recommended minimum).
7
+ * Clamped to [10, 31] — values below 10 are insecure,
8
+ * values above 31 would block the event loop for an
9
+ * impractical amount of time.
10
+ * @returns Object containing the generated `salt` and `hash`.
11
+ * @throws If `password` is empty or not a string.
12
+ */
1
13
  export declare const getSaltAndHash: (password: string, saltRounds?: number) => Promise<{
2
14
  salt: string;
3
15
  hash: string;
4
16
  }>;
17
+ /**
18
+ * Compares a plaintext password against a bcrypt hash.
19
+ *
20
+ * Returns false immediately if either argument is missing or not a string —
21
+ * avoids passing invalid input to bcrypt which may throw or behave unexpectedly.
22
+ *
23
+ * @param password The plaintext password to verify.
24
+ * @param hashedPassword The stored bcrypt hash to compare against.
25
+ * @returns True if the password matches the hash, false otherwise.
26
+ */
5
27
  export declare const checkPassword: (password: string, hashedPassword: string) => Promise<boolean>;
@@ -1,21 +1,53 @@
1
1
  "use strict";
2
+ // ./src/passwordHelpers.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
7
  exports.checkPassword = exports.getSaltAndHash = void 0;
7
8
  const bcrypt_1 = __importDefault(require("bcrypt"));
8
- const getSaltAndHash = async (password, saltRounds = 10) => {
9
- const salt = await bcrypt_1.default.genSalt(saltRounds);
9
+ const MIN_SALT_ROUNDS = 10;
10
+ const MAX_SALT_ROUNDS = 31; // bcrypt max — 32+ would block the event loop indefinitely
11
+ /**
12
+ * Generates a bcrypt salt and hashes the provided password.
13
+ *
14
+ * @param password The plaintext password to hash. Must be a non-empty string.
15
+ * @param saltRounds The bcrypt cost factor. Higher = slower but more secure.
16
+ * Defaults to 10 (OWASP recommended minimum).
17
+ * Clamped to [10, 31] — values below 10 are insecure,
18
+ * values above 31 would block the event loop for an
19
+ * impractical amount of time.
20
+ * @returns Object containing the generated `salt` and `hash`.
21
+ * @throws If `password` is empty or not a string.
22
+ */
23
+ const getSaltAndHash = async (password, saltRounds = MIN_SALT_ROUNDS) => {
24
+ if (!password || typeof password !== 'string') {
25
+ throw new Error('getSaltAndHash: password must be a non-empty string');
26
+ }
27
+ // Clamp saltRounds to a safe range — bcrypt cost factor grows exponentially
28
+ const rounds = Math.max(MIN_SALT_ROUNDS, Math.min(saltRounds, MAX_SALT_ROUNDS));
29
+ const salt = await bcrypt_1.default.genSalt(rounds);
10
30
  const hash = await bcrypt_1.default.hash(password, salt);
11
- return {
12
- salt,
13
- hash,
14
- };
31
+ return { salt, hash };
15
32
  };
16
33
  exports.getSaltAndHash = getSaltAndHash;
34
+ /**
35
+ * Compares a plaintext password against a bcrypt hash.
36
+ *
37
+ * Returns false immediately if either argument is missing or not a string —
38
+ * avoids passing invalid input to bcrypt which may throw or behave unexpectedly.
39
+ *
40
+ * @param password The plaintext password to verify.
41
+ * @param hashedPassword The stored bcrypt hash to compare against.
42
+ * @returns True if the password matches the hash, false otherwise.
43
+ */
17
44
  const checkPassword = async (password, hashedPassword) => {
18
- const isCorrect = await bcrypt_1.default.compare(password, hashedPassword);
19
- return isCorrect;
45
+ if (!password || typeof password !== 'string') {
46
+ return false;
47
+ }
48
+ if (!hashedPassword || typeof hashedPassword !== 'string') {
49
+ return false;
50
+ }
51
+ return bcrypt_1.default.compare(password, hashedPassword);
20
52
  };
21
53
  exports.checkPassword = checkPassword;
@@ -1,17 +1,70 @@
1
+ /**
2
+ * Configuration for creating a Redis client via `createRedisClient()`.
3
+ */
1
4
  interface CreateRedisClientInterface {
5
+ /** Redis server hostname or IP address. Required — returns null if not provided. */
2
6
  redisHost: string;
7
+ /** Redis server port. Coerced to Number internally. */
3
8
  redisPort: string | number;
9
+ /** Redis AUTH password. Pass empty string or omit for no authentication. */
4
10
  redisPassword: string;
11
+ /** When true, enables TLS for the connection. */
5
12
  redisSsl: boolean;
6
- retryAttempts?: number;
7
- firstTimeout?: number;
8
- pingInterval?: number;
13
+ /**
14
+ * When true, disables TLS certificate validation.
15
+ * Only applies when `redisSsl` is true.
16
+ * Defaults to true (certificates are validated).
17
+ * Set to false only for self-signed certs in development environments.
18
+ */
19
+ rejectUnauthorized?: boolean;
20
+ /**
21
+ * Maximum reconnect delay in milliseconds.
22
+ * Reconnect delay grows as `retries × 50ms`, capped at this value.
23
+ * Defaults to 500ms.
24
+ */
25
+ maxReconnectDelay?: number;
26
+ /**
27
+ * TCP connection timeout in milliseconds.
28
+ * Defaults to 5000ms.
29
+ */
9
30
  connectionTimeout?: number;
31
+ /**
32
+ * TCP keep-alive initial delay in milliseconds.
33
+ * Defaults to 5000ms.
34
+ */
35
+ pingInterval?: number;
36
+ /** Called when the client begins connecting to the server. */
10
37
  onConnecting?(): void;
38
+ /** Called when the client is connected and ready to accept commands. */
11
39
  onConnected?(): void;
40
+ /** Called when the connection is closed. */
12
41
  onDisconnected?(): void;
42
+ /** Called when the client is attempting to reconnect. */
13
43
  onReconnecting?(): void;
44
+ /**
45
+ * Called when the client encounters an error.
46
+ * If not provided, errors are logged to console.error to prevent
47
+ * unhandled 'error' events from crashing the Node.js process.
48
+ */
14
49
  onError?(err: any): void;
15
50
  }
51
+ /**
52
+ * Creates and configures a Redis client without connecting.
53
+ *
54
+ * The caller is responsible for calling `await redisClient.connect()`
55
+ * when ready — this is intentional to allow the client to be created
56
+ * early in the startup sequence and connected at a controlled point.
57
+ *
58
+ * Returns null if `redisHost` is not provided.
59
+ *
60
+ * Socket behaviour:
61
+ * - `family: 0` — tries IPv6 first, falls back to IPv4
62
+ * - `noDelay: true` — disables Nagle's algorithm for lower latency
63
+ * - `keepAlive: true` — enables TCP keep-alive to detect dead connections
64
+ * - Reconnect delay grows linearly (retries × 50ms), capped at `maxReconnectDelay`
65
+ *
66
+ * @param args CreateRedisClientInterface configuration
67
+ * @returns Configured but unconnected Redis client, or null if redisHost is absent
68
+ */
16
69
  declare const createRedisClient: (args: CreateRedisClientInterface) => any;
17
- export { createRedisClient };
70
+ export { createRedisClient, CreateRedisClientInterface };