@notchjs/core 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Augustus Kamau
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # @notchjs/core
2
+
3
+ > A dependency injection based web framework (Node.js).
4
+
5
+ ## Installation
6
+
7
+ Using npm:
8
+
9
+ ```sh
10
+ npm install --save @notchjs/core
11
+ ```
12
+
13
+ or using yarn:
14
+
15
+ ```sh
16
+ yarn add @notchjs/core
17
+ ```
18
+
19
+ ## :memo: License
20
+
21
+ This project is licensed under the **MIT license**.
22
+
23
+ See [LICENSE](LICENSE) for more information.
@@ -0,0 +1,29 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import * as http from 'node:http';
4
+ import * as https from 'node:https';
5
+ import type { HttpAdapter } from '@notchjs/types';
6
+ import type { HookCollector } from './hook-collector';
7
+ import type { ApplicationEnvironment } from './interfaces';
8
+ export declare class Application {
9
+ protected httpServer: http.Server | https.Server;
10
+ private readonly adapter;
11
+ private readonly hooks;
12
+ private readonly _environment;
13
+ private isInitialized;
14
+ private isListening;
15
+ constructor(adapter: HttpAdapter, hooks: HookCollector, environment: ApplicationEnvironment);
16
+ get environment(): ApplicationEnvironment;
17
+ init(): Promise<this>;
18
+ getHttpAdapter<T extends HttpAdapter = HttpAdapter>(): T;
19
+ getHttpServer(): http.Server | https.Server;
20
+ registerHttpServer(): void;
21
+ createServer<T = any>(): T;
22
+ listen(port: string | number, callback?: () => void): Promise<any>;
23
+ listen(port: string | number, hostname: string, callback?: () => void): Promise<any>;
24
+ close(signal?: string): Promise<void>;
25
+ getUrl(): Promise<string>;
26
+ protected dispose(): Promise<void>;
27
+ private formatAddress;
28
+ private getProtocol;
29
+ }
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Application = void 0;
4
+ const node_os_1 = require("node:os");
5
+ const notions_1 = require("@hemjs/notions");
6
+ class Application {
7
+ constructor(adapter, hooks, environment) {
8
+ this.isInitialized = false;
9
+ this.isListening = false;
10
+ this.adapter = adapter;
11
+ this.hooks = hooks;
12
+ this._environment = environment;
13
+ this.registerHttpServer();
14
+ }
15
+ get environment() {
16
+ return this._environment;
17
+ }
18
+ async init() {
19
+ if (this.isInitialized) {
20
+ return this;
21
+ }
22
+ await this.hooks.addStartupHook();
23
+ this.isInitialized = true;
24
+ return this;
25
+ }
26
+ getHttpAdapter() {
27
+ return this.adapter;
28
+ }
29
+ getHttpServer() {
30
+ return this.httpServer;
31
+ }
32
+ registerHttpServer() {
33
+ this.httpServer = this.createServer();
34
+ }
35
+ createServer() {
36
+ this.adapter.initHttpServer();
37
+ return this.adapter.getHttpServer();
38
+ }
39
+ async listen(port, ...args) {
40
+ if (!this.isInitialized)
41
+ await this.init();
42
+ return new Promise((resolve, reject) => {
43
+ const errorHandler = (e) => {
44
+ this.environment.log?.error(e?.toString?.());
45
+ reject(e);
46
+ };
47
+ this.httpServer.once('error', errorHandler);
48
+ const isCallbackInOriginalArgs = (0, notions_1.isFunction)(args[args.length - 1]);
49
+ const listenFnArgs = isCallbackInOriginalArgs
50
+ ? args.slice(0, args.length - 1)
51
+ : args;
52
+ this.httpServer.listen(port, ...listenFnArgs, (...originalCallbackArgs) => {
53
+ if (originalCallbackArgs[0] instanceof Error) {
54
+ return reject(originalCallbackArgs[0]);
55
+ }
56
+ const address = this.httpServer.address();
57
+ if (address) {
58
+ this.httpServer.removeListener('error', errorHandler);
59
+ this.isListening = true;
60
+ resolve(this.httpServer);
61
+ }
62
+ if (isCallbackInOriginalArgs) {
63
+ args[args.length - 1](...originalCallbackArgs);
64
+ }
65
+ });
66
+ });
67
+ }
68
+ async close(signal) {
69
+ await this.dispose();
70
+ await this.hooks.addShutdownHook(signal);
71
+ this.isListening = false;
72
+ }
73
+ async getUrl() {
74
+ return new Promise((resolve, reject) => {
75
+ if (!this.isListening) {
76
+ reject('Server not listening!');
77
+ return;
78
+ }
79
+ const address = this.httpServer.address();
80
+ resolve(this.formatAddress(address));
81
+ });
82
+ }
83
+ async dispose() {
84
+ this.adapter && (await this.adapter.close());
85
+ }
86
+ formatAddress(address) {
87
+ if ((0, notions_1.isString)(address)) {
88
+ if ((0, node_os_1.platform)() === 'win32') {
89
+ return address;
90
+ }
91
+ const basePath = encodeURIComponent(address);
92
+ return `${this.getProtocol()}+unix://${basePath}`;
93
+ }
94
+ let host = address.address;
95
+ if ([6, 'IPv6'].includes(address.family)) {
96
+ if (host === '::') {
97
+ host = '[::1]';
98
+ }
99
+ else {
100
+ host = `[${host}]`;
101
+ }
102
+ }
103
+ else if (host === '0.0.0.0') {
104
+ host = '127.0.0.1';
105
+ }
106
+ return `${this.getProtocol()}://${host}:${address.port}`;
107
+ }
108
+ getProtocol() {
109
+ return this.environment.config?.tls ? 'https' : 'http';
110
+ }
111
+ }
112
+ exports.Application = Application;
@@ -0,0 +1,2 @@
1
+ export declare const HTTP_ADAPTER = "HTTP_ADAPTER";
2
+ export declare const LOGGER = "LOGGER";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LOGGER = exports.HTTP_ADAPTER = void 0;
4
+ exports.HTTP_ADAPTER = 'HTTP_ADAPTER';
5
+ exports.LOGGER = 'LOGGER';
@@ -0,0 +1,12 @@
1
+ import type { HookProvider } from '@armscye/hooks';
2
+ import type { HookFactory } from './hook-factory';
3
+ export declare class HookCollector {
4
+ private readonly records;
5
+ constructor(factory: HookFactory, hooks?: HookProvider[]);
6
+ addStartupHook(): Promise<void>;
7
+ addShutdownHook(signal?: string): Promise<void>;
8
+ private runStartupHook;
9
+ private runShutdownHook;
10
+ private isStartupHook;
11
+ private isShutdownHook;
12
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookCollector = void 0;
4
+ const notions_1 = require("@hemjs/notions");
5
+ const iterare_1 = require("iterare");
6
+ class HookCollector {
7
+ constructor(factory, hooks = []) {
8
+ this.records = factory.prepare(hooks);
9
+ }
10
+ async addStartupHook() {
11
+ await Promise.all(this.runStartupHook(this.records));
12
+ }
13
+ async addShutdownHook(signal) {
14
+ await Promise.all(this.runShutdownHook(this.records, signal));
15
+ }
16
+ runStartupHook(records) {
17
+ return (0, iterare_1.iterate)(records)
18
+ .filter((record) => !(0, notions_1.isNil)(record))
19
+ .filter(({ hook }) => this.isStartupHook(hook))
20
+ .map(async ({ hook }) => hook.onStartup())
21
+ .toArray();
22
+ }
23
+ runShutdownHook(records, signal) {
24
+ return (0, iterare_1.iterate)(records)
25
+ .filter((record) => !(0, notions_1.isNil)(record))
26
+ .filter(({ hook }) => this.isShutdownHook(hook))
27
+ .map(async ({ hook }) => hook.onShutdown(signal))
28
+ .toArray();
29
+ }
30
+ isStartupHook(hook) {
31
+ return (0, notions_1.isFunction)(hook.onStartup);
32
+ }
33
+ isShutdownHook(hook) {
34
+ return (0, notions_1.isFunction)(hook.onShutdown);
35
+ }
36
+ }
37
+ exports.HookCollector = HookCollector;
@@ -0,0 +1,7 @@
1
+ import type { Container, ProviderToken } from '@armscye/container';
2
+ export declare class HookContainer implements Container {
3
+ private readonly container;
4
+ constructor(container: Container);
5
+ get<T>(token: ProviderToken): T;
6
+ has(token: ProviderToken): boolean;
7
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookContainer = void 0;
4
+ const util_1 = require("@notchjs/util");
5
+ class HookContainer {
6
+ constructor(container) {
7
+ this.container = container;
8
+ }
9
+ get(token) {
10
+ if (!this.has(token)) {
11
+ throw new Error(`Cannot fetch hook provider for (${(0, util_1.stringify)(token)}); provider not registered.`);
12
+ }
13
+ return this.container.get(token);
14
+ }
15
+ has(token) {
16
+ if (this.container.has(token)) {
17
+ return true;
18
+ }
19
+ return false;
20
+ }
21
+ }
22
+ exports.HookContainer = HookContainer;
@@ -0,0 +1,9 @@
1
+ import type { HookContainer } from './hook-container';
2
+ import type { HookRecord } from './interfaces';
3
+ export declare class HookFactory {
4
+ private readonly container;
5
+ constructor(container: HookContainer);
6
+ prepare(hook: any): HookRecord | HookRecord[];
7
+ lazy<T>(hook: string | symbol): T;
8
+ pipeline(hooks: any[]): any[];
9
+ }
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HookFactory = void 0;
4
+ const notions_1 = require("@hemjs/notions");
5
+ const util_1 = require("@notchjs/util");
6
+ class HookFactory {
7
+ constructor(container) {
8
+ this.container = container;
9
+ }
10
+ prepare(hook) {
11
+ if (Array.isArray(hook)) {
12
+ return this.pipeline(hook);
13
+ }
14
+ if ((0, notions_1.isObject)(hook)) {
15
+ return {
16
+ name: hook.constructor?.name,
17
+ hook: hook,
18
+ };
19
+ }
20
+ if ((0, notions_1.isFunction)(hook)) {
21
+ const funcAsString = hook.toString();
22
+ const isClass = /^class\s/.test(funcAsString);
23
+ if (isClass) {
24
+ return {
25
+ name: hook.name,
26
+ hook: new hook(),
27
+ };
28
+ }
29
+ return {
30
+ name: hook.name,
31
+ hook: hook(),
32
+ };
33
+ }
34
+ if (!(0, notions_1.isString)(hook) && !(0, notions_1.isSymbol)(hook)) {
35
+ throw new Error(`Hook (${(0, util_1.stringify)(hook)}) is neither a provider token, a class, a function, or an array of such arguments.`);
36
+ }
37
+ return {
38
+ name: (0, notions_1.isSymbol)(hook) ? hook.toString() : hook,
39
+ hook: this.lazy(hook),
40
+ };
41
+ }
42
+ lazy(hook) {
43
+ return this.container.get(hook);
44
+ }
45
+ pipeline(hooks) {
46
+ return hooks.map((hook) => this.prepare(hook));
47
+ }
48
+ }
49
+ exports.HookFactory = HookFactory;
@@ -0,0 +1,6 @@
1
+ import type { HttpAdapter } from '@notchjs/types';
2
+ export declare class HttpAdapterHost {
3
+ private _httpAdapter;
4
+ constructor(httpAdapter?: HttpAdapter);
5
+ get httpAdapter(): HttpAdapter | undefined;
6
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpAdapterHost = void 0;
4
+ class HttpAdapterHost {
5
+ constructor(httpAdapter) {
6
+ this._httpAdapter = httpAdapter;
7
+ }
8
+ get httpAdapter() {
9
+ return this._httpAdapter;
10
+ }
11
+ }
12
+ exports.HttpAdapterHost = HttpAdapterHost;
@@ -0,0 +1,9 @@
1
+ export * from './application';
2
+ export * from './constants';
3
+ export * from './hook-collector';
4
+ export * from './hook-container';
5
+ export * from './hook-factory';
6
+ export * from './http-adapter-host';
7
+ export * from './interfaces';
8
+ export * from './logger-host';
9
+ export * from './notch.module';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./application"), exports);
5
+ tslib_1.__exportStar(require("./constants"), exports);
6
+ tslib_1.__exportStar(require("./hook-collector"), exports);
7
+ tslib_1.__exportStar(require("./hook-container"), exports);
8
+ tslib_1.__exportStar(require("./hook-factory"), exports);
9
+ tslib_1.__exportStar(require("./http-adapter-host"), exports);
10
+ tslib_1.__exportStar(require("./interfaces"), exports);
11
+ tslib_1.__exportStar(require("./logger-host"), exports);
12
+ tslib_1.__exportStar(require("./notch.module"), exports);
@@ -0,0 +1,5 @@
1
+ /// <reference types="node" />
2
+ import type { TlsOptions } from 'node:tls';
3
+ export interface ApplicationConfig {
4
+ tls?: TlsOptions;
5
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,6 @@
1
+ import type { Logger } from '@armscye/logging';
2
+ import type { ApplicationConfig } from './application-config';
3
+ export interface ApplicationEnvironment {
4
+ log?: Logger;
5
+ config?: ApplicationConfig;
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ export interface HookRecord {
2
+ name: string;
3
+ hook: unknown;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ export * from './application-config';
2
+ export * from './application-environment';
3
+ export * from './hook-record';
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./application-config"), exports);
5
+ tslib_1.__exportStar(require("./application-environment"), exports);
6
+ tslib_1.__exportStar(require("./hook-record"), exports);
@@ -0,0 +1,6 @@
1
+ import type { Logger } from '@armscye/logging';
2
+ export declare class LoggerHost {
3
+ private _logger;
4
+ constructor(logger?: Logger);
5
+ get logger(): Logger | undefined;
6
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoggerHost = void 0;
4
+ class LoggerHost {
5
+ constructor(logger) {
6
+ this._logger = logger;
7
+ }
8
+ get logger() {
9
+ return this._logger;
10
+ }
11
+ }
12
+ exports.LoggerHost = LoggerHost;
@@ -0,0 +1,7 @@
1
+ import type { Provider } from '@armscye/container';
2
+ import type { Module } from '@armscye/module';
3
+ export declare class NotchModule implements Module {
4
+ register(): {
5
+ providers: Provider[];
6
+ };
7
+ }
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NotchModule = void 0;
4
+ const util_1 = require("@notchjs/util");
5
+ const application_1 = require("./application");
6
+ const constants_1 = require("./constants");
7
+ const hook_collector_1 = require("./hook-collector");
8
+ const hook_container_1 = require("./hook-container");
9
+ const hook_factory_1 = require("./hook-factory");
10
+ const http_adapter_host_1 = require("./http-adapter-host");
11
+ const logger_host_1 = require("./logger-host");
12
+ class NotchModule {
13
+ register() {
14
+ return {
15
+ providers: [
16
+ {
17
+ provide: http_adapter_host_1.HttpAdapterHost.name,
18
+ useFactory: (container) => {
19
+ const adapter = container.has(constants_1.HTTP_ADAPTER)
20
+ ? container.get(constants_1.HTTP_ADAPTER)
21
+ : undefined;
22
+ return new http_adapter_host_1.HttpAdapterHost(adapter);
23
+ },
24
+ },
25
+ {
26
+ provide: logger_host_1.LoggerHost.name,
27
+ useFactory: (container) => {
28
+ const logger = container.has(constants_1.LOGGER)
29
+ ? container.get(constants_1.LOGGER)
30
+ : new util_1.NoopLogger();
31
+ return new logger_host_1.LoggerHost(logger);
32
+ },
33
+ },
34
+ {
35
+ provide: hook_container_1.HookContainer.name,
36
+ useFactory: (container) => {
37
+ return new hook_container_1.HookContainer(container);
38
+ },
39
+ },
40
+ {
41
+ provide: hook_factory_1.HookFactory.name,
42
+ useFactory: (container) => {
43
+ return new hook_factory_1.HookFactory(container.get(hook_container_1.HookContainer.name));
44
+ },
45
+ },
46
+ {
47
+ provide: hook_collector_1.HookCollector.name,
48
+ useFactory: (container) => {
49
+ const config = container.has('config')
50
+ ? container.get('config')
51
+ : {};
52
+ return new hook_collector_1.HookCollector(container.get(hook_factory_1.HookFactory.name), config.hooks);
53
+ },
54
+ },
55
+ {
56
+ provide: application_1.Application.name,
57
+ useFactory: (container) => {
58
+ const httpAdapterHost = container.get(http_adapter_host_1.HttpAdapterHost.name);
59
+ if (!httpAdapterHost.httpAdapter) {
60
+ throw new Error('HTTP adapter missing');
61
+ }
62
+ const config = container.has('config')
63
+ ? container.get('config')
64
+ : {};
65
+ const loggerHost = container.get(logger_host_1.LoggerHost.name);
66
+ const hooks = container.get(hook_collector_1.HookCollector.name);
67
+ return new application_1.Application(httpAdapterHost.httpAdapter, hooks, {
68
+ log: loggerHost.logger?.getLogger(application_1.Application.name),
69
+ config: config.notch,
70
+ });
71
+ },
72
+ },
73
+ ],
74
+ };
75
+ }
76
+ }
77
+ exports.NotchModule = NotchModule;
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@notchjs/core",
3
+ "version": "0.2.1",
4
+ "description": "A dependency injection based web framework (Node.js)",
5
+ "license": "MIT",
6
+ "author": "Augustus Kamau",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "keywords": [
13
+ "notchjs",
14
+ "notch",
15
+ "framework"
16
+ ],
17
+ "scripts": {
18
+ "test": "jest --detectOpenHandles"
19
+ },
20
+ "dependencies": {
21
+ "@notchjs/util": "^0.2.1",
22
+ "iterare": "1.2.1",
23
+ "tslib": "2.6.2"
24
+ },
25
+ "devDependencies": {
26
+ "@notchjs/express": "^0.2.1",
27
+ "@notchjs/types": "^0.2.1"
28
+ },
29
+ "homepage": "https://github.com/notchjs/notch",
30
+ "bugs": {
31
+ "url": "https://github.com/notchjs/notch/issues"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/notchjs/notch.git"
36
+ },
37
+ "engines": {
38
+ "node": ">=18.17.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "gitHead": "4776f48b4b1f809d36e2f3cf26f752956a21e3ab"
44
+ }