@sdflc/backend-helpers 1.0.111 → 1.0.113

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 (206) 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 +470 -33
  5. package/build/BaseCore.js +613 -126
  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/RedisDataLoader.d.ts +144 -21
  19. package/build/RedisDataLoader.js +178 -49
  20. package/build/apiContext.d.ts +0 -8
  21. package/build/apiContext.js +12 -27
  22. package/build/checkItHelpers.d.ts +32 -0
  23. package/build/checkItHelpers.js +73 -7
  24. package/build/commonValidators.d.ts +107 -16
  25. package/build/commonValidators.js +211 -106
  26. package/build/configBuilder.d.ts +23 -0
  27. package/build/configBuilder.js +73 -0
  28. package/build/constants.d.ts +134 -17
  29. package/build/constants.js +95 -15
  30. package/build/dbHelpers.d.ts +89 -29
  31. package/build/dbHelpers.js +175 -86
  32. package/build/dbSeeder.d.ts +10 -1
  33. package/build/dbSeeder.js +80 -15
  34. package/build/dbTableHelpers.d.ts +122 -5
  35. package/build/dbTableHelpers.js +151 -13
  36. package/build/downloadHelpers.d.ts +24 -1
  37. package/build/downloadHelpers.js +51 -21
  38. package/build/esm/BaseController.d.ts +20 -0
  39. package/build/esm/BaseController.js +58 -0
  40. package/build/esm/BaseCore.d.ts +470 -33
  41. package/build/esm/BaseCore.js +615 -128
  42. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  43. package/build/esm/BaseExternalApiGateway.js +48 -0
  44. package/build/esm/BaseGateway.d.ts +455 -17
  45. package/build/esm/BaseGateway.js +503 -57
  46. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  47. package/build/esm/BaseRestApiCrudController.js +131 -0
  48. package/build/esm/DataCache.d.ts +116 -5
  49. package/build/esm/DataCache.js +142 -20
  50. package/build/esm/Database.d.ts +165 -4
  51. package/build/esm/Database.js +224 -51
  52. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  53. package/build/esm/DbMigratorAndSeeder.js +184 -71
  54. package/build/esm/RedisDataLoader.d.ts +144 -21
  55. package/build/esm/RedisDataLoader.js +179 -50
  56. package/build/esm/apiContext.d.ts +0 -8
  57. package/build/esm/apiContext.js +12 -27
  58. package/build/esm/checkItHelpers.d.ts +32 -0
  59. package/build/esm/checkItHelpers.js +73 -7
  60. package/build/esm/commonValidators.d.ts +107 -16
  61. package/build/esm/commonValidators.js +209 -105
  62. package/build/esm/configBuilder.d.ts +23 -0
  63. package/build/esm/configBuilder.js +69 -0
  64. package/build/esm/constants.d.ts +134 -17
  65. package/build/esm/constants.js +94 -14
  66. package/build/esm/dbHelpers.d.ts +89 -29
  67. package/build/esm/dbHelpers.js +171 -81
  68. package/build/esm/dbSeeder.d.ts +10 -1
  69. package/build/esm/dbSeeder.js +81 -16
  70. package/build/esm/dbTableHelpers.d.ts +122 -5
  71. package/build/esm/dbTableHelpers.js +152 -14
  72. package/build/esm/downloadHelpers.d.ts +24 -1
  73. package/build/esm/downloadHelpers.js +51 -21
  74. package/build/esm/index.d.ts +5 -2
  75. package/build/esm/index.js +5 -2
  76. package/build/esm/interfaces/ApiContext.d.ts +7 -3
  77. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  78. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  79. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  80. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  81. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  82. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +87 -9
  83. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  84. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  85. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  86. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  87. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  88. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  89. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  90. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  91. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  92. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  93. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  94. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  95. package/build/esm/interfaces/CacheInterface.js +1 -0
  96. package/build/esm/interfaces/CoreActionInterface.d.ts +20 -0
  97. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  98. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  99. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  100. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  101. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  102. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  103. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  104. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  106. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  107. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  110. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  111. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  112. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  113. package/build/esm/interfaces/LoaderInterface.js +1 -0
  114. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  115. package/build/esm/interfaces/UserTokenParams.js +1 -0
  116. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  117. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  118. package/build/esm/interfaces/index.d.ts +4 -0
  119. package/build/esm/interfaces/index.js +4 -0
  120. package/build/esm/knexConfigBuilder.d.ts +25 -0
  121. package/build/esm/knexConfigBuilder.js +100 -36
  122. package/build/esm/parseIds.d.ts +6 -0
  123. package/build/esm/parseIds.js +13 -0
  124. package/build/esm/passwordHelpers.d.ts +22 -0
  125. package/build/esm/passwordHelpers.js +40 -8
  126. package/build/esm/redisClient.d.ts +57 -4
  127. package/build/esm/redisClient.js +40 -54
  128. package/build/esm/resolveClientIp.d.ts +15 -0
  129. package/build/esm/resolveClientIp.js +34 -0
  130. package/build/esm/resolversHelpers.d.ts +21 -1
  131. package/build/esm/resolversHelpers.js +48 -26
  132. package/build/esm/userToken.d.ts +50 -1
  133. package/build/esm/userToken.js +85 -20
  134. package/build/esm/utils.d.ts +20 -0
  135. package/build/esm/utils.js +23 -1
  136. package/build/index.d.ts +5 -2
  137. package/build/index.js +5 -2
  138. package/build/interfaces/ApiContext.d.ts +7 -3
  139. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  140. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  141. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  142. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  143. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  144. package/build/interfaces/BaseCorePropsInterface.d.ts +87 -9
  145. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  146. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  147. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  148. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  149. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  150. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  151. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  152. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  153. package/build/interfaces/BuildConfigOptions.js +1 -0
  154. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  155. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  156. package/build/interfaces/CacheInterface.d.ts +18 -1
  157. package/build/interfaces/CacheInterface.js +1 -0
  158. package/build/interfaces/CoreActionInterface.d.ts +20 -0
  159. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  160. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  161. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  162. package/build/interfaces/DataCachePropsInterface.js +3 -0
  163. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  164. package/build/interfaces/DatabaseOptions.js +1 -0
  165. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  166. package/build/interfaces/DatabaseReadInterface.js +1 -0
  167. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  168. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  169. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  170. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  171. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  172. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  173. package/build/interfaces/ListArgsInterface.js +1 -0
  174. package/build/interfaces/LoaderInterface.d.ts +36 -1
  175. package/build/interfaces/LoaderInterface.js +1 -0
  176. package/build/interfaces/UserTokenParams.d.ts +23 -5
  177. package/build/interfaces/UserTokenParams.js +1 -0
  178. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  179. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  180. package/build/interfaces/index.d.ts +4 -0
  181. package/build/interfaces/index.js +4 -0
  182. package/build/knexConfigBuilder.d.ts +25 -0
  183. package/build/knexConfigBuilder.js +99 -35
  184. package/build/parseIds.d.ts +6 -0
  185. package/build/parseIds.js +17 -0
  186. package/build/passwordHelpers.d.ts +22 -0
  187. package/build/passwordHelpers.js +40 -8
  188. package/build/redisClient.d.ts +57 -4
  189. package/build/redisClient.js +40 -54
  190. package/build/resolveClientIp.d.ts +15 -0
  191. package/build/resolveClientIp.js +38 -0
  192. package/build/resolversHelpers.d.ts +21 -1
  193. package/build/resolversHelpers.js +48 -26
  194. package/build/userToken.d.ts +50 -1
  195. package/build/userToken.js +85 -20
  196. package/build/utils.d.ts +20 -0
  197. package/build/utils.js +23 -1
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -63
  201. package/build/configBulder.d.ts +0 -2
  202. package/build/configBulder.js +0 -36
  203. package/build/esm/baseController.d.ts +0 -17
  204. package/build/esm/baseController.js +0 -57
  205. package/build/esm/configBulder.d.ts +0 -2
  206. package/build/esm/configBulder.js +0 -32
