@cyberskill/shared 3.3.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/graphql-codegen/graphql-codegen.type.d.ts +1 -1
- package/dist/config/storybook/storybook.preview.js +8 -15
- package/dist/config/storybook/storybook.preview.js.map +1 -1
- package/dist/config/vitest/vitest.unit.js.map +1 -1
- package/dist/constant/index.js +2 -2
- package/dist/constant/response-status.d.ts +254 -0
- package/dist/constant/response-status.js +65 -1
- package/dist/constant/response-status.js.map +1 -1
- package/dist/node/cli/index.js +10 -9
- package/dist/node/cli/index.js.map +1 -1
- package/dist/node/command/command.util.js +32 -20
- package/dist/node/command/command.util.js.map +1 -1
- package/dist/node/express/express.type.d.ts +2 -0
- package/dist/node/express/express.util.js +11 -4
- package/dist/node/express/express.util.js.map +1 -1
- package/dist/node/log/log.type.d.ts +1 -5
- package/dist/node/log/log.type.js.map +1 -1
- package/dist/node/log/log.util.d.ts +2 -4
- package/dist/node/log/log.util.js +38 -40
- package/dist/node/log/log.util.js.map +1 -1
- package/dist/node/mongo/mongo.controller.d.ts +3 -1
- package/dist/node/mongo/mongo.controller.mongoose.js +75 -78
- package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
- package/dist/node/mongo/mongo.controller.native.d.ts +9 -1
- package/dist/node/mongo/mongo.controller.native.js +17 -14
- package/dist/node/mongo/mongo.controller.native.js.map +1 -1
- package/dist/node/mongo/mongo.controller.type.d.ts +76 -0
- package/dist/node/mongo/mongo.dynamic-populate.d.ts +2 -1
- package/dist/node/mongo/mongo.dynamic-populate.js +12 -12
- package/dist/node/mongo/mongo.dynamic-populate.js.map +1 -1
- package/dist/node/mongo/mongo.internal-types.d.ts +81 -0
- package/dist/node/mongo/mongo.internal-types.js +40 -0
- package/dist/node/mongo/mongo.internal-types.js.map +1 -0
- package/dist/node/mongo/mongo.populate.d.ts +2 -1
- package/dist/node/mongo/mongo.populate.js +130 -171
- package/dist/node/mongo/mongo.populate.js.map +1 -1
- package/dist/node/mongo/mongo.type.d.ts +1 -1
- package/dist/node/mongo/mongo.type.js.map +1 -1
- package/dist/node/mongo/mongo.util.d.ts +8 -8
- package/dist/node/mongo/mongo.util.js +34 -32
- package/dist/node/mongo/mongo.util.js.map +1 -1
- package/dist/node/path/path.constant.d.ts +3 -6
- package/dist/node/path/path.constant.js +31 -25
- package/dist/node/path/path.constant.js.map +1 -1
- package/dist/node/storage/index.js +2 -2
- package/dist/node/storage/storage.util.d.ts +6 -0
- package/dist/node/storage/storage.util.js +4 -1
- package/dist/node/storage/storage.util.js.map +1 -1
- package/dist/react/log/log.type.d.ts +1 -5
- package/dist/react/log/log.util.d.ts +2 -5
- package/dist/react/log/log.util.js +21 -25
- package/dist/react/log/log.util.js.map +1 -1
- package/dist/util/common/common.util.d.ts +8 -0
- package/dist/util/common/common.util.js +4 -1
- package/dist/util/common/common.util.js.map +1 -1
- package/dist/util/common/index.js +2 -2
- package/dist/util/index.d.ts +1 -0
- package/dist/util/index.js +7 -6
- package/dist/util/log/index.d.ts +2 -0
- package/dist/util/log/index.js +2 -0
- package/dist/util/log/log.type.d.ts +8 -0
- package/dist/util/log/log.util.d.ts +17 -0
- package/dist/util/log/log.util.js +14 -0
- package/dist/util/log/log.util.js.map +1 -0
- package/package.json +83 -40
|
@@ -8,7 +8,7 @@ import u from "node:process";
|
|
|
8
8
|
import { exec as d, execFile as f } from "node:child_process";
|
|
9
9
|
import * as p from "node:util";
|
|
10
10
|
//#region src/node/command/command.util.ts
|
|
11
|
-
var m = p.promisify(d), h = p.promisify(f), g = /[|&;<>`$(){}[\]!#~*?]/, _ = /^\s*(\d+):(\d+)\s+(error|warning)\s+(
|
|
11
|
+
var m = p.promisify(d), h = p.promisify(f), g = /[|&;<>`$(){}[\]!#~*?]/, _ = /^\s*(\d+):(\d+)\s+(error|warning)\s+(\S+(?:\s+\S+)*)\s+(\S+)$/, v = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+TS\d+:\s+(\S.+)$/, y = /^✖\s+(\S+(?:\s+\S+)*)\s+\[([^\]]*)\]$/, b = /\s+/;
|
|
12
12
|
async function x() {
|
|
13
13
|
let e = await i();
|
|
14
14
|
return e.success ? e.result.name : Date.now().toString();
|
|
@@ -47,24 +47,32 @@ async function T(e) {
|
|
|
47
47
|
e.split("\n").forEach((e) => {
|
|
48
48
|
if (e.startsWith("/")) a = e.trim();
|
|
49
49
|
else {
|
|
50
|
-
let r = o.exec(e)
|
|
51
|
-
r
|
|
50
|
+
let r = o.exec(e);
|
|
51
|
+
if (r && a) n.push({
|
|
52
52
|
file: a,
|
|
53
53
|
position: `${r[1]}:${r[2]}`,
|
|
54
54
|
type: r[3] === t.Error ? t.Error : t.Warning,
|
|
55
55
|
message: r?.[4]?.trim() ?? "",
|
|
56
56
|
rule: r?.[5]?.trim() ?? ""
|
|
57
|
-
})
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
57
|
+
});
|
|
58
|
+
else {
|
|
59
|
+
let r = s.exec(e);
|
|
60
|
+
if (r) n.push({
|
|
61
|
+
file: r?.[1] ?? "",
|
|
62
|
+
position: `${r[2]}:${r[3]}`,
|
|
63
|
+
type: r[4] === t.Error ? t.Error : t.Warning,
|
|
64
|
+
message: r?.[5]?.trim() ?? ""
|
|
65
|
+
});
|
|
66
|
+
else {
|
|
67
|
+
let r = c.exec(e);
|
|
68
|
+
r ? n.push({
|
|
69
|
+
file: "commitlint",
|
|
70
|
+
type: t.Error,
|
|
71
|
+
message: r?.[1]?.trim() ?? "",
|
|
72
|
+
rule: r?.[2]?.trim() ?? ""
|
|
73
|
+
}) : i.push(e.trim());
|
|
74
|
+
}
|
|
75
|
+
}
|
|
68
76
|
}
|
|
69
77
|
}), n.length && await S(n), i.length && (r.warn("Unmatched lines:"), i.forEach((e) => r.info(` ${e}`)));
|
|
70
78
|
}
|
|
@@ -87,10 +95,10 @@ async function E(e) {
|
|
|
87
95
|
}
|
|
88
96
|
}
|
|
89
97
|
async function D(e, t = E, n = {}) {
|
|
90
|
-
let i = new AbortController()
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
98
|
+
let i = new AbortController(), a = () => {
|
|
99
|
+
r.warn("Process interrupted. Terminating..."), i.abort(), u.exit(130);
|
|
100
|
+
};
|
|
101
|
+
u.once("SIGINT", a);
|
|
94
102
|
try {
|
|
95
103
|
if (typeof e == "string") {
|
|
96
104
|
let r = {
|
|
@@ -108,6 +116,8 @@ async function D(e, t = E, n = {}) {
|
|
|
108
116
|
} catch (e) {
|
|
109
117
|
let { stdout: n, stderr: i, message: a } = e;
|
|
110
118
|
throw await Promise.all([n, i].map((e) => e && t(e))), !i && !n && r.error(`Command failed: ${a}`), e;
|
|
119
|
+
} finally {
|
|
120
|
+
u.removeListener("SIGINT", a);
|
|
111
121
|
}
|
|
112
122
|
}
|
|
113
123
|
function O(e) {
|
|
@@ -136,10 +146,12 @@ async function M(t, i, a = {}) {
|
|
|
136
146
|
r.start(`${t}`), e().DEBUG ? r.info(`→ ${i}`) : o = setInterval(() => {
|
|
137
147
|
let e = Math.floor((Date.now() - n) / 1e3);
|
|
138
148
|
e > 0 && u.stdout.write(`\r⏳ ${t}... ${e}s`);
|
|
139
|
-
},
|
|
149
|
+
}, 1e3), await D(i, E, a), r.success(`${t} done.`);
|
|
140
150
|
} catch (e) {
|
|
141
|
-
if (
|
|
151
|
+
if (a.throwOnError) throw e;
|
|
142
152
|
n(e);
|
|
153
|
+
} finally {
|
|
154
|
+
o && (clearInterval(o), u.stdout.write("\r\x1B[K"));
|
|
143
155
|
}
|
|
144
156
|
}
|
|
145
157
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"command.util.js","names":[],"sources":["../../../src/node/command/command.util.ts"],"sourcesContent":["import { exec, execFile } from 'node:child_process';\nimport process from 'node:process';\nimport * as util from 'node:util';\n\nimport { getEnv } from '#config/env/index.js';\n\nimport type { I_IssueEntry } from '../log/index.js';\nimport type { I_CommandContext, I_EslintError, T_Command, T_CommandMapInput } from './command.type.js';\n\nimport { catchError, E_IssueType, log } from '../log/index.js';\nimport { getPackage } from '../package/index.js';\nimport { CYBERSKILL_CLI, CYBERSKILL_CLI_PATH, CYBERSKILL_PACKAGE_NAME, PNPM_EXEC_CLI, TSX_CLI } from '../path/index.js';\nimport { storage } from '../storage/index.js';\n\nconst execPromise = util.promisify(exec);\nconst execFilePromise = util.promisify(execFile);\nconst SHELL_METACHARACTERS = /[|&;<>`$(){}[\\]!#~*?]/;\n// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/no-misleading-capturing-group\nconst RE_ESLINT_ERROR = /^\\s*(\\d+):(\\d+)\\s+(error|warning)\\s+(.+)\\s+(\\S+)$/;\nconst RE_TS_ERROR = /^(.+?)\\((\\d+),(\\d+)\\):\\s+(error|warning)\\s+TS\\d+:\\s+(\\S.+)$/;\n// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/no-misleading-capturing-group\nconst RE_COMMITLINT_ERROR = /^✖\\s+(.+)\\s+\\[([^\\]]*)\\]$/;\nconst RE_WHITESPACE = /\\s+/;\n\n/**\n * Retrieves the package name for the current project.\n * This function attempts to get the package name from the current project's package.json.\n * If the package information cannot be retrieved, it returns a timestamp as a fallback.\n *\n * @returns A promise that resolves to the package name or a timestamp string.\n */\nasync function getPackageName() {\n const pkg = await getPackage();\n\n if (!pkg.success) {\n return Date.now().toString();\n }\n\n return pkg.result.name;\n}\n\n/**\n * Saves a list of error entries to persistent storage.\n * This function stores error information with the package name as the key,\n * and provides a log link for manual inspection of the stored errors.\n *\n * @param errorList - An array of error entries to be stored.\n * @returns A promise that resolves when the storage operation is complete.\n */\nasync function saveErrorListToStorage(errorList: I_IssueEntry[]): Promise<void> {\n if (errorList.length === 0) {\n return;\n }\n\n const packageName = await getPackageName();\n\n try {\n const existingErrors = await getStoredErrorLists();\n const mergedErrors = [...existingErrors, ...errorList];\n\n await storage.set(packageName, mergedErrors);\n\n setTimeout(async () => {\n const logPath = await storage.getLogLink(packageName);\n\n if (logPath) {\n log.info(`📂 Open the error list manually: ${logPath}`);\n }\n }, 0);\n }\n catch (error) {\n catchError(error);\n }\n}\n\n/**\n * Retrieves all stored error lists from persistent storage.\n * This function fetches error entries that were previously saved using the package name as the key.\n *\n * @returns A promise that resolves to an array of error entries, or an empty array if none are found.\n */\nexport async function getStoredErrorLists(): Promise<I_IssueEntry[]> {\n try {\n const packageName = await getPackageName();\n const allErrors = await storage.get<I_IssueEntry[]>(packageName);\n\n return allErrors ?? [];\n }\n catch (error) {\n return catchError<I_IssueEntry[]>(error, {\n returnValue: [],\n });\n }\n}\n\n/**\n * Clears all stored error lists from persistent storage.\n * This function removes all error entries associated with the current package name.\n *\n * @returns A promise that resolves when the clearing operation is complete.\n */\nexport async function clearAllErrorLists(): Promise<void> {\n try {\n const packageName = await getPackageName();\n await storage.remove(packageName);\n }\n catch (error) {\n catchError(error);\n }\n}\n\n/**\n * Parses text-based error output and converts it to structured error entries.\n * This function processes command output that contains error information in text format,\n * extracting file paths, line numbers, error types, messages, and rule violations.\n * It handles multiple error formats including ESLint, TypeScript, and commitlint errors.\n *\n * @param output - The raw text output from a command execution containing error information.\n */\nasync function parseTextErrors(output: string): Promise<void> {\n const errorList: I_IssueEntry[] = [];\n const unmatchedLines: string[] = [];\n let lastFilePath = '';\n const eslintErrorDetailsRegex = RE_ESLINT_ERROR;\n const tsRegex = RE_TS_ERROR;\n const commitlintRegex = RE_COMMITLINT_ERROR;\n\n output.split('\\n').forEach((line) => {\n if (line.startsWith('/')) {\n lastFilePath = line.trim();\n }\n else {\n const eslintMatch = eslintErrorDetailsRegex.exec(line) || [];\n const tsMatch = tsRegex.exec(line) || [];\n const commitlintMatch = commitlintRegex.exec(line) || [];\n\n if (eslintMatch.length && lastFilePath) {\n errorList.push({\n file: lastFilePath,\n position: `${eslintMatch[1]}:${eslintMatch[2]}`,\n type: eslintMatch[3] === E_IssueType.Error ? E_IssueType.Error : E_IssueType.Warning,\n message: eslintMatch?.[4]?.trim() ?? '',\n rule: eslintMatch?.[5]?.trim() ?? '',\n });\n }\n else if (tsMatch.length) {\n errorList.push({\n file: tsMatch?.[1] ?? '',\n position: `${tsMatch[2]}:${tsMatch[3]}`,\n type: tsMatch[4] === E_IssueType.Error ? E_IssueType.Error : E_IssueType.Warning,\n message: tsMatch?.[5]?.trim() ?? '',\n });\n }\n else if (commitlintMatch.length) {\n errorList.push({\n file: 'commitlint',\n type: E_IssueType.Error,\n message: commitlintMatch?.[1]?.trim() ?? '',\n rule: commitlintMatch?.[2]?.trim() ?? '',\n });\n }\n else {\n unmatchedLines.push(line.trim());\n }\n }\n });\n\n if (errorList.length) {\n await saveErrorListToStorage(errorList);\n }\n\n if (unmatchedLines.length) {\n log.warn(`Unmatched lines:`);\n unmatchedLines.forEach(line => log.info(` ${line}`));\n }\n}\n\n/**\n * Parses command output that contains structured error information.\n * This function attempts to parse JSON-formatted error output (typically from ESLint)\n * and converts it to structured error entries. If JSON parsing fails, it falls back\n * to text-based parsing.\n *\n * @param output - The command output to parse, expected to be JSON-formatted error data.\n */\nasync function parseCommandOutput(output: string): Promise<void> {\n try {\n const results: I_EslintError[] = JSON.parse(output);\n const errorList: I_IssueEntry[] = [];\n\n results.forEach(({ filePath, messages }) => {\n messages.forEach(({ severity, line, column, ruleId, message }) => {\n errorList.push({\n type: severity === 2 ? E_IssueType.Error : E_IssueType.Warning,\n file: filePath,\n position: `${line}:${column}`,\n rule: ruleId,\n message,\n });\n });\n });\n\n if (errorList.length) {\n await saveErrorListToStorage(errorList);\n }\n }\n catch {\n await parseTextErrors(output);\n }\n}\n\n/**\n * Executes a command and processes its output for errors.\n * This function runs a command with proper signal handling for graceful termination,\n * processes both stdout and stderr for error information, and handles command failures.\n *\n * @param command - The command string to execute, or undefined if no command should be run.\n * @param parser - The function to use for parsing command output (defaults to parseCommandOutput).\n * @returns A promise that resolves when the command execution is complete.\n */\nasync function executeCommand(command: string | void, parser = parseCommandOutput, options: { timeout?: number } = {}): Promise<void> {\n const controller = new AbortController();\n\n process.on('SIGINT', () => {\n log.warn('Process interrupted. Terminating...');\n controller.abort();\n process.exit();\n });\n\n try {\n if (typeof command === 'string') {\n const execOptions = {\n maxBuffer: 10 * 1024 * 1024,\n signal: controller.signal,\n timeout: options.timeout,\n };\n\n let result: { stdout: string; stderr: string };\n\n if (SHELL_METACHARACTERS.test(command)) {\n result = await execPromise(command, execOptions);\n }\n else {\n const parts = command.split(RE_WHITESPACE).filter(Boolean);\n result = await execFilePromise(parts[0]!, parts.slice(1), execOptions);\n }\n\n await Promise.all([result.stdout, result.stderr].map(output => output && parser(output)));\n }\n }\n catch (error) {\n const { stdout, stderr, message } = error as {\n stdout?: string;\n stderr?: string;\n message: string;\n };\n\n await Promise.all([stdout, stderr].map(output => output && parser(output)));\n\n if (!stderr && !stdout) {\n log.error(`Command failed: ${message}`);\n }\n\n throw error;\n }\n}\n\n/**\n * Creates a raw command object that bypasses CLI formatting.\n * This function wraps a command string in an object that indicates it should be executed\n * as-is without any additional CLI formatting or path resolution.\n *\n * @param cmd - The raw command string to be executed directly.\n * @returns An object containing the raw command with a flag indicating it should not be formatted.\n */\nexport function rawCommand(cmd: string) {\n return { raw: true, cmd };\n}\n\n/**\n * Formats a command for CLI execution based on the current project context.\n * This function determines whether to use the current project's CLI path or the global CLI,\n * and formats the command accordingly with the appropriate executable paths.\n *\n * @param command - The command string to format.\n * @param context - Optional context information about the current project.\n * @returns The formatted command string ready for execution.\n */\nfunction formatCLI(command: string, context?: I_CommandContext) {\n if (context?.isCurrentProject) {\n return `${PNPM_EXEC_CLI} ${TSX_CLI} ${CYBERSKILL_CLI_PATH} ${command}`;\n }\n\n return `${PNPM_EXEC_CLI} ${CYBERSKILL_CLI} ${command}`;\n}\n\n/**\n * Formats a command based on its type and context.\n * This function handles different command types:\n * - Function commands: Executes the function with context and formats the result\n * - Raw commands: Returns the command as-is without formatting\n * - String commands: Formats them as CLI commands\n *\n * @param command - The command to format, which can be a string, function, or raw command object.\n * @param context - Optional context information for command execution.\n * @returns The formatted command string ready for execution.\n */\nexport function formatCommand(command: T_Command, context?: I_CommandContext) {\n if (typeof command === 'function') {\n return formatCLI(command(context), context);\n }\n\n if (typeof command === 'object' && command?.raw === true) {\n return command.cmd;\n }\n\n if (typeof command === 'string') {\n return formatCLI(command, context);\n }\n\n return command;\n}\n\n/**\n * Resolves a map of commands by formatting them based on the current project context.\n * This function takes a command map (either static or dynamic) and formats all commands\n * using the appropriate CLI paths based on whether the current project is the Cyberskill package.\n *\n * @param input - The command map to resolve, which can be static or a function that returns a map.\n * @returns A promise that resolves to an object with formatted command strings, or undefined if package info cannot be retrieved.\n */\nexport async function resolveCommands(input: T_CommandMapInput) {\n const packageData = await getPackage({ name: CYBERSKILL_PACKAGE_NAME });\n\n if (packageData.success) {\n const ctx: I_CommandContext = { isCurrentProject: packageData.result.isCurrentProject };\n const commands = typeof input === 'function' ? input(ctx) : input;\n\n return Object.fromEntries(\n Object.entries(commands).map(([key, cmd]) => [key, formatCommand(cmd, ctx)]),\n );\n }\n}\n\n/**\n * Executes a command with proper logging and error handling.\n * This function provides a standardized way to run commands with:\n * - Progress logging with start and success messages\n * - Debug logging of the actual command when DEBUG mode is enabled\n * - Error handling and reporting\n *\n * @param label - A human-readable label describing what the command does.\n * @param command - The command string to execute, or undefined if no command should be run.\n * @returns A promise that resolves when the command execution is complete.\n */\nexport async function runCommand(label: string, command: string | void, options: { timeout?: number; throwOnError?: boolean } = {}) {\n let timer: NodeJS.Timeout | undefined;\n\n try {\n const startTime = Date.now();\n log.start(`${label}`);\n\n if (getEnv().DEBUG) {\n log.info(`→ ${command}`);\n }\n else {\n timer = setInterval(() => {\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n\n if (elapsed > 0) {\n process.stdout.write(`\\r⏳ ${label}... ${elapsed}s`);\n }\n }, 100);\n }\n\n await executeCommand(command, parseCommandOutput, options);\n\n if (timer) {\n clearInterval(timer);\n process.stdout.write(`\\r\\x1B[K`);\n }\n\n log.success(`${label} done.`);\n }\n catch (error) {\n if (timer) {\n clearInterval(timer);\n process.stdout.write(`\\r\\x1B[K`);\n }\n\n if (options.throwOnError) {\n throw error;\n }\n catchError(error);\n }\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAM,IAAc,EAAK,UAAU,EAAK,EAClC,IAAkB,EAAK,UAAU,EAAS,EAC1C,IAAuB,yBAEvB,IAAkB,qDAClB,IAAc,+DAEd,IAAsB,6BACtB,IAAgB;AAStB,eAAe,IAAiB;CAC5B,IAAM,IAAM,MAAM,GAAY;AAM9B,QAJK,EAAI,UAIF,EAAI,OAAO,OAHP,KAAK,KAAK,CAAC,UAAU;;AAcpC,eAAe,EAAuB,GAA0C;AAC5E,KAAI,EAAU,WAAW,EACrB;CAGJ,IAAM,IAAc,MAAM,GAAgB;AAE1C,KAAI;EAEA,IAAM,IAAe,CAAC,GADC,MAAM,GAAqB,EACT,GAAG,EAAU;AAItD,EAFA,MAAM,EAAQ,IAAI,GAAa,EAAa,EAE5C,WAAW,YAAY;GACnB,IAAM,IAAU,MAAM,EAAQ,WAAW,EAAY;AAErD,GAAI,KACA,EAAI,KAAK,oCAAoC,IAAU;KAE5D,EAAE;UAEF,GAAO;AACV,IAAW,EAAM;;;AAUzB,eAAsB,IAA+C;AACjE,KAAI;EACA,IAAM,IAAc,MAAM,GAAgB;AAG1C,SAFkB,MAAM,EAAQ,IAAoB,EAAY,IAE5C,EAAE;UAEnB,GAAO;AACV,SAAO,EAA2B,GAAO,EACrC,aAAa,EAAE,EAClB,CAAC;;;AAUV,eAAsB,IAAoC;AACtD,KAAI;EACA,IAAM,IAAc,MAAM,GAAgB;AAC1C,QAAM,EAAQ,OAAO,EAAY;UAE9B,GAAO;AACV,IAAW,EAAM;;;AAYzB,eAAe,EAAgB,GAA+B;CAC1D,IAAM,IAA4B,EAAE,EAC9B,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
|
|
1
|
+
{"version":3,"file":"command.util.js","names":[],"sources":["../../../src/node/command/command.util.ts"],"sourcesContent":["import { exec, execFile } from 'node:child_process';\nimport process from 'node:process';\nimport * as util from 'node:util';\n\nimport { getEnv } from '#config/env/index.js';\n\nimport type { I_IssueEntry } from '../log/index.js';\nimport type { I_CommandContext, I_EslintError, T_Command, T_CommandMapInput } from './command.type.js';\n\nimport { catchError, E_IssueType, log } from '../log/index.js';\nimport { getPackage } from '../package/index.js';\nimport { CYBERSKILL_CLI, CYBERSKILL_CLI_PATH, CYBERSKILL_PACKAGE_NAME, PNPM_EXEC_CLI, TSX_CLI } from '../path/index.js';\nimport { storage } from '../storage/index.js';\n\nconst execPromise = util.promisify(exec);\nconst execFilePromise = util.promisify(execFile);\nconst SHELL_METACHARACTERS = /[|&;<>`$(){}[\\]!#~*?]/;\nconst RE_ESLINT_ERROR = /^\\s*(\\d+):(\\d+)\\s+(error|warning)\\s+(\\S+(?:\\s+\\S+)*)\\s+(\\S+)$/;\nconst RE_TS_ERROR = /^(.+?)\\((\\d+),(\\d+)\\):\\s+(error|warning)\\s+TS\\d+:\\s+(\\S.+)$/;\nconst RE_COMMITLINT_ERROR = /^✖\\s+(\\S+(?:\\s+\\S+)*)\\s+\\[([^\\]]*)\\]$/;\nconst RE_WHITESPACE = /\\s+/;\n\n/**\n * Retrieves the package name for the current project.\n * This function attempts to get the package name from the current project's package.json.\n * If the package information cannot be retrieved, it returns a timestamp as a fallback.\n *\n * @returns A promise that resolves to the package name or a timestamp string.\n */\nasync function getPackageName() {\n const pkg = await getPackage();\n\n if (!pkg.success) {\n return Date.now().toString();\n }\n\n return pkg.result.name;\n}\n\n/**\n * Saves a list of error entries to persistent storage.\n * This function stores error information with the package name as the key,\n * and provides a log link for manual inspection of the stored errors.\n *\n * @param errorList - An array of error entries to be stored.\n * @returns A promise that resolves when the storage operation is complete.\n */\nasync function saveErrorListToStorage(errorList: I_IssueEntry[]): Promise<void> {\n if (errorList.length === 0) {\n return;\n }\n\n const packageName = await getPackageName();\n\n try {\n const existingErrors = await getStoredErrorLists();\n const mergedErrors = [...existingErrors, ...errorList];\n\n await storage.set(packageName, mergedErrors);\n\n setTimeout(async () => {\n const logPath = await storage.getLogLink(packageName);\n\n if (logPath) {\n log.info(`📂 Open the error list manually: ${logPath}`);\n }\n }, 0);\n }\n catch (error) {\n catchError(error);\n }\n}\n\n/**\n * Retrieves all stored error lists from persistent storage.\n * This function fetches error entries that were previously saved using the package name as the key.\n *\n * @returns A promise that resolves to an array of error entries, or an empty array if none are found.\n */\nexport async function getStoredErrorLists(): Promise<I_IssueEntry[]> {\n try {\n const packageName = await getPackageName();\n const allErrors = await storage.get<I_IssueEntry[]>(packageName);\n\n return allErrors ?? [];\n }\n catch (error) {\n return catchError<I_IssueEntry[]>(error, {\n returnValue: [],\n });\n }\n}\n\n/**\n * Clears all stored error lists from persistent storage.\n * This function removes all error entries associated with the current package name.\n *\n * @returns A promise that resolves when the clearing operation is complete.\n */\nexport async function clearAllErrorLists(): Promise<void> {\n try {\n const packageName = await getPackageName();\n await storage.remove(packageName);\n }\n catch (error) {\n catchError(error);\n }\n}\n\n/**\n * Parses text-based error output and converts it to structured error entries.\n * This function processes command output that contains error information in text format,\n * extracting file paths, line numbers, error types, messages, and rule violations.\n * It handles multiple error formats including ESLint, TypeScript, and commitlint errors.\n *\n * @param output - The raw text output from a command execution containing error information.\n */\nasync function parseTextErrors(output: string): Promise<void> {\n const errorList: I_IssueEntry[] = [];\n const unmatchedLines: string[] = [];\n let lastFilePath = '';\n const eslintErrorDetailsRegex = RE_ESLINT_ERROR;\n const tsRegex = RE_TS_ERROR;\n const commitlintRegex = RE_COMMITLINT_ERROR;\n\n output.split('\\n').forEach((line) => {\n if (line.startsWith('/')) {\n lastFilePath = line.trim();\n }\n else {\n const eslintMatch = eslintErrorDetailsRegex.exec(line);\n\n if (eslintMatch && lastFilePath) {\n errorList.push({\n file: lastFilePath,\n position: `${eslintMatch[1]}:${eslintMatch[2]}`,\n type: eslintMatch[3] === E_IssueType.Error ? E_IssueType.Error : E_IssueType.Warning,\n message: eslintMatch?.[4]?.trim() ?? '',\n rule: eslintMatch?.[5]?.trim() ?? '',\n });\n }\n else {\n const tsMatch = tsRegex.exec(line);\n\n if (tsMatch) {\n errorList.push({\n file: tsMatch?.[1] ?? '',\n position: `${tsMatch[2]}:${tsMatch[3]}`,\n type: tsMatch[4] === E_IssueType.Error ? E_IssueType.Error : E_IssueType.Warning,\n message: tsMatch?.[5]?.trim() ?? '',\n });\n }\n else {\n const commitlintMatch = commitlintRegex.exec(line);\n\n if (commitlintMatch) {\n errorList.push({\n file: 'commitlint',\n type: E_IssueType.Error,\n message: commitlintMatch?.[1]?.trim() ?? '',\n rule: commitlintMatch?.[2]?.trim() ?? '',\n });\n }\n else {\n unmatchedLines.push(line.trim());\n }\n }\n }\n }\n });\n\n if (errorList.length) {\n await saveErrorListToStorage(errorList);\n }\n\n if (unmatchedLines.length) {\n log.warn(`Unmatched lines:`);\n unmatchedLines.forEach(line => log.info(` ${line}`));\n }\n}\n\n/**\n * Parses command output that contains structured error information.\n * This function attempts to parse JSON-formatted error output (typically from ESLint)\n * and converts it to structured error entries. If JSON parsing fails, it falls back\n * to text-based parsing.\n *\n * @param output - The command output to parse, expected to be JSON-formatted error data.\n */\nasync function parseCommandOutput(output: string): Promise<void> {\n try {\n const results: I_EslintError[] = JSON.parse(output);\n const errorList: I_IssueEntry[] = [];\n\n results.forEach(({ filePath, messages }) => {\n messages.forEach(({ severity, line, column, ruleId, message }) => {\n errorList.push({\n type: severity === 2 ? E_IssueType.Error : E_IssueType.Warning,\n file: filePath,\n position: `${line}:${column}`,\n rule: ruleId,\n message,\n });\n });\n });\n\n if (errorList.length) {\n await saveErrorListToStorage(errorList);\n }\n }\n catch {\n await parseTextErrors(output);\n }\n}\n\n/**\n * Executes a command and processes its output for errors.\n * This function runs a command with proper signal handling for graceful termination,\n * processes both stdout and stderr for error information, and handles command failures.\n *\n * @param command - The command string to execute, or undefined if no command should be run.\n * @param parser - The function to use for parsing command output (defaults to parseCommandOutput).\n * @returns A promise that resolves when the command execution is complete.\n */\nasync function executeCommand(command: string | void, parser = parseCommandOutput, options: { timeout?: number } = {}): Promise<void> {\n const controller = new AbortController();\n\n const onSigint = () => {\n log.warn('Process interrupted. Terminating...');\n controller.abort();\n process.exit(130);\n };\n\n process.once('SIGINT', onSigint);\n\n try {\n if (typeof command === 'string') {\n const execOptions = {\n maxBuffer: 10 * 1024 * 1024,\n signal: controller.signal,\n timeout: options.timeout,\n };\n\n let result: { stdout: string; stderr: string };\n\n if (SHELL_METACHARACTERS.test(command)) {\n result = await execPromise(command, execOptions);\n }\n else {\n const parts = command.split(RE_WHITESPACE).filter(Boolean);\n result = await execFilePromise(parts[0]!, parts.slice(1), execOptions);\n }\n\n await Promise.all([result.stdout, result.stderr].map(output => output && parser(output)));\n }\n }\n catch (error) {\n const { stdout, stderr, message } = error as {\n stdout?: string;\n stderr?: string;\n message: string;\n };\n\n await Promise.all([stdout, stderr].map(output => output && parser(output)));\n\n if (!stderr && !stdout) {\n log.error(`Command failed: ${message}`);\n }\n\n throw error;\n }\n finally {\n process.removeListener('SIGINT', onSigint);\n }\n}\n\n/**\n * Creates a raw command object that bypasses CLI formatting.\n * This function wraps a command string in an object that indicates it should be executed\n * as-is without any additional CLI formatting or path resolution.\n *\n * @param cmd - The raw command string to be executed directly.\n * @returns An object containing the raw command with a flag indicating it should not be formatted.\n */\nexport function rawCommand(cmd: string) {\n return { raw: true, cmd };\n}\n\n/**\n * Formats a command for CLI execution based on the current project context.\n * This function determines whether to use the current project's CLI path or the global CLI,\n * and formats the command accordingly with the appropriate executable paths.\n *\n * @param command - The command string to format.\n * @param context - Optional context information about the current project.\n * @returns The formatted command string ready for execution.\n */\nfunction formatCLI(command: string, context?: I_CommandContext) {\n if (context?.isCurrentProject) {\n return `${PNPM_EXEC_CLI} ${TSX_CLI} ${CYBERSKILL_CLI_PATH} ${command}`;\n }\n\n return `${PNPM_EXEC_CLI} ${CYBERSKILL_CLI} ${command}`;\n}\n\n/**\n * Formats a command based on its type and context.\n * This function handles different command types:\n * - Function commands: Executes the function with context and formats the result\n * - Raw commands: Returns the command as-is without formatting\n * - String commands: Formats them as CLI commands\n *\n * @param command - The command to format, which can be a string, function, or raw command object.\n * @param context - Optional context information for command execution.\n * @returns The formatted command string ready for execution.\n */\nexport function formatCommand(command: T_Command, context?: I_CommandContext) {\n if (typeof command === 'function') {\n return formatCLI(command(context), context);\n }\n\n if (typeof command === 'object' && command?.raw === true) {\n return command.cmd;\n }\n\n if (typeof command === 'string') {\n return formatCLI(command, context);\n }\n\n return command;\n}\n\n/**\n * Resolves a map of commands by formatting them based on the current project context.\n * This function takes a command map (either static or dynamic) and formats all commands\n * using the appropriate CLI paths based on whether the current project is the Cyberskill package.\n *\n * @param input - The command map to resolve, which can be static or a function that returns a map.\n * @returns A promise that resolves to an object with formatted command strings, or undefined if package info cannot be retrieved.\n */\nexport async function resolveCommands(input: T_CommandMapInput) {\n const packageData = await getPackage({ name: CYBERSKILL_PACKAGE_NAME });\n\n if (packageData.success) {\n const ctx: I_CommandContext = { isCurrentProject: packageData.result.isCurrentProject };\n const commands = typeof input === 'function' ? input(ctx) : input;\n\n return Object.fromEntries(\n Object.entries(commands).map(([key, cmd]) => [key, formatCommand(cmd, ctx)]),\n );\n }\n}\n\n/**\n * Executes a command with proper logging and error handling.\n * This function provides a standardized way to run commands with:\n * - Progress logging with start and success messages\n * - Debug logging of the actual command when DEBUG mode is enabled\n * - Error handling and reporting\n *\n * @param label - A human-readable label describing what the command does.\n * @param command - The command string to execute, or undefined if no command should be run.\n * @returns A promise that resolves when the command execution is complete.\n */\nexport async function runCommand(label: string, command: string | void, options: { timeout?: number; throwOnError?: boolean } = {}) {\n let timer: NodeJS.Timeout | undefined;\n\n try {\n const startTime = Date.now();\n log.start(`${label}`);\n\n if (getEnv().DEBUG) {\n log.info(`→ ${command}`);\n }\n else {\n timer = setInterval(() => {\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n\n if (elapsed > 0) {\n process.stdout.write(`\\r⏳ ${label}... ${elapsed}s`);\n }\n }, 1000);\n }\n\n await executeCommand(command, parseCommandOutput, options);\n\n log.success(`${label} done.`);\n }\n catch (error) {\n if (options.throwOnError) {\n throw error;\n }\n catchError(error);\n }\n finally {\n if (timer) {\n clearInterval(timer);\n process.stdout.write(`\\r\\x1B[K`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAM,IAAc,EAAK,UAAU,EAAK,EAClC,IAAkB,EAAK,UAAU,EAAS,EAC1C,IAAuB,yBACvB,IAAkB,iEAClB,IAAc,+DACd,IAAsB,yCACtB,IAAgB;AAStB,eAAe,IAAiB;CAC5B,IAAM,IAAM,MAAM,GAAY;AAM9B,QAJK,EAAI,UAIF,EAAI,OAAO,OAHP,KAAK,KAAK,CAAC,UAAU;;AAcpC,eAAe,EAAuB,GAA0C;AAC5E,KAAI,EAAU,WAAW,EACrB;CAGJ,IAAM,IAAc,MAAM,GAAgB;AAE1C,KAAI;EAEA,IAAM,IAAe,CAAC,GADC,MAAM,GAAqB,EACT,GAAG,EAAU;AAItD,EAFA,MAAM,EAAQ,IAAI,GAAa,EAAa,EAE5C,WAAW,YAAY;GACnB,IAAM,IAAU,MAAM,EAAQ,WAAW,EAAY;AAErD,GAAI,KACA,EAAI,KAAK,oCAAoC,IAAU;KAE5D,EAAE;UAEF,GAAO;AACV,IAAW,EAAM;;;AAUzB,eAAsB,IAA+C;AACjE,KAAI;EACA,IAAM,IAAc,MAAM,GAAgB;AAG1C,SAFkB,MAAM,EAAQ,IAAoB,EAAY,IAE5C,EAAE;UAEnB,GAAO;AACV,SAAO,EAA2B,GAAO,EACrC,aAAa,EAAE,EAClB,CAAC;;;AAUV,eAAsB,IAAoC;AACtD,KAAI;EACA,IAAM,IAAc,MAAM,GAAgB;AAC1C,QAAM,EAAQ,OAAO,EAAY;UAE9B,GAAO;AACV,IAAW,EAAM;;;AAYzB,eAAe,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,EAAM,EACpB,EAAQ,OAAO,MAAM,WAAW"}
|
|
@@ -18,6 +18,8 @@ export interface I_ExpressOptions {
|
|
|
18
18
|
jsonLimit?: string;
|
|
19
19
|
trustProxy?: boolean | number | string | string[];
|
|
20
20
|
rateLimit?: false | I_RateLimitOptions;
|
|
21
|
+
/** Route path to scope graphqlUploadExpress middleware (defaults to '/graphql'). */
|
|
22
|
+
uploadPath?: string;
|
|
21
23
|
}
|
|
22
24
|
export interface I_NestOptions {
|
|
23
25
|
module: Type<object>;
|
|
@@ -14,7 +14,11 @@ import d from "helmet";
|
|
|
14
14
|
function f({ isDev: e, whiteList: t, ...n }) {
|
|
15
15
|
return {
|
|
16
16
|
origin: (n, r) => {
|
|
17
|
-
e
|
|
17
|
+
if (e && !n) {
|
|
18
|
+
r(null, !0);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
n && t?.includes(n) ? r(null, !0) : r(/* @__PURE__ */ Error("Not allowed by CORS"), !1);
|
|
18
22
|
},
|
|
19
23
|
credentials: !0,
|
|
20
24
|
...n
|
|
@@ -31,7 +35,8 @@ function m(t) {
|
|
|
31
35
|
cookie: {
|
|
32
36
|
httpOnly: !0,
|
|
33
37
|
sameSite: "lax",
|
|
34
|
-
secure: e.env.NODE_ENV === "production"
|
|
38
|
+
secure: e.env.NODE_ENV === "production",
|
|
39
|
+
maxAge: 1440 * 60 * 1e3
|
|
35
40
|
}
|
|
36
41
|
};
|
|
37
42
|
return c({
|
|
@@ -66,10 +71,12 @@ function g(e, n) {
|
|
|
66
71
|
}
|
|
67
72
|
function _(e) {
|
|
68
73
|
let n = t();
|
|
69
|
-
|
|
74
|
+
h(n, e?.isDev, e?.jsonLimit, e?.trustProxy, e?.rateLimit), g(n, e?.static);
|
|
75
|
+
let r = u({
|
|
70
76
|
maxFileSize: e?.maxFileSize ?? 1e7,
|
|
71
77
|
maxFiles: e?.maxFiles ?? 10
|
|
72
|
-
})
|
|
78
|
+
});
|
|
79
|
+
return n.use(e?.uploadPath ?? "/graphql", r), n;
|
|
73
80
|
}
|
|
74
81
|
async function v(e) {
|
|
75
82
|
let t = await n.create(e.module);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.util.js","names":[],"sources":["../../../src/node/express/express.util.ts"],"sourcesContent":["import type { INestApplication } from '@nestjs/common';\nimport type { Application, RequestHandler } from 'express';\nimport type { SessionOptions } from 'express-session';\n\nimport { NestFactory } from '@nestjs/core';\nimport bodyParser from 'body-parser';\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport cors from 'cors';\nimport express from 'express';\nimport rateLimit from 'express-rate-limit';\nimport session from 'express-session';\nimport { express as useragent } from 'express-useragent';\nimport graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';\nimport helmet from 'helmet';\nimport process from 'node:process';\n\nimport type { I_ExpressOptions, I_NestOptions, T_CorsOptions, T_CorsType } from './express.type.js';\n\n/**\n * Creates CORS options with environment-specific configuration.\n * This function generates CORS options based on the development environment,\n * including whitelist configuration for allowed origins.\n *\n * @param options - CORS configuration options.\n * @param options.isDev - Whether the application is running in development mode.\n * @param options.whiteList - Array of allowed origins for CORS requests.\n * @returns CORS options object configured for the specified environment.\n */\nexport function createCorsOptions<T extends T_CorsType>({ isDev, whiteList, ...rest }: T_CorsOptions<T>) {\n return {\n origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {\n if (isDev || !origin || whiteList?.includes(origin ?? '')) {\n callback(null, true);\n }\n else {\n callback(new Error('Not allowed by CORS'), false);\n }\n },\n credentials: true,\n ...rest,\n };\n}\n\n/**\n * Creates a CORS middleware function with the specified configuration.\n * This function creates a CORS middleware that can be used with both Express and NestJS applications,\n * applying the configured CORS options for origin validation and credential handling.\n *\n * @param options - CORS configuration options to apply to the middleware.\n * @returns A CORS middleware function ready to be used in Express or NestJS applications.\n */\nexport function createCors<T extends T_CorsType>(options: T_CorsOptions<T>) {\n return cors<cors.CorsRequest>(createCorsOptions(options));\n}\n\n/**\n * Creates a session middleware function with the specified configuration.\n * This function creates an Express session middleware that can be used to handle user sessions\n * with the provided session options including secret, cookie settings, and storage configuration.\n *\n * @param options - Session configuration options including secret, cookie settings, and storage.\n * @returns A session middleware function ready to be used in Express applications.\n */\nexport function createSession(options: SessionOptions): RequestHandler {\n if (!options.secret) {\n throw new Error('Session secret is required. Provide a strong secret string.');\n }\n\n const secureDefaults: Partial<SessionOptions> = {\n resave: false,\n saveUninitialized: false,\n cookie: {\n httpOnly: true,\n sameSite: 'lax',\n secure: process.env['NODE_ENV'] === 'production',\n },\n };\n\n return session({\n ...secureDefaults,\n ...options,\n cookie: { ...secureDefaults.cookie, ...options.cookie },\n });\n}\n\n/**\n * Sets up common middleware for Express applications.\n * This function configures essential middleware including:\n * - Trust proxy settings for proper IP handling\n * - Cookie parsing for request cookies\n * - URL-encoded body parsing for form data\n * - Compression for response optimization\n * - User agent parsing for device/browser detection\n *\n * @param app - The Express application instance to configure with middleware.\n * @param isDev - Whether the application is running in development mode.\n * @param jsonLimit - Maximum request body size for JSON payloads.\n * @param trustProxy - Trust proxy setting; pass a truthy value to enable.\n * @param rateLimitOptions - Rate limit configuration, or `false` to disable.\n */\nfunction setupMiddleware(\n app: Application,\n isDev = false,\n jsonLimit = '1mb',\n trustProxy: boolean | number | string | string[] = false,\n rateLimitOptions: false | import('./express.type.js').I_RateLimitOptions = {},\n) {\n if (trustProxy !== false) {\n app.set('trust proxy', trustProxy);\n }\n app.use(\n helmet({\n crossOriginEmbedderPolicy: isDev ? false : undefined,\n contentSecurityPolicy: isDev ? false : undefined,\n }),\n );\n if (rateLimitOptions !== false) {\n app.use(\n rateLimit({\n windowMs: rateLimitOptions.windowMs ?? 15 * 60 * 1000,\n limit: rateLimitOptions.limit ?? 1000,\n standardHeaders: true,\n legacyHeaders: false,\n ...(rateLimitOptions.store !== undefined && { store: rateLimitOptions.store }),\n ...(rateLimitOptions.skip !== undefined && { skip: rateLimitOptions.skip }),\n }),\n );\n }\n app.use(cookieParser());\n app.use(express.json({ limit: jsonLimit }));\n app.use(express.urlencoded({ extended: true, limit: jsonLimit }));\n app.use(compression());\n app.use(useragent());\n}\n\n/**\n * Sets up static file serving for Express applications.\n * This function configures static file serving for the specified folders,\n * making files in those directories accessible via HTTP requests.\n *\n * @param app - The Express application instance to configure with static file serving.\n * @param staticFolders - A string or array of strings representing the paths to serve statically.\n */\nfunction setupStaticFolders(app: Application, staticFolders?: string | string[]) {\n if (staticFolders) {\n const statics = Array.isArray(staticFolders) ? staticFolders : [staticFolders];\n statics.forEach((folder) => {\n app.use(`/${folder}`, express.static(folder));\n });\n }\n}\n\n/**\n * Creates and configures an Express application with common middleware and settings.\n * This function sets up a complete Express application with:\n * - Essential middleware (cookies, body parsing, compression, user agent)\n * - Static file serving for specified folders\n * - GraphQL upload support for file uploads\n *\n * @param options - Optional configuration for the Express application including static folder paths.\n * @returns A configured Express application instance ready for use.\n */\nexport function createExpress(options?: I_ExpressOptions): Application {\n const app = express();\n\n setupMiddleware(app, options?.isDev, options?.jsonLimit, options?.trustProxy, options?.rateLimit);\n setupStaticFolders(app, options?.static);\n app.use(graphqlUploadExpress({\n maxFileSize: options?.maxFileSize ?? 10_000_000,\n maxFiles: options?.maxFiles ?? 10,\n }));\n\n return app;\n}\n\n/**\n * Creates and configures a NestJS application with Express integration.\n * This function sets up a NestJS application with:\n * - Express HTTP adapter configuration\n * - Common middleware (cookies, body parsing, compression, user agent)\n * - Static file serving for specified folders\n * - Global filters and pipes if provided\n *\n * @param options - Configuration options for the NestJS application including module, static folders, filters, and pipes.\n * @returns A promise that resolves to a configured NestJS application instance.\n */\nexport async function createNest(options: I_NestOptions): Promise<INestApplication> {\n const app = await NestFactory.create(options.module);\n\n setupMiddleware(app.getHttpAdapter().getInstance(), options.isDev, options.jsonLimit, options.trustProxy, options.rateLimit);\n setupStaticFolders(app.getHttpAdapter().getInstance(), options.static);\n\n if (options.filters) {\n app.useGlobalFilters(...options.filters);\n }\n\n if (options.pipes) {\n app.useG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GAAc,CAAC,EACvB,EAAI,IAAI,EAAQ,KAAK,EAAE,OAAO,GAAW,CAAC,CAAC,EAC3C,EAAI,IAAI,EAAQ,WAAW;EAAE,UAAU;EAAM,OAAO;EAAW,CAAC,CAAC,EACjE,EAAI,IAAI,GAAa,CAAC,EACtB,EAAI,IAAI,GAAW,CAAC;;AAWxB,SAAS,EAAmB,GAAkB,GAAmC;AAC7E,CAAI,MACgB,MAAM,QAAQ,EAAc,GAAG,IAAgB,CAAC,EAAc,EACtE,SAAS,MAAW;AACxB,IAAI,IAAI,IAAI,KAAU,EAAQ,OAAO,EAAO,CAAC;GAC/C;;AAcV,SAAgB,EAAc,GAAyC;CACnE,IAAM,IAAM,GAAS;AASrB,QAPA,EAAgB,GAAK,GAAS,OAAO,GAAS,WAAW,GAAS,YAAY,GAAS,UAAU,EACjG,EAAmB,GAAK,GAAS,OAAO,EACxC,EAAI,IAAI,EAAqB;EACzB,aAAa,GAAS,eAAe;EACrC,UAAU,GAAS,YAAY;EAClC,CAAC,CAAC,EAEI;;AAcX,eAAsB,EAAW,GAAmD;CAChF,IAAM,IAAM,MAAM,EAAY,OAAO,EAAQ,OAAO;AAapD,QAXA,EAAgB,EAAI,gBAAgB,CAAC,aAAa,EAAE,EAAQ,OAAO,EAAQ,WAAW,EAAQ,YAAY,EAAQ,UAAU,EAC5H,EAAmB,EAAI,gBAAgB,CAAC,aAAa,EAAE,EAAQ,OAAO,EAElE,EAAQ,WACR,EAAI,iBAAiB,GAAG,EAAQ,QAAQ,EAGxC,EAAQ,SACR,EAAI,eAAe,GAAG,EAAQ,MAAM,EAGjC"}
|
|
1
|
+
{"version":3,"file":"express.util.js","names":[],"sources":["../../../src/node/express/express.util.ts"],"sourcesContent":["import type { INestApplication } from '@nestjs/common';\nimport type { Application, RequestHandler } from 'express';\nimport type { SessionOptions } from 'express-session';\n\nimport { NestFactory } from '@nestjs/core';\nimport bodyParser from 'body-parser';\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport cors from 'cors';\nimport express from 'express';\nimport rateLimit from 'express-rate-limit';\nimport session from 'express-session';\nimport { express as useragent } from 'express-useragent';\nimport graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';\nimport helmet from 'helmet';\nimport process from 'node:process';\n\nimport type { I_ExpressOptions, I_NestOptions, T_CorsOptions, T_CorsType } from './express.type.js';\n\n/**\n * Creates CORS options with environment-specific configuration.\n * This function generates CORS options based on the development environment,\n * including whitelist configuration for allowed origins.\n *\n * @param options - CORS configuration options.\n * @param options.isDev - Whether the application is running in development mode.\n * @param options.whiteList - Array of allowed origins for CORS requests.\n * @returns CORS options object configured for the specified environment.\n */\nexport function createCorsOptions<T extends T_CorsType>({ isDev, whiteList, ...rest }: T_CorsOptions<T>) {\n return {\n origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {\n // Allow requests without Origin header only in development mode.\n // In production, undefined origin (e.g., curl, server-to-server) is rejected.\n if (isDev && !origin) {\n callback(null, true);\n return;\n }\n\n if (origin && whiteList?.includes(origin)) {\n callback(null, true);\n }\n else {\n callback(new Error('Not allowed by CORS'), false);\n }\n },\n credentials: true,\n ...rest,\n };\n}\n\n/**\n * Creates a CORS middleware function with the specified configuration.\n * This function creates a CORS middleware that can be used with both Express and NestJS applications,\n * applying the configured CORS options for origin validation and credential handling.\n *\n * @param options - CORS configuration options to apply to the middleware.\n * @returns A CORS middleware function ready to be used in Express or NestJS applications.\n */\nexport function createCors<T extends T_CorsType>(options: T_CorsOptions<T>) {\n return cors<cors.CorsRequest>(createCorsOptions(options));\n}\n\n/**\n * Creates a session middleware function with the specified configuration.\n * This function creates an Express session middleware that can be used to handle user sessions\n * with the provided session options including secret, cookie settings, and storage configuration.\n *\n * @param options - Session configuration options including secret, cookie settings, and storage.\n * @returns A session middleware function ready to be used in Express applications.\n */\nexport function createSession(options: SessionOptions): RequestHandler {\n if (!options.secret) {\n throw new Error('Session secret is required. Provide a strong secret string.');\n }\n\n const secureDefaults: Partial<SessionOptions> = {\n resave: false,\n saveUninitialized: false,\n cookie: {\n httpOnly: true,\n sameSite: 'lax',\n secure: process.env['NODE_ENV'] === 'production',\n maxAge: 24 * 60 * 60 * 1000, // 24 hours\n },\n };\n\n return session({\n ...secureDefaults,\n ...options,\n cookie: { ...secureDefaults.cookie, ...options.cookie },\n });\n}\n\n/**\n * Sets up common middleware for Express applications.\n * This function configures essential middleware including:\n * - Trust proxy settings for proper IP handling\n * - Cookie parsing for request cookies\n * - URL-encoded body parsing for form data\n * - Compression for response optimization\n * - User agent parsing for device/browser detection\n *\n * @param app - The Express application instance to configure with middleware.\n * @param isDev - Whether the application is running in development mode.\n * @param jsonLimit - Maximum request body size for JSON payloads.\n * @param trustProxy - Trust proxy setting; pass a truthy value to enable.\n * @param rateLimitOptions - Rate limit configuration, or `false` to disable.\n */\nfunction setupMiddleware(\n app: Application,\n isDev = false,\n jsonLimit = '1mb',\n trustProxy: boolean | number | string | string[] = false,\n rateLimitOptions: false | import('./express.type.js').I_RateLimitOptions = {},\n) {\n if (trustProxy !== false) {\n app.set('trust proxy', trustProxy);\n }\n app.use(\n helmet({\n crossOriginEmbedderPolicy: isDev ? false : undefined,\n contentSecurityPolicy: isDev ? false : undefined,\n }),\n );\n if (rateLimitOptions !== false) {\n app.use(\n rateLimit({\n windowMs: rateLimitOptions.windowMs ?? 15 * 60 * 1000,\n limit: rateLimitOptions.limit ?? 1000,\n standardHeaders: true,\n legacyHeaders: false,\n ...(rateLimitOptions.store !== undefined && { store: rateLimitOptions.store }),\n ...(rateLimitOptions.skip !== undefined && { skip: rateLimitOptions.skip }),\n }),\n );\n }\n app.use(cookieParser());\n app.use(express.json({ limit: jsonLimit }));\n app.use(express.urlencoded({ extended: true, limit: jsonLimit }));\n app.use(compression());\n app.use(useragent());\n}\n\n/**\n * Sets up static file serving for Express applications.\n * This function configures static file serving for the specified folders,\n * making files in those directories accessible via HTTP requests.\n *\n * @param app - The Express application instance to configure with static file serving.\n * @param staticFolders - A string or array of strings representing the paths to serve statically.\n */\nfunction setupStaticFolders(app: Application, staticFolders?: string | string[]) {\n if (staticFolders) {\n const statics = Array.isArray(staticFolders) ? staticFolders : [staticFolders];\n statics.forEach((folder) => {\n app.use(`/${folder}`, express.static(folder));\n });\n }\n}\n\n/**\n * Creates and configures an Express application with common middleware and settings.\n * This function sets up a complete Express application with:\n * - Essential middleware (cookies, body parsing, compression, user agent)\n * - Static file serving for specified folders\n * - GraphQL upload support for file uploads\n *\n * @param options - Optional configuration for the Express application including static folder paths.\n * @returns A configured Express application instance ready for use.\n */\nexport function createExpress(options?: I_ExpressOptions): Application {\n const app = express();\n\n setupMiddleware(app, options?.isDev, options?.jsonLimit, options?.trustProxy, options?.rateLimit);\n setupStaticFolders(app, options?.static);\n const uploadMiddleware = graphqlUploadExpress({\n maxFileSize: options?.maxFileSize ?? 10_000_000,\n maxFiles: options?.maxFiles ?? 10,\n });\n app.use(options?.uploadPath ?? '/graphql', uploadMiddleware);\n\n return app;\n}\n\n/**\n * Creates and configures a NestJS application with Express integration.\n * This function sets up a NestJS application with:\n * - Express HTTP adapter configuration\n * - Common middleware (cookies, body parsing, compression, user agent)\n * - Static file serving for specified folders\n * - Global filters and pipes if provided\n *\n * @param options - Configuration options for the NestJS application including module, static folders, filters, and pipes.\n * @returns A promise that resolves to a configured NestJS application instance.\n */\nexport async function createNest(options: I_NestOptions): Promise<INestApplication> {\n const app = await NestFactory.create(options.module);\n\n setupMiddleware(app.getHttpAdapter().getInstance(), options.isDev, options.jsonLimit, options.trustProxy, options.rateLimit);\n setupStaticFolders(app.getHttpAdapter().getInstance(), options.static);\n\n if (options.filters) {\n app.useGlobalFilters(...options.filters);\n }\n\n if (options.pipes) {\n app.useGlobalPipes(...options.pipes);\n }\n\n return app;\n}\n\nexport { bodyParser, express };\n"],"mappings":";;;;;;;;;;;;;AA6BA,SAAgB,EAAwC,EAAE,UAAO,cAAW,GAAG,KAA0B;AACrG,QAAO;EACH,SAAS,GAA4B,MAA2D;AAG5F,OAA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EAAE,UAAU;EAAM,OAAO;EAAW,CAAC,CAAC,EACjE,EAAI,IAAI,GAAa,CAAC,EACtB,EAAI,IAAI,GAAW,CAAC;;AAWxB,SAAS,EAAmB,GAAkB,GAAmC;AAC7E,CAAI,MACgB,MAAM,QAAQ,EAAc,GAAG,IAAgB,CAAC,EAAc,EACtE,SAAS,MAAW;AACxB,IAAI,IAAI,IAAI,KAAU,EAAQ,OAAO,EAAO,CAAC;GAC/C;;AAcV,SAAgB,EAAc,GAAyC;CACnE,IAAM,IAAM,GAAS;AAGrB,CADA,EAAgB,GAAK,GAAS,OAAO,GAAS,WAAW,GAAS,YAAY,GAAS,UAAU,EACjG,EAAmB,GAAK,GAAS,OAAO;CACxC,IAAM,IAAmB,EAAqB;EAC1C,aAAa,GAAS,eAAe;EACrC,UAAU,GAAS,YAAY;EAClC,CAAC;AAGF,QAFA,EAAI,IAAI,GAAS,cAAc,YAAY,EAAiB,EAErD;;AAcX,eAAsB,EAAW,GAAmD;CAChF,IAAM,IAAM,MAAM,EAAY,OAAO,EAAQ,OAAO;AAapD,QAXA,EAAgB,EAAI,gBAAgB,CAAC,aAAa,EAAE,EAAQ,OAAO,EAAQ,WAAW,EAAQ,YAAY,EAAQ,UAAU,EAC5H,EAAmB,EAAI,gBAAgB,CAAC,aAAa,EAAE,EAAQ,OAAO,EAElE,EAAQ,WACR,EAAI,iBAAiB,GAAG,EAAQ,QAAQ,EAGxC,EAAQ,SACR,EAAI,eAAe,GAAG,EAAQ,MAAM,EAGjC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { I_Log as I_LogCommon } from '../../typescript/index.js';
|
|
2
|
+
export type { I_CatchErrorOptions } from '../../util/log/index.js';
|
|
2
3
|
/**
|
|
3
4
|
* Enum representing the type of issues for logging and error handling.
|
|
4
5
|
* - Error: Represents an error issue.
|
|
@@ -26,8 +27,3 @@ export interface I_ThrowError {
|
|
|
26
27
|
export interface I_Log extends I_LogCommon {
|
|
27
28
|
printBoxedLog: (title: string, issues: I_IssueEntry[], color?: string) => void;
|
|
28
29
|
}
|
|
29
|
-
export interface I_CatchErrorOptions {
|
|
30
|
-
shouldLog?: boolean;
|
|
31
|
-
returnValue?: unknown;
|
|
32
|
-
callback?: (error: Error) => void;
|
|
33
|
-
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.type.js","names":[],"sources":["../../../src/node/log/log.type.ts"],"sourcesContent":["import type { I_Log as I_LogCommon } from '#typescript/index.js';\n\n/**\n * Enum representing the type of issues for logging and error handling.\n * - Error: Represents an error issue.\n * - Warning: Represents a warning issue.\n */\nexport enum E_IssueType {\n Error = 'error',\n Warning = 'warning',\n}\n\nexport interface I_IssueEntry {\n type: E_IssueType;\n file: string;\n message: string;\n position?: string;\n rule?: string;\n}\n\nexport interface I_ThrowError {\n message?: string;\n status?: {\n CODE: string | number;\n MESSAGE: string;\n };\n type?: 'graphql' | 'rest';\n}\n\nexport interface I_Log extends I_LogCommon {\n printBoxedLog: (\n title: string,\n issues: I_IssueEntry[],\n color?: string,\n ) => void;\n}\n
|
|
1
|
+
{"version":3,"file":"log.type.js","names":[],"sources":["../../../src/node/log/log.type.ts"],"sourcesContent":["import type { I_Log as I_LogCommon } from '#typescript/index.js';\n\nexport type { I_CatchErrorOptions } from '#util/log/index.js';\n\n/**\n * Enum representing the type of issues for logging and error handling.\n * - Error: Represents an error issue.\n * - Warning: Represents a warning issue.\n */\nexport enum E_IssueType {\n Error = 'error',\n Warning = 'warning',\n}\n\nexport interface I_IssueEntry {\n type: E_IssueType;\n file: string;\n message: string;\n position?: string;\n rule?: string;\n}\n\nexport interface I_ThrowError {\n message?: string;\n status?: {\n CODE: string | number;\n MESSAGE: string;\n };\n type?: 'graphql' | 'rest';\n}\n\nexport interface I_Log extends I_LogCommon {\n printBoxedLog: (\n title: string,\n issues: I_IssueEntry[],\n color?: string,\n ) => void;\n}\n"],"mappings":";AASA,IAAY,IAAL,yBAAA,GAAA;QACH,EAAA,QAAA,SACA,EAAA,UAAA;KACH"}
|
|
@@ -21,10 +21,8 @@ export declare function throwError({ message, status, type, }: I_ThrowError): ne
|
|
|
21
21
|
export declare const log: I_Log;
|
|
22
22
|
/**
|
|
23
23
|
* Catches and handles errors with configurable behavior.
|
|
24
|
-
*
|
|
25
|
-
* -
|
|
26
|
-
* - Return value specification (what to return on error)
|
|
27
|
-
* - Custom callback execution (additional error handling)
|
|
24
|
+
* Delegates to the shared `baseCatchError` implementation, adding Node-specific
|
|
25
|
+
* log-level configuration via `ensureLogLevel()` before logging.
|
|
28
26
|
*
|
|
29
27
|
* @param errorInput - The error to catch and handle.
|
|
30
28
|
* @param options - Configuration options for error handling behavior.
|
|
@@ -1,56 +1,54 @@
|
|
|
1
1
|
import { RESPONSE_STATUS as e } from "../../constant/response-status.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import r from "
|
|
5
|
-
import i from "
|
|
2
|
+
import { baseCatchError as t } from "../../util/log/log.util.js";
|
|
3
|
+
import { getEnv as n } from "../../config/env/env.util.js";
|
|
4
|
+
import { GraphQLError as r } from "graphql";
|
|
5
|
+
import i from "chalk";
|
|
6
|
+
import a from "consola";
|
|
6
7
|
//#region src/node/log/log.util.ts
|
|
7
|
-
var
|
|
8
|
-
function
|
|
9
|
-
|
|
8
|
+
var o = !1;
|
|
9
|
+
function s() {
|
|
10
|
+
o || (o = !0, n().DEBUG || (a.level = 4));
|
|
10
11
|
}
|
|
11
|
-
function
|
|
12
|
-
let a = t ??
|
|
13
|
-
throw i === "graphql" ? new
|
|
12
|
+
function c({ message: t, status: n = e.INTERNAL_SERVER_ERROR, type: i = "graphql" }) {
|
|
13
|
+
let a = t ?? n.MESSAGE ?? "Internal server error";
|
|
14
|
+
throw i === "graphql" ? new r(a, { extensions: { code: n.CODE } }) : Error(a);
|
|
14
15
|
}
|
|
15
|
-
function
|
|
16
|
-
let t =
|
|
17
|
-
return typeof t == "function" ? t :
|
|
16
|
+
function l(e) {
|
|
17
|
+
let t = i[e];
|
|
18
|
+
return typeof t == "function" ? t : i.green;
|
|
18
19
|
}
|
|
19
|
-
var
|
|
20
|
-
silent:
|
|
21
|
-
level:
|
|
22
|
-
fatal:
|
|
23
|
-
error:
|
|
24
|
-
warn:
|
|
25
|
-
log:
|
|
26
|
-
info:
|
|
27
|
-
success:
|
|
28
|
-
ready:
|
|
29
|
-
start:
|
|
30
|
-
box:
|
|
31
|
-
debug:
|
|
32
|
-
trace:
|
|
33
|
-
verbose:
|
|
20
|
+
var u = {
|
|
21
|
+
silent: a.silent,
|
|
22
|
+
level: a.level,
|
|
23
|
+
fatal: a.fatal,
|
|
24
|
+
error: a.error,
|
|
25
|
+
warn: a.warn,
|
|
26
|
+
log: a.log,
|
|
27
|
+
info: a.info,
|
|
28
|
+
success: a.success,
|
|
29
|
+
ready: a.ready,
|
|
30
|
+
start: a.start,
|
|
31
|
+
box: a.box,
|
|
32
|
+
debug: a.debug,
|
|
33
|
+
trace: a.trace,
|
|
34
|
+
verbose: a.verbose,
|
|
34
35
|
printBoxedLog(e, t, n = "red") {
|
|
35
36
|
if (!t?.length) {
|
|
36
|
-
|
|
37
|
+
a.box(i.green(e));
|
|
37
38
|
return;
|
|
38
39
|
}
|
|
39
|
-
t.forEach(({ file: e, position: t, rule:
|
|
40
|
+
t.forEach(({ file: e, position: t, rule: r, message: o }) => {
|
|
40
41
|
let s = `${e}${t ? `:${t}` : ""}`;
|
|
41
|
-
|
|
42
|
-
}),
|
|
42
|
+
a.log(`${i.gray("File:")} ${i.blue(s)}`), r && a.log(` ${l(n)("Rule:")} ${r}`), a.log(` ${l(n)("Message:")} ${o}`);
|
|
43
|
+
}), a.box(l(n)(`${e} : ${t.length}`)), a.log(i.gray("─".repeat(40)));
|
|
43
44
|
}
|
|
44
45
|
};
|
|
45
|
-
function
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
message: s.message,
|
|
50
|
-
code: e.INTERNAL_SERVER_ERROR.CODE
|
|
51
|
-
} : i;
|
|
46
|
+
function d(e, n) {
|
|
47
|
+
return t(e, n, (e) => {
|
|
48
|
+
s(), u.error(e);
|
|
49
|
+
});
|
|
52
50
|
}
|
|
53
51
|
//#endregion
|
|
54
|
-
export {
|
|
52
|
+
export { d as catchError, u as log, c as throwError };
|
|
55
53
|
|
|
56
54
|
//# sourceMappingURL=log.util.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.util.js","names":[],"sources":["../../../src/node/log/log.util.ts"],"sourcesContent":["import type { ChalkInstance } from 'chalk';\n\nimport chalk from 'chalk';\nimport consola from 'consola';\nimport { GraphQLError } from 'graphql';\n\nimport type { I_Return } from '#typescript/index.js';\n\nimport { getEnv } from '#config/env/index.js';\nimport { RESPONSE_STATUS } from '#constant/index.js';\n\nimport type { I_CatchErrorOptions, I_IssueEntry, I_Log, I_ThrowError } from './log.type.js';\n\nlet _logLevelConfigured = false;\n\n/**\n * Lazily configures the consola log level based on the DEBUG environment variable.\n * Only runs once on first invocation to avoid repeated env loading.\n */\nfunction ensureLogLevel() {\n if (!_logLevelConfigured) {\n _logLevelConfigured = true;\n const env = getEnv();\n\n if (!env.DEBUG) {\n consola.level = 4;\n }\n }\n}\n\n/**\n * Throws a standardized error with optional status information and type specification.\n * This function creates and throws errors that can be either GraphQL errors (with extensions)\n * or standard JavaScript errors, depending on the specified type.\n *\n * @param options - Error configuration including message, status information, and error type.\n * @param options.message - The error message to display.\n * @param options.status - The response status information (defaults to INTERNAL_SERVER_ERROR).\n * @param options.type - The type of error to throw ('graphql' or 'rest', defaults to 'graphql').\n * @throws {GraphQLError} When type is 'graphql', throws a GraphQL error with extensions.\n * @throws {Error} When type is 'rest' or unspecified, throws a standard JavaScript error.\n */\nexport function throwError({\n message,\n status = RESPONSE_STATUS.INTERNAL_SERVER_ERROR,\n type = 'graphql',\n}: I_ThrowError): never {\n const responseMessage\n = message ?? status.MESSAGE ?? 'Internal server error';\n\n if (type === 'graphql') {\n throw new GraphQLError(responseMessage, {\n extensions: { code: status.CODE },\n });\n }\n\n
|
|
1
|
+
{"version":3,"file":"log.util.js","names":[],"sources":["../../../src/node/log/log.util.ts"],"sourcesContent":["import type { ChalkInstance } from 'chalk';\n\nimport chalk from 'chalk';\nimport consola from 'consola';\nimport { GraphQLError } from 'graphql';\n\nimport type { I_Return } from '#typescript/index.js';\n\nimport { getEnv } from '#config/env/index.js';\nimport { RESPONSE_STATUS } from '#constant/index.js';\nimport { baseCatchError } from '#util/log/index.js';\n\nimport type { I_CatchErrorOptions, I_IssueEntry, I_Log, I_ThrowError } from './log.type.js';\n\nlet _logLevelConfigured = false;\n\n/**\n * Lazily configures the consola log level based on the DEBUG environment variable.\n * Only runs once on first invocation to avoid repeated env loading.\n */\nfunction ensureLogLevel() {\n if (!_logLevelConfigured) {\n _logLevelConfigured = true;\n const env = getEnv();\n\n if (!env.DEBUG) {\n consola.level = 4;\n }\n }\n}\n\n/**\n * Throws a standardized error with optional status information and type specification.\n * This function creates and throws errors that can be either GraphQL errors (with extensions)\n * or standard JavaScript errors, depending on the specified type.\n *\n * @param options - Error configuration including message, status information, and error type.\n * @param options.message - The error message to display.\n * @param options.status - The response status information (defaults to INTERNAL_SERVER_ERROR).\n * @param options.type - The type of error to throw ('graphql' or 'rest', defaults to 'graphql').\n * @throws {GraphQLError} When type is 'graphql', throws a GraphQL error with extensions.\n * @throws {Error} When type is 'rest' or unspecified, throws a standard JavaScript error.\n */\nexport function throwError({\n message,\n status = RESPONSE_STATUS.INTERNAL_SERVER_ERROR,\n type = 'graphql',\n}: I_ThrowError): never {\n const responseMessage\n = message ?? status.MESSAGE ?? 'Internal server error';\n\n if (type === 'graphql') {\n throw new GraphQLError(responseMessage, {\n extensions: { code: status.CODE },\n });\n }\n\n throw new Error(responseMessage);\n}\n\n/**\n * Gets a chalk color instance by keyword name.\n * This function safely retrieves a chalk color function by name, falling back to green\n * if the specified color is not available or invalid.\n *\n * @param color - The color keyword to get the chalk instance for.\n * @returns A chalk instance for the specified color, or green as fallback.\n */\nfunction chalkKeyword(color: string): ChalkInstance {\n const chalkColor = chalk[color as keyof typeof chalk];\n\n return typeof chalkColor === 'function' ? (chalkColor as ChalkInstance) : chalk.green;\n}\n\n/**\n * Enhanced logging interface that extends consola with custom functionality.\n * This object provides all standard consola logging methods plus additional features\n * like boxed log printing for structured error/warning display.\n */\nexport const log: I_Log = {\n silent: consola.silent,\n level: consola.level,\n fatal: consola.fatal,\n error: consola.error,\n warn: consola.warn,\n log: consola.log,\n info: consola.info,\n success: consola.success,\n ready: consola.ready,\n start: consola.start,\n box: consola.box,\n debug: consola.debug,\n trace: consola.trace,\n verbose: consola.verbose,\n /**\n * Prints a boxed log with structured issue information.\n * This method displays issues (errors or warnings) in a formatted box with:\n * - File paths and line/column positions\n * - Rule violations (if applicable)\n * - Error/warning messages\n * - Color-coded output based on issue type\n *\n * @param title - The title to display in the box header.\n * @param issues - An array of issue entries to display.\n * @param color - The color to use for highlighting (defaults to 'red').\n */\n printBoxedLog(title: string, issues: I_IssueEntry[], color = 'red') {\n if (!issues?.length) {\n consola.box(chalk.green(title));\n return;\n }\n\n issues.forEach(({ file, position, rule, message }) => {\n const positionSuffix = position ? `:${position}` : '';\n const filePath = `${file}${positionSuffix}`;\n consola.log(`${chalk.gray('File:')} ${chalk.blue(filePath)}`);\n\n if (rule) {\n consola.log(` ${chalkKeyword(color)('Rule:')} ${rule}`);\n }\n\n consola.log(` ${chalkKeyword(color)('Message:')} ${message}`);\n });\n\n consola.box(chalkKeyword(color)(`${title} : ${issues.length}`));\n\n consola.log(chalk.gray('─'.repeat(40)));\n },\n};\n\n/**\n * Catches and handles errors with configurable behavior.\n * Delegates to the shared `baseCatchError` implementation, adding Node-specific\n * log-level configuration via `ensureLogLevel()` before logging.\n *\n * @param errorInput - The error to catch and handle.\n * @param options - Configuration options for error handling behavior.\n * @returns Either the specified return value or a standardized error response object.\n */\nexport function catchError<T = unknown>(errorInput: unknown, options: I_CatchErrorOptions & { returnValue: T }): T;\nexport function catchError<T = unknown>(errorInput: unknown, options?: I_CatchErrorOptions): I_Return<T>;\nexport function catchError<T = unknown>(errorInput: unknown, options?: I_CatchErrorOptions): I_Return<T> | T {\n return baseCatchError<T>(errorInput, options, (message) => {\n ensureLogLevel();\n log.error(message);\n });\n}\n"],"mappings":";;;;;;;AAcA,IAAI,IAAsB;AAM1B,SAAS,IAAiB;AACtB,CAAK,MACD,IAAsB,IACV,GAAQ,CAEX,UACL,EAAQ,QAAQ;;AAiB5B,SAAgB,EAAW,EACvB,YACA,YAAS,EAAgB,uBACzB,UAAO,aACa;CACpB,IAAM,IACA,KAAW,EAAO,WAAW;AAQnC,OANI,MAAS,YACH,IAAI,EAAa,GAAiB,EACpC,YAAY,EAAE,MAAM,EAAO,MAAM,EACpC,CAAC,GAGI,MAAM,EAAgB;;AAWpC,SAAS,EAAa,GAA8B;CAChD,IAAM,IAAa,EAAM;AAEzB,QAAO,OAAO,KAAe,aAAc,IAA+B,EAAM;;AAQpF,IAAa,IAAa;CACtB,QAAQ,EAAQ;CAChB,OAAO,EAAQ;CACf,OAAO,EAAQ;CACf,OAAO,EAAQ;CACf,MAAM,EAAQ;CACd,KAAK,EAAQ;CACb,MAAM,EAAQ;CACd,SAAS,EAAQ;CACjB,OAAO,EAAQ;CACf,OAAO,EAAQ;CACf,KAAK,EAAQ;CACb,OAAO,EAAQ;CACf,OAAO,EAAQ;CACf,SAAS,EAAQ;CAajB,cAAc,GAAe,GAAwB,IAAQ,OAAO;AAChE,MAAI,CAAC,GAAQ,QAAQ;AACjB,KAAQ,IAAI,EAAM,MAAM,EAAM,CAAC;AAC/B;;AAiBJ,EAdA,EAAO,SAAS,EAAE,SAAM,aAAU,SAAM,iBAAc;GAElD,IAAM,IAAW,GAAG,IADG,IAAW,IAAI,MAAa;AAQnD,GANA,EAAQ,IAAI,GAAG,EAAM,KAAK,QAAQ,CAAC,GAAG,EAAM,KAAK,EAAS,GAAG,EAEzD,KACA,EAAQ,IAAI,MAAM,EAAa,EAAM,CAAC,QAAQ,CAAC,GAAG,IAAO,EAG7D,EAAQ,IAAI,MAAM,EAAa,EAAM,CAAC,WAAW,CAAC,GAAG,IAAU;IACjE,EAEF,EAAQ,IAAI,EAAa,EAAM,CAAC,GAAG,EAAM,KAAK,EAAO,SAAS,CAAC,EAE/D,EAAQ,IAAI,EAAM,KAAK,IAAI,OAAO,GAAG,CAAC,CAAC;;CAE9C;AAaD,SAAgB,EAAwB,GAAqB,GAAgD;AACzG,QAAO,EAAkB,GAAY,IAAU,MAAY;AAEvD,EADA,GAAgB,EAChB,EAAI,MAAM,EAAQ;GACpB"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export * from './mongo.controller.mongoose.js';
|
|
2
2
|
/**
|
|
3
|
-
* Re-exports both MongoDB controller implementations.
|
|
3
|
+
* Re-exports both MongoDB controller implementations and the shared interface.
|
|
4
|
+
* - I_MongoController: Shared interface for both controller types
|
|
4
5
|
* - MongoController: Native MongoDB driver operations
|
|
5
6
|
* - MongooseController: Mongoose ORM with pagination, aggregation, and slug generation
|
|
6
7
|
*/
|
|
7
8
|
export * from './mongo.controller.native.js';
|
|
9
|
+
export * from './mongo.controller.type.js';
|