zibri 1.5.1 → 1.6.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.
package/dist/index.d.mts CHANGED
@@ -9,6 +9,7 @@ import { JwtHeader, Secret, SignOptions } from 'jsonwebtoken';
9
9
  import { Readable } from 'stream';
10
10
  import { Transporter } from 'nodemailer';
11
11
  import SMTPTransport from 'nodemailer/lib/smtp-transport';
12
+ import { Counter, Gauge, Histogram } from 'prom-client';
12
13
 
13
14
  /**
14
15
  * Metadata shared by all properties.
@@ -199,24 +200,56 @@ type DatePropertyMetadataInput = Partial<OmitStrict<DatePropertyMetadata, 'type'
199
200
  */
200
201
  declare enum HttpMethod {
201
202
  GET = "get",
203
+ HEAD = "head",
202
204
  POST = "post",
203
205
  PUT = "put",
204
206
  PATCH = "patch",
205
- DELETE = "delete"
207
+ DELETE = "delete",
208
+ OPTIONS = "options",
209
+ TRACE = "trace"
206
210
  }
207
211
 
208
212
  /**
209
213
  * Known http status.
210
214
  */
211
215
  declare enum HttpStatus {
216
+ CONTINUE = 100,
217
+ SWITCHING_PROTOCOLS = 101,
218
+ PROCESSING = 102,
212
219
  OK = 200,
213
220
  CREATED = 201,
221
+ ACCEPTED = 202,
222
+ NON_AUTHORITATIVE_INFORMATION = 203,
223
+ NO_CONTENT = 204,
224
+ RESET_CONTENT = 205,
225
+ PARTIAL_CONTENT = 206,
226
+ MULTIPLE_CHOICES = 300,
227
+ MOVED_PERMANENTLY = 301,
228
+ FOUND = 302,
229
+ SEE_OTHER = 303,
230
+ NOT_MODIFIED = 304,
231
+ TEMPORARY_REDIRECT = 307,
232
+ PERMANENT_REDIRECT = 308,
214
233
  BAD_REQUEST = 400,
215
234
  UNAUTHORIZED = 401,
235
+ PAYMENT_REQUIRED = 402,
216
236
  FORBIDDEN = 403,
217
237
  NOT_FOUND_ERROR = 404,
238
+ METHOD_NOT_ALLOWED = 405,
239
+ NOT_ACCEPTABLE = 406,
240
+ CONFLICT = 409,
241
+ GONE = 410,
242
+ PAYLOAD_TOO_LARGE = 413,
243
+ URI_TOO_LONG = 414,
244
+ UNSUPPORTED_MEDIA_TYPE = 415,
245
+ UNPROCESSABLE_ENTITY = 422,
218
246
  TOO_MANY_REQUESTS = 429,
219
- INTERNAL_SERVER_ERROR = 500
247
+ INTERNAL_SERVER_ERROR = 500,
248
+ NOT_IMPLEMENTED = 501,
249
+ BAD_GATEWAY = 502,
250
+ SERVICE_UNAVAILABLE = 503,
251
+ GATEWAY_TIMEOUT = 504,
252
+ HTTP_VERSION_NOT_SUPPORTED = 505
220
253
  }
221
254
 
222
255
  /**
@@ -382,6 +415,20 @@ type FilePropertyMetadata = BasePropertyMetadata & {
382
415
  */
383
416
  type FilePropertyMetadataInput = Partial<OmitStrict<FilePropertyMetadata, 'type'>>;
384
417
 
418
+ /**
419
+ * Metadata for unknown properties.
420
+ */
421
+ type UnknownPropertyMetadata = BasePropertyMetadata & {
422
+ /**
423
+ * The type of the property.
424
+ */
425
+ type: 'unknown';
426
+ };
427
+ /**
428
+ * Input Metadata for unknown properties.
429
+ */
430
+ type UnknownPropertyMetadataInput = Partial<OmitStrict<UnknownPropertyMetadata, 'type'>>;
431
+
385
432
  /**
386
433
  * Metadata for array properties.
387
434
  */
@@ -414,6 +461,8 @@ type ArrayPropertyItemMetadataInput = StringPropertyMetadataInput & {
414
461
  type: 'date';
415
462
  } | BooleanPropertyMetadataInput & {
416
463
  type: 'boolean';
464
+ } | UnknownPropertyMetadataInput & {
465
+ type: 'unknown';
417
466
  } | FilePropertyMetadataInput & {
418
467
  type: 'file';
419
468
  };
@@ -463,6 +512,16 @@ type BaseRelationMetadata<T extends BaseEntity> = BasePropertyMetadata & Require
463
512
  inverseSide: keyof T | undefined;
464
513
  };
465
514
 
515
+ /**
516
+ * All possible relations.
517
+ */
518
+ declare enum Relation {
519
+ ONE_TO_ONE = "one-to-one",
520
+ ONE_TO_MANY = "one-to-many",
521
+ MANY_TO_ONE = "many-to-one",
522
+ MANY_TO_MANY = "many-to-many"
523
+ }
524
+
466
525
  /**
467
526
  * Metadata for many to one properties.
468
527
  */
@@ -523,20 +582,10 @@ type ManyToManyPropertyMetadata<T extends BaseEntity> = BaseRelationMetadata<T>
523
582
  */
524
583
  type ManyToManyPropertyMetadataInput<T extends BaseEntity> = Partial<OmitStrict<ManyToManyPropertyMetadata<T>, 'type'>> & Pick<ManyToManyPropertyMetadata<T>, 'target' | 'joinTable'>;
525
584
 
526
- /**
527
- * All possible relations.
528
- */
529
- declare enum Relation {
530
- ONE_TO_ONE = "one-to-one",
531
- ONE_TO_MANY = "one-to-many",
532
- MANY_TO_ONE = "many-to-one",
533
- MANY_TO_MANY = "many-to-many"
534
- }
535
-
536
585
  /**
537
586
  * The metadata of a property.
538
587
  */
539
- type PropertyMetadata = StringPropertyMetadata | NumberPropertyMetadata | ObjectPropertyMetadata | ArrayPropertyMetadata | DatePropertyMetadata | BooleanPropertyMetadata | FilePropertyMetadata | RelationMetadata<BaseEntity>;
588
+ type PropertyMetadata = StringPropertyMetadata | NumberPropertyMetadata | ObjectPropertyMetadata | ArrayPropertyMetadata | DatePropertyMetadata | BooleanPropertyMetadata | FilePropertyMetadata | UnknownPropertyMetadata | RelationMetadata<BaseEntity>;
540
589
  /**
541
590
  * The metadata of relation properties.
542
591
  */
@@ -544,7 +593,7 @@ type RelationMetadata<T extends BaseEntity> = ManyToOnePropertyMetadata<T> | One
544
593
  /**
545
594
  * The metadata input to define a property.
546
595
  */
547
- type PropertyMetadataInput = StringPropertyMetadataInput | NumberPropertyMetadataInput | ObjectPropertyMetadataInput | ArrayPropertyMetadataInput | DatePropertyMetadataInput | FilePropertyMetadataInput | BooleanPropertyMetadataInput;
596
+ type PropertyMetadataInput = StringPropertyMetadataInput | NumberPropertyMetadataInput | ObjectPropertyMetadataInput | ArrayPropertyMetadataInput | DatePropertyMetadataInput | FilePropertyMetadataInput | BooleanPropertyMetadataInput | UnknownPropertyMetadataInput;
548
597
  /**
549
598
  * The metadata input to define a relation property.
550
599
  */
