@nattyjs/common 0.0.1-beta.5 → 0.0.1-beta.51

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.cjs CHANGED
@@ -4,6 +4,8 @@ const fs = require('fs');
4
4
  const dotenv = require('dotenv');
5
5
  const dotenvExpand = require('dotenv-expand');
6
6
  const path = require('path');
7
+ const child_process = require('child_process');
8
+ const getPortPlease = require('get-port-please');
7
9
 
8
10
  function _interopNamespaceCompat(e) {
9
11
  if (e && typeof e === 'object' && 'default' in e) return e;
@@ -25,6 +27,17 @@ const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
25
27
  const commonContainer = new class {
26
28
  constructor() {
27
29
  this.metadataConfig = { services: /* @__PURE__ */ new Map() };
30
+ this.types = {};
31
+ }
32
+ registerType(type) {
33
+ if (type) {
34
+ if (typeof type === "string")
35
+ type = JSON.parse(type);
36
+ this.types[type.name] = type;
37
+ }
38
+ }
39
+ setupCliConfig(config) {
40
+ this.nattyCliConfig = config;
28
41
  }
29
42
  setupConfig(config) {
30
43
  const modelBinding = {
@@ -35,7 +48,8 @@ const commonContainer = new class {
35
48
  }
36
49
  }
37
50
  };
38
- this.nattyConfig = { ...{ api: { rootPath: "api" }, autoGeneratePort: true, modelBinding, globalConfig: {} }, ...config };
51
+ const secureConfig = { sensitiveProps: ["password", "mobileNo", "email"] };
52
+ this.nattyConfig = { ...{ api: { rootPath: "api" }, autoGeneratePort: true, modelBinding, globalConfig: {}, secure: secureConfig }, ...config };
39
53
  }
40
54
  setupBuildOptions(options) {
41
55
  this.buildOptions = options;
@@ -225,20 +239,29 @@ function getPath(pathCollection, isIncludeRoot = true, isCreateFolder = false) {
225
239
  return currentPath;
226
240
  }
227
241
 
242
+ function resolvePath(path$1) {
243
+ return path.resolve(commonContainer.buildOptions.rootDir, path$1);
244
+ }
245
+
228
246
  async function readEnv() {
229
- let filePath = getPath([ENVIRONMENTS, commonContainer.buildOptions.mode && commonContainer.buildOptions.mode !== "dev" ? `.env.${commonContainer.buildOptions.mode}` : `.env`]);
247
+ const envConfig = commonContainer.nattyCliConfig.env;
248
+ let filePath = envConfig?.dictionary ? void 0 : getPath([ENVIRONMENTS, commonContainer.buildOptions.mode && commonContainer.buildOptions.mode !== "dev" ? `.env.${commonContainer.buildOptions.mode}` : `.env`]);
249
+ if (envConfig && envConfig.path)
250
+ filePath = resolvePath(envConfig.path);
230
251
  let parsedEnvTsDefinition = {};
231
- if (fs.existsSync(filePath)) {
252
+ let parsedEnv = commonContainer.nattyCliConfig.env?.dictionary;
253
+ if (!parsedEnv && filePath && fs.existsSync(filePath)) {
232
254
  const { parsed, error } = dotenv__namespace.config({
233
255
  debug: !!process.env.DEBUG || void 0,
234
256
  path: filePath
235
257
  });
236
- const info = getEnvTsDefinition(parsed);
237
- parsedEnvTsDefinition = info.parsedEnvTsDefinition;
238
- commonContainer.setEnvTsDefinition(parsedEnvTsDefinition);
239
- commonContainer.setEnvValueInfo(info.envVariableValueInfo);
240
- dotenvExpand__namespace.expand({ parsed });
258
+ parsedEnv = parsed;
241
259
  }
260
+ const info = getEnvTsDefinition(parsedEnv);
261
+ parsedEnvTsDefinition = info.parsedEnvTsDefinition;
262
+ commonContainer.setEnvTsDefinition(parsedEnvTsDefinition);
263
+ commonContainer.setEnvValueInfo(info.envVariableValueInfo);
264
+ dotenvExpand__namespace.expand({ parsed: parsedEnv });
242
265
  return parsedEnvTsDefinition;
243
266
  }
244
267
 
@@ -286,10 +309,10 @@ function readEnvKey(key) {
286
309
  }
287
310
 
288
311
  class UserIdentity {
289
- constructor(isAuthenticate, id, claim) {
312
+ constructor(isAuthenticate, id, claims) {
290
313
  this.isAuthenticate = isAuthenticate;
291
314
  this.id = id;
292
- this.claim = claim;
315
+ this.claims = claims;
293
316
  }
294
317
  }
295
318
 
@@ -381,7 +404,7 @@ class List {
381
404
  if (this.count()) {
382
405
  return predicate ? this.where(predicate).first() : this._entities[0];
383
406
  } else {
384
- throw new Error("No result found.");
407
+ return void 0;
385
408
  }
386
409
  }
387
410
  firstOrDefault(predicate) {
@@ -575,13 +598,150 @@ var FrameworkType = /* @__PURE__ */ ((FrameworkType2) => {
575
598
  return FrameworkType2;
576
599
  })(FrameworkType || {});
577
600
 
601
+ function registerType(type) {
602
+ commonContainer.registerType(type);
603
+ }
604
+
605
+ class AbstractRunner {
606
+ async stop() {
607
+ if (this.childProcess)
608
+ this.childProcess.kill();
609
+ }
610
+ async exec(command, args, cwd = process.cwd()) {
611
+ const options = {
612
+ cwd,
613
+ stdio: "pipe",
614
+ shell: true
615
+ };
616
+ return new Promise((resolve, reject) => {
617
+ const child = child_process.spawn(
618
+ `${command}`,
619
+ [...args],
620
+ options
621
+ );
622
+ this.childProcess = child;
623
+ child.stdout.on(
624
+ "data",
625
+ (data) => {
626
+ const writeData = data.toString().replace(/\r\n|\n/, "");
627
+ if (writeData.indexOf("[NATTYJS]") > -1 || writeData.indexOf("[NATTYJS:LOGGER]") > -1) {
628
+ console.log(writeData);
629
+ }
630
+ }
631
+ );
632
+ child.stderr.on("data", (data) => {
633
+ const writeData = data.toString().replace(/\r\n|\n/, "");
634
+ console.log(writeData);
635
+ });
636
+ child.on("close", (code) => {
637
+ if (code === 0) {
638
+ resolve(null);
639
+ } else {
640
+ console.error(
641
+ `${command} ${args}`
642
+ );
643
+ reject();
644
+ }
645
+ });
646
+ });
647
+ }
648
+ }
649
+
650
+ async function getPort() {
651
+ const portNumber = commonContainer.nattyConfig?.port || 3200;
652
+ if (portNumber)
653
+ return portNumber;
654
+ const port = await getPortPlease.getPort({ ports: [portNumber, ...Array(50).fill(3001).map((fillValue, index) => fillValue + index)] });
655
+ commonContainer.nattyConfig.port = port;
656
+ return port;
657
+ }
658
+
659
+ const reset = "\x1B[0m";
660
+ const NATTY_LOGGER = `[NATTYJS:LOGGER] `;
661
+ const log = {
662
+ green: (text) => console.log("\x1B[32m" + NATTY_LOGGER + text + reset),
663
+ red: (text) => console.log("\x1B[31m" + NATTY_LOGGER + text + reset),
664
+ blue: (text) => console.log("\x1B[34m" + NATTY_LOGGER + text + reset),
665
+ yellow: (text) => console.log("\x1B[33m" + NATTY_LOGGER + text + reset)
666
+ };
667
+ class AbstractConsoleLogger {
668
+ log(message) {
669
+ log.yellow(message);
670
+ }
671
+ info(message) {
672
+ log.blue(message);
673
+ }
674
+ warn(message) {
675
+ log.yellow(message);
676
+ }
677
+ error(message) {
678
+ log.red(message);
679
+ }
680
+ }
681
+
682
+ class ConsoleLogger extends AbstractConsoleLogger {
683
+ }
684
+
685
+ function typed() {
686
+ return function(OriginalClass) {
687
+ const extendedClass = class extends OriginalClass {
688
+ constructor(...args) {
689
+ super(...args);
690
+ const typeInfo = commonContainer.types[OriginalClass.name];
691
+ defineProps(this, typeInfo?.props, OriginalClass.name);
692
+ }
693
+ };
694
+ delete extendedClass.name;
695
+ Object.defineProperty(extendedClass, "name", {
696
+ value: OriginalClass.name,
697
+ writable: false
698
+ });
699
+ return extendedClass;
700
+ };
701
+ }
702
+ const types = ["string", "number", "boolean"];
703
+ function defineProps(instance, props, modelName) {
704
+ if (props && Array.isArray(props)) {
705
+ for (const prop of props) {
706
+ if (prop.type && types.indexOf(prop.type) > -1) {
707
+ overrideProp(instance, prop, modelName);
708
+ }
709
+ }
710
+ }
711
+ }
712
+ function overrideProp(instance, prop, modelName) {
713
+ let descriptor = Object.getOwnPropertyDescriptor(
714
+ Object.getPrototypeOf(instance),
715
+ prop.name
716
+ );
717
+ let value = instance[prop.name];
718
+ Object.defineProperty(instance, prop.name, {
719
+ enumerable: true,
720
+ configurable: true,
721
+ get: () => {
722
+ return descriptor ? descriptor.get.call(instance) : value;
723
+ },
724
+ set: (v) => {
725
+ if (prop.type == "boolean" && v !== null && v !== void 0)
726
+ v = v === 0 ? false : true;
727
+ const type = typeof v;
728
+ if (v === null || v === void 0 || prop.type == type)
729
+ value = v;
730
+ else
731
+ throw new Error(`Incorrect value type of ${modelName} class property '${prop.name}' `);
732
+ }
733
+ });
734
+ }
735
+
578
736
  exports.ALLOW_METHODS = ALLOW_METHODS;
737
+ exports.AbstractRunner = AbstractRunner;
579
738
  exports.ActionFilter = ActionFilter;
580
739
  exports.AuthenticationFilter = AuthenticationFilter;
581
740
  exports.AuthorizationFilter = AuthorizationFilter;
582
741
  exports.BACK_SLASH_REGEX = BACK_SLASH_REGEX;
583
742
  exports.BLANK = BLANK;
584
743
  exports.CONTROLLER = CONTROLLER;
744
+ exports.ConsoleLogger = ConsoleLogger;
585
745
  exports.DEFAULT_ACTIONS = DEFAULT_ACTIONS;
586
746
  exports.DEFAULT_CHILD_PATH = DEFAULT_CHILD_PATH;
587
747
  exports.DELETE = DELETE;
@@ -606,10 +766,13 @@ exports.commonContainer = commonContainer;
606
766
  exports.createPath = createPath;
607
767
  exports.createTestServer = createTestServer;
608
768
  exports.getPath = getPath;
769
+ exports.getPort = getPort;
609
770
  exports.isConstructor = isConstructor;
610
771
  exports.isEqual = isEqual;
611
772
  exports.isFunction = isFunction;
612
773
  exports.isObject = isObject;
613
774
  exports.readEnv = readEnv;
614
775
  exports.readEnvKey = readEnvKey;
776
+ exports.registerType = registerType;
615
777
  exports.typeContainer = typeContainer;
778
+ exports.typed = typed;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { RequestRouteInfo, IHttpResult, IModelBindingContext, ProblemDetail, IExceptionContext, HttpResponseInit, NattyTestModule, ModelBinding, BuildOptions, ClassTypeInfo } from '@nattyjs/types';
1
+ import { RequestRouteInfo, IHttpResult, Cookie, IModelBindingContext, ProblemDetail, IExceptionContext, HttpResponseInit, NattyTestModule, ModelBinding, BuildOptions, TypesInfo, ClassTypeInfo } from '@nattyjs/types';
2
+ import { ChildProcess } from 'child_process';
2
3
 
3
4
  interface ClassType<T> extends Function {
4
5
  new (...args: any[]): T;
@@ -7,8 +8,8 @@ interface ClassType<T> extends Function {
7
8
  declare class UserIdentity<T> {
8
9
  isAuthenticate: boolean;
9
10
  id?: any;
10
- claim?: T;
11
- constructor(isAuthenticate: boolean, id?: any, claim?: T);
11
+ claims?: T;
12
+ constructor(isAuthenticate: boolean, id?: any, claims?: T);
12
13
  }
13
14
 
14
15
  interface IExecutionContext {
@@ -21,6 +22,11 @@ interface IExecutionContext {
21
22
 
22
23
  interface IActionExecutedContext extends IExecutionContext {
23
24
  content: any;
25
+ get response(): {
26
+ cookies: Array<Cookie>;
27
+ headers: Headers;
28
+ status: number;
29
+ };
24
30
  }
25
31
 
26
32
  interface IActionExecutingContext extends IExecutionContext {
@@ -37,8 +43,12 @@ declare abstract class AuthenticationFilter {
37
43
  onFailedResponse(): ProblemDetail;
38
44
  }
39
45
 
46
+ interface IAuthorizationContext extends IActionExecutingContext {
47
+ config: any;
48
+ }
49
+
40
50
  declare abstract class AuthorizationFilter {
41
- abstract onAuthorization(httpContext: any, permissionRequirement: any): Promise<boolean>;
51
+ abstract onAuthorization(httpContext: IAuthorizationContext): Promise<boolean>;
42
52
  onFailedAuthorization(): ProblemDetail;
43
53
  }
44
54
 
@@ -53,6 +63,36 @@ interface GlobalConfig {
53
63
  onException?: ClassType<ExceptionFilter>;
54
64
  }
55
65
 
66
+ interface CorsConfig {
67
+ origin: string[];
68
+ methods: string;
69
+ preflightContinue: boolean;
70
+ optionsSuccessStatus: number;
71
+ credentials: boolean;
72
+ }
73
+
74
+ interface PayloadConfig {
75
+ limit?: number;
76
+ }
77
+
78
+ interface SecureConfig {
79
+ sensitiveProps?: String[];
80
+ }
81
+
82
+ interface PreInitEventConfig {
83
+ cors?: CorsConfig;
84
+ }
85
+
86
+ interface LifeCycleEvents {
87
+ preInit: () => PreInitEventConfig;
88
+ onStart: () => Promise<void>;
89
+ }
90
+
91
+ interface WebScheduleConfig {
92
+ interval: number;
93
+ scheduleFunction: () => Promise<void>;
94
+ }
95
+
56
96
  interface NattyConfig {
57
97
  app: any;
58
98
  testModule?: NattyTestModule;
@@ -62,12 +102,55 @@ interface NattyConfig {
62
102
  modelBinding?: ModelBinding;
63
103
  global?: GlobalConfig;
64
104
  autoGeneratePort?: boolean;
105
+ port?: number;
106
+ cors?: CorsConfig;
107
+ payload?: PayloadConfig;
108
+ secure?: SecureConfig;
109
+ lifeCycle?: LifeCycleEvents;
110
+ webSchedules?: Array<WebScheduleConfig>;
111
+ static?: {
112
+ dir: string;
113
+ indexFile?: string;
114
+ spaFallback?: boolean;
115
+ maxAge?: string | number;
116
+ };
117
+ }
118
+
119
+ declare abstract class AbstractRunner {
120
+ abstract run(): void;
121
+ childProcess: ChildProcess;
122
+ stop(): Promise<void>;
123
+ protected exec(command: string, args: any[], cwd?: string): Promise<null | string>;
124
+ }
125
+
126
+ interface EnvConfig {
127
+ path: string;
128
+ dictionary: {
129
+ [key: string]: any;
130
+ };
131
+ }
132
+
133
+ interface PackageJsonConfig {
134
+ addExports: string[];
135
+ }
136
+
137
+ interface LibraryConfig {
138
+ packageJson: PackageJsonConfig;
139
+ }
140
+
141
+ interface NattyCliConfig {
142
+ library?: Partial<LibraryConfig>;
143
+ env?: Partial<EnvConfig>;
144
+ runner?: ClassType<AbstractRunner>;
145
+ port?: number;
65
146
  }
66
147
 
67
148
  declare const commonContainer: {
68
149
  setupConfig(config?: NattyConfig): void;
150
+ setupCliConfig(config: NattyCliConfig): void;
69
151
  setupBuildOptions(options: BuildOptions): any;
70
152
  get nattyConfig(): NattyConfig;
153
+ get nattyCliConfig(): NattyCliConfig;
71
154
  get buildOptions(): BuildOptions;
72
155
  get envTsDefinition(): {
73
156
  [key: string]: string;
@@ -84,6 +167,8 @@ declare const commonContainer: {
84
167
  setMetadata(key: string, value: any, propName: string): void;
85
168
  getMetadataValue(key: string, propName: string): any;
86
169
  get globalConfig(): GlobalConfig;
170
+ registerType(type: TypesInfo): void;
171
+ types: TypesInfo;
87
172
  };
88
173
 
89
174
  declare const typeContainer: {
@@ -219,4 +304,22 @@ interface NattyAppConfig extends NattyConfig {
219
304
  framework: FrameworkType;
220
305
  }
221
306
 
222
- export { ALLOW_METHODS, ActionFilter, AuthenticationFilter, AuthorizationFilter, BACK_SLASH_REGEX, BLANK, CONTROLLER, Claim, ClassType, DEFAULT_ACTIONS, DEFAULT_CHILD_PATH, DELETE, ENVIRONMENTS, ExceptionFilter, FrameworkType, GET, GlobalConfig, HTTP_METHOD_ROUTES, IActionExecutedContext, IActionExecutingContext, IExecutionContext, IGNORE_METHODS, List, MetaConfigProps, Middleware, NattyAppConfig, NattyConfig, POST, PUT, RIGHT_SLASH, ROUTE_INSTANCES, ROUTE_METHODS, ROUTE_PATHS, TS_EXTENSION, UserIdentity, commonContainer, createPath, createTestServer, getPath, isConstructor, isEqual, isFunction, isObject, readEnv, readEnvKey, typeContainer };
307
+ declare function registerType(type: TypesInfo): void;
308
+
309
+ declare function getPort(): Promise<number>;
310
+
311
+ declare abstract class AbstractConsoleLogger {
312
+ log(message: any): void;
313
+ info(message: any): void;
314
+ warn(message: any): void;
315
+ error(message: any): void;
316
+ }
317
+
318
+ declare class ConsoleLogger extends AbstractConsoleLogger {
319
+ }
320
+
321
+ declare function typed(): <T extends {
322
+ new (...args: any[]): {};
323
+ }>(OriginalClass: T) => T;
324
+
325
+ export { ALLOW_METHODS, AbstractRunner, ActionFilter, AuthenticationFilter, AuthorizationFilter, BACK_SLASH_REGEX, BLANK, CONTROLLER, Claim, ClassType, ConsoleLogger, DEFAULT_ACTIONS, DEFAULT_CHILD_PATH, DELETE, ENVIRONMENTS, ExceptionFilter, FrameworkType, GET, GlobalConfig, HTTP_METHOD_ROUTES, IActionExecutedContext, IActionExecutingContext, IAuthorizationContext, IExecutionContext, IGNORE_METHODS, List, MetaConfigProps, Middleware, NattyAppConfig, NattyCliConfig, NattyConfig, POST, PUT, RIGHT_SLASH, ROUTE_INSTANCES, ROUTE_METHODS, ROUTE_PATHS, TS_EXTENSION, UserIdentity, WebScheduleConfig, commonContainer, createPath, createTestServer, getPath, getPort, isConstructor, isEqual, isFunction, isObject, readEnv, readEnvKey, registerType, typeContainer, typed };
package/dist/index.mjs CHANGED
@@ -3,10 +3,24 @@ import { existsSync } from 'fs';
3
3
  import * as dotenv from 'dotenv';
4
4
  import * as dotenvExpand from 'dotenv-expand';
5
5
  import * as path from 'path';
6
+ import { resolve } from 'path';
7
+ import { spawn } from 'child_process';
8
+ import { getPort as getPort$1 } from 'get-port-please';
6
9
 
7
10
  const commonContainer = new class {
8
11
  constructor() {
9
12
  this.metadataConfig = { services: /* @__PURE__ */ new Map() };
13
+ this.types = {};
14
+ }
15
+ registerType(type) {
16
+ if (type) {
17
+ if (typeof type === "string")
18
+ type = JSON.parse(type);
19
+ this.types[type.name] = type;
20
+ }
21
+ }
22
+ setupCliConfig(config) {
23
+ this.nattyCliConfig = config;
10
24
  }
11
25
  setupConfig(config) {
12
26
  const modelBinding = {
@@ -17,7 +31,8 @@ const commonContainer = new class {
17
31
  }
18
32
  }
19
33
  };
20
- this.nattyConfig = { ...{ api: { rootPath: "api" }, autoGeneratePort: true, modelBinding, globalConfig: {} }, ...config };
34
+ const secureConfig = { sensitiveProps: ["password", "mobileNo", "email"] };
35
+ this.nattyConfig = { ...{ api: { rootPath: "api" }, autoGeneratePort: true, modelBinding, globalConfig: {}, secure: secureConfig }, ...config };
21
36
  }
22
37
  setupBuildOptions(options) {
23
38
  this.buildOptions = options;
@@ -207,20 +222,29 @@ function getPath(pathCollection, isIncludeRoot = true, isCreateFolder = false) {
207
222
  return currentPath;
208
223
  }
209
224
 
225
+ function resolvePath(path) {
226
+ return resolve(commonContainer.buildOptions.rootDir, path);
227
+ }
228
+
210
229
  async function readEnv() {
211
- let filePath = getPath([ENVIRONMENTS, commonContainer.buildOptions.mode && commonContainer.buildOptions.mode !== "dev" ? `.env.${commonContainer.buildOptions.mode}` : `.env`]);
230
+ const envConfig = commonContainer.nattyCliConfig.env;
231
+ let filePath = envConfig?.dictionary ? void 0 : getPath([ENVIRONMENTS, commonContainer.buildOptions.mode && commonContainer.buildOptions.mode !== "dev" ? `.env.${commonContainer.buildOptions.mode}` : `.env`]);
232
+ if (envConfig && envConfig.path)
233
+ filePath = resolvePath(envConfig.path);
212
234
  let parsedEnvTsDefinition = {};
213
- if (existsSync(filePath)) {
235
+ let parsedEnv = commonContainer.nattyCliConfig.env?.dictionary;
236
+ if (!parsedEnv && filePath && existsSync(filePath)) {
214
237
  const { parsed, error } = dotenv.config({
215
238
  debug: !!process.env.DEBUG || void 0,
216
239
  path: filePath
217
240
  });
218
- const info = getEnvTsDefinition(parsed);
219
- parsedEnvTsDefinition = info.parsedEnvTsDefinition;
220
- commonContainer.setEnvTsDefinition(parsedEnvTsDefinition);
221
- commonContainer.setEnvValueInfo(info.envVariableValueInfo);
222
- dotenvExpand.expand({ parsed });
241
+ parsedEnv = parsed;
223
242
  }
243
+ const info = getEnvTsDefinition(parsedEnv);
244
+ parsedEnvTsDefinition = info.parsedEnvTsDefinition;
245
+ commonContainer.setEnvTsDefinition(parsedEnvTsDefinition);
246
+ commonContainer.setEnvValueInfo(info.envVariableValueInfo);
247
+ dotenvExpand.expand({ parsed: parsedEnv });
224
248
  return parsedEnvTsDefinition;
225
249
  }
226
250
 
@@ -268,10 +292,10 @@ function readEnvKey(key) {
268
292
  }
269
293
 
270
294
  class UserIdentity {
271
- constructor(isAuthenticate, id, claim) {
295
+ constructor(isAuthenticate, id, claims) {
272
296
  this.isAuthenticate = isAuthenticate;
273
297
  this.id = id;
274
- this.claim = claim;
298
+ this.claims = claims;
275
299
  }
276
300
  }
277
301
 
@@ -363,7 +387,7 @@ class List {
363
387
  if (this.count()) {
364
388
  return predicate ? this.where(predicate).first() : this._entities[0];
365
389
  } else {
366
- throw new Error("No result found.");
390
+ return void 0;
367
391
  }
368
392
  }
369
393
  firstOrDefault(predicate) {
@@ -557,4 +581,139 @@ var FrameworkType = /* @__PURE__ */ ((FrameworkType2) => {
557
581
  return FrameworkType2;
558
582
  })(FrameworkType || {});
559
583
 
560
- export { ALLOW_METHODS, ActionFilter, AuthenticationFilter, AuthorizationFilter, BACK_SLASH_REGEX, BLANK, CONTROLLER, DEFAULT_ACTIONS, DEFAULT_CHILD_PATH, DELETE, ENVIRONMENTS, ExceptionFilter, FrameworkType, GET, HTTP_METHOD_ROUTES, IGNORE_METHODS, List, MetaConfigProps, Middleware, POST, PUT, RIGHT_SLASH, ROUTE_INSTANCES, ROUTE_METHODS, ROUTE_PATHS, TS_EXTENSION, UserIdentity, commonContainer, createPath, createTestServer, getPath, isConstructor, isEqual, isFunction, isObject, readEnv, readEnvKey, typeContainer };
584
+ function registerType(type) {
585
+ commonContainer.registerType(type);
586
+ }
587
+
588
+ class AbstractRunner {
589
+ async stop() {
590
+ if (this.childProcess)
591
+ this.childProcess.kill();
592
+ }
593
+ async exec(command, args, cwd = process.cwd()) {
594
+ const options = {
595
+ cwd,
596
+ stdio: "pipe",
597
+ shell: true
598
+ };
599
+ return new Promise((resolve, reject) => {
600
+ const child = spawn(
601
+ `${command}`,
602
+ [...args],
603
+ options
604
+ );
605
+ this.childProcess = child;
606
+ child.stdout.on(
607
+ "data",
608
+ (data) => {
609
+ const writeData = data.toString().replace(/\r\n|\n/, "");
610
+ if (writeData.indexOf("[NATTYJS]") > -1 || writeData.indexOf("[NATTYJS:LOGGER]") > -1) {
611
+ console.log(writeData);
612
+ }
613
+ }
614
+ );
615
+ child.stderr.on("data", (data) => {
616
+ const writeData = data.toString().replace(/\r\n|\n/, "");
617
+ console.log(writeData);
618
+ });
619
+ child.on("close", (code) => {
620
+ if (code === 0) {
621
+ resolve(null);
622
+ } else {
623
+ console.error(
624
+ `${command} ${args}`
625
+ );
626
+ reject();
627
+ }
628
+ });
629
+ });
630
+ }
631
+ }
632
+
633
+ async function getPort() {
634
+ const portNumber = commonContainer.nattyConfig?.port || 3200;
635
+ if (portNumber)
636
+ return portNumber;
637
+ const port = await getPort$1({ ports: [portNumber, ...Array(50).fill(3001).map((fillValue, index) => fillValue + index)] });
638
+ commonContainer.nattyConfig.port = port;
639
+ return port;
640
+ }
641
+
642
+ const reset = "\x1B[0m";
643
+ const NATTY_LOGGER = `[NATTYJS:LOGGER] `;
644
+ const log = {
645
+ green: (text) => console.log("\x1B[32m" + NATTY_LOGGER + text + reset),
646
+ red: (text) => console.log("\x1B[31m" + NATTY_LOGGER + text + reset),
647
+ blue: (text) => console.log("\x1B[34m" + NATTY_LOGGER + text + reset),
648
+ yellow: (text) => console.log("\x1B[33m" + NATTY_LOGGER + text + reset)
649
+ };
650
+ class AbstractConsoleLogger {
651
+ log(message) {
652
+ log.yellow(message);
653
+ }
654
+ info(message) {
655
+ log.blue(message);
656
+ }
657
+ warn(message) {
658
+ log.yellow(message);
659
+ }
660
+ error(message) {
661
+ log.red(message);
662
+ }
663
+ }
664
+
665
+ class ConsoleLogger extends AbstractConsoleLogger {
666
+ }
667
+
668
+ function typed() {
669
+ return function(OriginalClass) {
670
+ const extendedClass = class extends OriginalClass {
671
+ constructor(...args) {
672
+ super(...args);
673
+ const typeInfo = commonContainer.types[OriginalClass.name];
674
+ defineProps(this, typeInfo?.props, OriginalClass.name);
675
+ }
676
+ };
677
+ delete extendedClass.name;
678
+ Object.defineProperty(extendedClass, "name", {
679
+ value: OriginalClass.name,
680
+ writable: false
681
+ });
682
+ return extendedClass;
683
+ };
684
+ }
685
+ const types = ["string", "number", "boolean"];
686
+ function defineProps(instance, props, modelName) {
687
+ if (props && Array.isArray(props)) {
688
+ for (const prop of props) {
689
+ if (prop.type && types.indexOf(prop.type) > -1) {
690
+ overrideProp(instance, prop, modelName);
691
+ }
692
+ }
693
+ }
694
+ }
695
+ function overrideProp(instance, prop, modelName) {
696
+ let descriptor = Object.getOwnPropertyDescriptor(
697
+ Object.getPrototypeOf(instance),
698
+ prop.name
699
+ );
700
+ let value = instance[prop.name];
701
+ Object.defineProperty(instance, prop.name, {
702
+ enumerable: true,
703
+ configurable: true,
704
+ get: () => {
705
+ return descriptor ? descriptor.get.call(instance) : value;
706
+ },
707
+ set: (v) => {
708
+ if (prop.type == "boolean" && v !== null && v !== void 0)
709
+ v = v === 0 ? false : true;
710
+ const type = typeof v;
711
+ if (v === null || v === void 0 || prop.type == type)
712
+ value = v;
713
+ else
714
+ throw new Error(`Incorrect value type of ${modelName} class property '${prop.name}' `);
715
+ }
716
+ });
717
+ }
718
+
719
+ export { ALLOW_METHODS, AbstractRunner, ActionFilter, AuthenticationFilter, AuthorizationFilter, BACK_SLASH_REGEX, BLANK, CONTROLLER, ConsoleLogger, DEFAULT_ACTIONS, DEFAULT_CHILD_PATH, DELETE, ENVIRONMENTS, ExceptionFilter, FrameworkType, GET, HTTP_METHOD_ROUTES, IGNORE_METHODS, List, MetaConfigProps, Middleware, POST, PUT, RIGHT_SLASH, ROUTE_INSTANCES, ROUTE_METHODS, ROUTE_PATHS, TS_EXTENSION, UserIdentity, commonContainer, createPath, createTestServer, getPath, getPort, isConstructor, isEqual, isFunction, isObject, readEnv, readEnvKey, registerType, typeContainer, typed };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nattyjs/common",
3
- "version": "0.0.1-beta.5",
3
+ "version": "0.0.1-beta.51",
4
4
  "description": "Now I’m the model of a modern major general / The venerated Virginian veteran whose men are all / Lining up, to put me up on a pedestal / Writin’ letters to relatives / Embellishin’ my elegance and eloquence / But the elephant is in the room / The truth is in ya face when ya hear the British cannons go / BOOM",
5
5
  "keywords": [],
6
6
  "author": "ajayojha <ojhaajay@outlook.com>",
@@ -16,11 +16,12 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "dotenv": "16.3.1",
19
- "dotenv-expand": "10.0.0"
19
+ "dotenv-expand": "10.0.0",
20
+ "get-port-please": "3.1.1"
20
21
  },
21
22
  "devDependencies": {
22
23
  "@types/node": "20.3.1",
23
- "@nattyjs/types": "0.0.1-beta.5",
24
+ "@nattyjs/types": "0.0.1-beta.51",
24
25
  "unbuild": "1.2.1"
25
26
  }
26
27
  }