@@ -1,14 +1,69 @@
1
1
  /**
2
- * Interface for Database.ReadAll method
2
+ * Arguments for the Database.read() convenience method.
3
+ * Provides a structured alternative to building a Knex query manually
4
+ * for simple SELECT operations with optional filtering, mapping, and
5
+ * computed field support.
3
6
  */
4
7
  export interface DatabaseReadInterface {
8
+ /**
9
+ * Table name to query. Passed directly to getBuilder().
10
+ */
5
11
  table?: string;
12
+ /**
13
+ * Columns to SELECT. Defaults to '*' if not provided or empty.
14
+ */
6
15
  selectFields?: string[];
16
+ /**
17
+ * Sort configuration. Declared for interface completeness but NOT
18
+ * currently applied inside read() — sorting must be handled by the
19
+ * caller via createLimitOffsetSortBy() before calling read(), or
20
+ * via extendQuery(). This field is a no-op in the current implementation.
21
+ */
7
22
  sortBy?: any;
23
+ /**
24
+ * Object passed to Knex's .where() for equality filtering.
25
+ * e.g. `{ status: 'active', spaceId: '123' }`
26
+ */
8
27
  where?: any;
9
- whereIn?: any;
28
+ /**
29
+ * Configures a Knex .whereIn() clause.
30
+ * e.g. `{ field: 'id', values: ['a', 'b', 'c'] }`
31
+ */
32
+ whereIn?: {
33
+ field: string;
34
+ values: any[];
35
+ };
36
+ /**
37
+ * Optional async function to extend the Knex query with additional
38
+ * clauses (JOINs, subqueries, additional WHERE conditions, etc.)
39
+ * before it is executed. Receives the live Knex query builder instance.
40
+ *
41
+ * @param query The Knex query builder, mutated in place
42
+ */
10
43
  extendQuery?(query: any): any;
44
+ /**
45
+ * When set, results are reduced into a `Record<string, row>` keyed by
46
+ * the camelCase value of this field on each row, processed through
47
+ * the `buildKey` function. Useful for building lookup maps.
48
+ * e.g. `mapBy: 'id'` produces `{ 'abc-123': row, ... }`
49
+ */
11
50
  mapBy?: string;
51
+ /**
52
+ * Computed field descriptors applied to each result row after the query.
53
+ * Each entry is `{ name: string, value: any | ((row) => any) }`.
54
+ * If `value` is a function it receives the row and returns the computed value.
55
+ * Entries missing `name` are skipped with a warning.
56
+ */
12
57
  calculated?: any[];
13
- buildKey?(key: string): string;
58
+ /**
59
+ * Custom key builder for the mapBy lookup map.
60
+ * Receives the raw field value from each row and returns the string key.
61
+ * Defaults to buildKey from @sdflc/utils if not provided.
62
+ * Typed as `any` input since the field value may not be a string
63
+ * (e.g. UUID objects, numbers, composite values).
64
+ *
65
+ * Fix: was typed as `(key: string) => string` but the input is the raw
66
+ * field value which may be of any type.
67
+ */
68
+ buildKey?(key: any): string;
14
69
  }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/DatabaseReadInterface.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,9 +1,40 @@
