@xrystal/core 3.4.2 → 3.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +1 -1
  2. package/x/dist/index.d.ts +2 -0
  3. package/x/dist/index.js +8 -0
  4. package/x/dist/loader/configs/index.d.ts +13 -0
  5. package/x/dist/loader/configs/index.js +17 -0
  6. package/x/dist/loader/events/index.d.ts +6 -0
  7. package/x/dist/loader/events/index.js +25 -0
  8. package/x/dist/loader/index.d.ts +6 -0
  9. package/x/dist/loader/index.js +6 -0
  10. package/x/dist/loader/localizations/index.d.ts +14 -0
  11. package/x/dist/loader/localizations/index.js +32 -0
  12. package/x/dist/loader/logger/index.d.ts +23 -0
  13. package/x/dist/loader/logger/index.js +126 -0
  14. package/x/dist/loader/system/index.d.ts +8 -0
  15. package/x/dist/loader/system/index.js +14 -0
  16. package/x/dist/project/index.d.ts +6 -0
  17. package/x/dist/project/index.js +63 -0
  18. package/x/dist/utils/constants/index.d.ts +8 -0
  19. package/x/dist/utils/constants/index.js +10 -0
  20. package/x/dist/utils/helpers/date/index.d.ts +16 -0
  21. package/x/dist/utils/helpers/date/index.js +48 -0
  22. package/x/dist/utils/helpers/filters/index.d.ts +17 -0
  23. package/x/dist/utils/helpers/filters/index.js +44 -0
  24. package/x/dist/utils/helpers/hash/crypto.d.ts +3 -0
  25. package/x/dist/utils/helpers/hash/crypto.js +22 -0
  26. package/x/dist/utils/helpers/id/index.d.ts +13 -0
  27. package/x/dist/utils/helpers/id/index.js +24 -0
  28. package/x/dist/utils/helpers/index.d.ts +16 -0
  29. package/x/dist/utils/helpers/index.js +16 -0
  30. package/x/dist/utils/helpers/ip/index.d.ts +1 -0
  31. package/x/dist/utils/helpers/ip/index.js +3 -0
  32. package/x/dist/utils/helpers/is/index.d.ts +11 -0
  33. package/x/dist/utils/helpers/is/index.js +35 -0
  34. package/x/dist/utils/helpers/locales/index.d.ts +52 -0
  35. package/x/dist/utils/helpers/locales/index.js +161 -0
  36. package/x/dist/utils/helpers/locales copy/index.d.ts +52 -0
  37. package/x/dist/utils/helpers/locales copy/index.js +161 -0
  38. package/x/dist/utils/helpers/math/index.d.ts +2 -0
  39. package/x/dist/utils/helpers/math/index.js +14 -0
  40. package/x/dist/utils/helpers/objects/index.d.ts +1 -0
  41. package/x/dist/utils/helpers/objects/index.js +55 -0
  42. package/x/dist/utils/helpers/path/index.d.ts +2 -0
  43. package/x/dist/utils/helpers/path/index.js +4 -0
  44. package/x/dist/utils/helpers/regex/checkSpecialRegexControl.d.ts +1 -0
  45. package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +3 -0
  46. package/x/dist/utils/helpers/string/index.d.ts +1 -0
  47. package/x/dist/utils/helpers/string/index.js +9 -0
  48. package/x/dist/utils/helpers/timer/index.d.ts +3 -0
  49. package/x/dist/utils/helpers/timer/index.js +5 -0
  50. package/x/dist/utils/helpers/tmp/index.d.ts +8 -0
  51. package/x/dist/utils/helpers/tmp/index.js +109 -0
  52. package/x/dist/utils/helpers/validates/index.d.ts +5 -0
  53. package/x/dist/utils/helpers/validates/index.js +20 -0
  54. package/x/dist/utils/index.d.ts +3 -0
  55. package/x/dist/utils/index.js +3 -0
  56. package/x/dist/utils/models/classes/class.controller.d.ts +121 -0
  57. package/x/dist/utils/models/classes/class.controller.js +421 -0
  58. package/x/dist/utils/models/classes/class.response.d.ts +17 -0
  59. package/x/dist/utils/models/classes/class.response.js +37 -0
  60. package/x/dist/utils/models/classes/class.services.d.ts +129 -0
  61. package/x/dist/utils/models/classes/class.services.js +344 -0
  62. package/x/dist/utils/models/classes/class.tmp-file-loader.d.ts +8 -0
  63. package/x/dist/utils/models/classes/class.tmp-file-loader.js +38 -0
  64. package/x/dist/utils/models/classes/class.x.d.ts +12 -0
  65. package/x/dist/utils/models/classes/class.x.js +16 -0
  66. package/x/dist/utils/models/enums/index.d.ts +117 -0
  67. package/x/dist/utils/models/enums/index.js +133 -0
  68. package/x/dist/utils/models/index.d.ts +8 -0
  69. package/x/dist/utils/models/index.js +8 -0
  70. package/x/dist/utils/models/types/index.d.ts +3 -0
  71. package/x/dist/utils/models/types/index.js +2 -0
  72. package/x/docker/Dockerfile +24 -0
  73. package/x/logs/critical/2025-11-30_critical.log +0 -0
  74. package/x/logs/error/2025-11-30_error.log +0 -0
  75. package/x/tmp.yml +25 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xrystal/core",