@@ -588,6 +637,11 @@ declare namespace Property {
588
637
  * @param data - Additional data to specify the property.
589
638
  */
590
639
  function array(data: ArrayPropertyMetadataInput): PropertyDecorator;
640
+ /**
641
+ * Defines an unknown property.
642
+ * @param data - Additional data to specify the property.
643
+ */
644
+ function unknown(data?: UnknownPropertyMetadataInput): PropertyDecorator;
591
645
  /**
592
646
  * Defines a many to one property.
593
647
  * @param metadata - Additional data to specify the property.
@@ -1023,21 +1077,21 @@ interface RouterInterface {
1023
1077
  /**
1024
1078
  * Register a controller.
1025
1079
  */
1026
- registerController: (controllerClass: Newable<unknown>, ...params: any[]) => void;
1080
+ registerController: (controllerClass: Newable<unknown>, ...params: any[]) => void | Promise<void>;
1027
1081
  /**
1028
1082
  * Register a route.
1029
1083
  */
1030
1084
  register: <BodyMetaInputObject extends BodyMetadataInput & {
1031
1085
  modelClass: Newable<unknown>;
1032
- }, PathMetaInputObject extends Record<string, PathParamMetadataInput>, QueryMetaInputObject extends Record<string, QueryParamMetadataInput>, HeaderMetaInputObject extends Record<string, HeaderParamMetadataInput>>(route: RouteConfigurationInput<BodyMetaInputObject, PathMetaInputObject, QueryMetaInputObject, HeaderMetaInputObject>, ...params: any[]) => void;
1086
+ }, PathMetaInputObject extends Record<string, PathParamMetadataInput>, QueryMetaInputObject extends Record<string, QueryParamMetadataInput>, HeaderMetaInputObject extends Record<string, HeaderParamMetadataInput>>(route: RouteConfigurationInput<BodyMetaInputObject, PathMetaInputObject, QueryMetaInputObject, HeaderMetaInputObject>, ...params: any[]) => void | Promise<void>;
1033
1087
  /**
1034
1088
  * Initializes the router, registers controllers etc.
1035
1089
  */
1036
- init: (app: ZibriApplication, ...params: any[]) => void;
1090
+ init: (app: ZibriApplication, ...params: any[]) => void | Promise<void>;
1037
1091
  /**
1038
1092
  * Attaches the router to the app.
1039
1093
  */
1040
- attachTo: (app: ZibriApplication, ...params: any[]) => void;
1094
+ attachTo: (app: ZibriApplication, ...params: any[]) => void | Promise<void>;
1041
1095
  /**
1042
1096
  * All routes that have been manually registered by calling the .register method.
1043
1097
  */
@@ -1056,14 +1110,14 @@ declare class Router implements RouterInterface {
1056
1110
  private readonly allowedOrphans;
1057
1111
  readonly manuallyRegisteredRoutes: RouteConfiguration<BodyMetadata, Record<string, PathParamMetadata>, Record<string, QueryParamMetadata>, Record<string, HeaderParamMetadata>>[];
1058
1112
  constructor();
1059
- init(app: ZibriApplication): void;
1113
+ init(app: ZibriApplication): Promise<void>;
1060
1114
  attachTo(app: ZibriApplication): void;
1061
1115
  private checkForOrphanedControllers;
1062
1116
  register<BodyMetaInputObject extends BodyMetadataInput & {
1063
1117
  modelClass: Newable<unknown>;
1064
- }, PathMetaInputObject extends Record<string, PathParamMetadataInput>, QueryMetaInputObject extends Record<string, QueryParamMetadataInput>, HeaderMetaInputObject extends Record<string, HeaderParamMetadataInput>>(input: RouteConfigurationInput<BodyMetaInputObject, PathMetaInputObject, QueryMetaInputObject, HeaderMetaInputObject>): void;
1118
+ }, PathMetaInputObject extends Record<string, PathParamMetadataInput>, QueryMetaInputObject extends Record<string, QueryParamMetadataInput>, HeaderMetaInputObject extends Record<string, HeaderParamMetadataInput>>(input: RouteConfigurationInput<BodyMetaInputObject, PathMetaInputObject, QueryMetaInputObject, HeaderMetaInputObject>): Promise<void>;
1065
1119
  private createOpenApiRouteConfiguration;
1066
- registerController(controllerClass: Newable<unknown>): void;
1120
+ registerController(controllerClass: Newable<unknown>): Promise<void>;
1067
1121
  private routeToRequestHandler;
1068
1122
  private controllerRouteToRequestHandler;
1069
1123
  private returnResult;
@@ -1208,11 +1262,11 @@ interface OpenApiServiceInterface {
1208
1262
  /**
1209
1263
  * Attaches the service to the Zibri application.
1210
1264
  */
1211
- attachTo: (app: ZibriApplication) => void;
1265
+ attachTo: (app: ZibriApplication) => void | Promise<void>;
1212
1266
  /**
1213
1267
  * Creates the open api definition.
1214
1268
  */
1215
- createOpenApiDefinition: (app: ZibriApplication) => OpenApiDefinition;
1269
+ createOpenApiDefinition: (app: ZibriApplication) => OpenApiDefinition | Promise<OpenApiDefinition>;
1216
1270
  }
1217
1271
 
1218
1272
  /**
@@ -1224,8 +1278,8 @@ declare class OpenApiService implements OpenApiServiceInterface {
1224
1278
  private readonly assetService;
1225
1279
  private readonly authService;
1226
1280
  constructor();
1227
- attachTo(app: ZibriApplication): void;
1228
- createOpenApiDefinition(app: ZibriApplication): OpenApiDefinition;
1281
+ attachTo(app: ZibriApplication): Promise<void>;
1282
+ createOpenApiDefinition(app: ZibriApplication): Promise<OpenApiDefinition>;
1229
1283
  private resolveSecuritySchemes;
1230
1284
  private resolveOpenApiPaths;
1231
1285
  private buildResponses;
@@ -1638,7 +1692,7 @@ interface AuthServiceInterface {
1638
1692
  /**
1639
1693
  * Initializes the service.
1640
1694
  */
1641
- init: (strategies: AuthStrategies) => void;
1695
+ init: (strategies: AuthStrategies) => void | Promise<void>;
1642
1696
  /**
1643
1697
  * Checks if the provided method on the provided controller can be accessed by the current user.
1644
1698
  */