1
1
  export interface DbFieldAddDefaultInterface {
2
- addUserInfo?: boolean;
3
- addVersion?: boolean;
2
+ /**
3
+ * When true, adds a `status` integer column (indexed) with default STATUSES.ACTIVE.
4
+ */
4
5
  addStatus?: boolean;
5
- skipTimestamps?: boolean;
6
- skipRemovedAtStr?: boolean;
6
+ /**
7
+ * Custom comment for the status column.
8
+ * Defaults to a description of all known status values.
9
+ */
7
10
  statusComment?: string;
11
+ /**
12
+ * When true, adds a `version` integer column defaulting to 0.
13
+ * Used for optimistic locking — incremented on each update.
14
+ */
15
+ addVersion?: boolean;
16
+ /**
17
+ * Custom comment for the version column.
18
+ */
8
19
  versionComment?: string;
20
+ /**
21
+ * When true, adds created_by, updated_by, and removed_by UUID columns.
22
+ * These reference the user who performed each operation.
23
+ * removed_by is always added alongside the others for schema consistency,
24
+ * even if the table uses hard deletes.
25
+ */
26
+ addUserInfo?: boolean;
27
+ /**
28
+ * When true, skips adding all timestamp-related columns:
29
+ * created_at, updated_at, removed_at, and removed_at_str.
30
+ * Also skips their associated indexes.
31
+ * Defaults to false (timestamps are added by default).
32
+ */
33
+ skipTimestamps?: boolean;
34
+ /**
35
+ * When true, skips adding the `removed_at_str` column and its index.
36
+ * Has no effect when `skipTimestamps` is also true.
37
+ * Defaults to false (removed_at_str is added by default with timestamps).
38
+ */
39
+ skipRemovedAtStr?: boolean;
9
40
  }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