3
- "version": "3.4.2",
3
+ "version": "3.4.3",
4
4
  "description": "Project core for xrystal",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -0,0 +1,2 @@
1
+ declare let tmp: any;
2
+ export default tmp;
@@ -0,0 +1,8 @@
1
+ import coreLoader from "./project/index.js";
2
+ let tmp;
3
+ // => tmp project tool => xrystal
4
+ await (async () => {
5
+ tmp = await coreLoader();
6
+ })();
7
+ //
8
+ export default tmp;
@@ -0,0 +1,13 @@
1
+ import SystemService from '../system/index';
2
+ export default class ConfigsService {
3
+ protected _globalEnvFileName: string;
4
+ protected _systemService: SystemService;
5
+ static tmpFolderPath: string;
6
+ private _envLoadPath;
7
+ load: ({ tmpFolderPath, systemService, envLoadPath, globalEnvFileName }: {
8
+ tmpFolderPath: string;
9
+ systemService: SystemService;
10
+ envLoadPath: string;
11
+ globalEnvFileName?: string | null;
12
+ }) => any;
13
+ }
@@ -0,0 +1,17 @@
1
+ export default class ConfigsService {
2
+ _globalEnvFileName = 'global';
3
+ _systemService;
4
+ static tmpFolderPath;
5
+ _envLoadPath = '';
6
+ load = ({ tmpFolderPath, systemService, envLoadPath, globalEnvFileName }) => {
7
+ ConfigsService.tmpFolderPath = tmpFolderPath;
8
+ this._systemService = systemService;
9
+ this._envLoadPath = `${envLoadPath}`;
10
+ /*
11
+ this._dynamicEnvLoader({
12
+ nodeEnv
13
+ globalEnvFileName
14
+ })
15
+ */
16
+ };
17
+ }
@@ -0,0 +1,6 @@
1
+ export default class EventsService {
2
+ private logger;
3
+ load: ({}: {}) => any;
4
+ private _globalLoader;
5
+ get global(): any;
6
+ }
@@ -0,0 +1,25 @@
1
+ import LoggersLoader from '../logger/index';
2
+ import { x, LoggerLayerEnum } from '../../utils/index';
3
+ export default class EventsService {
4
+ logger = x.get(LoggersLoader);
5
+ load = ({}) => {
6
+ this._globalLoader();
7
+ };
8
+ _globalLoader = () => {
9
+ process.on("uncaughtException", (exception) => {
10
+ this.logger.winston.log({
11
+ level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
12
+ message: `UncaughtException: ${exception}`,
13
+ });
14
+ });
15
+ process.on("unhandledRejection", (exception) => {
16
+ this.logger.winston.log({
17
+ level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
18
+ message: `UnhandledRejection: ${exception}`,
19
+ });
20
+ });
21
+ };
22
+ get global() {
23
+ return this._globalLoader();
24
+ }
25
+ }
@@ -0,0 +1,6 @@
1
+ import SystemService from "./system";
2
+ import ConfigsService from "./configs";
3
+ import LoggerService from "./logger";
4
+ import EventsService from "./events";
5
+ import LocalizationsService from "./localizations";
6
+ export { SystemService, ConfigsService, LoggerService, EventsService, LocalizationsService };
@@ -0,0 +1,6 @@
1
+ import SystemService from "./system";
2
+ import ConfigsService from "./configs";
3
+ import LoggerService from "./logger";
4
+ import EventsService from "./events";
5
+ import LocalizationsService from "./localizations";
6
+ export { SystemService, ConfigsService, LoggerService, EventsService, LocalizationsService };
@@ -0,0 +1,14 @@
1
+ export default class LocalizationsService {
2
+ _instance: any;
3
+ load: ({ loadPath, fallbackLang, preloadLang, }: {
4
+ loadPath: string;
5
+ fallbackLang: string;
6
+ preloadLang: string;
7
+ }) => any;
8
+ i18next: ({ loadPath, fallbackLang, preloadLang, }: {
9
+ loadPath?: string;
10
+ fallbackLang?: string;
11
+ preloadLang?: any;
12
+ }) => any;
13
+ get instance(): any;
14
+ }
@@ -0,0 +1,32 @@
1
+ import i18next from "i18next";
2
+ import Backend from 'i18next-fs-backend';
3
+ import * as middleware from 'i18next-http-middleware';
4
+ export default class LocalizationsService {
5
+ _instance = null;
6
+ load = ({ loadPath, fallbackLang, preloadLang, }) => {
7
+ this.i18next({
8
+ loadPath,
9
+ fallbackLang,
10
+ preloadLang,
11
+ });
12
+ };
13
+ i18next = ({ loadPath, fallbackLang, preloadLang, }) => {
14
+ if (this._instance) {
15
+ return this._instance;
16
+ }
17
+ i18next
18
+ .use(Backend)
19
+ .use(middleware.LanguageDetector)
20
+ .init({
21
+ fallbackLng: fallbackLang,
22
+ preload: preloadLang,
23
+ backend: { loadPath: `${loadPath}/{{lng}}.json` }
24
+ });
25
+ if (i18next)
26
+ this._instance = i18next;
27
+ return i18next;
28
+ };
29
+ get instance() {
30
+ return this._instance;
31
+ }
32
+ }
@@ -0,0 +1,23 @@
1
+ import winston from 'winston';
2
+ import 'winston-daily-rotate-file';
3
+ interface CustomLogger extends winston.Logger {
4
+ critical: winston.LeveledLogMethod;
5
+ http: winston.LeveledLogMethod;
6
+ }
7
+ export default class LoggerService {
8
+ private serviceName;
9
+ private environment;
10
+ private kafkaProducer;
11
+ private kafkaTopic;
12
+ private isKafkaReady;
13
+ private getConsoleFormat;
14
+ winston: CustomLogger;
15
+ constructor();
16
+ load: (config: any) => Promise<void>;
17
+ winstonLoader: ({ loadPath, loggerLevel }: {
18
+ loadPath: string;
19
+ loggerLevel: string;
20
+ }) => CustomLogger;
21
+ private logToKafka;
22
+ }
23
+ export {};
@@ -0,0 +1,126 @@
1
+ import winston, { format } from 'winston';
2
+ import 'winston-daily-rotate-file';
3
+ import path from 'path';
4
+ import { Kafka, Partitioners } from 'kafkajs';
5
+ import { LoggerLayerEnum } from '../../utils';
6
+ const customLevels = {
7
+ critical: LoggerLayerEnum.CRITICAL, // 0
8
+ error: LoggerLayerEnum.ERROR, // 1
9
+ info: LoggerLayerEnum.INFO, // 2
10
+ http: LoggerLayerEnum.HTTP, // 4
11
+ debug: LoggerLayerEnum.DEBUG, // 5
12
+ };
13
+ const customColors = {
14
+ critical: 'red',
15
+ error: 'magenta',
16
+ warn: 'yellow',
17
+ info: 'green',
18
+ http: 'cyan',
19
+ debug: 'blue'
20
+ };
21
+ export default class LoggerService {
22
+ serviceName = "";
23
+ environment = "";
24
+ kafkaProducer = null;
25
+ kafkaTopic = "";
26
+ isKafkaReady = false;
27
+ getConsoleFormat() {
28
+ return format.combine(format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), format.colorize({ all: true }), format.printf((info) => {
29
+ const msg = typeof info.message === 'object' ? JSON.stringify(info.message) : info.message;
30
+ return `${info.timestamp} [${this.serviceName}] ${info.level}: ${msg}`;
31
+ }));
32
+ }
33
+ winston = winston.createLogger({
34
+ level: 'debug',
35
+ levels: customLevels,
36
+ transports: [
37
+ new winston.transports.Console({
38
+ format: this.getConsoleFormat()
39
+ })
40
+ ]
41
+ });
42
+ constructor() {
43
+ winston.addColors(customColors);
44
+ }
45
+ load = async (config) => {
46
+ this.serviceName = config?.serviceName || "service";
47
+ this.environment = config?.env || "dev";
48
+ this.kafkaTopic = config?.kafkaTopic || "logs";
49
+ this.winstonLoader({
50
+ loadPath: config?.loadPath || "./logs",
51
+ loggerLevel: config?.loggerLevel || "debug"
52
+ });
53
+ const rawBrokers = config?.kafkaBrokers;
54
+ const brokers = rawBrokers ? String(rawBrokers).split(',').map((b) => b.trim()) : [];
55
+ if (brokers.length > 0) {
56
+ try {
57
+ const kafka = new Kafka({
58
+ clientId: this.serviceName,
59
+ brokers: brokers,
60
+ retry: { initialRetryTime: 100, retries: 3 }
61
+ });
62
+ this.kafkaProducer = kafka.producer({ createPartitioner: Partitioners.LegacyPartitioner });
63
+ await this.kafkaProducer.connect();
64
+ this.isKafkaReady = true;
65
+ this.winston.info('Logger connected to Kafka');
66
+ }
67
+ catch (err) {
68
+ console.error(`Kafka error: ${err.message}`);
69
+ }
70
+ }
71
+ };
72
+ winstonLoader = ({ loadPath, loggerLevel }) => {
73
+ const { combine, timestamp, json, errors } = format;
74
+ const jsonFileFormat = combine(timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), errors({ stack: true }), json());
75
+ const winstonLogger = winston.createLogger({
76
+ level: loggerLevel,
77
+ levels: customLevels,
78
+ transports: [
79
+ new winston.transports.Console({
80
+ format: this.getConsoleFormat()
81
+ }),
82
+ new winston.transports.DailyRotateFile({
83
+ filename: path.resolve(loadPath, 'error', '%DATE%_error.log'),
84
+ level: 'error',
85
+ format: jsonFileFormat,
86
+ maxSize: '2mb',
87
+ maxFiles: '7d'
88
+ }),
89
+ new winston.transports.DailyRotateFile({
90
+ filename: path.resolve(loadPath, 'critical', '%DATE%_critical.log'),
91
+ level: 'critical',
92
+ format: jsonFileFormat,
93
+ maxSize: '2mb',
94
+ maxFiles: '14d'
95
+ })
96
+ ]
97
+ });
98
+ winstonLogger.on('data', (info) => {
99
+ if (this.isKafkaReady) {
100
+ this.logToKafka(info);
101
+ }
102
+ });
103
+ this.winston = winstonLogger;
104
+ return winstonLogger;
105
+ };
106
+ async logToKafka(info) {
107
+ if (!this.kafkaProducer || !this.isKafkaReady)
108
+ return;
109
+ try {
110
+ await this.kafkaProducer.send({
111
+ topic: this.kafkaTopic,
112
+ messages: [{
113
+ value: JSON.stringify({
114
+ ...info,
115
+ service: this.serviceName,
116
+ env: this.environment,
117
+ timestamp: new Date().toISOString()
118
+ })
119
+ }]
120
+ });
121
+ }
122
+ catch (err) {
123
+ this.isKafkaReady = false;
124
+ }
125
+ }
126
+ }
@@ -0,0 +1,8 @@
1
+ export default class SystemService {
2
+ private static _tmp;
3
+ load: ({ tmp, }: {
4
+ tmp: any;
5
+ }) => Promise<void>;
6
+ private _systemLoader;
7
+ static get tmp(): any;
8
+ }
@@ -0,0 +1,14 @@
1
+ export default class SystemService {
2
+ static _tmp;
3
+ load = async ({ tmp, }) => {
4
+ SystemService._tmp = tmp;
5
+ await this._systemLoader({});
6
+ };
7
+ _systemLoader = async ({}) => {
8
+ //console.log(this._tmp)
9
+ };
10
+ // => getters
11
+ static get tmp() {
12
+ return SystemService._tmp;
13
+ }
14
+ }
@@ -0,0 +1,6 @@
1
+ declare const coreLoader: () => Promise<{
2
+ _?: undefined;
3
+ } | {
4
+ _: any;
5
+ }>;
6
+ export default coreLoader;
@@ -0,0 +1,63 @@
1
+ // => import dependencies
2
+ import path from 'path';
3
+ import { SystemService, ConfigsService, LoggerService, EventsService, LocalizationsService } from '../loader/index';
4
+ import { packageName, tmpFileDefaultName, tmpFileDefaultExt, findFileRecursively, TmpFileLoader, x, kafkaBrokers, systemLoggerLayer, } from '../utils/index';
5
+ //
6
+ let coreHasRun = false;
7
+ const coreLoader = async () => {
8
+ if (coreHasRun)
9
+ return {};
10
+ try {
11
+ const ownerTmpFilePath = findFileRecursively(".", tmpFileDefaultName, tmpFileDefaultExt);
12
+ if (!ownerTmpFilePath) {
13
+ throw new Error(`${tmpFileDefaultName} file not found`);
14
+ }
15
+ const tmpFileObject = new TmpFileLoader({ filePath: ownerTmpFilePath });
16
+ const r = tmpFileObject.getResolvedTmpFile();
17
+ const { configs } = r;
18
+ const rootFolderPath = configs.rootFolderPath;
19
+ const services = [
20
+ SystemService,
21
+ ConfigsService,
22
+ LoggerService,
23
+ EventsService,
24
+ LocalizationsService
25
+ ];
26
+ services.forEach(service => x.set({ service, reference: service }));
27
+ const system = x.get(SystemService);
28
+ const configService = x.get(ConfigsService);
29
+ const logger = x.get(LoggerService);
30
+ const events = x.get(EventsService);
31
+ const i18n = x.get(LocalizationsService);
32
+ await system.load({
33
+ tmp: { _: r }
34
+ });
35
+ await configService.load({
36
+ tmpFolderPath: rootFolderPath,
37
+ systemService: system,
38
+ envLoadPath: path.join(rootFolderPath, configs.loaders.configs.envLoadPath),
39
+ ...(configs.loaders.configs.globalEnvFileName && { globalEnvFileName: configs.loaders.configs.globalEnvFileName })
40
+ });
41
+ await logger.load({
42
+ loadPath: path.join(rootFolderPath, configs.loaders.loggers.loadPath),
43
+ loggerLevel: systemLoggerLayer ?? configs.loaders.loggers.logLevel,
44
+ serviceName: configs.service,
45
+ env: process.env.NODE_ENV,
46
+ kafkaBrokers: kafkaBrokers ?? "",
47
+ kafkaTopic: configs.loaders.loggers.topic
48
+ });
49
+ await events.load({});
50
+ await i18n.load({
51
+ loadPath: path.resolve(rootFolderPath, configs.loaders.localization.loadPath),
52
+ fallbackLang: configs.loaders.localization.fallbackLang,
53
+ preloadLang: configs.loaders.localization.preloadLangs
54
+ });
55
+ coreHasRun = true;
56
+ return { _: r };
57
+ }
58
+ catch (error) {
59
+ const errorMessage = error instanceof Error ? error.message : String(error);
60
+ console.error(`[${packageName} core failure]: ${errorMessage}`);
61
+ }
62
+ };
63
+ export default coreLoader;
@@ -0,0 +1,8 @@
1
+ export declare const packageName: string;
2
+ export declare const tmpFileDefaultMainFolderName: string;
3
+ export declare const tmpFileDefaultName: string;
4
+ export declare const tmpFileDefaultExt = ".yml";
5
+ export declare const defaultTmpFilePath: string;
6
+ export declare const defaultOwnerTmpFilePath: string;
7
+ export declare const systemLoggerLayer: string;
8
+ export declare const kafkaBrokers: string;
@@ -0,0 +1,10 @@
1
+ import path from 'path';
2
+ import { __dirname } from '../helpers/path';
3
+ export const packageName = 'x';
4
+ export const tmpFileDefaultMainFolderName = 'x';
5
+ export const tmpFileDefaultName = 'tmp';
6
+ export const tmpFileDefaultExt = '.yml';
7
+ export const defaultTmpFilePath = path.resolve(__dirname(import.meta.url), `../../${tmpFileDefaultMainFolderName}/${tmpFileDefaultName}.yml`);
8
+ export const defaultOwnerTmpFilePath = path.resolve(`./${tmpFileDefaultMainFolderName}/${tmpFileDefaultName}.yml`);
9
+ export const systemLoggerLayer = process.env.SYSTEM_LOGGER_LAYER;
10
+ export const kafkaBrokers = process.env.KAFKA_BROKERS;
@@ -0,0 +1,16 @@
1
+ import { PolarityTypeEnum } from "../../models";
2
+ export declare function dateZoneConverter({ polarity, date, zone, factor }: {
3
+ polarity: PolarityTypeEnum;
4
+ date: Date;
5
+ zone: number;
6
+ factor?: number;
7
+ }): string;
8
+ export declare function convertDate(date: string, splitCharacter?: string, replaceCharacter?: string): string[];
9
+ export declare function convertTime(time: string, splitCharacter?: string, replaceCharacter?: string): string[];
10
+ export declare function getDateAndTime({ getDate, getTime, dateCharacter, timeCharacter, separatorCharacter }: {
11
+ getDate: boolean;
12
+ getTime: boolean;
13
+ dateCharacter: string;
14
+ timeCharacter: string;
15
+ separatorCharacter: string;
16
+ }): string;
@@ -0,0 +1,48 @@
1
+ import { PolarityTypeEnum } from "../../models";
2
+ export function dateZoneConverter({ polarity, date, zone, factor = 1000 }) {
3
+ let convertedZoneTime = null;
4
+ if (polarity === PolarityTypeEnum.NEGATIVE) {
5
+ convertedZoneTime = date.getTime() - factor * zone;
6
+ }
7
+ else {
8
+ convertedZoneTime = date.getTime() + factor * zone;
9
+ }
10
+ return new Date(convertedZoneTime).toISOString();
11
+ }
12
+ export function convertDate(date, splitCharacter = '/', replaceCharacter = '-') {
13
+ const convertDate = date.split(splitCharacter).map((value, index) => index !== 2 ? replaceCharacter : value);
14
+ return convertDate;
15
+ }
16
+ export function convertTime(time, splitCharacter = ':', replaceCharacter = '-') {
17
+ const convertDate = time.split(splitCharacter).map((value, index) => index !== 2 ? replaceCharacter : value);
18
+ return convertDate;
19
+ }
20
+ export function getDateAndTime({ getDate = true, getTime = true, dateCharacter = '-', timeCharacter = ':', separatorCharacter = '&' }) {
21
+ const date = new Date();
22
+ let formattedDate = '';
23
+ if (!getDate && !getTime) {
24
+ throw new Error("Invalid options! Required one true value");
25
+ }
26
+ if (getDate) {
27
+ const day = date.getDate().toString().padStart(2, '0');
28
+ const month = (date.getMonth() + 1).toString().padStart(2, '0');
29
+ const year = date.getFullYear();
30
+ formattedDate = `${year}${dateCharacter}${month}${dateCharacter}${day}`;
31
+ }
32
+ if (getTime) {
33
+ const hours = date.getHours().toString().padStart(2, '0');
34
+ const minutes = date.getMinutes().toString().padStart(2, '0');
35
+ const seconds = date.getSeconds().toString().padStart(2, '0');
36
+ formattedDate = `${hours}${timeCharacter}${minutes}${timeCharacter}${seconds}`;
37
+ }
38
+ if (getDate && getTime) {
39
+ const day = date.getDate().toString().padStart(2, '0');
40
+ const month = (date.getMonth() + 1).toString().padStart(2, '0');
41
+ const year = date.getFullYear();
42
+ const hours = date.getHours().toString().padStart(2, '0');
43
+ const minutes = date.getMinutes().toString().padStart(2, '0');
44
+ const seconds = date.getSeconds().toString().padStart(2, '0');
45
+ formattedDate = `${year}${dateCharacter}${month}${dateCharacter}${day}${separatorCharacter}${hours}${timeCharacter}${minutes}${timeCharacter}${seconds}`;
46
+ }
47
+ return formattedDate;
48
+ }
@@ -0,0 +1,17 @@
1
+ declare function mongoFilter(start: any, end: any, objPath: string): any;
2
+ declare function filterUniqueOnce<T extends Record<string, any>>({ arr, key, uniqueOnceValues }: {
3
+ arr: T[];
4
+ key: keyof T;
5
+ uniqueOnceValues: (T[keyof T])[];
6
+ }): T[];
7
+ declare function filterSortByPropOrder<T extends Record<string, any>>({ arr, key, desiredOrder }: {
8
+ arr: T[];
9
+ key: keyof T;
10
+ desiredOrder: T[keyof T][];
11
+ }): T[];
12
+ declare function filterRemoveItemsByProps<T extends Record<string, any>>({ arr, key, valuesToRemove }: {
13
+ arr: T[];
14
+ key: keyof T;
15
+ valuesToRemove: (T[keyof T])[];
16
+ }): T[];
17
+ export { mongoFilter, filterUniqueOnce, filterSortByPropOrder, filterRemoveItemsByProps };
@@ -0,0 +1,44 @@
1
+ function mongoFilter(start, end, objPath) {
2
+ const filter = {};
3
+ if (!objPath) {
4
+ throw new Error('MongoFilter helper property is required.');
5
+ }
6
+ filter[objPath] = filter[objPath] || {};
7
+ if (start && end) {
8
+ filter[objPath].$gte = start;
9
+ filter[objPath].$lte = end;
10
+ }
11
+ else if (start) {
12
+ filter[objPath].$gte = start;
13
+ }
14
+ else if (end) {
15
+ filter[objPath].$lte = end;
16
+ }
17
+ return filter;
18
+ }
19
+ function filterUniqueOnce({ arr, key, uniqueOnceValues }) {
20
+ const seen = new Set();
21
+ return arr.filter(item => {
22
+ const val = item[key];
23
+ if (uniqueOnceValues.includes(val)) {
24
+ if (seen.has(val))
25
+ return false;
26
+ seen.add(val);
27
+ return true;
28
+ }
29
+ return true;
30
+ });
31
+ }
32
+ function filterSortByPropOrder({ arr, key, desiredOrder }) {
33
+ const orderMap = new Map();
34
+ desiredOrder.forEach((value, index) => orderMap.set(value, index));
35
+ return [...arr].sort((a, b) => {
36
+ const aIndex = orderMap.get(a[key]) ?? Infinity;
37
+ const bIndex = orderMap.get(b[key]) ?? Infinity;
38
+ return aIndex - bIndex;
39
+ });
40
+ }
41
+ function filterRemoveItemsByProps({ arr, key, valuesToRemove }) {
42
+ return arr.filter(item => !valuesToRemove.includes(item[key]));
43
+ }
44
+ export { mongoFilter, filterUniqueOnce, filterSortByPropOrder, filterRemoveItemsByProps };
@@ -0,0 +1,3 @@
1
+ export declare function generateSHA256Hash(secret: any, payload?: any): string;
2
+ export declare function generateNumberAndLetter(length?: number): string;
3
+ export declare function generateCodeChallenge(codeVerifier: string): string;
@@ -0,0 +1,22 @@
1
+ import crypto from 'crypto';
2
+ export function generateSHA256Hash(secret, payload) {
3
+ return crypto
4
+ .createHmac('sha256', secret)
5
+ .update(payload ? payload : '')
6
+ .digest('hex');
7
+ }
8
+ export function generateNumberAndLetter(length = 8) {
9
+ const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
10
+ const array = new Uint8Array(length);
11
+ crypto.getRandomValues(array);
12
+ return Array.from(array, byte => charset[byte % charset.length]).join('');
13
+ }
14
+ export function generateCodeChallenge(codeVerifier) {
15
+ return crypto
16
+ .createHash('sha256')
17
+ .update(codeVerifier)
18
+ .digest('base64')
19
+ .replace(/\+/g, '-')
20
+ .replace(/\//g, '_')
21
+ .replace(/=+$/, '');
22
+ }
@@ -0,0 +1,13 @@
1
+ export declare const serverIdNameGenerator: ({ prefix, payload, suffix }: {
2
+ prefix?: string;
3
+ payload: any;
4
+ suffix?: string;
5
+ }) => string;
6
+ export declare function generateRandomKey(options: {
7
+ length?: number;
8
+ format?: 'hex' | 'base64';
9
+ prefix?: string;
10
+ suffix?: string;
11
+ separator?: string;
12
+ }): string;
13
+ export declare function generateReferenceCode(length: number, prefix?: string, middle?: string, suffix?: string): string;
@@ -0,0 +1,24 @@
1
+ import crypto from 'crypto';
2
+ export const serverIdNameGenerator = ({ prefix, payload, suffix }) => {
3
+ return `${prefix}-${payload.toString()}-${suffix}`;
4
+ };
5
+ export function generateRandomKey(options) {
6
+ const { length = 48, format = 'hex', prefix = '', suffix = '', separator = '-', } = options;
7
+ const randomPart = crypto.randomBytes(length).toString(format);
8
+ const parts = [prefix, randomPart, suffix].filter(Boolean);
9
+ return parts.join(separator);
10
+ }
11
+ export function generateReferenceCode(length, prefix = "", middle = "", suffix = "") {
12
+ const totalLength = prefix.length + length + middle.length + suffix.length;
13
+ if (totalLength <= 0) {
14
+ throw new Error("The total length (including prefix, middle, and suffix) must be greater than 0.");
15
+ }
16
+ let referenceCode = "";
17
+ for (let i = 0; i < length; i++) {
18
+ const randomDigit = Math.floor(Math.random() * 10);
19
+ referenceCode += randomDigit.toString();
20
+ }
21
+ const middleIndex = Math.floor(referenceCode.length / 2);
22
+ const referenceWithMiddle = referenceCode.slice(0, middleIndex) + middle + referenceCode.slice(middleIndex);
23
+ return `${prefix}${referenceWithMiddle}${suffix}`;
24
+ }
@@ -0,0 +1,16 @@
1
+ export * from './tmp/index';
2
+ export * from './path/index';
3
+ export * from './is/index';
4
+ export * from './id/index';
5
+ export * from './validates/index';
6
+ export * from './ip/index';
7
+ export * from './hash/crypto';
8
+ export * from './string/index';
9
+ export * from './objects/index';
10
+ export * from './locales/index';
11
+ export * from './timer/index';
12
+ export * from './date/index';
13
+ export * from './math/index';
14
+ export * from './regex/checkSpecialRegexControl';
15
+ export * from './filters/index';
16
+ export * from './locales/index';
@@ -0,0 +1,16 @@
1
+ export * from './tmp/index';
2
+ export * from './path/index';
3
+ export * from './is/index';
4
+ export * from './id/index';
5
+ export * from './validates/index';
6
+ export * from './ip/index';
7
+ export * from './hash/crypto';
8
+ export * from './string/index';
9
+ export * from './objects/index';
10
+ export * from './locales/index';
11
+ export * from './timer/index';
12
+ export * from './date/index';
13
+ export * from './math/index';
14
+ export * from './regex/checkSpecialRegexControl';
15
+ export * from './filters/index';
16
+ export * from './locales/index';
@@ -0,0 +1 @@
1
+ export declare const getClientIp: (req: any) => any;