@@ -1659,22 +1713,22 @@ interface AuthServiceInterface {
1659
1713
  * Resolves the is logged in metadata for the provided controller method.
1660
1714
  * (Whether it's required to be logged in, etc.).
1661
1715
  */
1662
- resolveIsLoggedInMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => IsLoggedInMetadata | undefined;
1716
+ resolveIsLoggedInMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => IsLoggedInMetadata | undefined | Promise<IsLoggedInMetadata | undefined>;
1663
1717
  /**
1664
1718
  * Resolves the is not logged in metadata for the provided controller method.
1665
1719
  * (Whether it's required to be logged out, etc.).
1666
1720
  */
1667
- resolveIsNotLoggedInMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => IsNotLoggedInMetadata | undefined;
1721
+ resolveIsNotLoggedInMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => IsNotLoggedInMetadata | undefined | Promise<IsNotLoggedInMetadata | undefined>;
1668
1722
  /**
1669
1723
  * Resolves the has role metadata for the provided controller method.
1670
1724
  * (Whether it's required for the user to have a certain role etc.).
1671
1725
  */
1672
- resolveHasRoleMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => HasRoleMetadata | undefined;
1726
+ resolveHasRoleMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => HasRoleMetadata | undefined | Promise<HasRoleMetadata | undefined>;
1673
1727
  /**
1674
1728
  * Resolves the belongs to metadata for the provided controller method.
1675
1729
  * (Whether it's required for the user to somehow belong to the requested entity, etc.).
1676
1730
  */
1677
- resolveBelongsToMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => BelongsToMetadata<Newable<BaseEntity>> | undefined;
1731
+ resolveBelongsToMetadata: (controllerClass: Newable<unknown>, controllerMethod: string) => BelongsToMetadata<Newable<BaseEntity>> | undefined | Promise<BelongsToMetadata<Newable<BaseEntity>> | undefined>;
1678
1732
  /**
1679
1733
  * Logs in a user using the provided auth strategy and credentials.
1680
1734
  */
@@ -1698,182 +1752,126 @@ interface AuthServiceInterface {
1698
1752
  }
1699
1753
 
1700
1754
  /**
1701
- * Interface for a logger.
1755
+ * Context information about a request that triggered a log.
1702
1756
  */
1703
- interface LoggerInterface {
1757
+ declare class LogRequestContext {
1704
1758
  /**
1705
- * Logs a debug message.
1759
+ * The http method of the request.
1706
1760
  */
1707
- debug: (...messages: (string | number)[]) => void;
1761
+ method: HttpMethod;
1708
1762
  /**
1709
- * Logs a info message.
1763
+ * The complete url that was requested.
1710
1764
  */
1711
- info: (...messages: (string | number)[]) => void;
1765
+ url: string;
1712
1766
  /**
1713
- * Logs a warning.
1767
+ * The ip address of the client.
1714
1768
  */
1715
- warn: (...messages: (string | number)[]) => void;
1769
+ clientIp: string;
1716
1770
  /**
1717
- * Logs a error.
1771
+ * The user agent of the client.
1718
1772
  */
1719
- error: (...messages: (string | number | Error)[]) => void;
1773
+ userAgent: string;
1720
1774
  /**
1721
- * Logs a critical error.
1775
+ * The http status of the response, if the request already finished.
1722
1776
  */
1723
- critical: (...messages: (string | number | Error)[]) => void;
1724
- }
1725
-
1726
- declare const LOG_LEVEL_VALUES: {
1727
- readonly debug: 0;
1728
- readonly info: 1;
1729
- readonly warn: 2;
1730
- readonly error: 3;
1731
- readonly critical: 4;
1732
- };
1733
- type LogLevels = typeof LOG_LEVEL_VALUES;
1734
- /**
1735
- * The possible log levels.
1736
- */
1737
- type LogLevel = keyof LogLevels;
1738
- /**
1739
- * Default logger implementation of Zibri.
1740
- */
1741
- declare class Logger implements LoggerInterface {
1742
- debug(...messages: (string | number)[]): void;
1743
- info(...messages: (string | number)[]): void;
1744
- warn(...messages: (string | number)[]): void;
1745
- error(...messages: (string | number | Error)[]): void;
1746
- critical(...messages: (string | number | Error)[]): void;
1747
- private log;
1777
+ status?: HttpStatus;
1778
+ /**
1779
+ * The duration that the request took in ms, if it already finished.
1780
+ */
1781
+ durationInMs?: number;
1748
1782
  }
1749
-
1750
1783
  /**
1751
- * Default auth service implementation of Zibri.
1784
+ * Context for the log, like the request, the id of the user if applicable and the stack trace.
1752
1785
  */
1753
- declare class AuthService implements AuthServiceInterface {
1786
+ declare class LogContext {
1754
1787
  /**
1755
- * A logger.
1788
+ * The path of the file where the log originated from.
1756
1789
  */
1757
- protected readonly logger: LoggerInterface;
1758
- readonly strategies: AuthStrategies;
1759
- constructor();
1760
- init(authStrategies: AuthStrategies): void;
1761
- login<Role extends string, UserType extends BaseUser<Role>, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, credentials: CredentialsType): Promise<AuthDataType>;
1762
- refreshLogin<Role extends string, UserType extends BaseUser<Role>, RefreshLoginDataType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, data: RefreshLoginDataType): Promise<AuthDataType>;
1763
- getCurrentUser<Role extends string, UserType extends BaseUser<Role>, B extends boolean = true>(request: HttpRequest, allowedStrategies: AuthStrategies, required: B): Promise<B extends false ? UserType | undefined : UserType>;
1764
- requestPasswordReset<Role extends string, UserType extends BaseUser<Role>, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, data: RequestPasswordResetDataType): Promise<void>;
1765
- confirmPasswordReset<Role extends string, UserType extends BaseUser<Role>, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, data: ConfirmPasswordResetDataType): Promise<void>;
1766
- checkAccess(controllerClass: Newable<unknown>, controllerMethod: string, request: HttpRequest): Promise<void>;
1767
- isLoggedIn(request: HttpRequest, allowedStrategies: AuthStrategies): Promise<boolean>;
1768
- hasRole(request: HttpRequest, allowedStrategies: AuthStrategies, allowedRoles: string[]): Promise<boolean>;
1769
- belongsTo<TargetEntity extends Newable<BaseEntity>>(request: HttpRequest, allowedStrategies: AuthStrategies, targetEntity: TargetEntity, targetUserIdKey: keyof InstanceType<TargetEntity>, targetIdParamKey: string): Promise<boolean>;
1770
- resolveIsLoggedInMetadata(controllerClass: Newable<unknown>, controllerMethod: string): IsLoggedInMetadata | undefined;
1771
- resolveIsNotLoggedInMetadata(controllerClass: Newable<unknown>, controllerMethod: string): IsNotLoggedInMetadata | undefined;
1772
- resolveHasRoleMetadata(controllerClass: Newable<unknown>, controllerMethod: string): HasRoleMetadata | undefined;
1773
- resolveBelongsToMetadata(controllerClass: Newable<unknown>, controllerMethod: string): BelongsToMetadata<Newable<BaseEntity>> | undefined;
1790
+ origin: string;
1791
+ /**
1792
+ * Context information about the request that triggered the log.
1793
+ */
1794
+ request?: LogRequestContext;
1774
1795
  }
1796
+ /**
1797
+ * The input for creating a new log context.
1798
+ */
1799
+ type LogContextInput = OmitStrict<LogContext, 'origin'>;
1775
1800
 
1776
1801
  /**
1777
- * The payload of a jwt access token.
1802
+ * The different possible log levels.
1778
1803
  */
