@cyberskill/shared 3.1.0 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/config.util.js +3 -2
- package/dist/config/config.util.js.map +1 -1
- package/dist/config/storybook/storybook.preview.d.ts +1 -1
- package/dist/config/storybook/storybook.preview.js +5 -4
- package/dist/config/storybook/storybook.preview.js.map +1 -1
- package/dist/config/vitest/vitest.e2e.d.ts +2 -0
- package/dist/config/vitest/vitest.e2e.js +11 -18
- package/dist/config/vitest/vitest.e2e.js.map +1 -1
- package/dist/config/vitest/vitest.unit.d.ts +2 -0
- package/dist/config/vitest/vitest.unit.js +7 -5
- package/dist/config/vitest/vitest.unit.js.map +1 -1
- package/dist/node/cli/index.js +55 -45
- package/dist/node/cli/index.js.map +1 -1
- package/dist/node/command/command.util.js +75 -75
- package/dist/node/command/command.util.js.map +1 -1
- package/dist/node/express/express.util.js +16 -16
- package/dist/node/express/express.util.js.map +1 -1
- package/dist/node/mongo/mongo.controller.d.ts +1 -1
- package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
- package/dist/node/mongo/mongo.dynamic-populate.js +64 -64
- package/dist/node/mongo/mongo.dynamic-populate.js.map +1 -1
- package/dist/node/mongo/mongo.populate.js.map +1 -1
- package/dist/node/mongo/mongo.util.d.ts +16 -16
- package/dist/node/mongo/mongo.util.js.map +1 -1
- package/dist/node/path/path.constant.js +9 -9
- package/dist/node/path/path.constant.js.map +1 -1
- package/dist/node/ws/index.d.ts +1 -1
- package/dist/node_modules/.pnpm/{vitest@4.0.18_@types_node@25.3.3_jiti@2.6.1_jsdom@28.1.0_@noble_hashes@1.8.0__sass@1.97.3_tsx@4.21.0_yaml@2.8.2 → vitest@4.0.18_@types_node@25.3.5_jiti@2.6.1_jsdom@28.1.0_@noble_hashes@1.8.0__sass@1.97.3_tsx@4.21.0_yaml@2.8.2}/node_modules/vitest/dist/config.js.map +1 -1
- package/dist/react/apollo-client/apollo-client.util.js +13 -13
- package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
- package/dist/react/apollo-error/apollo-error.component.js +22 -21
- package/dist/react/apollo-error/apollo-error.component.js.map +1 -1
- package/dist/util/common/common.util.js +26 -25
- package/dist/util/common/common.util.js.map +1 -1
- package/dist/util/object/object.util.js +49 -49
- package/dist/util/object/object.util.js.map +1 -1
- package/dist/util/serializer/serializer.util.js +12 -12
- package/dist/util/serializer/serializer.util.js.map +1 -1
- package/dist/util/string/string.util.js +29 -28
- package/dist/util/string/string.util.js.map +1 -1
- package/dist/util/validate/validate.util.d.ts +0 -4
- package/dist/util/validate/validate.util.js +3 -3
- package/dist/util/validate/validate.util.js.map +1 -1
- package/package.json +31 -29
- package/public/tsconfig.base.json +1 -1
- package/dist/config/config.test.unit.d.ts +0 -1
- package/dist/config/config.type.test.unit.d.ts +0 -1
- package/dist/constant/constant.test.unit.d.ts +0 -1
- package/dist/node/command/command.test.unit.d.ts +0 -1
- package/dist/node/fs/fs.test.unit.d.ts +0 -1
- package/dist/node/log/log.test.unit.d.ts +0 -1
- package/dist/node/mongo/mongo.controller.test.unit.d.ts +0 -1
- package/dist/node/mongo/mongo.util.test.unit.d.ts +0 -1
- package/dist/node/package/package.test.unit.d.ts +0 -1
- package/dist/node/path/path.test.unit.d.ts +0 -1
- package/dist/react/apollo-error/apollo-error.test.unit.d.ts +0 -1
- package/dist/react/loading/loading.test.unit.d.ts +0 -1
- package/dist/react/storage/storage.test.unit.d.ts +0 -1
- package/dist/typescript/typescript.test.unit.d.ts +0 -1
- package/dist/util/common/common.test.unit.d.ts +0 -1
- package/dist/util/object/object.test.unit.d.ts +0 -1
- package/dist/util/serializer/serializer.test.unit.d.ts +0 -1
- package/dist/util/string/string.test.unit.d.ts +0 -1
- package/dist/util/validate/validate.test.unit.d.ts +0 -1
- /package/dist/node_modules/.pnpm/{vitest@4.0.18_@types_node@25.3.3_jiti@2.6.1_jsdom@28.1.0_@noble_hashes@1.8.0__sass@1.97.3_tsx@4.21.0_yaml@2.8.2 → vitest@4.0.18_@types_node@25.3.5_jiti@2.6.1_jsdom@28.1.0_@noble_hashes@1.8.0__sass@1.97.3_tsx@4.21.0_yaml@2.8.2}/node_modules/vitest/dist/config.js +0 -0
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
import { exec as
|
|
1
|
+
import { exec as x, execFile as I } from "node:child_process";
|
|
2
2
|
import m from "node:process";
|
|
3
|
-
import * as
|
|
3
|
+
import * as C from "node:util";
|
|
4
4
|
import { storage as g } from "../storage/storage.util.js";
|
|
5
|
-
import { getPackage as
|
|
6
|
-
import { CYBERSKILL_PACKAGE_NAME as
|
|
5
|
+
import { getPackage as $ } from "../package/package.util.js";
|
|
6
|
+
import { CYBERSKILL_PACKAGE_NAME as d, PNPM_EXEC_CLI as w, TSX_CLI as P, CYBERSKILL_CLI_PATH as S, CYBERSKILL_CLI as T } from "../path/path.constant.js";
|
|
7
7
|
import { E_IssueType as f } from "../log/log.type.js";
|
|
8
|
-
import { log as u, catchError as
|
|
9
|
-
import { getEnv as
|
|
10
|
-
const
|
|
8
|
+
import { log as u, catchError as E } from "../log/log.util.js";
|
|
9
|
+
import { getEnv as _ } from "../../config/env/env.util.js";
|
|
10
|
+
const O = C.promisify(x), A = C.promisify(I), N = /[|&;<>`$(){}[\]!#~*?]/, M = /^\s*(\d+):(\d+)\s+(error|warning)\s+(.+)\s+(\S+)$/, k = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+TS\d+:\s+(\S.+)$/, B = /^✖\s+(.+)\s+\[([^\]]*)\]$/, v = /\s+/;
|
|
11
11
|
async function h() {
|
|
12
|
-
const t = await
|
|
12
|
+
const t = await $();
|
|
13
13
|
return t.success ? t.result.name : Date.now().toString();
|
|
14
14
|
}
|
|
15
|
-
async function
|
|
15
|
+
async function L(t) {
|
|
16
16
|
if (t.length === 0)
|
|
17
17
|
return;
|
|
18
18
|
const r = await h();
|
|
19
19
|
try {
|
|
20
|
-
const
|
|
21
|
-
await g.set(r,
|
|
22
|
-
const
|
|
23
|
-
|
|
20
|
+
const o = [...await j(), ...t];
|
|
21
|
+
await g.set(r, o), setTimeout(async () => {
|
|
22
|
+
const e = await g.getLogLink(r);
|
|
23
|
+
e && u.info(`📂 Open the error list manually: ${e}`);
|
|
24
24
|
}, 0);
|
|
25
|
-
} catch (
|
|
26
|
-
|
|
25
|
+
} catch (s) {
|
|
26
|
+
E(s);
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
async function
|
|
29
|
+
async function j() {
|
|
30
30
|
try {
|
|
31
31
|
const t = await h();
|
|
32
32
|
return await g.get(t) ?? [];
|
|
33
33
|
} catch (t) {
|
|
34
|
-
return
|
|
34
|
+
return E(t, {
|
|
35
35
|
returnValue: []
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
|
-
async function
|
|
39
|
+
async function V() {
|
|
40
40
|
try {
|
|
41
41
|
const t = await h();
|
|
42
42
|
await g.remove(t);
|
|
43
43
|
} catch (t) {
|
|
44
|
-
|
|
44
|
+
E(t);
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
async function
|
|
48
|
-
const r = [],
|
|
49
|
-
let
|
|
50
|
-
const
|
|
47
|
+
async function D(t) {
|
|
48
|
+
const r = [], s = [];
|
|
49
|
+
let o = "";
|
|
50
|
+
const e = M, i = k, n = B;
|
|
51
51
|
t.split(`
|
|
52
52
|
`).forEach((a) => {
|
|
53
53
|
if (a.startsWith("/"))
|
|
54
|
-
|
|
54
|
+
o = a.trim();
|
|
55
55
|
else {
|
|
56
|
-
const c =
|
|
57
|
-
c.length &&
|
|
58
|
-
file:
|
|
56
|
+
const c = e.exec(a) || [], l = i.exec(a) || [], p = n.exec(a) || [];
|
|
57
|
+
c.length && o ? r.push({
|
|
58
|
+
file: o,
|
|
59
59
|
position: `${c[1]}:${c[2]}`,
|
|
60
60
|
type: c[3] === f.Error ? f.Error : f.Warning,
|
|
61
61
|
message: c?.[4]?.trim() ?? "",
|
|
@@ -65,97 +65,97 @@ async function v(t) {
|
|
|
65
65
|
position: `${l[2]}:${l[3]}`,
|
|
66
66
|
type: l[4] === f.Error ? f.Error : f.Warning,
|
|
67
67
|
message: l?.[5]?.trim() ?? ""
|
|
68
|
-
}) :
|
|
68
|
+
}) : p.length ? r.push({
|
|
69
69
|
file: "commitlint",
|
|
70
70
|
type: f.Error,
|
|
71
|
-
message:
|
|
72
|
-
rule:
|
|
73
|
-
}) :
|
|
71
|
+
message: p?.[1]?.trim() ?? "",
|
|
72
|
+
rule: p?.[2]?.trim() ?? ""
|
|
73
|
+
}) : s.push(a.trim());
|
|
74
74
|
}
|
|
75
|
-
}), r.length && await
|
|
75
|
+
}), r.length && await L(r), s.length && (u.warn("Unmatched lines:"), s.forEach((a) => u.info(` ${a}`)));
|
|
76
76
|
}
|
|
77
|
-
async function
|
|
77
|
+
async function R(t) {
|
|
78
78
|
try {
|
|
79
|
-
const r = JSON.parse(t),
|
|
80
|
-
r.forEach(({ filePath:
|
|
81
|
-
|
|
82
|
-
|
|
79
|
+
const r = JSON.parse(t), s = [];
|
|
80
|
+
r.forEach(({ filePath: o, messages: e }) => {
|
|
81
|
+
e.forEach(({ severity: i, line: n, column: a, ruleId: c, message: l }) => {
|
|
82
|
+
s.push({
|
|
83
83
|
type: i === 2 ? f.Error : f.Warning,
|
|
84
|
-
file:
|
|
84
|
+
file: o,
|
|
85
85
|
position: `${n}:${a}`,
|
|
86
86
|
rule: c,
|
|
87
87
|
message: l
|
|
88
88
|
});
|
|
89
89
|
});
|
|
90
|
-
}),
|
|
90
|
+
}), s.length && await L(s);
|
|
91
91
|
} catch {
|
|
92
|
-
await
|
|
92
|
+
await D(t);
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
-
async function
|
|
96
|
-
const
|
|
95
|
+
async function K(t, r = R, s = {}) {
|
|
96
|
+
const o = new AbortController();
|
|
97
97
|
m.on("SIGINT", () => {
|
|
98
|
-
u.warn("Process interrupted. Terminating..."),
|
|
98
|
+
u.warn("Process interrupted. Terminating..."), o.abort(), m.exit();
|
|
99
99
|
});
|
|
100
100
|
try {
|
|
101
101
|
if (typeof t == "string") {
|
|
102
|
-
const
|
|
102
|
+
const e = {
|
|
103
103
|
maxBuffer: 10485760,
|
|
104
|
-
signal:
|
|
105
|
-
timeout:
|
|
104
|
+
signal: o.signal,
|
|
105
|
+
timeout: s.timeout
|
|
106
106
|
};
|
|
107
107
|
let i;
|
|
108
108
|
if (N.test(t))
|
|
109
|
-
i = await
|
|
109
|
+
i = await O(t, e);
|
|
110
110
|
else {
|
|
111
|
-
const n = t.split(
|
|
112
|
-
i = await
|
|
111
|
+
const n = t.split(v).filter(Boolean);
|
|
112
|
+
i = await A(n[0], n.slice(1), e);
|
|
113
113
|
}
|
|
114
114
|
await Promise.all([i.stdout, i.stderr].map((n) => n && r(n)));
|
|
115
115
|
}
|
|
116
|
-
} catch (
|
|
117
|
-
const { stdout: i, stderr: n, message: a } =
|
|
118
|
-
await Promise.all([i, n].map((c) => c && r(c))), !n && !i && u.error(`Command failed: ${a}`);
|
|
116
|
+
} catch (e) {
|
|
117
|
+
const { stdout: i, stderr: n, message: a } = e;
|
|
118
|
+
throw await Promise.all([i, n].map((c) => c && r(c))), !n && !i && u.error(`Command failed: ${a}`), e;
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
|
-
function
|
|
121
|
+
function q(t) {
|
|
122
122
|
return { raw: !0, cmd: t };
|
|
123
123
|
}
|
|
124
124
|
function y(t, r) {
|
|
125
|
-
return r?.isCurrentProject ? `${w} ${
|
|
125
|
+
return r?.isCurrentProject ? `${w} ${P} ${S} ${t}` : `${w} ${T} ${t}`;
|
|
126
126
|
}
|
|
127
|
-
function
|
|
127
|
+
function W(t, r) {
|
|
128
128
|
return typeof t == "function" ? y(t(r), r) : typeof t == "object" && t?.raw === !0 ? t.cmd : typeof t == "string" ? y(t, r) : t;
|
|
129
129
|
}
|
|
130
|
-
async function
|
|
131
|
-
const r = await
|
|
130
|
+
async function z(t) {
|
|
131
|
+
const r = await $({ name: d });
|
|
132
132
|
if (r.success) {
|
|
133
|
-
const
|
|
133
|
+
const s = { isCurrentProject: r.result.isCurrentProject }, o = typeof t == "function" ? t(s) : t;
|
|
134
134
|
return Object.fromEntries(
|
|
135
|
-
Object.entries(
|
|
135
|
+
Object.entries(o).map(([e, i]) => [e, W(i, s)])
|
|
136
136
|
);
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
|
-
async function
|
|
140
|
-
let
|
|
139
|
+
async function Q(t, r, s = {}) {
|
|
140
|
+
let o;
|
|
141
141
|
try {
|
|
142
|
-
const
|
|
143
|
-
u.start(`${t}`),
|
|
144
|
-
const i = Math.floor((Date.now() -
|
|
142
|
+
const e = Date.now();
|
|
143
|
+
u.start(`${t}`), _().DEBUG ? u.info(`→ ${r}`) : o = setInterval(() => {
|
|
144
|
+
const i = Math.floor((Date.now() - e) / 1e3);
|
|
145
145
|
i > 0 && m.stdout.write(`\r⏳ ${t}... ${i}s`);
|
|
146
|
-
}, 100), await
|
|
147
|
-
} catch (
|
|
148
|
-
if (
|
|
149
|
-
throw
|
|
150
|
-
|
|
146
|
+
}, 100), await K(r, R, s), o && (clearInterval(o), m.stdout.write("\r\x1B[K")), u.success(`${t} done.`);
|
|
147
|
+
} catch (e) {
|
|
148
|
+
if (o && (clearInterval(o), m.stdout.write("\r\x1B[K")), s.throwOnError)
|
|
149
|
+
throw e;
|
|
150
|
+
E(e);
|
|
151
151
|
}
|
|
152
152
|
}
|
|
153
153
|
export {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
154
|
+
V as clearAllErrorLists,
|
|
155
|
+
W as formatCommand,
|
|
156
|
+
j as getStoredErrorLists,
|
|
157
|
+
q as rawCommand,
|
|
158
|
+
z as resolveCommands,
|
|
159
|
+
Q as runCommand
|
|
160
160
|
};
|
|
161
161
|
//# sourceMappingURL=command.util.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"command.util.js","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\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 = /^\\s*(\\d+):(\\d+)\\s+(error|warning)\\s+(.+)\\s+(\\S+)$/;\n const tsRegex = /^(.+?)\\((\\d+),(\\d+)\\):\\s+(error|warning)\\s+TS\\d+:\\s+(\\S.+)$/;\n const commitlintRegex = /^✖\\s+(.+)\\s+\\[([^\\]]*)\\]$/;\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 (getEnv().DEBUG && 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(/\\s+/).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}\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"],"names":["exec","execFile","process","util","storage","getPackage","CYBERSKILL_PACKAGE_NAME","PNPM_EXEC_CLI","TSX_CLI","CYBERSKILL_CLI_PATH","CYBERSKILL_CLI","E_IssueType","log","catchError","getEnv","execPromise","execFilePromise","SHELL_METACHARACTERS","getPackageName","pkg","saveErrorListToStorage","errorList","packageName","mergedErrors","getStoredErrorLists","logPath","error","clearAllErrorLists","parseTextErrors","output","unmatchedLines","lastFilePath","eslintErrorDetailsRegex","tsRegex","commitlintRegex","line","eslintMatch","tsMatch","commitlintMatch","parseCommandOutput","results","filePath","messages","severity","column","ruleId","message","executeCommand","command","parser","options","controller","execOptions","result","parts","stdout","stderr","rawCommand","cmd","formatCLI","context","formatCommand","resolveCommands","input","packageData","ctx","commands","key","runCommand","label","timer","startTime","elapsed"],"mappings":"AAcA,SAAA,QAAAA,GAAA,YAAAC,SAAA;AAAA,OAAAC,OAAA;AAAA,YAAAC,OAAA;AAAA,SAAA,WAAAC,SAAA;AAAA,SAAA,cAAAC,SAAA;AAAA,SAAA,2BAAAC,GAAA,iBAAAC,GAAA,WAAAC,GAAA,uBAAAC,GAAA,kBAAAC,SAAA;AAAA,SAAA,eAAAC,SAAA;AAAA,SAAA,OAAAC,GAAA,cAAAC,SAAA;AAAA,SAAA,UAAAC,SAAA;AAAA,MAAMC,IAAcZ,EAAK,UAAUH,CAAI,GACjCgB,IAAkBb,EAAK,UAAUF,CAAQ,GACzCgB,IAAuB;AAS7B,eAAeC,IAAiB;AAC5B,QAAMC,IAAM,MAAMd,EAAA;AAElB,SAAKc,EAAI,UAIFA,EAAI,OAAO,OAHP,KAAK,IAAA,EAAM,SAAA;AAI1B;AAUA,eAAeC,EAAuBC,GAA0C;AAC5E,MAAIA,EAAU,WAAW;AACrB;AAGJ,QAAMC,IAAc,MAAMJ,EAAA;AAE1B,MAAI;AAEA,UAAMK,IAAe,CAA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B,IAAQ,YAAY,MAAM;AACtB,YAAME,IAAU,KAAK,OAAO,KAAK,IAAA,IAAQD,KAAa,GAAI;AAE1D,MAAIC,IAAU,KACVtE,EAAQ,OAAO,MAAM,OAAOmE,CAAK,OAAOG,CAAO,GAAG;AAAA,IAE1D,GAAG,GAAG,GAGV,MAAMzB,EAAeC,GAAST,GAAoBW,CAAO,GAErDoB,MACA,cAAcA,CAAK,GACnBpE,EAAQ,OAAO,MAAM,UAAU,IAGnCU,EAAI,QAAQ,GAAGyD,CAAK,QAAQ;AAAA,EAChC,SACO3C,GAAO;AAMV,QALI4C,MACA,cAAcA,CAAK,GACnBpE,EAAQ,OAAO,MAAM,UAAU,IAG/BgD,EAAQ;AACR,YAAMxB;AAEV,IAAAb,EAAWa,CAAK;AAAA,EACpB;AACJ;"}
|
|
1
|
+
{"version":3,"file":"command.util.js","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"],"names":["exec","execFile","process","util","storage","getPackage","CYBERSKILL_PACKAGE_NAME","PNPM_EXEC_CLI","TSX_CLI","CYBERSKILL_CLI_PATH","CYBERSKILL_CLI","E_IssueType","log","catchError","getEnv","execPromise","execFilePromise","SHELL_METACHARACTERS","RE_ESLINT_ERROR","RE_TS_ERROR","RE_COMMITLINT_ERROR","RE_WHITESPACE","getPackageName","pkg","saveErrorListToStorage","errorList","packageName","mergedErrors","getStoredErrorLists","logPath","error","clearAllErrorLists","parseTextErrors","output","unmatchedLines","lastFilePath","eslintErrorDetailsRegex","tsRegex","commitlintRegex","line","eslintMatch","tsMatch","commitlintMatch","parseCommandOutput","results","filePath","messages","severity","column","ruleId","message","executeCommand","command","parser","options","controller","execOptions","result","parts","stdout","stderr","rawCommand","cmd","formatCLI","context","formatCommand","resolveCommands","input","packageData","ctx","commands","key","runCommand","label","timer","startTime","elapsed"],"mappings":"AAcA,SAAA,QAAAA,GAAA,YAAAC,SAAA;AAAA,OAAAC,OAAA;AAAA,YAAAC,OAAA;AAAA,SAAA,WAAAC,SAAA;AAAA,SAAA,cAAAC,SAAA;AAAA,SAAA,2BAAAC,GAAA,iBAAAC,GAAA,WAAAC,GAAA,uBAAAC,GAAA,kBAAAC,SAAA;AAAA,SAAA,eAAAC,SAAA;AAAA,SAAA,OAAAC,GAAA,cAAAC,SAAA;AAAA,SAAA,UAAAC,SAAA;AAAA,MAAMC,IAAcZ,EAAK,UAAUH,CAAI,GACjCgB,IAAkBb,EAAK,UAAUF,CAAQ,GACzCgB,IAAuB,yBAEvBC,IAAkB,qDAClBC,IAAc,+DAEdC,IAAsB,6BACtBC,IAAgB;AAStB,eAAeC,IAAiB;AAC5B,QAAMC,IAAM,MAAMlB,EAAA;AAElB,SAAKkB,EAAI,UAIFA,EAAI,OAAO,OAHP,KAAK,IAAA,EAAM,SAAA;AAI1B;AAUA,eAAeC,EAAuBC,GAA0C;AAC5E,MAAIA,EAAU,WAAW;AACrB;AAGJ,QAAMC,IAAc,MAAMJ,EAAA;AAE1B,MAAI;AAEA,UAAMK,IAAe,CAAC,GADC,MAAMC,EAAA,GACY,GAAGH,CAAS;AAErD,UAAMrB,EAAQ,IAAIsB,GAAaC,CAAY,GAE3C,WAAW,YAAY;AACnB,YAAME,IAAU,MAAMzB,EAAQ,WAAWsB,CAAW;AAEpD,MAAIG,KACAjB,EAAI,KAAK,oCAAoCiB,CAAO,EAAE;AAAA,IAE9D,GAAG,CAAC;AAAA,EACR,SACOC,GAAO;AACV,IAAAjB,EAAWiB,CAAK;AAAA,EACpB;AACJ;AAQA,eAAsBF,IAA+C;AACjE,MAAI;AACA,UAAMF,IAAc,MA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EAChC,SACO3C,GAAO;AAMV,QALI4C,MACA,cAAcA,CAAK,GACnBxE,EAAQ,OAAO,MAAM,UAAU,IAG/BoD,EAAQ;AACR,YAAMxB;AAEV,IAAAjB,EAAWiB,CAAK;AAAA,EACpB;AACJ;"}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import u from "
|
|
2
|
-
import
|
|
3
|
-
import l from "
|
|
4
|
-
import m from "
|
|
5
|
-
import f from "cors";
|
|
1
|
+
import { NestFactory as u } from "@nestjs/core";
|
|
2
|
+
import n from "compression";
|
|
3
|
+
import l from "cookie-parser";
|
|
4
|
+
import m from "cors";
|
|
6
5
|
import i from "express";
|
|
7
6
|
import { default as G } from "express";
|
|
8
|
-
import
|
|
9
|
-
import { express as
|
|
10
|
-
import
|
|
11
|
-
import
|
|
7
|
+
import f from "express-session";
|
|
8
|
+
import { express as d } from "express-useragent";
|
|
9
|
+
import p from "graphql-upload/graphqlUploadExpress.mjs";
|
|
10
|
+
import x from "helmet";
|
|
11
|
+
import y from "node:process";
|
|
12
12
|
function E({ isDev: e, whiteList: r, ...t }) {
|
|
13
13
|
return {
|
|
14
14
|
origin: (s, o) => {
|
|
@@ -19,7 +19,7 @@ function E({ isDev: e, whiteList: r, ...t }) {
|
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
21
|
function F(e) {
|
|
22
|
-
return
|
|
22
|
+
return m(E(e));
|
|
23
23
|
}
|
|
24
24
|
function P(e) {
|
|
25
25
|
const r = {
|
|
@@ -28,10 +28,10 @@ function P(e) {
|
|
|
28
28
|
cookie: {
|
|
29
29
|
httpOnly: !0,
|
|
30
30
|
sameSite: "lax",
|
|
31
|
-
secure:
|
|
31
|
+
secure: y.env.NODE_ENV === "production"
|
|
32
32
|
}
|
|
33
33
|
};
|
|
34
|
-
return
|
|
34
|
+
return f({
|
|
35
35
|
...r,
|
|
36
36
|
...e,
|
|
37
37
|
cookie: { ...r.cookie, ...e.cookie }
|
|
@@ -39,11 +39,11 @@ function P(e) {
|
|
|
39
39
|
}
|
|
40
40
|
function c(e, r = !1, t = "1mb") {
|
|
41
41
|
e.set("trust proxy", 1), e.use(
|
|
42
|
-
|
|
42
|
+
x({
|
|
43
43
|
crossOriginEmbedderPolicy: r ? !1 : void 0,
|
|
44
44
|
contentSecurityPolicy: r ? !1 : void 0
|
|
45
45
|
})
|
|
46
|
-
), e.use(
|
|
46
|
+
), e.use(l()), e.use(i.json({ limit: t })), e.use(i.urlencoded({ extended: !0, limit: t })), e.use(n()), e.use(d());
|
|
47
47
|
}
|
|
48
48
|
function a(e, r) {
|
|
49
49
|
r && (Array.isArray(r) ? r : [r]).forEach((s) => {
|
|
@@ -52,13 +52,13 @@ function a(e, r) {
|
|
|
52
52
|
}
|
|
53
53
|
function z(e) {
|
|
54
54
|
const r = i();
|
|
55
|
-
return c(r, e?.isDev, e?.jsonLimit), a(r, e?.static), r.use(
|
|
55
|
+
return c(r, e?.isDev, e?.jsonLimit), a(r, e?.static), r.use(p({
|
|
56
56
|
maxFileSize: e?.maxFileSize ?? 1e7,
|
|
57
57
|
maxFiles: e?.maxFiles ?? 10
|
|
58
58
|
})), r;
|
|
59
59
|
}
|
|
60
60
|
async function C(e) {
|
|
61
|
-
const r = await
|
|
61
|
+
const r = await u.create(e.module);
|
|
62
62
|
return c(r.getHttpAdapter().getInstance(), e.isDev, e.jsonLimit), a(r.getHttpAdapter().getInstance(), e.static), e.filters && r.useGlobalFilters(...e.filters), e.pipes && r.useGlobalPipes(...e.pipes), r;
|
|
63
63
|
}
|
|
64
64
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.util.js","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
|
|
1
|
+
{"version":3,"file":"express.util.js","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 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 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 */\nfunction setupMiddleware(app: Application, isDev = false, jsonLimit = '1mb') {\n app.set('trust proxy', 1);\n app.use(\n helmet({\n crossOriginEmbedderPolicy: isDev ? false : undefined,\n contentSecurityPolicy: isDev ? false : undefined,\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);\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);\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"],"names":["createCorsOptions","isDev","whiteList","rest","origin","callback","createCors","options","cors","createSession","secureDefaults","process","session","setupMiddleware","app","jsonLimit","helmet","cookieParser","express","compression","useragent","setupStaticFolders","staticFolders","folder","createExpress","graphqlUploadExpress","createNest","NestFactory"],"mappings":";;;;;;;;;;;AA4BO,SAASA,EAAwC,EAAE,OAAAC,GAAO,WAAAC,GAAW,GAAGC,KAA0B;AACrG,SAAO;AAAA,IACH,QAAQ,CAACC,GAA4BC,MAA2D;AAC5F,MAAIJ,KAAS,CAACG,KAAUF,GAAW,SAASE,KAAU,EAAE,IACpDC,EAAS,MAAM,EAAI,IAGnBA,EAAS,IAAI,MAAM,qBAAqB,GAAG,EAAK;AAAA,IAExD;AAAA,IACA,aAAa;AAAA,IACb,GAAGF;AAAA,EAAA;AAEX;AAUO,SAASG,EAAiCC,GAA2B;AACxE,SAAOC,EAAuBR,EAAkBO,CAAO,CAAC;AAC5D;AAUO,SAASE,EAAcF,GAAyC;AACnE,QAAMG,IAA0C;AAAA,IAC5C,QAAQ;AAAA,IACR,mBAAmB;AAAA,IACnB,QAAQ;AAAA,MACJ,UAAU;AAAA,MACV,UAAU;AAAA,MACV,QAAQC,EAAQ,IAAI,aAAgB;A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AiB,YAAA,GAAeP,EAAQ,OAAOA,EAAQ,SAAS,GACpFc,EAAmBP,EAAI,eAAA,EAAiB,YAAA,GAAeP,EAAQ,MAAM,GAEjEA,EAAQ,WACRO,EAAI,iBAAiB,GAAGP,EAAQ,OAAO,GAGvCA,EAAQ,SACRO,EAAI,eAAe,GAAGP,EAAQ,KAAK,GAGhCO;AACX;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
export * from './mongo.controller.mongoose.js';
|
|
1
2
|
/**
|
|
2
3
|
* Re-exports both MongoDB controller implementations.
|
|
3
4
|
* - MongoController: Native MongoDB driver operations
|
|
4
5
|
* - MongooseController: Mongoose ORM with pagination, aggregation, and slug generation
|
|
5
6
|
*/
|
|
6
7
|
export * from './mongo.controller.native.js';
|
|
7
|
-
export * from './mongo.controller.mongoose.js';
|