typeshi 1.0.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.
Files changed (55) hide show
  1. package/dist/config/dataLoader.d.ts +37 -0
  2. package/dist/config/dataLoader.js +171 -0
  3. package/dist/config/env.d.ts +23 -0
  4. package/dist/config/env.js +55 -0
  5. package/dist/config/index.d.ts +6 -0
  6. package/dist/config/index.js +22 -0
  7. package/dist/config/setupLog.d.ts +39 -0
  8. package/dist/config/setupLog.js +144 -0
  9. package/dist/index.d.ts +8 -0
  10. package/dist/index.js +44 -0
  11. package/dist/utils/argumentValidation.d.ts +192 -0
  12. package/dist/utils/argumentValidation.js +807 -0
  13. package/dist/utils/io/dateTime.d.ts +96 -0
  14. package/dist/utils/io/dateTime.js +202 -0
  15. package/dist/utils/io/index.d.ts +8 -0
  16. package/dist/utils/io/index.js +24 -0
  17. package/dist/utils/io/logging.d.ts +34 -0
  18. package/dist/utils/io/logging.js +260 -0
  19. package/dist/utils/io/reading.d.ts +265 -0
  20. package/dist/utils/io/reading.js +1245 -0
  21. package/dist/utils/io/types/Csv.d.ts +31 -0
  22. package/dist/utils/io/types/Csv.js +29 -0
  23. package/dist/utils/io/types/Io.TypeGuards.d.ts +31 -0
  24. package/dist/utils/io/types/Io.TypeGuards.js +75 -0
  25. package/dist/utils/io/types/Io.d.ts +49 -0
  26. package/dist/utils/io/types/Io.js +2 -0
  27. package/dist/utils/io/types/index.d.ts +6 -0
  28. package/dist/utils/io/types/index.js +22 -0
  29. package/dist/utils/io/writing.d.ts +67 -0
  30. package/dist/utils/io/writing.js +333 -0
  31. package/dist/utils/regex/cleaning.d.ts +65 -0
  32. package/dist/utils/regex/cleaning.js +162 -0
  33. package/dist/utils/regex/configureParameters.d.ts +23 -0
  34. package/dist/utils/regex/configureParameters.js +63 -0
  35. package/dist/utils/regex/email.d.ts +6 -0
  36. package/dist/utils/regex/email.js +37 -0
  37. package/dist/utils/regex/entity.d.ts +59 -0
  38. package/dist/utils/regex/entity.js +168 -0
  39. package/dist/utils/regex/index.d.ts +11 -0
  40. package/dist/utils/regex/index.js +27 -0
  41. package/dist/utils/regex/misc.d.ts +37 -0
  42. package/dist/utils/regex/misc.js +75 -0
  43. package/dist/utils/regex/phone.d.ts +83 -0
  44. package/dist/utils/regex/phone.js +132 -0
  45. package/dist/utils/regex/stringOperations.d.ts +45 -0
  46. package/dist/utils/regex/stringOperations.js +201 -0
  47. package/dist/utils/regex/types/StringOptions.d.ts +87 -0
  48. package/dist/utils/regex/types/StringOptions.js +25 -0
  49. package/dist/utils/regex/types/index.d.ts +5 -0
  50. package/dist/utils/regex/types/index.js +21 -0
  51. package/dist/utils/regex/types/typeGuards.d.ts +12 -0
  52. package/dist/utils/regex/types/typeGuards.js +15 -0
  53. package/dist/utils/typeValidation.d.ts +163 -0
  54. package/dist/utils/typeValidation.js +308 -0
  55. package/package.json +56 -0
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @enum {string} **`DataDomainEnum`** `string`
3
+ * @property **`REGEX`** = `'regex'`
4
+ */
5
+ export declare enum DataDomainEnum {
6
+ REGEX = "regex"
7
+ }
8
+ /**
9
+ * Initialize all data required by the application.
10
+ * This should be called once at the start of the application.
11
+ */
12
+ export declare function initializeData(...domains: DataDomainEnum[]): Promise<void>;
13
+ export declare function getRegexConstants(): RegexConstants;
14
+ /**
15
+ * `Sync` Get company keyword list
16
+ * @returns **`COMPANY_KEYWORD_LIST`** `string[]`
17
+ */
18
+ export declare function getCompanyKeywordList(): string[];
19
+ /**
20
+ * Get job title suffix list
21
+ * @returns **`JOB_TITLE_SUFFIX_LIST`** `string[]`
22
+ */
23
+ export declare function getJobTitleSuffixList(): string[];
24
+ export declare function isDataInitialized(): boolean;
25
+ /**
26
+ * @interface **`RegexConstants`**
27
+ * @property **`COMPANY_KEYWORD_LIST`** `string[]`
28
+ * @property **`JOB_TITLE_SUFFIX_LIST`** `string[]`
29
+ */
30
+ export interface RegexConstants {
31
+ COMPANY_KEYWORD_LIST: string[];
32
+ JOB_TITLE_SUFFIX_LIST: string[];
33
+ }
34
+ export type DataLoaderConfig = {
35
+ regexFile: string;
36
+ [key: string]: string;
37
+ };
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.DataDomainEnum = void 0;
40
+ exports.initializeData = initializeData;
41
+ exports.getRegexConstants = getRegexConstants;
42
+ exports.getCompanyKeywordList = getCompanyKeywordList;
43
+ exports.getJobTitleSuffixList = getJobTitleSuffixList;
44
+ exports.isDataInitialized = isDataInitialized;
45
+ /**
46
+ * @file src/config/dataLoader.ts
47
+ * @TODO change this file and env.ts to use initializeEnvironment() pattern
48
+ */
49
+ const env_1 = require("./env");
50
+ const setupLog_1 = require("./setupLog");
51
+ const reading_1 = require("../utils/io/reading");
52
+ const typeValidation_1 = require("../utils/typeValidation");
53
+ const node_path_1 = __importDefault(require("node:path"));
54
+ const validate = __importStar(require("../utils/argumentValidation"));
55
+ let dataInitialized = false;
56
+ let config = null;
57
+ /**
58
+ * @enum {string} **`DataDomainEnum`** `string`
59
+ * @property **`REGEX`** = `'regex'`
60
+ */
61
+ var DataDomainEnum;
62
+ (function (DataDomainEnum) {
63
+ DataDomainEnum["REGEX"] = "regex";
64
+ })(DataDomainEnum || (exports.DataDomainEnum = DataDomainEnum = {}));
65
+ /* ---------------------- LOAD REGEX CONFIG -------------------------- */
66
+ let regexConstants = null;
67
+ /* ------------------------- MAIN FUNCTION ----------------------------- */
68
+ const DEFAULT_DOMAINS_TO_LOAD = [
69
+ DataDomainEnum.REGEX,
70
+ ];
71
+ /**
72
+ * Initialize all data required by the application.
73
+ * This should be called once at the start of the application.
74
+ */
75
+ async function initializeData(...domains) {
76
+ const source = getSourceString(__filename, initializeData.name);
77
+ if (dataInitialized) {
78
+ setupLog_1.typeshiLogger.info(`${source} Data already initialized, skipping...`);
79
+ return;
80
+ }
81
+ if (!domains || domains.length === 0) {
82
+ domains.push(...DEFAULT_DOMAINS_TO_LOAD);
83
+ }
84
+ setupLog_1.typeshiSimpleLogger.info(`${source} Starting data initialization...`);
85
+ try {
86
+ const configPath = node_path_1.default.join(env_1.DATA_DIR, `typeshi.data.config.json`);
87
+ config = await loadConfig(configPath);
88
+ for (const d of domains) {
89
+ switch (d) {
90
+ case DataDomainEnum.REGEX:
91
+ regexConstants = await loadRegexConstants(node_path_1.default.join(env_1.DATA_DIR, DataDomainEnum.REGEX, config.regexFile));
92
+ break;
93
+ default:
94
+ setupLog_1.typeshiLogger.warn(`${source} Unrecognized data domain: '${d}'. Skipping...`);
95
+ continue;
96
+ }
97
+ }
98
+ dataInitialized = true;
99
+ setupLog_1.typeshiSimpleLogger.info(`${source} ✓ All data initialized successfully`);
100
+ }
101
+ catch (error) {
102
+ setupLog_1.typeshiLogger.error(`${source} ✗ Failed to initialize data:`, error);
103
+ (0, env_1.STOP_RUNNING)(1, `Data initialization failed`);
104
+ }
105
+ }
106
+ function getRegexConstants() {
107
+ if (!dataInitialized || !regexConstants) {
108
+ throw new Error('[dataLoader.getRegexConstants()] Regex constants not initialized. Call initializeData() first.');
109
+ }
110
+ return regexConstants;
111
+ }
112
+ /**
113
+ * `Sync` Get company keyword list
114
+ * @returns **`COMPANY_KEYWORD_LIST`** `string[]`
115
+ */
116
+ function getCompanyKeywordList() {
117
+ const constants = getRegexConstants();
118
+ return constants.COMPANY_KEYWORD_LIST;
119
+ }
120
+ /**
121
+ * Get job title suffix list
122
+ * @returns **`JOB_TITLE_SUFFIX_LIST`** `string[]`
123
+ */
124
+ function getJobTitleSuffixList() {
125
+ const constants = getRegexConstants();
126
+ return constants.JOB_TITLE_SUFFIX_LIST;
127
+ }
128
+ function isDataInitialized() {
129
+ return dataInitialized;
130
+ }
131
+ async function loadConfig(jsonPath) {
132
+ const source = getSourceString(__filename, loadConfig.name);
133
+ validate.existingFileArgument(source, '.json', { jsonPath });
134
+ let configData = (0, reading_1.readJsonFileAsObject)(jsonPath);
135
+ validate.objectArgument(source, { configData, isDataLoaderConfig });
136
+ return configData;
137
+ }
138
+ /**
139
+ * Load regex constants
140
+ */
141
+ async function loadRegexConstants(filePath) {
142
+ const source = getSourceString(__filename, loadRegexConstants.name);
143
+ setupLog_1.typeshiSimpleLogger.info(`${source} Loading regex constants...`);
144
+ validate.existingFileArgument(source, '.json', { filePath });
145
+ const REGEX_CONSTANTS = (0, reading_1.readJsonFileAsObject)(filePath);
146
+ if (!REGEX_CONSTANTS || !(0, typeValidation_1.hasKeys)(REGEX_CONSTANTS, ['COMPANY_KEYWORD_LIST', 'JOB_TITLE_SUFFIX_LIST'])) {
147
+ throw new Error(`${source} Invalid REGEX_CONSTANTS file at '${filePath}'. Expected json object to have 'COMPANY_KEYWORD_LIST' and 'JOB_TITLE_SUFFIX_LIST' keys.`);
148
+ }
149
+ const COMPANY_KEYWORD_LIST = REGEX_CONSTANTS.COMPANY_KEYWORD_LIST || [];
150
+ if (!(0, typeValidation_1.isNonEmptyArray)(COMPANY_KEYWORD_LIST)) {
151
+ throw new Error(`${source} Invalid COMPANY_KEYWORD_LIST in REGEX_CONSTANTS file at '${filePath}'`);
152
+ }
153
+ const JOB_TITLE_SUFFIX_LIST = REGEX_CONSTANTS.JOB_TITLE_SUFFIX_LIST || [];
154
+ if (!(0, typeValidation_1.isNonEmptyArray)(JOB_TITLE_SUFFIX_LIST)) {
155
+ throw new Error(`${source} Invalid JOB_TITLE_SUFFIX_LIST in REGEX_CONSTANTS file at '${filePath}'`);
156
+ }
157
+ setupLog_1.typeshiSimpleLogger.info(`${source} ✓ Regex constants loaded successfully`);
158
+ return {
159
+ COMPANY_KEYWORD_LIST,
160
+ JOB_TITLE_SUFFIX_LIST,
161
+ };
162
+ }
163
+ function isDataLoaderConfig(value) {
164
+ return ((0, typeValidation_1.isObject)(value)
165
+ && Object.values(value).every(v => (0, typeValidation_1.isNonEmptyString)(v)));
166
+ }
167
+ function getSourceString(fileName, func, funcInfo) {
168
+ fileName = node_path_1.default.basename(fileName).replace(/(?<=.+)\.[a-z0-9]{1,}$/i, '');
169
+ let funcName = typeof func === 'string' ? func : func.name;
170
+ return `[typeshi.${fileName}.${funcName}(${(0, typeValidation_1.isNonEmptyString)(funcInfo) ? ` ${funcInfo} ` : ''})]`;
171
+ }
@@ -0,0 +1,23 @@
1
+ /** = `process.cwd()` */
2
+ export declare const NODE_HOME_DIR: string;
3
+ /** = {@link NODE_HOME_DIR}`/src` = `process.cwd()/src`*/
4
+ export declare const SRC_DIR: string;
5
+ /** = `typeshi/src/data` */
6
+ export declare const DATA_DIR: string;
7
+ /**
8
+ * @description Exit the program/script for debugging purposes
9
+ * @param exitCode `number` - The exit code to use when exiting the program. Default is `0`. Use `1` for error.
10
+ * @param msg `any[]` `(optional)` - The message to log before exiting.
11
+ * @returns {void}
12
+ * */
13
+ export declare const STOP_RUNNING: (exitCode?: number, ...msg: any[]) => void;
14
+ /**
15
+ * @description `async` func to pause execution for specified amount of milliseconds
16
+ * - default message = `'> Pausing for ${ms} milliseconds.'`
17
+ * - `if` pass in `null` as second argument, no message will be logged
18
+ * @param ms `number` - milliseconds to pause execution for.
19
+ * @param msg `any[]` `(optional)` The message to log before pausing.
20
+ * @returns {Promise<void>}
21
+ * @example DELAY(1000) // pauses for 1 second
22
+ * */
23
+ export declare const DELAY: (ms: number, ...msg: any[]) => Promise<void>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DELAY = exports.STOP_RUNNING = exports.DATA_DIR = exports.SRC_DIR = exports.NODE_HOME_DIR = void 0;
7
+ /**
8
+ * @file src/config/env.ts
9
+ */
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ /** = `process.cwd()` */
12
+ exports.NODE_HOME_DIR = process.cwd();
13
+ /** = {@link NODE_HOME_DIR}`/src` = `process.cwd()/src`*/
14
+ exports.SRC_DIR = node_path_1.default.join(exports.NODE_HOME_DIR, 'node_modules', 'typeshi', 'dist');
15
+ /** = `typeshi/src/data` */
16
+ exports.DATA_DIR = node_path_1.default.join(exports.SRC_DIR, 'data');
17
+ /**
18
+ * @description Exit the program/script for debugging purposes
19
+ * @param exitCode `number` - The exit code to use when exiting the program. Default is `0`. Use `1` for error.
20
+ * @param msg `any[]` `(optional)` - The message to log before exiting.
21
+ * @returns {void}
22
+ * */
23
+ const STOP_RUNNING = (exitCode = 0, ...msg) => {
24
+ console.log(` > STOP_RUNNING() called with exitCode ${exitCode} at (${new Date().toLocaleString()}).`, ...(msg || []));
25
+ process.exit(exitCode);
26
+ };
27
+ exports.STOP_RUNNING = STOP_RUNNING;
28
+ /**
29
+ * @description `async` func to pause execution for specified amount of milliseconds
30
+ * - default message = `'> Pausing for ${ms} milliseconds.'`
31
+ * - `if` pass in `null` as second argument, no message will be logged
32
+ * @param ms `number` - milliseconds to pause execution for.
33
+ * @param msg `any[]` `(optional)` The message to log before pausing.
34
+ * @returns {Promise<void>}
35
+ * @example DELAY(1000) // pauses for 1 second
36
+ * */
37
+ const DELAY = async (ms, ...msg) => {
38
+ let pauseMsg = ` > Pausing for ${ms} milliseconds.`;
39
+ let msgArr = Array.isArray(msg) && msg.length > 0 ? msg : [pauseMsg];
40
+ if (msgArr[0] !== null) {
41
+ console.log(...msgArr);
42
+ }
43
+ return new Promise(resolve => setTimeout(resolve, ms));
44
+ };
45
+ exports.DELAY = DELAY;
46
+ // const envSummary: {
47
+ // pathLabel: string,
48
+ // pathValue: string,
49
+ // exists: boolean
50
+ // }[] = [];
51
+ // console.log(` > [@typeshi.env.ts] Loading env variables...`)
52
+ // for (let [pName, p] of Object.entries({NODE_HOME_DIR, SRC_DIR, DATA_DIR})) {
53
+ // envSummary.push({pathLabel: pName, pathValue: p, exists: fs.existsSync(p)})
54
+ // }
55
+ // console.table(envSummary);
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @file src/config/index.ts
3
+ */
4
+ export * from "./setupLog";
5
+ export * from "./env";
6
+ export * from "./dataLoader";
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ * @file src/config/index.ts
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ __exportStar(require("./setupLog"), exports);
21
+ __exportStar(require("./env"), exports);
22
+ __exportStar(require("./dataLoader"), exports);
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @file src/config/setupLog.ts
3
+ * @reference https://tslog.js.org/#/?id=pretty-templates-and-styles-color-settings
4
+ */
5
+ import { Logger, ILogObj, ILogObjMeta } from 'tslog';
6
+ /**
7
+ * `TAB = INDENT_LOG_LINE = '\n\t• '` = newLine + tab + bullet + space
8
+ * - log.debug(s1, INDENT_LOG_LINE + s2, INDENT_LOG_LINE + s3,...)
9
+ * */
10
+ export declare const INDENT_LOG_LINE: string;
11
+ /**
12
+ * `NL = NEW_LINE = '\n > '` = newLine + space + > + space
13
+ * */
14
+ export declare const NEW_LINE: string;
15
+ /**
16
+ * `type: "pretty"`
17
+ * @example
18
+ *
19
+ * mainLogger.attachTransport((logObj: ILogObj & ILogObjMeta) => {
20
+ * appendFileSync(
21
+ * DEFAULT_LOG_FILEPATH,
22
+ * JSON.stringify(formatLogObj(logObj)) + "\n",
23
+ * { encoding: "utf-8" }
24
+ * );
25
+ * });
26
+ *
27
+ * */
28
+ export declare const typeshiLogger: Logger<ILogObj>;
29
+ export declare const typeshiSimpleLogger: Logger<ILogObj>;
30
+ /**
31
+ * compress metadata into `logObj['-1']` then return stringified `logObj`
32
+ * @param logObj {@link ILogObj}
33
+ * @returns `string`
34
+ */
35
+ export declare function formatLogObj(logObj: ILogObj | (ILogObj & ILogObjMeta)): string;
36
+ /**suppress logs by putting them here (do not print to console) */
37
+ export declare const SUPPRESSED_LOGS: any[];
38
+ export declare const INFO_LOGS: any[];
39
+ export declare const DEBUG_LOGS: any[];
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEBUG_LOGS = exports.INFO_LOGS = exports.SUPPRESSED_LOGS = exports.typeshiSimpleLogger = exports.typeshiLogger = exports.NEW_LINE = exports.INDENT_LOG_LINE = void 0;
4
+ exports.formatLogObj = formatLogObj;
5
+ /**
6
+ * @file src/config/setupLog.ts
7
+ * @reference https://tslog.js.org/#/?id=pretty-templates-and-styles-color-settings
8
+ */
9
+ const tslog_1 = require("tslog");
10
+ /**
11
+ * `TAB = INDENT_LOG_LINE = '\n\t• '` = newLine + tab + bullet + space
12
+ * - log.debug(s1, INDENT_LOG_LINE + s2, INDENT_LOG_LINE + s3,...)
13
+ * */
14
+ exports.INDENT_LOG_LINE = '\n\t• ';
15
+ /**
16
+ * `NL = NEW_LINE = '\n > '` = newLine + space + > + space
17
+ * */
18
+ exports.NEW_LINE = '\n > ';
19
+ const dateTemplate = "{{yyyy}}-{{mm}}-{{dd}}";
20
+ const timeTemplate = "{{hh}}:{{MM}}:{{ss}}"; //.{{ms}}";
21
+ const timestampTemplate = `(${dateTemplate} ${timeTemplate})`;
22
+ /**not included for now */
23
+ const logNameTemplate = "[{{name}}]"; //"[{{nameWithDelimiterPrefix}}{{name}}{{nameWithDelimiterSuffix}}]";
24
+ /** e.g. [INFO] */
25
+ const logLevelTemplate = "[{{logLevelName}}]";
26
+ const fileInfoTemplate = "{{filePathWithLine}}";
27
+ //:{{fileColumn}} {{method}}";
28
+ // "{{fileName}}:{{fileLine}}";
29
+ /**
30
+ * use as value for {@link ISettingsParam.prettyLogTemplate}
31
+ * = {@link timestampTemplate} + {@link logNameTemplate} + {@link logLevelTemplate} + {@link fileInfoTemplate} + `\n\t{{logObjMeta}}`
32
+ * - {@link timestampTemplate} = `({{yyyy}}-{{mm}}-{{dd}} {{hh}}:{{MM}}:{{ss}}.{{ms}})`
33
+ * - {@link logNameTemplate} = `"[{{name}}]"`
34
+ * - {@link logLevelTemplate} = `{{logLevelName}}:`
35
+ * - {@link fileInfoTemplate} = `{{fileName}}:{{fileLine}}`
36
+ * */
37
+ const LOG_TEMPLATE = [
38
+ logLevelTemplate,
39
+ timestampTemplate,
40
+ // logNameTemplate,
41
+ fileInfoTemplate,
42
+ ].join(' ') + exports.NEW_LINE;
43
+ /** `"{{errorName}}: {{errorMessage}}{INDENT_LOG_LINE}{{errorStack}}"` */
44
+ const errorInfoTemplate = [
45
+ "{{errorName}}: {{errorMessage}}", "{{errorStack}}"
46
+ ].join(exports.INDENT_LOG_LINE);
47
+ /**
48
+ * use as value for {@link ISettingsParam.prettyErrorTemplate}
49
+ * @description template string for error message.
50
+ * */
51
+ const ERROR_TEMPLATE = `${errorInfoTemplate}`; //`${timestampTemplate} ${logNameTemplate} ${logLevelTemplate} ${fileInfoTemplate}\n${errorInfoTemplate}`;
52
+ /**
53
+ * use as value for {@link ISettingsParam.prettyErrorStackTemplate}.
54
+ * @description template string for error stack trace lines.
55
+ * */
56
+ const ERROR_STACK_TEMPLATE = `${fileInfoTemplate}:{{method}} {{stack}}`;
57
+ const PRETTY_LOG_STYLES = {
58
+ yyyy: "green",
59
+ mm: "green",
60
+ dd: "green",
61
+ hh: "greenBright",
62
+ MM: "greenBright",
63
+ ss: "greenBright",
64
+ ms: "greenBright",
65
+ dateIsoStr: ["redBright", "italic"], //dateIsoStr is = Shortcut for {{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}
66
+ logLevelName: {
67
+ "*": ["bold", "black", "bgWhiteBright", "dim"],
68
+ SILLY: ["bold", "white"],
69
+ TRACE: ["bold", "whiteBright"],
70
+ DEBUG: ["bold", "green"],
71
+ INFO: ["bold", "cyan"],
72
+ WARN: ["bold", "yellow"],
73
+ ERROR: ["bold", "red"],
74
+ FATAL: ["bold", "redBright"],
75
+ },
76
+ fileName: "cyan",
77
+ filePath: "blue",
78
+ fileLine: ["cyanBright", "bold"],
79
+ filePathWithLine: ["blueBright", "italic"],
80
+ name: "blue",
81
+ nameWithDelimiterPrefix: ["whiteBright", "bold", "bgBlackBright"],
82
+ nameWithDelimiterSuffix: ["whiteBright", "bold", "bgBlack"],
83
+ errorName: ["red", "bold"],
84
+ errorMessage: "redBright",
85
+ };
86
+ const MAIN_LOGGER_SETTINGS = {
87
+ type: "pretty",
88
+ name: "typeshi_main",
89
+ minLevel: 0,
90
+ prettyLogTemplate: LOG_TEMPLATE,
91
+ prettyErrorTemplate: ERROR_TEMPLATE,
92
+ prettyErrorStackTemplate: ERROR_STACK_TEMPLATE,
93
+ stylePrettyLogs: true,
94
+ prettyLogTimeZone: "local",
95
+ prettyLogStyles: PRETTY_LOG_STYLES,
96
+ };
97
+ /**
98
+ * `type: "pretty"`
99
+ * @example
100
+ *
101
+ * mainLogger.attachTransport((logObj: ILogObj & ILogObjMeta) => {
102
+ * appendFileSync(
103
+ * DEFAULT_LOG_FILEPATH,
104
+ * JSON.stringify(formatLogObj(logObj)) + "\n",
105
+ * { encoding: "utf-8" }
106
+ * );
107
+ * });
108
+ *
109
+ * */
110
+ exports.typeshiLogger = new tslog_1.Logger(MAIN_LOGGER_SETTINGS);
111
+ const SIMPLE_LOG_TEMPLATE = ` > `;
112
+ /** `type: "pretty"`, `template` = `" > {{logObjMeta}}"` */
113
+ const SIMPLE_LOGGER_SETTINGS = {
114
+ type: "pretty",
115
+ name: "typeshi_simple",
116
+ minLevel: 0,
117
+ prettyLogTemplate: SIMPLE_LOG_TEMPLATE,
118
+ prettyErrorTemplate: ERROR_TEMPLATE,
119
+ prettyErrorStackTemplate: ERROR_STACK_TEMPLATE,
120
+ stylePrettyLogs: true,
121
+ prettyLogTimeZone: "local",
122
+ prettyLogStyles: PRETTY_LOG_STYLES,
123
+ };
124
+ exports.typeshiSimpleLogger = new tslog_1.Logger(SIMPLE_LOGGER_SETTINGS);
125
+ /**
126
+ * compress metadata into `logObj['-1']` then return stringified `logObj`
127
+ * @param logObj {@link ILogObj}
128
+ * @returns `string`
129
+ */
130
+ function formatLogObj(logObj) {
131
+ const meta = logObj['_meta'];
132
+ const { logLevelName, date, path } = meta;
133
+ const timestamp = date ? date.toLocaleString() : '';
134
+ const fileInfo = `${path?.filePathWithLine}:${path?.fileColumn}`;
135
+ const methodInfo = `${path?.method ? path.method + '()' : ''}`;
136
+ delete logObj['_meta'];
137
+ logObj['meta0'] = `[${logLevelName}] (${timestamp})`;
138
+ logObj['meta1'] = `${fileInfo} @ ${methodInfo}`;
139
+ return JSON.stringify(logObj, null, 4) + "\n";
140
+ }
141
+ /**suppress logs by putting them here (do not print to console) */
142
+ exports.SUPPRESSED_LOGS = [];
143
+ exports.INFO_LOGS = [];
144
+ exports.DEBUG_LOGS = [];
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file src/index.ts
3
+ */
4
+ export * as re from "./utils/regex";
5
+ export * as io from "./utils/io";
6
+ export * as config from "./config";
7
+ export * as TypeValidation from "./utils/typeValidation";
8
+ export * as ArgumentValidation from "./utils/argumentValidation";
package/dist/index.js ADDED
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ /**
3
+ * @file src/index.ts
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.ArgumentValidation = exports.TypeValidation = exports.config = exports.io = exports.re = void 0;
40
+ exports.re = __importStar(require("./utils/regex"));
41
+ exports.io = __importStar(require("./utils/io"));
42
+ exports.config = __importStar(require("./config"));
43
+ exports.TypeValidation = __importStar(require("./utils/typeValidation"));
44
+ exports.ArgumentValidation = __importStar(require("./utils/argumentValidation"));