@flusys/nestjs-shared 1.1.0-beta → 1.2.0-rc.1

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 (198) hide show
  1. package/README.md +146 -1330
  2. package/cjs/classes/api-controller.class.js +325 -49
  3. package/cjs/classes/api-service.class.js +271 -149
  4. package/cjs/classes/handle-custome-db.js +37 -0
  5. package/cjs/classes/index.js +2 -2
  6. package/cjs/classes/winston.logger.class.js +103 -70
  7. package/cjs/constants/index.js +15 -4
  8. package/cjs/constants/message-keys.js +68 -0
  9. package/cjs/constants/permissions.js +287 -0
  10. package/cjs/decorators/api-response.decorator.js +2 -3
  11. package/cjs/decorators/index.js +1 -0
  12. package/cjs/decorators/log-action.decorator.js +149 -0
  13. package/cjs/decorators/require-permission.decorator.js +5 -5
  14. package/cjs/dtos/delete.dto.js +10 -0
  15. package/cjs/dtos/filter-and-pagination.dto.js +24 -34
  16. package/cjs/dtos/get-by-ids.dto.js +65 -0
  17. package/cjs/dtos/identity-response.dto.js +4 -8
  18. package/cjs/dtos/index.js +1 -0
  19. package/cjs/dtos/pagination.dto.js +4 -8
  20. package/cjs/dtos/response-payload.dto.js +68 -112
  21. package/cjs/entities/identity.js +12 -6
  22. package/cjs/entities/index.js +1 -0
  23. package/cjs/entities/raw-type.js +4 -0
  24. package/cjs/entities/user-root.js +15 -15
  25. package/cjs/enums/index.js +20 -0
  26. package/cjs/enums/notification-type.enum.js +17 -0
  27. package/cjs/enums/participant-status.enum.js +17 -0
  28. package/cjs/enums/recurrence-type.enum.js +18 -0
  29. package/cjs/exceptions/base-app.exception.js +151 -0
  30. package/cjs/exceptions/index.js +1 -0
  31. package/cjs/exceptions/permission.exception.js +13 -9
  32. package/cjs/filters/global-exception.filter.js +279 -0
  33. package/cjs/filters/index.js +18 -0
  34. package/cjs/guards/jwt-auth.guard.js +4 -1
  35. package/cjs/guards/permission.guard.js +88 -148
  36. package/cjs/index.js +2 -0
  37. package/cjs/interceptors/idempotency.interceptor.js +1 -1
  38. package/cjs/interceptors/index.js +1 -4
  39. package/cjs/interceptors/set-user-field-on-body.interceptor.js +60 -0
  40. package/cjs/interceptors/slug.interceptor.js +30 -9
  41. package/cjs/interfaces/datasource.interface.js +4 -0
  42. package/cjs/interfaces/event-manager-adapter.interface.js +11 -0
  43. package/cjs/interfaces/index.js +4 -2
  44. package/cjs/interfaces/module-config.interface.js +4 -0
  45. package/cjs/interfaces/notification-adapter.interface.js +11 -0
  46. package/cjs/interfaces/permission.interface.js +1 -1
  47. package/cjs/middlewares/logger.middleware.js +133 -115
  48. package/cjs/modules/cache/cache.module.js +3 -3
  49. package/cjs/modules/datasource/index.js +0 -1
  50. package/cjs/modules/datasource/multi-tenant-datasource.service.js +60 -183
  51. package/cjs/modules/utils/utils.service.js +27 -206
  52. package/cjs/utils/date-time.util.js +94 -0
  53. package/cjs/utils/html-sanitizer.util.js +64 -0
  54. package/cjs/utils/index.js +5 -1
  55. package/cjs/utils/query-helpers.util.js +60 -0
  56. package/cjs/utils/request.util.js +96 -0
  57. package/cjs/utils/string.util.js +63 -0
  58. package/classes/api-controller.class.d.ts +16 -8
  59. package/classes/api-service.class.d.ts +30 -25
  60. package/classes/handle-custome-db.d.ts +3 -0
  61. package/classes/index.d.ts +2 -2
  62. package/classes/winston.logger.class.d.ts +1 -0
  63. package/constants/index.d.ts +2 -1
  64. package/constants/message-keys.d.ts +45 -0
  65. package/constants/permissions.d.ts +306 -0
  66. package/decorators/api-response.decorator.d.ts +1 -1
  67. package/decorators/current-user.decorator.d.ts +1 -1
  68. package/decorators/index.d.ts +1 -0
  69. package/decorators/log-action.decorator.d.ts +8 -0
  70. package/decorators/require-permission.decorator.d.ts +2 -2
  71. package/dtos/delete.dto.d.ts +1 -0
  72. package/dtos/filter-and-pagination.dto.d.ts +0 -2
  73. package/dtos/get-by-ids.dto.d.ts +4 -0
  74. package/dtos/index.d.ts +1 -0
  75. package/dtos/response-payload.dto.d.ts +8 -20
  76. package/entities/index.d.ts +1 -0
  77. package/entities/raw-type.d.ts +1 -0
  78. package/enums/index.d.ts +3 -0
  79. package/enums/notification-type.enum.d.ts +6 -0
  80. package/enums/participant-status.enum.d.ts +6 -0
  81. package/enums/recurrence-type.enum.d.ts +7 -0
  82. package/exceptions/base-app.exception.d.ts +41 -0
  83. package/exceptions/index.d.ts +1 -0
  84. package/exceptions/permission.exception.d.ts +2 -2
  85. package/fesm/classes/api-controller.class.js +326 -50
  86. package/fesm/classes/api-service.class.js +274 -152
  87. package/fesm/classes/handle-custome-db.js +19 -0
  88. package/fesm/classes/index.js +3 -2
  89. package/fesm/classes/winston.logger.class.js +100 -68
  90. package/fesm/constants/index.js +4 -1
  91. package/fesm/constants/message-keys.js +49 -0
  92. package/fesm/constants/permissions.js +200 -0
  93. package/fesm/decorators/api-response.decorator.js +3 -21
  94. package/fesm/decorators/index.js +1 -0
  95. package/fesm/decorators/log-action.decorator.js +139 -0
  96. package/fesm/decorators/require-permission.decorator.js +17 -65
  97. package/fesm/dtos/delete.dto.js +12 -2
  98. package/fesm/dtos/filter-and-pagination.dto.js +26 -47
  99. package/fesm/dtos/get-by-ids.dto.js +55 -0
  100. package/fesm/dtos/identity-response.dto.js +4 -8
  101. package/fesm/dtos/index.js +1 -0
  102. package/fesm/dtos/pagination.dto.js +4 -8
  103. package/fesm/dtos/response-payload.dto.js +68 -103
  104. package/fesm/entities/identity.js +12 -6
  105. package/fesm/entities/index.js +1 -0
  106. package/fesm/entities/raw-type.js +1 -0
  107. package/fesm/entities/user-root.js +15 -15
  108. package/fesm/enums/index.js +3 -0
  109. package/fesm/enums/notification-type.enum.js +7 -0
  110. package/fesm/enums/participant-status.enum.js +7 -0
  111. package/fesm/enums/recurrence-type.enum.js +8 -0
  112. package/fesm/exceptions/base-app.exception.js +115 -0
  113. package/fesm/exceptions/index.js +1 -0
  114. package/fesm/exceptions/permission.exception.js +16 -18
  115. package/fesm/filters/global-exception.filter.js +269 -0
  116. package/fesm/filters/index.js +1 -0
  117. package/fesm/guards/jwt-auth.guard.js +5 -2
  118. package/fesm/guards/permission.guard.js +90 -150
  119. package/fesm/index.js +2 -0
  120. package/fesm/interceptors/idempotency.interceptor.js +2 -2
  121. package/fesm/interceptors/index.js +1 -4
  122. package/fesm/interceptors/set-user-field-on-body.interceptor.js +39 -0
  123. package/fesm/interceptors/slug.interceptor.js +31 -10
  124. package/fesm/interfaces/datasource.interface.js +1 -0
  125. package/fesm/interfaces/event-manager-adapter.interface.js +1 -0
  126. package/fesm/interfaces/index.js +4 -2
  127. package/fesm/interfaces/module-config.interface.js +5 -0
  128. package/fesm/interfaces/notification-adapter.interface.js +1 -0
  129. package/fesm/interfaces/permission.interface.js +1 -3
  130. package/fesm/middlewares/logger.middleware.js +133 -109
  131. package/fesm/modules/cache/cache.module.js +2 -2
  132. package/fesm/modules/datasource/index.js +0 -1
  133. package/fesm/modules/datasource/multi-tenant-datasource.service.js +61 -184
  134. package/fesm/modules/utils/utils.service.js +27 -206
  135. package/fesm/utils/date-time.util.js +70 -0
  136. package/fesm/utils/html-sanitizer.util.js +69 -0
  137. package/fesm/utils/index.js +5 -1
  138. package/fesm/utils/query-helpers.util.js +85 -0
  139. package/fesm/utils/request.util.js +81 -0
  140. package/fesm/utils/string.util.js +71 -0
  141. package/filters/global-exception.filter.d.ts +9 -0
  142. package/filters/index.d.ts +1 -0
  143. package/guards/permission.guard.d.ts +4 -6
  144. package/index.d.ts +2 -0
  145. package/interceptors/idempotency.interceptor.d.ts +1 -1
  146. package/interceptors/index.d.ts +1 -4
  147. package/interceptors/set-user-field-on-body.interceptor.d.ts +5 -0
  148. package/interceptors/slug.interceptor.d.ts +2 -1
  149. package/interfaces/api.interface.d.ts +4 -2
  150. package/interfaces/datasource.interface.d.ts +5 -0
  151. package/interfaces/event-manager-adapter.interface.d.ts +43 -0
  152. package/interfaces/identity.interface.d.ts +4 -4
  153. package/interfaces/index.d.ts +4 -2
  154. package/interfaces/logged-user-info.interface.d.ts +0 -2
  155. package/interfaces/module-config.interface.d.ts +6 -0
  156. package/interfaces/notification-adapter.interface.d.ts +21 -0
  157. package/interfaces/permission.interface.d.ts +13 -9
  158. package/middlewares/logger.middleware.d.ts +2 -2
  159. package/modules/datasource/index.d.ts +0 -1
  160. package/modules/datasource/multi-tenant-datasource.service.d.ts +5 -16
  161. package/modules/utils/utils.service.d.ts +3 -14
  162. package/package.json +21 -14
  163. package/utils/date-time.util.d.ts +8 -0
  164. package/utils/html-sanitizer.util.d.ts +2 -0
  165. package/utils/index.d.ts +5 -1
  166. package/utils/query-helpers.util.d.ts +16 -0
  167. package/utils/request.util.d.ts +6 -0
  168. package/utils/string.util.d.ts +2 -0
  169. package/cjs/classes/request-scoped-api.service.js +0 -61
  170. package/cjs/classes/winston-logger-adapter.class.js +0 -121
  171. package/cjs/interceptors/query-performance.interceptor.js +0 -66
  172. package/cjs/interceptors/set-create-by-on-body.interceptor.js +0 -40
  173. package/cjs/interceptors/set-delete-by-on-body.interceptor.js +0 -40
  174. package/cjs/interceptors/set-update-by-on-body.interceptor.js +0 -40
  175. package/cjs/interfaces/base-query.interface.js +0 -6
  176. package/cjs/interfaces/logger.interface.js +0 -7
  177. package/cjs/modules/datasource/datasource.module.js +0 -120
  178. package/cjs/utils/error-handler.util.js +0 -67
  179. package/classes/request-scoped-api.service.d.ts +0 -13
  180. package/classes/winston-logger-adapter.class.d.ts +0 -20
  181. package/fesm/classes/request-scoped-api.service.js +0 -51
  182. package/fesm/classes/winston-logger-adapter.class.js +0 -124
  183. package/fesm/interceptors/query-performance.interceptor.js +0 -56
  184. package/fesm/interceptors/set-create-by-on-body.interceptor.js +0 -30
  185. package/fesm/interceptors/set-delete-by-on-body.interceptor.js +0 -30
  186. package/fesm/interceptors/set-update-by-on-body.interceptor.js +0 -30
  187. package/fesm/interfaces/base-query.interface.js +0 -3
  188. package/fesm/interfaces/logger.interface.js +0 -4
  189. package/fesm/modules/datasource/datasource.module.js +0 -110
  190. package/fesm/utils/error-handler.util.js +0 -59
  191. package/interceptors/query-performance.interceptor.d.ts +0 -8
  192. package/interceptors/set-create-by-on-body.interceptor.d.ts +0 -5
  193. package/interceptors/set-delete-by-on-body.interceptor.d.ts +0 -5
  194. package/interceptors/set-update-by-on-body.interceptor.d.ts +0 -5
  195. package/interfaces/base-query.interface.d.ts +0 -7
  196. package/interfaces/logger.interface.d.ts +0 -7
  197. package/modules/datasource/datasource.module.d.ts +0 -18
  198. package/utils/error-handler.util.d.ts +0 -24