+ // ./src/interfaces/DbFieldAddDefaultInterface.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,6 +1,25 @@
1
+ import type { Writable } from 'stream';
1
2
  export interface DownloadFileArgs {
3
+ /**
4
+ * URL of the file to download. Required.
5
+ */
2
6
  url: string;
3
- fileName: string;
7
+ /**
8
+ * Local file name to save as. Optional — if not provided, the file name
9
+ * is derived from the last path segment of the URL, or `<hostname>.html`
10
+ * for root URLs.
11
+ */
12
+ fileName?: string;
13
+ /**
14
+ * Absolute path to the folder where the file should be saved.
15
+ * Optional — defaults to process.cwd() if not provided.
16
+ */
4
17
  folder?: string;
5
- stream?: any;
18
+ /**
19
+ * Custom writable stream to pipe the download into.
20
+ * Optional — if not provided, a write stream to `folder/fileName` is created.
21
+ * Use this for in-memory targets, cloud storage uploads, or other
22
+ * non-filesystem destinations.
23
+ */
24
+ stream?: Writable;
6
25
  }
@@ -1,19 +1,30 @@
1
1
  export interface ExtractCredentialsArgs {
2
2
  /**
3
- * Req is a request object of the Express library
3
+ * Express request object. Used to read cookies and headers.
4
4
  */
5
5
  req: any;
6
6
  /**
7
- * Space is an object with configuration where to get data from
7
+ * The resolved space object for the current request.
8
+ * Provides cookieName and fingerprintCookieName for cookie-based auth,
9
+ * and apiKey for API key auth fallback.
8
10
  */
9
11
  space: any;
10
12
  /**
11
- * Authorization is a token from the Authorization header
13
+ * Authorization token extracted from the Authorization header upstream
14
+ * (e.g. already stripped of 'Bearer ' prefix in createContextDefault).
15
+ * Used as a fallback if no cookie or header token is found on req.
12
16
  */
13
17
  authorization?: string;
18
+ /**
19
+ * Fingerprint value extracted upstream (e.g. from X-Fingerprint header).
20
+ * Used as a fallback if no fingerprint cookie or header is found on req.
21
+ */
14
22
  fingerprint?: string;
15
23
  /**
16
- * An object with parameters passed to the authenticate methods
24
+ * The original args object passed to the authenticating action.
25
+ * Available for subclasses that override extractCredentials() and need
26
+ * to derive credentials from action-specific parameters.
27
+ * Not used in the base implementation.
17
28
  */
18
29
  params?: any;
19
30
  }
@@ -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>;