1779
- type JwtAccessTokenPayload<Role extends string, T extends BaseUser<Role>> = {
1804
+ declare enum LogLevel {
1780
1805
  /**
1781
- * The id of the user.
1806
+ * Used only for debugging, is only active after manually enabling it.
1807
+ * Data is deleted as soon as debug is turned off again.
1782
1808
  */
1783
- id: T['id'];
1809
+ DEBUG = 0,
1784
1810
  /**
1785
- * The email of the user.
1811
+ * A simple information of what is happening.
1786
1812
  */
1787
- email: T['email'];
1813
+ INFO = 1,
1788
1814
  /**
1789
- * The roles of the user.
1815
+ * A warning, that the application has reached a state that might lead to errors.
1790
1816
  */
1791
- roles: T['roles'];
1792
- };
1793
-
1794
- /**
1795
- * A Jwt, consisting of the token value and the expiration date.
1796
- */
1797
- declare class Jwt {
1817
+ WARN = 2,
1798
1818
  /**
1799
- * The token value.
1819
+ * Something is not working as intended.
1800
1820
  */
1801
- value: string;
1821
+ ERROR = 3,
1802
1822
  /**
1803
- * The timestamp at which the token is no longer valid.
1823
+ * Immediate action is required.
1804
1824
  */
1805
- expirationDate: Date;
1825
+ CRITICAL = 4
1806
1826
  }
1807
1827
 
1808
1828
  /**
1809
- * The authentication data that gets returned when logging in or refreshing the login.
1829
+ * A logged error.
1810
1830
  */
1811
- declare class JwtAuthData<Role extends string> {
1812
- /**
1813
- * The id of the user of the jwt.
1814
- */
1815
- userId: string;
1831
+ declare class LoggedError {
1816
1832
  /**
1817
- * The short lived access token.
1833
+ * The name of the error.
1818
1834
  */
1819
- accessToken: Jwt;
1835
+ name: string;
1820
1836
  /**
1821
- * The long lived refresh token.
1837
+ * A paragraphs error with the error message.
1822
1838
  */
1823
- refreshToken: Jwt;
1839
+ paragraphs: string[];
1824
1840
  /**
1825
- * The roles of the user.
1841
+ * The stack trace of the error.
1826
1842
  */
1827
- roles: Role[];
1843
+ stackTrace: string[];
1828
1844
  }
1829
1845
 
1830
1846
  /**
1831
- * The data used to confirm a password reset.
1847
+ * The data saved for a log entry.
1832
1848
  */
1833
- declare class JwtConfirmPasswordResetData {
1849
+ declare class Log implements BaseEntity {
1850
+ id: string;
1834
1851
  /**
1835
- * The reset token value.
1852
+ * The log level.
1836
1853
  */
1837
- resetToken: string;
1854
+ level: LogLevel;
1838
1855
  /**
1839
- * The new password that should be used from now on.
1856
+ * The message that was logged.
1840
1857
  */
1841
- newPassword: string;
1842
- }
1843
-
1844
- /**
1845
- * The credentials used by the jwt auth strategy.
1846
- */
1847
- declare class JwtCredentials implements Pick<BaseUser<string>, 'id' | 'email'> {
1848
- id: string;
1858
+ message: string;
1849
1859
  /**
1850
- * The id of the user that this credentials belong to.
1860
+ * An error logged by LogLevel.ERROR and LogLevel.CRITICAL.
1851
1861
  */
1852
- userId: string;
1862
+ error?: LoggedError;
1853
1863
  /**
1854
- * The email of the user.
1864
+ * The context of the log.
1855
1865
  */
1856
- email: string;
1866
+ context: LogContext;
1857
1867
  /**
1858
- * The password.
1868
+ * A timestamp of the log.
1859
1869
  */
1860
- password: string;
1861
- }
1862
- declare const JwtCredentialsDto_base: Newable<Omit<JwtCredentials, "id" | "userId">>;
1863
- /**
1864
- * The actual credentials sent over http.
1865
- */
1866
- declare class JwtCredentialsDto extends JwtCredentialsDto_base {
1867
- }
1868
-
1869
- /**
1870
- * The data used to refresh a login inside the jwt auth strategy.
1871
- */
1872
- declare class JwtRefreshLoginData {
1870
+ createdAt: Date;
1873
1871
  /**
1874
- * The long lived refresh token.
1872
+ * The timestamp after which the log will be deleted.
1875
1873
  */
1876
- refreshToken: string;
1874
+ cleanupAt: Date;
1877
1875
  }
1878
1876
 
1879
1877
  /**
@@ -2109,12 +2107,24 @@ type BaseRepositoryOptions = {
2109
2107
  /**
2110
2108
  * Options for creating a single entity.
2111
2109
  */
2112
- type CreateOptions = BaseRepositoryOptions;
2110
+ type CreateOptions = BaseRepositoryOptions & {
2111
+ /**
2112
+ * Whether or not setting the id property manually is allowed.
2113
+ * @default false.
2114
+ */
2115
+ allowId?: boolean;
2116
+ };
2113
2117
 
2114
2118
  /**
2115
2119
  * Options for creating multiple entities.
2116
2120
  */
2117
- type CreateAllOptions = BaseRepositoryOptions;
2121
+ type CreateAllOptions = BaseRepositoryOptions & {
2122
+ /**
2123
+ * Whether or not setting the id property manually is allowed.
2124
+ * @default false.
2125
+ */
2126
+ allowId?: boolean;
2127
+ };
2118
2128
 
2119
2129
  /**
2120
2130
  * A filter for an array where property.
@@ -2314,12 +2324,24 @@ type FindByIdOptions<T extends BaseEntity> = OmitStrict<FindOneOptions<T>, 'wher
2314
2324
  /**
2315
2325
  * Options for updating multiple entities at once.
2316
2326
  */
2317
- type UpdateAllOptions = BaseRepositoryOptions;
2327
+ type UpdateAllOptions = BaseRepositoryOptions & {
2328
+ /**
2329
+ * Whether or not setting the id property manually is allowed.
2330
+ * @default false.
2331
+ */
2332
+ allowId?: boolean;
2333
+ };
2318
2334
 
2319
2335
  /**
2320
2336
  * Options for updating an entity by its id.
2321
2337
  */
2322
- type UpdateByIdOptions = BaseRepositoryOptions;
2338
+ type UpdateByIdOptions = BaseRepositoryOptions & {
2339
+ /**
2340
+ * Whether or not setting the id property manually is allowed.
2341
+ * @default false.
2342
+ */
2343
+ allowId?: boolean;
2344
+ };
2323
2345
 
2324
2346
  /**
2325
2347
  * A repository that handles database related things for its entity.
@@ -2916,6 +2938,19 @@ declare function renderTemplate<T extends Record<string, unknown>>(path: `${stri
2916
2938
  */
2917
2939
  declare function renderTemplateString<T extends Record<string, unknown>>(templateString: string, data: T): string;
2918
2940
 
2941
+ /**
2942
+ * Utilities for handling handlebar templates.
2943
+ */
2944
+ declare abstract class HandlebarUtilities {
2945
+ private static H;
2946
+ /**
2947
+ * Initializes the handlebar utilities.
2948
+ * @param H - The external handlebar object. Is needed so helpers can be registered both inside and outside of Zibri.
2949
+ */
2950
+ static init(H: typeof Handlebars): void;
2951
+ private static registerHelper;
2952
+ }
2953
+
2919
2954
  /**
2920
2955
  * The data required to queue a new mailing list email.
2921
2956
  */
@@ -2999,9 +3034,20 @@ interface AssetServiceInterface {
2999
3034
  /**
3000
3035
  * Attaches the service to the application.
3001
3036
  */
3002
- attachTo: (app: ZibriApplication, ...params: any[]) => void;
3037
+ attachTo: (app: ZibriApplication, ...params: any[]) => void | Promise<void>;
3003
3038
  }
3004
3039
 
3040
+ type FileNode = {
3041
+ type: 'file';
3042
+ name: string;
3043
+ route: string;
3044
+ };
3045
+ type DirectoryNode = {
3046
+ type: 'directory';
3047
+ name: string;
3048
+ children: TreeNode[];
3049
+ };
3050
+ type TreeNode = FileNode | DirectoryNode;
3005
3051
  /**
3006
3052
  * Default asset service implementation of Zibri.
3007
3053
  */
@@ -3013,7 +3059,7 @@ declare class AssetService implements AssetServiceInterface {
3013
3059
  readonly emailTemplatePath: string;
3014
3060
  readonly assetsRoute: Route;
3015
3061
  constructor();
3016
- attachTo(app: ZibriApplication): void;
3062
+ attachTo(app: ZibriApplication): Promise<void>;
3017
3063
  private buildFileTree;
3018
3064
  private mapToTree;
3019
3065
  private walk;
@@ -3038,9 +3084,9 @@ declare class MailingListService implements MailingListServiceInterface {
3038
3084
  protected readonly mailingListSubscriptionConfirmationTokenExpiresInMs: number;
3039
3085
  protected get mailingListRepository(): Repository<MailingList>;
3040
3086
  protected get subscriberRepository(): Repository<MailingListSubscriber, MailingListSubscriberCreateData>;
3087
+ protected get confirmationTokenRepository(): Repository<MailingListSubscriptionConfirmationToken, MailingListSubscriptionConfirmationTokenCreateData>;
3041
3088
  constructor();
3042
- attachTo(app: ZibriApplication): void;
3043
- private registerRoutes;
3089
+ attachTo(): void;
3044
3090
  private validate;
3045
3091
  queueEmailForList<T extends BaseMailingListEmailTemplateData>(listId: string, data: MailingListQueueEmailData<T>): Promise<void>;
3046
3092
  requestSubscribeToList<T extends BaseMailingListEmailTemplateData>(listId: string, subscriber: MailingListSubscriberCreateData, emailData: MailingListQueueEmailData<T>): Promise<void>;
@@ -3048,6 +3094,263 @@ declare class MailingListService implements MailingListServiceInterface {
3048
3094
  unsubscribeFromList(listId: string, subscriberId: string): Promise<void>;
3049
3095
  }
3050
3096
 
3097
+ /**
3098
+ * The input for creating a email logger transport.
3099
+ */
3100
+ type EmailLoggerTransportConfigInput = OmitStrict<BaseLoggerTransportConfig, 'register' | 'name'> & Partial<{
3101
+ [K in keyof Email]: (log: Log) => Email[K];
3102
+ }> & {
3103
+ recipients: (log: Log) => string[];
3104
+ };
3105
+ /**
3106
+ * The configuration of a email logger transport.
3107
+ */
3108
+ type EmailLoggerTransportConfig = EmailLoggerTransportConfigInput & Pick<BaseLoggerTransportConfig, 'register' | 'name'>;
3109
+
3110
+ /**
3111
+ * The base configuration options shared by all logger transports.
3112
+ */
3113
+ type BaseLoggerTransportConfig = {
3114
+ /**
3115
+ * The name of the transport.
3116
+ */
3117
+ name: string;
3118
+ /**
3119
+ * The log level at which the transport should be active.
3120
+ */
3121
+ level: LogLevel;
3122
+ /**
3123
+ * Whether to register the transport as soon as possible or after the startup of the app.
3124
+ *
3125
+ * This is useful if the transport eg. Depends on the database being available.
3126
+ */
3127
+ register: 'directly' | 'afterStartup';
3128
+ };
3129
+ type LoggerTransportSend<T extends BaseLoggerTransportConfig> = (log: Log, config: T) => void | Promise<void>;
3130
+ declare class LoggerTransport<T extends BaseLoggerTransportConfig> {
3131
+ /**
3132
+ * The configuration options of the transport.
3133
+ */
3134
+ config: T;
3135
+ /**
3136
+ * What should happen when a new log should be send.
3137
+ */
3138
+ send: LoggerTransportSend<T>;
3139
+ private constructor();
3140
+ /**
3141
+ * Creates a new logger transport.
3142
+ * @param config - The configuration to be used by the transport.
3143
+ * @param send - What should happen when a new log should be send.
3144
+ * @returns The newly created transport.
3145
+ */
3146
+ static create<X extends BaseLoggerTransportConfig>(config: X, send: LoggerTransportSend<X>): LoggerTransport<X>;
3147
+ /**
3148
+ * Creates a new logger transport that prints the log to the console.
3149
+ * @param level - The log level at which the transport should be active.
3150
+ * @returns The newly created transport.
3151
+ */
3152
+ static console(level: LogLevel): LoggerTransport<BaseLoggerTransportConfig>;
3153
+ /**
3154
+ * Creates a new logger transport that saves the log into the database.
3155
+ * @param level - The log level at which the transport should be active.
3156
+ * @returns The newly created transport.
3157
+ */
3158
+ static db(level: LogLevel): LoggerTransport<BaseLoggerTransportConfig>;
3159
+ /**
3160
+ * Creates a new logger transport that sends the log via email.
3161
+ * @param config - The log level at which the transport should be active.
3162
+ * @returns The newly created transport.
3163
+ */
3164
+ static email(config: EmailLoggerTransportConfigInput): LoggerTransport<EmailLoggerTransportConfig>;
3165
+ }
3166
+
3167
+ /**
3168
+ * Interface for a logger.
3169
+ */
3170
+ interface LoggerInterface {
3171
+ /**
3172
+ * The transports to be used by the logger.
3173
+ */
3174
+ transports: LoggerTransport<BaseLoggerTransportConfig>[];
3175
+ /**
3176
+ * Attaches the service to the Zibri application.
3177
+ */
3178
+ attachTo: (app: ZibriApplication) => void | Promise<void>;
3179
+ /**
3180
+ * Logs a debug message.
3181
+ */
3182
+ debug: (message: string, context?: LogContextInput) => void | Promise<void>;
3183
+ /**
3184
+ * Logs a info message.
3185
+ */
3186
+ info: (message: string, context?: LogContextInput) => void | Promise<void>;
3187
+ /**
3188
+ * Logs a warning.
3189
+ */
3190
+ warn: (message: string, context?: LogContextInput) => void | Promise<void>;
3191
+ /**
3192
+ * Logs a error.
3193
+ */
3194
+ error: (error: Error, context?: LogContextInput) => void | Promise<void>;
3195
+ /**
3196
+ * Logs a critical error.
3197
+ */
3198
+ critical: (error: Error, context?: LogContextInput) => void | Promise<void>;
3199
+ }
3200
+
3201
+ /**
3202
+ * Default logger implementation of Zibri.
3203
+ */
3204
+ declare class Logger implements LoggerInterface {
3205
+ readonly transports: LoggerTransport<BaseLoggerTransportConfig>[];
3206
+ protected readonly cleanupAfterMs: Record<LogLevel, number>;
3207
+ constructor();
3208
+ attachTo(app: ZibriApplication): void;
3209
+ debug(message: string, context?: LogContextInput): Promise<void>;
3210
+ info(message: string, context?: LogContextInput): Promise<void>;
3211
+ warn(message: string, context?: LogContextInput): Promise<void>;
3212
+ error(error: Error, context?: LogContextInput): Promise<void>;
3213
+ critical(error: Error, context?: LogContextInput): Promise<void>;
3214
+ private log;
3215
+ }
3216
+
3217
+ declare function errorToLoggedError(error: Error): LoggedError;
3218
+
3219
+ /**
3220
+ * Default auth service implementation of Zibri.
3221
+ */
3222
+ declare class AuthService implements AuthServiceInterface {
3223
+ /**
3224
+ * A logger.
3225
+ */
3226
+ protected readonly logger: LoggerInterface;
3227
+ readonly strategies: AuthStrategies;
3228
+ constructor();
3229
+ init(authStrategies: AuthStrategies): Promise<void>;
3230
+ login<Role extends string, UserType extends BaseUser<Role>, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, credentials: CredentialsType): Promise<AuthDataType>;
3231
+ refreshLogin<Role extends string, UserType extends BaseUser<Role>, RefreshLoginDataType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, data: RefreshLoginDataType): Promise<AuthDataType>;
3232
+ getCurrentUser<Role extends string, UserType extends BaseUser<Role>, B extends boolean = true>(request: HttpRequest, allowedStrategies: AuthStrategies, required: B): Promise<B extends false ? UserType | undefined : UserType>;
3233
+ requestPasswordReset<Role extends string, UserType extends BaseUser<Role>, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, data: RequestPasswordResetDataType): Promise<void>;
3234
+ confirmPasswordReset<Role extends string, UserType extends BaseUser<Role>, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>(strategy: Newable<AuthStrategyInterface<Role, UserType, AuthDataType, CredentialsType, RequestPasswordResetDataType, ConfirmPasswordResetDataType, RefreshLoginDataType>>, data: ConfirmPasswordResetDataType): Promise<void>;
3235
+ checkAccess(controllerClass: Newable<unknown>, controllerMethod: string, request: HttpRequest): Promise<void>;
3236
+ isLoggedIn(request: HttpRequest, allowedStrategies: AuthStrategies): Promise<boolean>;
3237
+ hasRole(request: HttpRequest, allowedStrategies: AuthStrategies, allowedRoles: string[]): Promise<boolean>;
3238
+ belongsTo<TargetEntity extends Newable<BaseEntity>>(request: HttpRequest, allowedStrategies: AuthStrategies, targetEntity: TargetEntity, targetUserIdKey: keyof InstanceType<TargetEntity>, targetIdParamKey: string): Promise<boolean>;
3239
+ resolveIsLoggedInMetadata(controllerClass: Newable<unknown>, controllerMethod: string): Promise<IsLoggedInMetadata | undefined>;
3240
+ resolveIsNotLoggedInMetadata(controllerClass: Newable<unknown>, controllerMethod: string): Promise<IsNotLoggedInMetadata | undefined>;
3241
+ resolveHasRoleMetadata(controllerClass: Newable<unknown>, controllerMethod: string): Promise<HasRoleMetadata | undefined>;
3242
+ resolveBelongsToMetadata(controllerClass: Newable<unknown>, controllerMethod: string): Promise<BelongsToMetadata<Newable<BaseEntity>> | undefined>;
3243
+ }
3244
+
3245
+ /**
3246
+ * The payload of a jwt access token.
3247
+ */
3248
+ type JwtAccessTokenPayload<Role extends string, T extends BaseUser<Role>> = {
3249
+ /**
3250
+ * The id of the user.
3251
+ */
3252
+ id: T['id'];
3253
+ /**
3254
+ * The email of the user.
3255
+ */
3256
+ email: T['email'];
3257
+ /**
3258
+ * The roles of the user.
3259
+ */
3260
+ roles: T['roles'];
3261
+ };
3262
+
3263
+ /**
3264
+ * A Jwt, consisting of the token value and the expiration date.
3265
+ */
3266
+ declare class Jwt {
3267
+ /**
3268
+ * The token value.
3269
+ */
3270
+ value: string;
3271
+ /**
3272
+ * The timestamp at which the token is no longer valid.
3273
+ */
3274
+ expirationDate: Date;
3275
+ }
3276
+
3277
+ /**
3278
+ * The authentication data that gets returned when logging in or refreshing the login.
3279
+ */
3280
+ declare class JwtAuthData<Role extends string> {
3281
+ /**
3282
+ * The id of the user of the jwt.
3283
+ */
3284
+ userId: string;
3285
+ /**
3286
+ * The short lived access token.
3287
+ */
3288
+ accessToken: Jwt;
3289
+ /**
3290
+ * The long lived refresh token.
3291
+ */
3292
+ refreshToken: Jwt;
3293
+ /**
3294
+ * The roles of the user.
3295
+ */
3296
+ roles: Role[];
3297
+ }
3298
+
3299
+ /**
3300
+ * The data used to confirm a password reset.
3301
+ */
3302
+ declare class JwtConfirmPasswordResetData {
3303
+ /**
3304
+ * The reset token value.
3305
+ */
3306
+ resetToken: string;
3307
+ /**
3308
+ * The new password that should be used from now on.
3309
+ */
3310
+ newPassword: string;
3311
+ }
3312
+
3313
+ /**
3314
+ * The credentials used by the jwt auth strategy.
3315
+ */
3316
+ declare class JwtCredentials implements Pick<BaseUser<string>, 'id' | 'email'> {
3317
+ id: string;
3318
+ /**
3319
+ * The id of the user that this credentials belong to.
3320
+ */
3321
+ userId: string;
3322
+ /**
3323
+ * The email of the user.
3324
+ */
3325
+ email: string;
3326
+ /**
3327
+ * The password.
3328
+ */
3329
+ password: string;
3330
+ }
3331
+ declare const JwtCredentialsDto_base: Newable<Omit<JwtCredentials, "id" | "userId">>;
3332
+ /**
3333
+ * The actual credentials sent over http.
3334
+ */
3335
+ declare class JwtCredentialsDto extends JwtCredentialsDto_base {
3336
+ }
3337
+ declare const JwtCredentialsCreateData_base: Newable<Omit<JwtCredentials, "id">>;
3338
+ /**
3339
+ * The data for creating new jwt credentials.
3340
+ */
3341
+ declare class JwtCredentialsCreateData extends JwtCredentialsCreateData_base {
3342
+ }
3343
+
3344
+ /**
3345
+ * The data used to refresh a login inside the jwt auth strategy.
3346
+ */
3347
+ declare class JwtRefreshLoginData {
3348
+ /**
3349
+ * The long lived refresh token.
3350
+ */
3351
+ refreshToken: string;
3352
+ }
3353
+
3051
3354
  /**
3052
3355
  * The data used by the jwt auth strategy to request a password reset.
3053
3356
  */
@@ -3079,9 +3382,11 @@ declare class JwtAuthStrategy<RoleType extends string, UserType extends BaseUser
3079
3382
  private readonly refreshTokenExpiresInMs;
3080
3383
  private readonly passwordResetTokenExpiresInMs;
3081
3384
  private readonly userService;
3082
- private readonly logger;
3083
3385
  private readonly emailService;
3084
3386
  private readonly confirmPasswordResetUrl;
3387
+ private get refreshTokenRepository();
3388
+ private get passwordResetTokenRepository();
3389
+ private get credentialsRepository();
3085
3390
  constructor();
3086
3391
  init(): void;
3087
3392
  private checkForEntities;
@@ -3534,8 +3839,10 @@ declare function InjectRepository<T extends BaseEntity>(entityClass: Newable<T>)
3534
3839
  */
3535
3840
  declare const ZIBRI_DI_TOKENS: {
3536
3841
  readonly ROUTER: "zi.router";
3537
- readonly LOG_LEVEL: "zi.log_level";
3538
3842
  readonly LOGGER: "zi.logger";
3843
+ readonly LOGGER_TRANSPORTS: "zi.logger_transports";
3844
+ readonly LOGGER_CLEANUP_AFTER_MS: "zi.logger_cleanup_after_ms";
3845
+ readonly METRICS_SERVICE: "zi.metrics_service";
3539
3846
  readonly ASSET_SERVICE: "zi.asset_service";
3540
3847
  readonly GLOBAL_ERROR_HANDLER: "zi.global_error_handler";
3541
3848
  readonly OPEN_API_SERVICE: "zi.open_api_service";
@@ -3861,6 +4168,7 @@ declare class ZibriApplication {
3861
4168
  */
3862
4169
  get router(): RouterInterface;
3863
4170
  private logger;
4171
+ private metricsService;
3864
4172
  private assetService;
3865
4173
  private openApiService;
3866
4174
  private parser;
@@ -3880,20 +4188,21 @@ declare class ZibriApplication {
3880
4188
  use(path: Route, handlers: RequestHandler[]): void;
3881
4189
  /**
3882
4190
  * Initializes the app.
4191
+ * @param H - The global handlebars instance, needed to provide some helpers used in templating.
3883
4192
  */
3884
- init(): Promise<void>;
4193
+ init(H: typeof Handlebars): Promise<void>;
3885
4194
  /**
3886
4195
  * Starts on the given port.
3887
4196
  * @param port - The port to start on.
3888
4197
  * @throws When the app has already been started.
3889
4198
  */
3890
- start(port: number): void;
4199
+ start(port: number): Promise<void>;
3891
4200
  }
3892
4201
 
3893
4202
  /**
3894
4203
  * A global error handler function.
3895
4204
  */
3896
- type GlobalErrorHandler = (err: unknown, req: HttpRequest, res: HttpResponse, next: NextFunction) => void;
4205
+ type GlobalErrorHandler = (err: unknown, req: HttpRequest, res: HttpResponse, next: NextFunction) => void | Promise<void>;
3897
4206
 
3898
4207
  /**
3899
4208
  * The default error handler implementation of Zibri.
@@ -4183,6 +4492,175 @@ declare abstract class GlobalRegistry {
4183
4492
  private static changeAppState;
4184
4493
  }
4185
4494
 
4495
+ /**
4496
+ * Operations you can do on a counter.
4497
+ */
4498
+ interface CounterInterface {
4499
+ /**
4500
+ * Increases the value of the counter.
4501
+ */
4502
+ increase: (labels?: Record<string, string>, value?: number) => void;
4503
+ }
4504
+
4505
+ /**
4506
+ * Operations you can do on a gauge.
4507
+ */
4508
+ interface GaugeInterface {
4509
+ /**
4510
+ * Increases the value of the gauge.
4511
+ */
4512
+ increase: (labels?: Record<string, string>, value?: number) => void;
4513
+ /**
4514
+ * Decreases the value of the gauge.
4515
+ */
4516
+ decrease: (labels?: Record<string, string>, value?: number) => void;
4517
+ /**
4518
+ * Sets the value of the gauge.
4519
+ */
4520
+ set: (labels: Record<string, string>, value: number) => void;
4521
+ }
4522
+
4523
+ /**
4524
+ * Operations you can do on a histogram.
4525
+ */
4526
+ interface HistogramInterface {
4527
+ /**
4528
+ * Observes a new value.
4529
+ */
4530
+ observe: (labels: Record<string, string>, value: number) => void;
4531
+ }
4532
+
4533
+ /**
4534
+ * The type of the metric.
4535
+ */
4536
+ declare enum MetricType {
4537
+ COUNTER = "counter",
4538
+ GAUGE = "gauge",
4539
+ HISTOGRAM = "histogram"
4540
+ }
4541
+
4542
+ /**
4543
+ * A single recorded measurement.
4544
+ */
4545
+ declare class Metric {
4546
+ /**
4547
+ * Metric name (e.g. 'http_requests_total').
4548
+ */
4549
+ name: string;
4550
+ /**
4551
+ * Metric type.
4552
+ */
4553
+ type: MetricType;
4554
+ /**
4555
+ * One sample value (cumulative for counter, gauge value, histogram bucket/summary).
4556
+ */
4557
+ value: number;
4558
+ /**
4559
+ * The combination of labels that this sample applies to.
4560
+ */
4561
+ labels: Record<string, string | number | undefined>;
4562
+ }
4563
+
4564
+ /**
4565
+ * Name of a counter metric.
4566
+ */
4567
+ type CounterMetricName = 'http_requests_total' | string & {};
4568
+ /**
4569
+ * The name of a gauge metric.
4570
+ */
4571
+ type GaugeMetricName = string;
4572
+ /**
4573
+ * The name of a histogram metric.
4574
+ */
4575
+ type HistogramMetricName = 'http_request_duration_ms' | string & {};
4576
+ /**
4577
+ * A collected snapshot of all metrics.
4578
+ */
4579
+ type MetricsSnapshot = {
4580
+ /**
4581
+ * The time at which the snapshot was taken.
4582
+ */
4583
+ timestamp: Date;
4584
+ /**
4585
+ * All metrics at the timestamp.
4586
+ */
4587
+ metrics: Metric[];
4588
+ };
4589
+ /**
4590
+ * Interface for a metrics service.
4591
+ */
4592
+ interface MetricsServiceInterface {
4593
+ /**
4594
+ * Attaches the service to the Zibri application.
4595
+ */
4596
+ attachTo: (app: ZibriApplication) => void | Promise<void>;
4597
+ /**
4598
+ * Collects metrics about a finished request.
4599
+ */
4600
+ measureFinishedRequest: (req: HttpRequest, res: HttpResponse, durationInMs: number) => void | Promise<void>;
4601
+ /**
4602
+ * Create or retrieve a counter metric.
4603
+ */
4604
+ getCounter: (name: CounterMetricName, labelNames?: string[]) => CounterInterface;
4605
+ /**
4606
+ * Create or retrieve a gauge metric.
4607
+ */
4608
+ getGauge: (name: GaugeMetricName, labelNames?: string[]) => GaugeInterface;
4609
+ /**
4610
+ * Create or retrieve a histogram metric.
4611
+ */
4612
+ getHistogram: (name: HistogramMetricName, labelNames?: string[], buckets?: number[]) => HistogramInterface;
4613
+ /**
4614
+ * Collect a snapshot of every metric’s current samples.
4615
+ * This will usually be called in regular intervals, eg. From a cron job.
4616
+ *
4617
+ * To retrieve the metrics use the getMetrics method.
4618
+ */
4619
+ collect: () => Promise<void>;
4620
+ /**
4621
+ * Returns all 60 buffered snapshots.
4622
+ *
4623
+ * IF YOU WANT A LONGER HISTORY YOU SHOULD USE AN EXTERNAL TOOL LIKE PROMETHEUS TO SCRAPE THE DATA.
4624
+ */
4625
+ getMetricSnapshots: () => MetricsSnapshot[];
4626
+ }
4627
+
4628
+ declare class PromCounter implements CounterInterface {
4629
+ private readonly inner;
4630
+ constructor(inner: Counter<string>);
4631
+ increase(labels?: Record<string, string>, v?: number): void;
4632
+ }
4633
+ declare class PromGauge implements GaugeInterface {
4634
+ private readonly inner;
4635
+ constructor(inner: Gauge<string>);
4636
+ increase(labels?: Record<string, string>, v?: number): void;
4637
+ decrease(labels?: Record<string, string>, v?: number): void;
4638
+ set(labels: Record<string, string>, v: number): void;
4639
+ }
4640
+ declare class PromHistogram implements HistogramInterface {
4641
+ private readonly inner;
4642
+ constructor(inner: Histogram<string>);
4643
+ observe(labels: Record<string, string>, v: number): void;
4644
+ }
4645
+ /**
4646
+ * Default metrics service implementation of Zibri.
4647
+ */
4648
+ declare class PrometheusMetricsService implements MetricsServiceInterface {
4649
+ private readonly registry;
4650
+ private readonly counters;
4651
+ private readonly gauges;
4652
+ private readonly histograms;
4653
+ private readonly metricSnapshots;
4654
+ constructor();
4655
+ attachTo(app: ZibriApplication): void;
4656
+ measureFinishedRequest(req: HttpRequest, res: HttpResponse, durationInMs: number): void;
4657
+ getCounter(name: CounterMetricName, labelNames?: string[]): PromCounter;
4658
+ getGauge(name: GaugeMetricName, labelNames?: string[]): PromGauge;
4659
+ getHistogram(name: HistogramMetricName, labelNames?: string[], buckets?: number[]): PromHistogram;
4660
+ collect(): Promise<void>;
4661
+ getMetricSnapshots(): MetricsSnapshot[];
4662
+ }
4663
+
4186
4664
  /**
4187
4665
  * Compares the given versions and check if the first one is bigger, equal or smaller than the second one.
4188
4666
  * @param v1 - The first version.
@@ -4219,4 +4697,4 @@ type ChunkingOptions = {
4219
4697
  */
4220
4698
  declare function chunkedPromiseAll<T>(promises: Promise<T>[], options?: ChunkingOptions): Promise<T[]>;
4221
4699
 
4222
- export { type AppData, AppState, type ArrayParamMetadata, type ArrayParamMetadataInput, type ArrayPropertyItemMetadata, type ArrayPropertyItemMetadataInput, type ArrayPropertyMetadata, type ArrayPropertyMetadataInput, type ArrayWhereFilter, AssetService, type AssetServiceInterface, Auth, type AuthControllerInterface, AuthService, type AuthServiceInterface, type AuthStrategies, type AuthStrategyInterface, BadRequestError, BaseDataSource, type BaseEmailTemplateData, type BaseEmailTemplateDataInput, type BaseEntity, type BaseMailingListEmailTemplateData, type BasePageTemplateData, type BasePageTemplateDataInput, type BaseRepositoryOptions, type BaseUser, type BelongsToMetadata, Body, type BodyMetadata, type BodyMetadataInput, BodyParser, type BodyParserInterface, type BooleanParamMetadata, type BooleanParamMetadataInput, type BooleanPropertyMetadata, type BooleanPropertyMetadataInput, type BooleanWhereFilter, CLEANUP_AT_FILE_NAME, type ChunkingOptions, type ColumnType, CombinedType, Controller, type ControllerRouteConfiguration, type CreateAllOptions, type CreateCronJobEntityData, CreateEmailData, type CreateOptions, type CronConfig, CronJob, CronJobEntity, CronService, type CronServiceInterface, type CronUpdateData, CurrentUser, type CurrentUserMetadata, DataSource, type DataSourceOptions, DataSourceService, type DataSourceServiceInterface, type DateParamMetadata, type DateParamMetadataInput, type DatePropertyMetadata, type DatePropertyMetadataInput, type DateWhereFilter, Delete, type DeleteAllOptions, type DeleteByIdOptions, type DiProvider, type DiToken, Email, EmailAttachment, type EmailConfig, type EmailConfigInput, EmailPriority, EmailService, type EmailServiceInterface, EmailStatus, type EncodedJwtAccessToken, Entity, type EntityMetadata, type ErrorOpenApiResponse, File, type FileExtension, type FileMimeType, type FileOpenApiResponse, type FilePropertyMetadata, type FilePropertyMetadataInput, FileResponse, type FileSize, type FindAllOptions, type FindAllPaginatedOptions, type FindByIdOptions, type FindOneOptions, FormData, type FormDataBodyMetadata, FormDataBodyParser, type FormDataValue, type FormatDateFn, Get, type GlobalErrorHandler, GlobalRegistry, type HasRoleMetadata, HashUtilities, type Header, type HeaderParamMetadata, type HeaderParamMetadataInput, type HtmlOpenApiResponse, HtmlResponse, HttpError, HttpMethod, type HttpRequest, type HttpResponse, HttpStatus, type InitialCronConfig, Inject, InjectRepository, Injectable, InternalServerError, type IsLoggedInMetadata, type IsNotLoggedInMetadata, IsRequiredValidationProblem, type JsonBodyMetadata, JsonBodyParser, type JsonOpenApiResponse, Jwt, type JwtAccessTokenPayload, JwtAuthController, JwtAuthData, JwtAuthStrategy, JwtConfirmPasswordResetData, JwtCredentials, JwtCredentialsDto, JwtRefreshToken, JwtRefreshTokenCreateDto, type JwtRefreshTokenPayload, type JwtRequestPasswordResetData, JwtUtilities, KnownHeader, type LogLevel, Logger, type LoggerInterface, type LooseFileMimeType, MailingList, type MailingListQueueEmailData, MailingListService, type MailingListServiceInterface, MailingListSubscriber, MailingListSubscriberCreateData, MailingListSubscriptionConfirmationToken, MailingListSubscriptionConfirmationTokenCreateData, type ManyToManyPropertyMetadata, type ManyToManyPropertyMetadataInput, type ManyToOnePropertyMetadata, type ManyToOnePropertyMetadataInput, MaxFileSizeValidationProblem, Migration, MigrationEntity, MimeType, MimeTypeMismatchValidationProblem, type MulterFile, NO_USER_REPOSITORIES_PROVIDED_ERROR_MESSAGE, type Newable, NotFoundError, type NumberParamMetadata, type NumberParamMetadataInput, type NumberPropertyMetadata, type NumberPropertyMetadataInput, type NumberWhereFilter, type ObjectParamMetadata, type ObjectParamMetadataInput, type ObjectPropertyMetadata, type ObjectPropertyMetadataInput, type ObjectWhereFilter, OmitType, type OneToManyPropertyMetadata, type OneToManyPropertyMetadataInput, type OneToOnePropertyMetadata, type OneToOnePropertyMetadataInput, type OpenApiDefinition, type OpenApiOperation, type OpenApiParameter, type OpenApiPaths, type OpenApiRequestBodyObject, type OpenApiResponse, type OpenApiRouteConfiguration, type OpenApiSchemaObject, type OpenApiSecurityRequirementObject, type OpenApiSecuritySchemeObject, OpenApiService, type OpenApiServiceInterface, type PaginationResult, Param, Parser, type ParserInterface, PartialType, PasswordResetToken, PasswordResetTokenCreateData, Patch, type PathParamMetadata, type PathParamMetadataInput, type PathTree, PickType, Post, Property, type PropertyMetadata, type PropertyMetadataInput, type QueryParamMetadata, type QueryParamMetadataInput, QueueEmailData, RateLimiter, Relation, type RelationMetadata, type RelationMetadataInput, RelationsNotAllowedValidationProblem, Repository, Response, type Route, type RouteConfiguration, type RouteConfigurationInput, type RouteHandler, Router, type RouterInterface, type SkipAuthMetadata, type SkipBelongsToMetadata, type SkipHasRoleMetadata, type SkipIsLoggedInMetadata, type SkipIsNotLoggedInMetadata, type StringFormat, type StringParamMetadata, type StringParamMetadataInput, type StringPropertyMetadata, type StringPropertyMetadataInput, type StringWhereFilter, TooManyRequestsError, type Transaction, TypeMismatchValidationProblem, UnauthorizedError, UnmatchedRouteError, type UpdateAllOptions, type UpdateByIdOptions, UpdateMailingListPreferences, UserRepo, type UserRepositories, type UserRepositoryInterface, UserService, type UserServiceInterface, ValidationError, type ValidationProblem, ValidationService, type ValidationServiceInterface, type Version, type Where, type WhereFilter, type WhereFilterProperty, ZIBRI_DI_TOKENS, ZibriApplication, type ZibriApplicationOptions, chunkedPromiseAll, compareVersion, createArrayItemPropertyMetadata, errorHandler, fileSizeToBytes, generateHandlebarType, generateHandlebarTypeFiles, inject, isHttpError, isMimeType, isVersion, renderEmailTemplate, renderPageTemplate, renderTemplate, renderTemplateString, repositoryTokenFor, resolveFileExtension, resolveMimeType };
4700
+ export { type AppData, AppState, type ArrayParamMetadata, type ArrayParamMetadataInput, type ArrayPropertyItemMetadata, type ArrayPropertyItemMetadataInput, type ArrayPropertyMetadata, type ArrayPropertyMetadataInput, type ArrayWhereFilter, AssetService, type AssetServiceInterface, Auth, type AuthControllerInterface, AuthService, type AuthServiceInterface, type AuthStrategies, type AuthStrategyInterface, BadRequestError, BaseDataSource, type BaseEmailTemplateData, type BaseEmailTemplateDataInput, type BaseEntity, type BaseLoggerTransportConfig, type BaseMailingListEmailTemplateData, type BasePageTemplateData, type BasePageTemplateDataInput, type BaseRepositoryOptions, type BaseUser, type BelongsToMetadata, Body, type BodyMetadata, type BodyMetadataInput, BodyParser, type BodyParserInterface, type BooleanParamMetadata, type BooleanParamMetadataInput, type BooleanPropertyMetadata, type BooleanPropertyMetadataInput, type BooleanWhereFilter, CLEANUP_AT_FILE_NAME, type ChunkingOptions, type ColumnType, CombinedType, Controller, type ControllerRouteConfiguration, type CounterInterface, type CounterMetricName, type CreateAllOptions, type CreateCronJobEntityData, CreateEmailData, type CreateOptions, type CronConfig, CronJob, CronJobEntity, CronService, type CronServiceInterface, type CronUpdateData, CurrentUser, type CurrentUserMetadata, DataSource, type DataSourceOptions, DataSourceService, type DataSourceServiceInterface, type DateParamMetadata, type DateParamMetadataInput, type DatePropertyMetadata, type DatePropertyMetadataInput, type DateWhereFilter, Delete, type DeleteAllOptions, type DeleteByIdOptions, type DiProvider, type DiToken, Email, EmailAttachment, type EmailConfig, type EmailConfigInput, EmailPriority, EmailService, type EmailServiceInterface, EmailStatus, type EncodedJwtAccessToken, Entity, type EntityMetadata, type ErrorOpenApiResponse, File, type FileExtension, type FileMimeType, type FileOpenApiResponse, type FilePropertyMetadata, type FilePropertyMetadataInput, FileResponse, type FileSize, type FindAllOptions, type FindAllPaginatedOptions, type FindByIdOptions, type FindOneOptions, FormData, type FormDataBodyMetadata, FormDataBodyParser, type FormDataValue, type FormatDateFn, type GaugeInterface, type GaugeMetricName, Get, type GlobalErrorHandler, GlobalRegistry, HandlebarUtilities, type HasRoleMetadata, HashUtilities, type Header, type HeaderParamMetadata, type HeaderParamMetadataInput, type HistogramInterface, type HistogramMetricName, type HtmlOpenApiResponse, HtmlResponse, HttpError, HttpMethod, type HttpRequest, type HttpResponse, HttpStatus, type InitialCronConfig, Inject, InjectRepository, Injectable, InternalServerError, type IsLoggedInMetadata, type IsNotLoggedInMetadata, IsRequiredValidationProblem, type JsonBodyMetadata, JsonBodyParser, type JsonOpenApiResponse, Jwt, type JwtAccessTokenPayload, JwtAuthController, JwtAuthData, JwtAuthStrategy, JwtConfirmPasswordResetData, JwtCredentials, JwtCredentialsCreateData, JwtCredentialsDto, JwtRefreshToken, JwtRefreshTokenCreateDto, type JwtRefreshTokenPayload, type JwtRequestPasswordResetData, JwtUtilities, KnownHeader, Log, LogLevel, LoggedError, Logger, type LoggerInterface, LoggerTransport, type LoggerTransportSend, type LooseFileMimeType, MailingList, type MailingListQueueEmailData, MailingListService, type MailingListServiceInterface, MailingListSubscriber, MailingListSubscriberCreateData, MailingListSubscriptionConfirmationToken, MailingListSubscriptionConfirmationTokenCreateData, type ManyToManyPropertyMetadata, type ManyToManyPropertyMetadataInput, type ManyToOnePropertyMetadata, type ManyToOnePropertyMetadataInput, MaxFileSizeValidationProblem, Metric, MetricType, type MetricsServiceInterface, type MetricsSnapshot, Migration, MigrationEntity, MimeType, MimeTypeMismatchValidationProblem, type MulterFile, NO_USER_REPOSITORIES_PROVIDED_ERROR_MESSAGE, type Newable, NotFoundError, type NumberParamMetadata, type NumberParamMetadataInput, type NumberPropertyMetadata, type NumberPropertyMetadataInput, type NumberWhereFilter, type ObjectParamMetadata, type ObjectParamMetadataInput, type ObjectPropertyMetadata, type ObjectPropertyMetadataInput, type ObjectWhereFilter, OmitType, type OneToManyPropertyMetadata, type OneToManyPropertyMetadataInput, type OneToOnePropertyMetadata, type OneToOnePropertyMetadataInput, type OpenApiDefinition, type OpenApiOperation, type OpenApiParameter, type OpenApiPaths, type OpenApiRequestBodyObject, type OpenApiResponse, type OpenApiRouteConfiguration, type OpenApiSchemaObject, type OpenApiSecurityRequirementObject, type OpenApiSecuritySchemeObject, OpenApiService, type OpenApiServiceInterface, type PaginationResult, Param, Parser, type ParserInterface, PartialType, PasswordResetToken, PasswordResetTokenCreateData, Patch, type PathParamMetadata, type PathParamMetadataInput, type PathTree, PickType, Post, PrometheusMetricsService, Property, type PropertyMetadata, type PropertyMetadataInput, type QueryParamMetadata, type QueryParamMetadataInput, QueueEmailData, RateLimiter, Relation, type RelationMetadata, type RelationMetadataInput, RelationsNotAllowedValidationProblem, Repository, Response, type Route, type RouteConfiguration, type RouteConfigurationInput, type RouteHandler, Router, type RouterInterface, type SkipAuthMetadata, type SkipBelongsToMetadata, type SkipHasRoleMetadata, type SkipIsLoggedInMetadata, type SkipIsNotLoggedInMetadata, type StringFormat, type StringParamMetadata, type StringParamMetadataInput, type StringPropertyMetadata, type StringPropertyMetadataInput, type StringWhereFilter, TooManyRequestsError, type Transaction, type TreeNode, TypeMismatchValidationProblem, UnauthorizedError, type UnknownPropertyMetadata, type UnknownPropertyMetadataInput, UnmatchedRouteError, type UpdateAllOptions, type UpdateByIdOptions, UpdateMailingListPreferences, UserRepo, type UserRepositories, type UserRepositoryInterface, UserService, type UserServiceInterface, ValidationError, type ValidationProblem, ValidationService, type ValidationServiceInterface, type Version, type Where, type WhereFilter, type WhereFilterProperty, ZIBRI_DI_TOKENS, ZibriApplication, type ZibriApplicationOptions, chunkedPromiseAll, compareVersion, createArrayItemPropertyMetadata, errorHandler, errorToLoggedError, fileSizeToBytes, generateHandlebarType, generateHandlebarTypeFiles, inject, isHttpError, isMimeType, isVersion, renderEmailTemplate, renderPageTemplate, renderTemplate, renderTemplateString, repositoryTokenFor, resolveFileExtension, resolveMimeType };