@@ -0,0 +1,70 @@
1
+ function getOffsetMinutes(utcDate, timezone) {
2
+ const extract = (tz)=>{
3
+ const parts = new Intl.DateTimeFormat('en-US', {
4
+ timeZone: tz,
5
+ year: 'numeric',
6
+ month: '2-digit',
7
+ day: '2-digit',
8
+ hour: '2-digit',
9
+ minute: '2-digit',
10
+ second: '2-digit',
11
+ hour12: false
12
+ }).formatToParts(utcDate);
13
+ const p = Object.fromEntries(parts.filter((x)=>x.type !== 'literal').map((x)=>[
14
+ x.type,
15
+ parseInt(x.value)
16
+ ]));
17
+ return Date.UTC(p['year'], p['month'] - 1, p['day'], p['hour'], p['minute'], p['second']);
18
+ };
19
+ return (extract(timezone) - extract('UTC')) / 60_000;
20
+ }
21
+ export function localToUtc(dateStr, timeStr, timezone) {
22
+ const [year, month, day] = dateStr.split('-').map(Number);
23
+ const [hours, minutes] = timeStr.split(':').map(Number);
24
+ const approx = new Date(Date.UTC(year, month - 1, day, hours, minutes, 0));
25
+ const offset = getOffsetMinutes(approx, timezone);
26
+ const utcDate = new Date(approx.getTime() - offset * 60_000);
27
+ // DST boundary guard: re-check offset after adjustment
28
+ const finalOffset = getOffsetMinutes(utcDate, timezone);
29
+ return finalOffset !== offset ? new Date(approx.getTime() - finalOffset * 60_000) : utcDate;
30
+ }
31
+ export function utcToLocal(utcDate, timezone) {
32
+ const d = typeof utcDate === 'string' ? new Date(utcDate) : utcDate;
33
+ const parts = new Intl.DateTimeFormat('en-CA', {
34
+ timeZone: timezone,
35
+ year: 'numeric',
36
+ month: '2-digit',
37
+ day: '2-digit',
38
+ hour: '2-digit',
39
+ minute: '2-digit',
40
+ hour12: false
41
+ }).formatToParts(d);
42
+ const p = Object.fromEntries(parts.filter((x)=>x.type !== 'literal').map((x)=>[
43
+ x.type,
44
+ x.value
45
+ ]));
46
+ // en-CA formats midnight hour as '24' — normalize to '00'
47
+ const hour = p['hour'] === '24' ? '00' : p['hour'];
48
+ return {
49
+ date: `${p['year']}-${p['month']}-${p['day']}`,
50
+ time: `${hour}:${p['minute']}`,
51
+ display: new Intl.DateTimeFormat('en-US', {
52
+ timeZone: timezone,
53
+ dateStyle: 'medium',
54
+ timeStyle: 'short'
55
+ }).format(d)
56
+ };
57
+ }
58
+ export function formatInTimezone(utcDate, timezone, options = {
59
+ dateStyle: 'medium',
60
+ timeStyle: 'short'
61
+ }) {
62
+ const d = typeof utcDate === 'string' ? new Date(utcDate) : utcDate;
63
+ return new Intl.DateTimeFormat('en-US', {
64
+ ...options,
65
+ timeZone: timezone
66
+ }).format(d);
67
+ }
68
+ export function getTodayInTimezone(timezone) {
69
+ return utcToLocal(new Date(), timezone).date;
70
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * HTML Sanitizer Utilities
3
+ *
4
+ * Provides functions for escaping HTML content to prevent XSS attacks.
5
+ * Use these utilities when interpolating user-provided variables into HTML content.
6
+ */ /**
7
+ * HTML entity mapping for escaping special characters
8
+ */ const HTML_ESCAPE_MAP = {
9
+ '&': '&',
10
+ '<': '&lt;',
11
+ '>': '&gt;',
12
+ '"': '&quot;',
13
+ "'": '&#x27;',
14
+ '/': '&#x2F;',
15
+ '`': '&#x60;',
16
+ '=': '&#x3D;'
17
+ };
18
+ /**
19
+ * Regex pattern matching characters that need HTML escaping
20
+ */ const HTML_ESCAPE_REGEX = /[&<>"'`=/]/g;
21
+ /**
22
+ * Escapes HTML special characters to prevent XSS attacks.
23
+ *
24
+ * @param str - The string to escape
25
+ * @returns The escaped string safe for HTML insertion
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * escapeHtml('<script>alert("xss")</script>')
30
+ * // Returns: '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
31
+ * ```
32
+ */ export function escapeHtml(str) {
33
+ if (!str || typeof str !== 'string') {
34
+ return str ?? '';
35
+ }
36
+ return str.replace(HTML_ESCAPE_REGEX, (char)=>HTML_ESCAPE_MAP[char]);
37
+ }
38
+ /**
39
+ * Escapes all string values in a variables object for safe HTML interpolation.
40
+ * Non-string values are converted to strings and escaped.
41
+ *
42
+ * @param variables - Object containing template variables
43
+ * @returns New object with all string values HTML-escaped
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * escapeHtmlVariables({ name: '<script>xss</script>', count: 5 })
48
+ * // Returns: { name: '&lt;script&gt;xss&lt;/script&gt;', count: '5' }
49
+ * ```
50
+ */ export function escapeHtmlVariables(variables) {
51
+ if (!variables || typeof variables !== 'object') {
52
+ return {};
53
+ }
54
+ const escaped = {};
55
+ for (const [key, value] of Object.entries(variables)){
56
+ if (value === null || value === undefined) {
57
+ escaped[key] = '';
58
+ } else if (typeof value === 'string') {
59
+ escaped[key] = escapeHtml(value);
60
+ } else if (typeof value === 'object') {
61
+ // For objects/arrays, stringify and escape
62
+ escaped[key] = escapeHtml(JSON.stringify(value));
63
+ } else {
64
+ // For numbers, booleans, etc., convert to string (no escaping needed)
65
+ escaped[key] = String(value);
66
+ }
67
+ }
68
+ return escaped;
69
+ }
@@ -1 +1,5 @@
1
- export * from './error-handler.util';
1
+ export * from './date-time.util';
2
+ export * from './html-sanitizer.util';
3
+ export * from './query-helpers.util';
4
+ export * from './request.util';
5
+ export * from './string.util';
@@ -0,0 +1,85 @@
1
+ import { BadRequestException } from '@nestjs/common';
2
+ import { AUTH_MESSAGES } from '../constants';
3
+ /**
4
+ * Apply company filter to a query builder if company feature is enabled.
5
+ * Centralizes the common pattern of filtering by user's company.
6
+ *
7
+ * @param query - TypeORM SelectQueryBuilder
8
+ * @param config - Company filter configuration
9
+ * @param user - Current logged user (may be null)
10
+ * @returns The modified query builder
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * applyCompanyFilter(query, {
15
+ * isCompanyFeatureEnabled: this.config.isCompanyFeatureEnabled(),
16
+ * entityAlias: 'file_manager',
17
+ * }, user);
18
+ * ```
19
+ */ export function applyCompanyFilter(query, config, user) {
20
+ const columnName = config.columnName ?? 'companyId';
21
+ if (config.isCompanyFeatureEnabled && user?.companyId) {
22
+ query.andWhere(`${config.entityAlias}.${columnName} = :companyId`, {
23
+ companyId: user.companyId
24
+ });
25
+ }
26
+ return query;
27
+ }
28
+ /**
29
+ * Build a where condition object with optional company filter.
30
+ *
31
+ * @param baseWhere - Base where condition object
32
+ * @param isCompanyFeatureEnabled - Whether company feature is enabled
33
+ * @param user - Current logged user
34
+ * @returns Where condition with companyId added if applicable
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * const where = buildCompanyWhereCondition(
39
+ * { id: dto.id },
40
+ * this.config.isCompanyFeatureEnabled(),
41
+ * user
42
+ * );
43
+ * // Returns { id: dto.id, companyId: user.companyId } if company feature enabled
44
+ * ```
45
+ */ export function buildCompanyWhereCondition(baseWhere, isCompanyFeatureEnabled, user) {
46
+ if (isCompanyFeatureEnabled && user?.companyId) {
47
+ return {
48
+ ...baseWhere,
49
+ companyId: user.companyId
50
+ };
51
+ }
52
+ return baseWhere;
53
+ }
54
+ /**
55
+ * Type guard to check if entity has companyId property
56
+ */ export function hasCompanyId(entity) {
57
+ return entity !== null && typeof entity === 'object' && 'companyId' in entity;
58
+ }
59
+ /**
60
+ * Validates that an entity with companyId belongs to the user's company.
61
+ * Throws BadRequestException if the entity belongs to another company.
62
+ *
63
+ * @param entity - Entity to validate
64
+ * @param user - Current logged user
65
+ * @param isCompanyFeatureEnabled - Whether company feature is enabled
66
+ * @param entityName - Name of entity for error message (e.g., 'Email configuration')
67
+ * @throws BadRequestException if entity belongs to another company
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * validateCompanyOwnership(config, user, this.config.isCompanyFeatureEnabled(), 'Email configuration');
72
+ * ```
73
+ */ export function validateCompanyOwnership(entity, user, isCompanyFeatureEnabled, entityName) {
74
+ if (isCompanyFeatureEnabled && user?.companyId && hasCompanyId(entity)) {
75
+ if (entity.companyId && entity.companyId !== user.companyId) {
76
+ throw new BadRequestException({
77
+ message: `${entityName} belongs to another company`,
78
+ messageKey: AUTH_MESSAGES.ENTITY_BELOG_ANOTHER_COMPANY,
79
+ messageVariables: {
80
+ entity: entityName
81
+ }
82
+ });
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,81 @@
1
+ import { envConfig } from '@flusys/nestjs-core/config';
2
+ import { CLIENT_TYPE_HEADER } from '../constants';
3
+ /** Time unit multipliers in milliseconds */ const TIME_UNIT_MS = {
4
+ s: 1000,
5
+ m: 60 * 1000,
6
+ h: 60 * 60 * 1000,
7
+ d: 24 * 60 * 60 * 1000,
8
+ w: 7 * 24 * 60 * 60 * 1000
9
+ };
10
+ /** Get normalized client type from request header */ function getClientType(req) {
11
+ const clientType = req.headers[CLIENT_TYPE_HEADER];
12
+ return clientType ? clientType.toLowerCase() : null;
13
+ }
14
+ /**
15
+ * Detect if request is from a browser client.
16
+ * Uses x-client-type header first, then falls back to user-agent detection.
17
+ */ export function isBrowserRequest(req) {
18
+ const clientType = getClientType(req);
19
+ if (clientType) {
20
+ return clientType === 'browser' || clientType === 'web';
21
+ }
22
+ const accept = req.headers['accept'] || '';
23
+ if (accept.includes('text/html')) return true;
24
+ const userAgent = req.headers['user-agent'] || '';
25
+ const browserPatterns = /mozilla|chrome|safari|firefox|edge|opera|msie/i;
26
+ return browserPatterns.test(userAgent) && !userAgent.includes('Postman');
27
+ }
28
+ /**
29
+ * Build secure cookie options based on request context.
30
+ * Handles HTTPS detection for TLS-terminating proxies.
31
+ */ export function buildCookieOptions(req) {
32
+ const hostname = req.hostname || '';
33
+ const origin = req.headers.origin || '';
34
+ const isProduction = envConfig.isProduction();
35
+ const forwardedProto = req.headers['x-forwarded-proto'];
36
+ const isHttps = isProduction || forwardedProto === 'https' || origin.startsWith('https://') || req.secure;
37
+ let domain;
38
+ const domainParts = hostname.split('.');
39
+ if (domainParts.length > 2 && !hostname.includes('localhost')) {
40
+ domain = '.' + domainParts.slice(-2).join('.');
41
+ }
42
+ return {
43
+ secure: isHttps,
44
+ sameSite: isHttps ? 'strict' : 'lax',
45
+ ...domain && {
46
+ domain
47
+ }
48
+ };
49
+ }
50
+ /**
51
+ * Parse duration string to milliseconds.
52
+ * @example '7d' → 604800000, '24h' → 86400000, '30m' → 1800000
53
+ */ export function parseDurationToMs(duration, defaultMs = TIME_UNIT_MS.w) {
54
+ const match = duration.match(/^(\d+)(s|m|h|d|w)$/);
55
+ if (!match) return defaultMs;
56
+ const value = parseInt(match[1], 10);
57
+ const unit = match[2];
58
+ return value * (TIME_UNIT_MS[unit] ?? TIME_UNIT_MS.d);
59
+ }
60
+ /**
61
+ * Determine the frontend base URL for auth-related links.
62
+ * Uses allowed origins from envConfig first, then falls back to request host.
63
+ */ export function extractFrontendUrl(req) {
64
+ const allowedOrigins = envConfig.getOrigins();
65
+ const origin = (req.get('origin') ?? req.get('referer') ?? '').trim();
66
+ if (origin && allowedOrigins.length) {
67
+ const matched = allowedOrigins.find((u)=>origin.startsWith(u));
68
+ if (matched) {
69
+ return matched;
70
+ }
71
+ }
72
+ const host = req.get('host');
73
+ if (!host) {
74
+ throw new Error('Unable to determine frontend URL from request');
75
+ }
76
+ return `${req.protocol}://${host}`;
77
+ }
78
+ export function buildFrontendUrl(req, path) {
79
+ const baseUrl = extractFrontendUrl(req);
80
+ return `${baseUrl}${path}`;
81
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * String utility functions
3
+ */ /**
4
+ * Generate URL-friendly slug from a string
5
+ * @param text - The text to convert to slug
6
+ * @param maxLength - Maximum length of the slug (default: 100)
7
+ * @returns URL-friendly slug
8
+ *
9
+ * @example
10
+ * generateSlug('My Company Name') // 'my-company-name'
11
+ * generateSlug('Hello World!') // 'hello-world'
12
+ */ export function generateSlug(text, maxLength = 100) {
13
+ return text.toLowerCase().trim().replace(/[^a-z0-9\s-]/g, '') // Remove special characters
14
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
15
+ .replace(/-+/g, '-') // Replace multiple hyphens with single
16
+ .replace(/^-+|-+$/g, '') // Remove leading/trailing hyphens
17
+ .substring(0, maxLength);
18
+ }
19
+ /**
20
+ * Generate unique slug using single database query (optimized for large datasets)
21
+ * Appends numeric suffix if collision exists (e.g., 'my-company-1', 'my-company-2')
22
+ *
23
+ * Performance: O(1) database query regardless of collision count
24
+ * - Works efficiently with millions of records
25
+ * - Requires index on slug column for best performance
26
+ *
27
+ * @param text - The text to convert to slug
28
+ * @param findMatchingSlugs - Async function that returns all slugs matching base pattern
29
+ * Should query: WHERE slug = baseSlug OR slug LIKE 'baseSlug-%'
30
+ * @param maxLength - Maximum length of the base slug (default: 100)
31
+ * @returns Unique URL-friendly slug
32
+ *
33
+ * @example
34
+ * const slug = await generateUniqueSlug('My Company', async (baseSlug) => {
35
+ * return repo
36
+ * .createQueryBuilder('c')
37
+ * .select('c.slug')
38
+ * .where('c.slug = :base OR c.slug LIKE :pattern', {
39
+ * base: baseSlug,
40
+ * pattern: `${baseSlug}-%`,
41
+ * })
42
+ * .getMany()
43
+ * .then(rows => rows.map(r => r.slug));
44
+ * });
45
+ */ export async function generateUniqueSlug(text, findMatchingSlugs, maxLength = 100) {
46
+ const baseSlug = generateSlug(text, maxLength);
47
+ // Single query to get all matching slugs
48
+ const existingSlugs = await findMatchingSlugs(baseSlug);
49
+ // No collisions - base slug is available
50
+ if (existingSlugs.length === 0) {
51
+ return baseSlug;
52
+ }
53
+ // Build set for O(1) lookup
54
+ const existingSet = new Set(existingSlugs);
55
+ // Base slug not taken (only suffixed versions exist)
56
+ if (!existingSet.has(baseSlug)) {
57
+ return baseSlug;
58
+ }
59
+ // Find next available suffix in memory (fast)
60
+ let counter = 1;
61
+ while(counter < 10000){
62
+ const slugWithSuffix = `${baseSlug}-${counter}`;
63
+ if (!existingSet.has(slugWithSuffix)) {
64
+ return slugWithSuffix;
65
+ }
66
+ counter++;
67
+ }
68
+ // Fallback: append random string (extremely rare edge case)
69
+ const randomSuffix = Math.random().toString(36).substring(2, 8);
70
+ return `${baseSlug}-${randomSuffix}`;
71
+ }
@@ -0,0 +1,9 @@
1
+ import { ArgumentsHost, ExceptionFilter } from '@nestjs/common';
2
+ export declare class GlobalExceptionFilter implements ExceptionFilter {
3
+ private readonly logger;
4
+ catch(exception: unknown, host: ArgumentsHost): void;
5
+ private resolveException;
6
+ private resolveHttpException;
7
+ private resolveQueryFailedError;
8
+ private toHumanReadable;
9
+ }
@@ -0,0 +1 @@
1
+ export * from './global-exception.filter';
@@ -1,18 +1,16 @@
1
1
  import { CanActivate, ExecutionContext } from '@nestjs/common';
2
2
  import { Reflector } from '@nestjs/core';
3
3
  import { HybridCache } from '../classes/hybrid-cache.class';
4
- import { ILogger } from '../interfaces/logger.interface';
5
4
  import { PermissionGuardConfig } from '../interfaces/permission.interface';
6
5
  export declare class PermissionGuard implements CanActivate {
7
6
  private readonly reflector;
8
7
  private readonly cache?;
9
8
  private readonly config;
10
- private readonly logger;
11
- constructor(reflector: Reflector, cache?: HybridCache, config?: PermissionGuardConfig, logger?: ILogger);
9
+ constructor(reflector: Reflector, cache?: HybridCache | undefined, config?: PermissionGuardConfig);
12
10
  canActivate(context: ExecutionContext): Promise<boolean>;
13
- private normalizePermissionConfig;
14
- private isNestedCondition;
15
- private evaluateCondition;
11
+ private normalizeToLogicNode;
12
+ private evaluateLogicNode;
16
13
  private getUserPermissions;
14
+ private buildPermissionCacheKey;
17
15
  private hasPermission;
18
16
  }
package/index.d.ts CHANGED
@@ -3,7 +3,9 @@ export * from './constants';
3
3
  export * from './decorators';
4
4
  export * from './dtos';
5
5
  export * from './entities';
6
+ export * from './enums';
6
7
  export * from './exceptions';
8
+ export * from './filters';
7
9
  export * from './guards';
8
10
  export * from './interceptors';
9
11
  export * from './interfaces';
@@ -5,6 +5,6 @@ export declare class IdempotencyInterceptor implements NestInterceptor {
5
5
  private readonly cache?;
6
6
  private readonly CACHE_TTL;
7
7
  private readonly PROCESSING_MARKER;
8
- constructor(cache?: HybridCache);
8
+ constructor(cache?: HybridCache | undefined);
9
9
  intercept<T = any>(context: ExecutionContext, next: CallHandler<T>): Promise<Observable<T>>;
10
10
  }
@@ -1,8 +1,5 @@
1
1
  export * from './delete-empty-id-from-body.interceptor';
2
2
  export * from './idempotency.interceptor';
3
- export * from './query-performance.interceptor';
4
3
  export * from './response-meta.interceptor';
5
- export * from './set-create-by-on-body.interceptor';
6
- export * from './set-delete-by-on-body.interceptor';
7
- export * from './set-update-by-on-body.interceptor';
4
+ export * from './set-user-field-on-body.interceptor';
8
5
  export * from './slug.interceptor';
@@ -0,0 +1,5 @@
1
+ import { NestInterceptor, Type } from '@nestjs/common';
2
+ export declare function createSetUserFieldInterceptor(fieldName: string): Type<NestInterceptor>;
3
+ export declare const SetCreatedByOnBody: Type<NestInterceptor<any, any>>;
4
+ export declare const SetUpdateByOnBody: Type<NestInterceptor<any, any>>;
5
+ export declare const SetDeletedByOnBody: Type<NestInterceptor<any, any>>;
@@ -2,6 +2,7 @@ import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
2
2
  import { Observable } from 'rxjs';
3
3
  import { UtilsService } from '../modules/utils/utils.service';
4
4
  export declare class Slug implements NestInterceptor {
5
- utilsService: UtilsService;
5
+ private readonly utilsService;
6
+ constructor(utilsService: UtilsService);
6
7
  intercept<T = any>(context: ExecutionContext, next: CallHandler<T>): Observable<T>;
7
8
  }
@@ -1,14 +1,16 @@
1
- import { DeleteDto, FilterAndPaginationDto } from '@flusys/nestjs-shared/dtos';
2
- import { ILoggedUserInfo } from '@flusys/nestjs-shared/interfaces';
1
+ import { DeleteDto, FilterAndPaginationDto } from '../dtos';
2
+ import { ILoggedUserInfo } from './logged-user-info.interface';
3
3
  export interface IService<CreateDtoT, UpdateDtoT, InterfaceT> {
4
4
  insert(addDto: CreateDtoT, user: ILoggedUserInfo | null): Promise<InterfaceT>;
5
5
  insertMany(addDto: Array<CreateDtoT>, user: ILoggedUserInfo | null): Promise<Array<InterfaceT>>;
6
6
  findById(id: string, user: ILoggedUserInfo | null, select?: string[]): Promise<InterfaceT>;
7
+ findByIds(ids: string[], user: ILoggedUserInfo | null, select?: string[] | string): Promise<Array<InterfaceT>>;
7
8
  getAll(search: string, filterAndPaginationDto: FilterAndPaginationDto, user: ILoggedUserInfo | null): Promise<{
8
9
  data: Array<InterfaceT>;
9
10
  total: number;
10
11
  }>;
11
12
  update(updateDto: UpdateDtoT, user: ILoggedUserInfo | null): Promise<InterfaceT>;
12
13
  updateMany(updateDto: Array<UpdateDtoT>, user: ILoggedUserInfo | null): Promise<Array<InterfaceT>>;
14
+ bulkUpsert(toInsert: Array<CreateDtoT>, toUpdate: Array<UpdateDtoT>, user: ILoggedUserInfo | null): Promise<Array<InterfaceT>>;
13
15
  delete(deleteDto: DeleteDto, user: ILoggedUserInfo | null): Promise<null>;
14
16
  }
@@ -0,0 +1,5 @@
1
+ import { DataSource, EntityTarget, ObjectLiteral, Repository } from 'typeorm';
2
+ export interface IDataSourceProvider {
3
+ getRepository<T extends ObjectLiteral>(entity: EntityTarget<T>): Promise<Repository<T>>;
4
+ getDataSource(): Promise<DataSource>;
5
+ }
@@ -0,0 +1,43 @@
1
+ import { ParticipantStatus } from '../enums/participant-status.enum';
2
+ import { RecurrenceType } from '../enums/recurrence-type.enum';
3
+ export interface IEventManagerAdapter {
4
+ createEvent(options: CreateEventOptions): Promise<EventResult>;
5
+ updateParticipantStatus(participantId: string, status: ParticipantStatus): Promise<void>;
6
+ getEventsForUser?(userId: string, startDate: Date, endDate: Date, companyId?: string): Promise<EventResult[]>;
7
+ getEventById?(eventId: string): Promise<EventResult | null>;
8
+ }
9
+ export interface CreateEventOptions {
10
+ title: string;
11
+ description?: string;
12
+ eventDate: string;
13
+ startTime: string;
14
+ endTime: string;
15
+ isAllDay?: boolean;
16
+ recurrenceType?: RecurrenceType;
17
+ recurrenceEndDate?: string | null;
18
+ weekDays?: string[] | null;
19
+ color?: string;
20
+ meetingLink?: string | null;
21
+ participantIds?: string[];
22
+ organizerId?: string;
23
+ companyId?: string;
24
+ }
25
+ export interface EventResult {
26
+ id: string;
27
+ title: string;
28
+ description?: string | null;
29
+ eventDate: string;
30
+ startTime: string;
31
+ endTime: string;
32
+ isAllDay: boolean;
33
+ recurrenceType: string;
34
+ recurrenceEndDate?: string | null;
35
+ weekDays?: string[] | null;
36
+ color: string;
37
+ meetingLink?: string | null;
38
+ isActive: boolean;
39
+ companyId?: string | null;
40
+ createdAt: Date;
41
+ updatedAt: Date;
42
+ }
43
+ export declare const EVENT_MANAGER_ADAPTER = "EVENT_MANAGER_ADAPTER";
@@ -2,8 +2,8 @@ export interface IIdentity {
2
2
  id: string;
3
3
  createdAt: Date;
4
4
  updatedAt: Date;
5
- deletedAt: Date;
6
- createdById: string;
7
- updatedById: string;
8
- deletedById: string;
5
+ deletedAt: Date | null;
6
+ createdById: string | null;
7
+ updatedById: string | null;
8
+ deletedById: string | null;
9
9
  }
@@ -1,6 +1,8 @@
1
1
  export * from './api.interface';
2
- export * from './base-query.interface';
2
+ export * from './datasource.interface';
3
+ export * from './event-manager-adapter.interface';
3
4
  export * from './identity.interface';
4
5
  export * from './logged-user-info.interface';
5
- export * from './logger.interface';
6
+ export * from './module-config.interface';
7
+ export * from './notification-adapter.interface';
6
8
  export * from './permission.interface';
@@ -6,6 +6,4 @@ export interface ILoggedUserInfo {
6
6
  profilePictureId?: string;
7
7
  companyId?: string;
8
8
  branchId?: string;
9
- companyLogoId?: string;
10
- branchLogoId?: string;
11
9
  }
@@ -0,0 +1,6 @@
1
+ import { DatabaseMode } from '@flusys/nestjs-core';
2
+ export interface IModuleConfigService {
3
+ getDatabaseMode(): DatabaseMode;
4
+ isMultiTenant(): boolean;
5
+ isCompanyFeatureEnabled(): boolean;
6
+ }
@@ -0,0 +1,21 @@
1
+ import { NotificationType } from '../enums/notification-type.enum';
2
+ export declare const NOTIFICATION_ADAPTER = "NOTIFICATION_ADAPTER";
3
+ export interface INotificationContent {
4
+ title: string;
5
+ message?: string | null;
6
+ type?: NotificationType;
7
+ data?: Record<string, unknown> | null;
8
+ companyId?: string | null;
9
+ realtime?: boolean;
10
+ }
11
+ export interface INotificationSendOptions extends INotificationContent {
12
+ userId: string;
13
+ }
14
+ export interface INotificationBulkSendOptions extends INotificationContent {
15
+ userIds: string[];
16
+ }
17
+ export interface INotificationAdapter {
18
+ send(options: INotificationSendOptions): Promise<void>;
19
+ sendToMany(options: INotificationBulkSendOptions): Promise<void>;
20
+ isUserOnline?(userId: string): boolean;
21
+ }
@@ -1,17 +1,21 @@
1
- export type PermissionOperator = 'and' | 'or';
2
- export interface PermissionCondition {
3
- permissions?: string[];
4
- operator: PermissionOperator;
5
- children?: PermissionCondition[];
1
+ export interface IActionNode {
2
+ type: 'action';
3
+ actionId: string;
6
4
  }
7
- export interface LegacyPermissionConfig {
5
+ export interface IGroupNode {
6
+ type: 'group';
7
+ operator: 'AND' | 'OR';
8
+ children: ILogicNode[];
9
+ }
10
+ export type ILogicNode = IActionNode | IGroupNode;
11
+ export type IPermissionLogic = string | ILogicNode;
12
+ export interface SimplePermissionConfig {
8
13
  permissions: string[];
9
- operator: PermissionOperator;
14
+ operator: 'AND' | 'OR';
10
15
  }
11
- export type PermissionConfig = PermissionCondition | LegacyPermissionConfig | string[];
16
+ export type PermissionConfig = IPermissionLogic | SimplePermissionConfig | string[];
12
17
  export interface PermissionGuardConfig {
13
18
  enableCompanyFeature?: boolean;
14
- cacheKeyPrefix?: string;
15
19
  userPermissionKeyFormat?: string;
16
20
  companyPermissionKeyFormat?: string;
17
21
  }
@@ -13,11 +13,11 @@ export declare const getRequestId: () => string | undefined;
13
13
  export declare const getTenantId: () => string | undefined;
14
14
  export declare const getUserId: () => string | undefined;
15
15
  export declare const getCompanyId: () => string | undefined;
16
- export declare const setUserId: (userId: string) => void;
17
- export declare const setCompanyId: (companyId: string) => void;
18
16
  export declare class LoggerMiddleware implements NestMiddleware {
19
17
  private readonly logger;
20
18
  use(req: Request, res: Response, next: NextFunction): void;
19
+ private setupResponseLogging;
21
20
  private logRequest;
22
21
  private logResponse;
22
+ private buildBaseLogData;
23
23
  }
@@ -1,2 +1 @@
1
- export * from './datasource.module';
2
1
  export * from './multi-tenant-datasource.service';