@expressots/core 2.5.0 → 2.7.0

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/lib/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
 
2
2
 
3
+ ## [2.6.0](https://github.com/expressots/expressots/compare/2.5.0...2.6.0) (2023-10-09)
4
+
5
+
6
+ ### Features
7
+
8
+ * Added express-session middleware for expressots ([9d0c79f](https://github.com/expressots/expressots/commit/9d0c79f7c4b18cfcac17443c7f76c4384a563471))
9
+ * bump vite from 4.4.10 to 4.4.11 ([45c8a80](https://github.com/expressots/expressots/commit/45c8a804e85875743cc18d95ec5441e19b7df7d3))
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * Auto setup husky with project setup and installation ([dcdc279](https://github.com/expressots/expressots/commit/dcdc279f9dffe82e739396df763f494c97a3e914))
15
+ * remove prepare husky install from lib ([ba9b536](https://github.com/expressots/expressots/commit/ba9b5363904a7d8981ec49705d5fbf22e20c8dbd))
16
+ * typo ([079aad6](https://github.com/expressots/expressots/commit/079aad6c125fcd100cde5cf98ce84125e7381879))
17
+
3
18
  ## [2.5.0](https://github.com/expressots/expressots/compare/2.4.0...2.5.0) (2023-10-04)
4
19
 
5
20
 
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -26,6 +26,7 @@ class MiddlewareResolver {
26
26
  morgan: "morgan",
27
27
  helmet: "helmet",
28
28
  rateLimit: "express-rate-limit",
29
+ session: "express-session",
29
30
  // Add other middlewares
30
31
  };
31
32
  /**
@@ -177,6 +177,22 @@ let Middleware = Middleware_1 = class Middleware {
177
177
  });
178
178
  }
179
179
  }
180
+ /**
181
+ * Add a middleware to enable express-session.
182
+ *
183
+ * @param options - Optional configuration options for Session.
184
+ *
185
+ */
186
+ addSession(options) {
187
+ const middleware = (0, middleware_resolver_1.middlewareResolver)("session", options);
188
+ const middlewareExist = this.middlewareExists("session");
189
+ if (middleware && !middlewareExist) {
190
+ this.middlewarePipeline.push({
191
+ timestamp: new Date(),
192
+ middleware,
193
+ });
194
+ }
195
+ }
180
196
  /**
181
197
  * Configures the error handling middleware for the application.
182
198
  *
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var InMemoryDB_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.InMemoryDB = void 0;
11
+ const decorator_1 = require("../../decorator");
12
+ /**
13
+ * InMemoryDB Class
14
+ *
15
+ * This class and its methods offer functionalities to simulate an in-memory database.
16
+ * It is particularly useful for developers starting with ExpressoTS without any database connection.
17
+ *
18
+ * @decorator @provideSingleton(InMemoryDB)
19
+ */
20
+ let InMemoryDB = exports.InMemoryDB = InMemoryDB_1 = class InMemoryDB {
21
+ tables = {};
22
+ /**
23
+ * getTable Method
24
+ *
25
+ * Retrieves a table by its name from the in-memory database.
26
+ *
27
+ * @param tableName - The name of the table to retrieve.
28
+ * @returns {IEntity[]} - An array of entities.
29
+ */
30
+ getTable(tableName) {
31
+ if (!this.tables[tableName]) {
32
+ this.tables[tableName] = [];
33
+ }
34
+ return this.tables[tableName];
35
+ }
36
+ /**
37
+ * showTables Method
38
+ *
39
+ * Prints a list of all tables in the in-memory database to the standard output.
40
+ */
41
+ showTables() {
42
+ if (!this.tables) {
43
+ process.stdout.write("No tables exist.");
44
+ return;
45
+ }
46
+ process.stdout.write("List of tables:");
47
+ for (const tableName in this.tables) {
48
+ process.stdout.write(`\n- ${tableName}`);
49
+ }
50
+ }
51
+ /**
52
+ * printTable Method
53
+ *
54
+ * Prints all records in a specific table to the console.
55
+ * If the table doesn't exist or is empty, it notifies the user.
56
+ *
57
+ * @param tableName - The name of the table to print.
58
+ */
59
+ printTable(tableName) {
60
+ if (!this.tables) {
61
+ process.stdout.write("No tables exist.");
62
+ return;
63
+ }
64
+ const table = this.getTable(tableName);
65
+ if (table.length === 0) {
66
+ process.stdout.write(`Table '${tableName}' is empty.`);
67
+ return;
68
+ }
69
+ process.stdout.write(`\nRecords in table '${tableName}':\n`);
70
+ console.table(table);
71
+ }
72
+ };
73
+ exports.InMemoryDB = InMemoryDB = InMemoryDB_1 = __decorate([
74
+ (0, decorator_1.provideSingleton)(InMemoryDB_1)
75
+ ], InMemoryDB);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ValidateDTO = exports.Env = exports.Logger = exports.Provider = void 0;
3
+ exports.InMemoryDB = exports.ValidateDTO = exports.Env = exports.Logger = exports.Provider = void 0;
4
4
  var provider_service_1 = require("./provider-service");
5
5
  Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return provider_service_1.Provider; } });
6
6
  var logger_service_1 = require("./logger/logger-service");
@@ -9,3 +9,5 @@ var env_validator_provider_1 = require("./environment/env-validator.provider");
9
9
  Object.defineProperty(exports, "Env", { enumerable: true, get: function () { return env_validator_provider_1.EnvValidatorProvider; } });
10
10
  var dto_validator_provider_1 = require("./dto-validator/dto-validator.provider");
11
11
  Object.defineProperty(exports, "ValidateDTO", { enumerable: true, get: function () { return dto_validator_provider_1.ValidateDTO; } });
12
+ var db_in_memory_provider_1 = require("./db-in-memory/db-in-memory.provider");
13
+ Object.defineProperty(exports, "InMemoryDB", { enumerable: true, get: function () { return db_in_memory_provider_1.InMemoryDB; } });
@@ -4,6 +4,7 @@ export { CorsOptions } from "./interfaces/cors.interface";
4
4
  export { CompressionOptions } from "./interfaces/compression.interface";
5
5
  export { CookieSessionOptions } from "./interfaces/cookie-session/cookie-session.interface";
6
6
  export { OptionsHelmet } from "./interfaces/helmet.interface";
7
+ export { SessionOptions } from "./interfaces/express-session.interface";
7
8
  export { Keygrip } from "./interfaces/cookie-session/keygrip.interface";
8
9
  export { CookieParserOptions } from "./interfaces/cookie-parser.interface";
9
10
  export { ServeFaviconOptions } from "./interfaces/serve-favicon.interface";
@@ -0,0 +1,208 @@
1
+ /// <reference types="express-serve-static-core" />
2
+ import { Request } from "express";
3
+ interface SessionData {
4
+ cookie: Cookie;
5
+ }
6
+ interface Cookie extends CookieOptions {
7
+ /** Returns the original `maxAge` (time-to-live), in milliseconds, of the session cookie. */
8
+ originalMaxAge: number | null;
9
+ }
10
+ interface Session {
11
+ id: string;
12
+ cookie: Cookie;
13
+ regenerate(callback: (err: any) => void): this;
14
+ destroy(callback: (err: any) => void): this;
15
+ reload(callback: (err: any) => void): this;
16
+ resetMaxAge(): this;
17
+ save(callback?: (err: any) => void): this;
18
+ touch(): this;
19
+ }
20
+ interface Store {
21
+ regenerate(req: Request, callback: (err?: any) => any): void;
22
+ load(sid: string, callback: (err: any, session?: SessionData) => any): void;
23
+ createSession(req: Request, session: SessionData): Session & SessionData;
24
+ get(sid: string, callback: (err: any, session?: SessionData | null) => void): void;
25
+ set(sid: string, session: SessionData, callback?: (err?: any) => void): void;
26
+ destroy(sid: string, callback?: (err?: any) => void): void;
27
+ all?(callback: (err: any, obj?: Array<SessionData> | {
28
+ [sid: string]: SessionData;
29
+ } | null) => void): void;
30
+ length?(callback: (err: any, length?: number) => void): void;
31
+ clear?(callback?: (err?: any) => void): void;
32
+ touch?(sid: string, session: SessionData, callback?: () => void): void;
33
+ }
34
+ interface CookieOptions {
35
+ /**
36
+ * Specifies the number (in milliseconds) to use when calculating the `Expires Set-Cookie` attribute.
37
+ * This is done by taking the current server time and adding `maxAge` milliseconds to the value to calculate an `Expires` datetime. By default, no maximum age is set.
38
+ *
39
+ * If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used.
40
+ * `maxAge` should be preferred over `expires`.
41
+ *
42
+ * @see expires
43
+ */
44
+ maxAge?: number | undefined;
45
+ signed?: boolean | undefined;
46
+ /**
47
+ * Specifies the `Date` object to be the value for the `Expires Set-Cookie` attribute.
48
+ * By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.
49
+ *
50
+ * If both `expires` and `maxAge` are set in the options, then the last one defined in the object is what is used.
51
+ *
52
+ * @deprecated The `expires` option should not be set directly; instead only use the `maxAge` option
53
+ * @see maxAge
54
+ */
55
+ expires?: Date | null | undefined;
56
+ /**
57
+ * Specifies the boolean value for the `HttpOnly Set-Cookie` attribute. When truthy, the `HttpOnly` attribute is set, otherwise it is not.
58
+ * By default, the `HttpOnly` attribute is set.
59
+ *
60
+ * Be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`.
61
+ */
62
+ httpOnly?: boolean | undefined;
63
+ /**
64
+ * Specifies the value for the `Path Set-Cookie` attribute.
65
+ * By default, this is set to '/', which is the root path of the domain.
66
+ */
67
+ path?: string | undefined;
68
+ /**
69
+ * Specifies the value for the `Domain Set-Cookie` attribute.
70
+ * By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
71
+ */
72
+ domain?: string | undefined;
73
+ /**
74
+ * Specifies the boolean value for the `Secure Set-Cookie` attribute. When truthy, the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
75
+ * Be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.
76
+ *
77
+ * Please note that `secure: true` is a **recommended option**.
78
+ * However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies.
79
+ * If `secure` is set, and you access your site over HTTP, **the cookie will not be set**.
80
+ *
81
+ * The cookie.secure option can also be set to the special value `auto` to have this setting automatically match the determined security of the connection.
82
+ * Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP.
83
+ * This is useful when the Express "trust proxy" setting is properly setup to simplify development vs production configuration.
84
+ *
85
+ * If you have your node.js behind a proxy and are using `secure: true`, you need to set "trust proxy" in express. Please see the [README](https://github.com/expressjs/session) for details.
86
+ *
87
+ * Please see the [README](https://github.com/expressjs/session) for an example of using secure cookies in production, but allowing for testing in development based on NODE_ENV.
88
+ */
89
+ secure?: boolean | "auto" | undefined;
90
+ encode?: ((val: string) => string) | undefined;
91
+ /**
92
+ * Specifies the boolean or string to be the value for the `SameSite Set-Cookie` attribute.
93
+ * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
94
+ * - `false` will not set the `SameSite` attribute.
95
+ * - `lax` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
96
+ * - `none` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
97
+ * - `strict` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
98
+ *
99
+ * More information about the different enforcement levels can be found in the specification.
100
+ *
101
+ * **Note:** This is an attribute that has not yet been fully standardized, and may change in the future.
102
+ * This also means many clients may ignore this attribute until they understand it.
103
+ */
104
+ sameSite?: boolean | "lax" | "strict" | "none" | undefined;
105
+ }
106
+ interface SessionOptions {
107
+ /**
108
+ * This is the secret used to sign the session cookie. This can be either a string for a single secret, or an array of multiple secrets.
109
+ * If an array of secrets is provided, **only the first element will be used to sign** the session ID cookie,
110
+ * while **all the elements will be considered when verifying the signature** in requests.
111
+ * The secret itself should be not easily parsed by a human and would best be a random set of characters
112
+ *
113
+ * Best practices may include:
114
+ * - The use of environment variables to store the secret, ensuring the secret itself does not exist in your repository.
115
+ * - Periodic updates of the secret, while ensuring the previous secret is in the array.
116
+ *
117
+ * Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the `genid` option).
118
+ *
119
+ * Changing the secret value will invalidate all existing sessions.
120
+ * In order to rotate the secret without invalidating sessions, provide an array of secrets,
121
+ * with the new secret as first element of the array, and including previous secrets as the later elements.
122
+ */
123
+ secret: string | Array<string>;
124
+ /**
125
+ * Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID.
126
+ * The function is given the request as the first argument if you want to use some value attached to it when generating the ID.
127
+ *
128
+ * The default value is a function which uses the uid-safe library to generate IDs.
129
+ * Be careful to generate unique IDs so your sessions do not conflict.
130
+ */
131
+ genid?(req: Express.Request): string;
132
+ /**
133
+ * The name of the session ID cookie to set in the response (and read from in the request).
134
+ * The default value is 'connect.sid'.
135
+ *
136
+ * Note if you have multiple apps running on the same hostname (this is just the name, i.e. `localhost` or `127.0.0.1`; different schemes and ports do not name a different hostname),
137
+ * then you need to separate the session cookies from each other.
138
+ * The simplest method is to simply set different names per app.
139
+ */
140
+ name?: string | undefined;
141
+ /**
142
+ * The session store instance, defaults to a new `MemoryStore` instance.
143
+ * @see MemoryStore
144
+ */
145
+ store?: Store | undefined;
146
+ /**
147
+ * Settings object for the session ID cookie.
148
+ * @see CookieOptions
149
+ */
150
+ cookie?: CookieOptions | undefined;
151
+ /**
152
+ * Force the session identifier cookie to be set on every response. The expiration is reset to the original `maxAge`, resetting the expiration countdown.
153
+ * The default value is `false`.
154
+ *
155
+ * With this enabled, the session identifier cookie will expire in `maxAge` *since the last response was sent* instead of in `maxAge` *since the session was last modified by the server*.
156
+ * This is typically used in conjuction with short, non-session-length `maxAge` values to provide a quick timeout of the session data
157
+ * with reduced potential of it occurring during on going server interactions.
158
+ *
159
+ * Note that when this option is set to `true` but the `saveUninitialized` option is set to `false`, the cookie will not be set on a response with an uninitialized session.
160
+ * This option only modifies the behavior when an existing session was loaded for the request.
161
+ *
162
+ * @see saveUninitialized
163
+ */
164
+ rolling?: boolean | undefined;
165
+ /**
166
+ * Forces the session to be saved back to the session store, even if the session was never modified during the request.
167
+ * Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server
168
+ * and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using).
169
+ *
170
+ * The default value is `true`, but using the default has been deprecated, as the default will change in the future.
171
+ * Please research into this setting and choose what is appropriate to your use-case. Typically, you'll want `false`.
172
+ *
173
+ * How do I know if this is necessary for my store? The best way to know is to check with your store if it implements the `touch` method.
174
+ * If it does, then you can safely set `resave: false`.
175
+ * If it does not implement the `touch` method and your store sets an expiration date on stored sessions, then you likely need `resave: true`.
176
+ */
177
+ resave?: boolean | undefined;
178
+ /**
179
+ * Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header).
180
+ * The default value is undefined.
181
+ *
182
+ * - `true`: The `X-Forwarded-Proto` header will be used.
183
+ * - `false`: All headers are ignored and the connection is considered secure only if there is a direct TLS/SSL connection.
184
+ * - `undefined`: Uses the "trust proxy" setting from express
185
+ */
186
+ proxy?: boolean | undefined;
187
+ /**
188
+ * Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
189
+ * Choosing `false` is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie.
190
+ * Choosing `false` will also help with race conditions where a client makes multiple parallel requests without a session.
191
+ *
192
+ * The default value is `true`, but using the default has been deprecated, as the default will change in the future.
193
+ * Please research into this setting and choose what is appropriate to your use-case.
194
+ *
195
+ * **If you are using `express-session` in conjunction with PassportJS:**
196
+ * Passport will add an empty Passport object to the session for use after a user is authenticated, which will be treated as a modification to the session, causing it to be saved.
197
+ * This has been fixed in PassportJS 0.3.0.
198
+ */
199
+ saveUninitialized?: boolean | undefined;
200
+ /**
201
+ * Control the result of unsetting req.session (through delete, setting to null, etc.).
202
+ * - `destroy`: The session will be destroyed (deleted) when the response ends.
203
+ * - `keep`: The session in the store will be kept, but modifications made during the request are ignored and not saved.
204
+ * @default 'keep'
205
+ */
206
+ unset?: "destroy" | "keep" | undefined;
207
+ }
208
+ export { SessionOptions };
@@ -10,6 +10,7 @@ import { ServeFaviconOptions } from "./interfaces/serve-favicon.interface";
10
10
  import { FormatFn, OptionsMorgan } from "./interfaces/morgan.interface";
11
11
  import { RateLimitOptions } from "./interfaces/express-rate-limit.interface";
12
12
  import { OptionsHelmet } from "./interfaces/helmet.interface";
13
+ import { SessionOptions } from "./interfaces/express-session.interface";
13
14
  /**
14
15
  * ExpressHandler Type
15
16
  *
@@ -109,6 +110,13 @@ interface IMiddleware {
109
110
  * @param options - Optional configuration options for serving the favicon. Defines the behavior of the favicon middleware like cache control, custom headers, etc.
110
111
  */
111
112
  addServeFavicon(path: string | Buffer, options?: ServeFaviconOptions): void;
113
+ /**
114
+ * Add a middleware to enable express-session.
115
+ *
116
+ * @param options - Optional configuration options for Session.
117
+ *
118
+ */
119
+ addSession(options: SessionOptions): void;
112
120
  /**
113
121
  * Configures the error handling middleware for the application.
114
122
  *
@@ -223,6 +231,13 @@ declare class Middleware implements IMiddleware {
223
231
  *
224
232
  */
225
233
  addHelmet(options?: OptionsHelmet): void;
234
+ /**
235
+ * Add a middleware to enable express-session.
236
+ *
237
+ * @param options - Optional configuration options for Session.
238
+ *
239
+ */
240
+ addSession(options: SessionOptions): void;
226
241
  /**
227
242
  * Configures the error handling middleware for the application.
228
243
  *
@@ -0,0 +1,38 @@
1
+ export interface IInMemoryDBEntity {
2
+ id: string;
3
+ }
4
+ /**
5
+ * InMemoryDB Class
6
+ *
7
+ * This class and its methods offer functionalities to simulate an in-memory database.
8
+ * It is particularly useful for developers starting with ExpressoTS without any database connection.
9
+ *
10
+ * @decorator @provideSingleton(InMemoryDB)
11
+ */
12
+ export declare class InMemoryDB {
13
+ private tables;
14
+ /**
15
+ * getTable Method
16
+ *
17
+ * Retrieves a table by its name from the in-memory database.
18
+ *
19
+ * @param tableName - The name of the table to retrieve.
20
+ * @returns {IEntity[]} - An array of entities.
21
+ */
22
+ getTable(tableName: string): Array<IInMemoryDBEntity>;
23
+ /**
24
+ * showTables Method
25
+ *
26
+ * Prints a list of all tables in the in-memory database to the standard output.
27
+ */
28
+ showTables(): void;
29
+ /**
30
+ * printTable Method
31
+ *
32
+ * Prints all records in a specific table to the console.
33
+ * If the table doesn't exist or is empty, it notifies the user.
34
+ *
35
+ * @param tableName - The name of the table to print.
36
+ */
37
+ printTable(tableName: string): void;
38
+ }
@@ -2,3 +2,4 @@ export { Provider, IProvider } from "./provider-service";
2
2
  export { Logger } from "./logger/logger-service";
3
3
  export { EnvValidatorProvider as Env } from "./environment/env-validator.provider";
4
4
  export { ValidateDTO } from "./dto-validator/dto-validator.provider";
5
+ export { InMemoryDB, IInMemoryDBEntity, } from "./db-in-memory/db-in-memory.provider";
package/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/core",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "Expressots - modern, fast, lightweight nodejs web framework (@core)",
5
5
  "author": "Richard Zampieri",
6
6
  "main": "./lib/cjs/index.js",
@@ -88,7 +88,7 @@
88
88
  "release-it": "^16.1.5",
89
89
  "ts-jest": "^29.0.5",
90
90
  "typescript": "^5.0.3",
91
- "vite": "4.4.10",
91
+ "vite": "4.4.11",
92
92
  "vitest": "0.34.6"
93
93
  },
94
94
  "release-it": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/core",
3
- "version": "2.5.0",
3
+ "version": "2.7.0",
4
4
  "description": "Expressots - modern, fast, lightweight nodejs web framework (@core)",
5
5
  "author": "Richard Zampieri",
6
6
  "main": "./lib/cjs/index.js",
@@ -88,7 +88,7 @@
88
88
  "release-it": "^16.1.5",
89
89
  "ts-jest": "^29.0.5",
90
90
  "typescript": "^5.0.3",
91
- "vite": "4.4.10",
91
+ "vite": "4.4.11",
92
92
  "vitest": "0.34.6"
93
93
  },
94
94
  "release-it": {