@cyberskill/shared 3.13.0 → 3.15.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/env/env.util.d.ts +5 -0
- package/dist/config/env/env.util.js +20 -16
- package/dist/config/env/env.util.js.map +1 -1
- package/dist/config/env/index.js +2 -2
- package/dist/config/vitest/vitest.e2e.js +4 -4
- package/dist/config/vitest/vitest.e2e.js.map +1 -1
- package/dist/config/vitest/vitest.unit.js +5 -5
- package/dist/config/vitest/vitest.unit.js.map +1 -1
- package/dist/config/vitest/vitest.unit.setup.js +10 -0
- package/dist/config/vitest/vitest.unit.setup.js.map +1 -0
- package/dist/node/apollo-server/apollo-server.type.d.ts +13 -1
- package/dist/node/apollo-server/apollo-server.util.d.ts +1 -0
- package/dist/node/apollo-server/apollo-server.util.js +40 -16
- package/dist/node/apollo-server/apollo-server.util.js.map +1 -1
- package/dist/node/cli/index.js +26 -28
- package/dist/node/cli/index.js.map +1 -1
- package/dist/node/command/command.util.d.ts +5 -0
- package/dist/node/command/command.util.js +49 -48
- package/dist/node/command/command.util.js.map +1 -1
- package/dist/node/command/index.js +2 -2
- package/dist/node/express/express.type.d.ts +11 -0
- package/dist/node/express/express.util.d.ts +34 -6
- package/dist/node/express/express.util.js +81 -56
- package/dist/node/express/express.util.js.map +1 -1
- package/dist/node/express/index.js +2 -2
- package/dist/node/log/log.type.d.ts +17 -0
- package/dist/node/log/log.type.js.map +1 -1
- package/dist/node/log/log.util.js +25 -11
- package/dist/node/log/log.util.js.map +1 -1
- package/dist/node/mongo/index.d.ts +2 -1
- package/dist/node/mongo/index.js +7 -8
- package/dist/node/mongo/mongo.constant.d.ts +5 -0
- package/dist/node/mongo/mongo.constant.js +2 -2
- package/dist/node/mongo/mongo.constant.js.map +1 -1
- package/dist/node/mongo/mongo.controller.mongoose.d.ts +3 -0
- package/dist/node/mongo/mongo.controller.mongoose.js +41 -55
- package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
- package/dist/node/mongo/mongo.controller.native.d.ts +29 -2
- package/dist/node/mongo/mongo.controller.native.js +31 -14
- package/dist/node/mongo/mongo.controller.native.js.map +1 -1
- package/dist/node/mongo/mongo.type.d.ts +3 -1
- package/dist/node/mongo/mongo.util.d.ts +1 -0
- package/dist/node/mongo/mongo.util.js +38 -17
- package/dist/node/mongo/mongo.util.js.map +1 -1
- package/dist/node/package/package.util.js +47 -47
- package/dist/node/path/index.js +2 -2
- package/dist/node/path/path.constant.d.ts +4 -0
- package/dist/node/path/path.constant.js +75 -72
- package/dist/node/path/path.constant.js.map +1 -1
- package/dist/node/storage/storage.util.d.ts +50 -1
- package/dist/node/storage/storage.util.js +79 -54
- package/dist/node/storage/storage.util.js.map +1 -1
- package/dist/node/upload/upload.type.d.ts +2 -0
- package/dist/node/upload/upload.type.js.map +1 -1
- package/dist/node/upload/upload.util.d.ts +1 -0
- package/dist/node/upload/upload.util.js +62 -52
- package/dist/node/upload/upload.util.js.map +1 -1
- package/dist/node/ws/ws.util.d.ts +7 -0
- package/dist/node/ws/ws.util.js +20 -19
- package/dist/node/ws/ws.util.js.map +1 -1
- package/dist/react/apollo-client/apollo-client.component.js.map +1 -1
- package/dist/react/apollo-client/apollo-client.type.d.ts +2 -0
- package/dist/react/apollo-client/apollo-client.util.js +6 -6
- package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
- package/dist/react/apollo-error/apollo-error.component.js +1 -1
- package/dist/react/apollo-error/apollo-error.component.js.map +1 -1
- package/dist/react/apollo-error/apollo-error.util.js.map +1 -1
- package/dist/react/i18next/i18next.server.d.ts +17 -0
- package/dist/react/i18next/i18next.server.js +9 -0
- package/dist/react/i18next/i18next.server.js.map +1 -0
- package/dist/react/next-intl/next-intl.hoc.d.ts +4 -8
- package/dist/react/next-intl/next-intl.hoc.js +14 -10
- package/dist/react/next-intl/next-intl.hoc.js.map +1 -1
- package/dist/react/next-intl/next-intl.server.d.ts +10 -0
- package/dist/react/next-intl/next-intl.server.js +7 -0
- package/dist/react/next-intl/next-intl.server.js.map +1 -0
- package/dist/react/storage/storage.util.d.ts +34 -1
- package/dist/react/storage/storage.util.js +30 -5
- package/dist/react/storage/storage.util.js.map +1 -1
- package/dist/react/userback/userback.component.js.map +1 -1
- package/dist/typescript/common.type.d.ts +4 -0
- package/dist/typescript/common.type.js +2 -2
- package/dist/typescript/common.type.js.map +1 -1
- package/dist/typescript/index.js +2 -2
- package/dist/util/object/object.util.js +29 -18
- package/dist/util/object/object.util.js.map +1 -1
- package/dist/util/serializer/serializer.util.d.ts +8 -0
- package/dist/util/serializer/serializer.util.js +51 -64
- package/dist/util/serializer/serializer.util.js.map +1 -1
- package/dist/util/storage/storage-envelope.d.ts +25 -0
- package/dist/util/storage/storage-envelope.js +18 -0
- package/dist/util/storage/storage-envelope.js.map +1 -0
- package/package.json +33 -12
- package/dist/node/mongo/mongo.type.js +0 -8
- package/dist/node/mongo/mongo.type.js.map +0 -1
- package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js +0 -8
- package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { E_IssueType as e } from "../log/log.type.js";
|
|
2
|
+
import { getEnv as t } from "../../config/env/env.util.js";
|
|
3
3
|
import { catchError as n, log as r } from "../log/log.util.js";
|
|
4
4
|
import { getPackage as i } from "../package/package.util.js";
|
|
5
5
|
import { storage as a } from "../storage/storage.util.js";
|
|
@@ -14,11 +14,14 @@ async function S() {
|
|
|
14
14
|
let e = await i();
|
|
15
15
|
return e.success ? (x = e.result.name, x) : Date.now().toString();
|
|
16
16
|
}
|
|
17
|
-
|
|
17
|
+
function C() {
|
|
18
|
+
x = null;
|
|
19
|
+
}
|
|
20
|
+
async function w(e) {
|
|
18
21
|
if (e.length === 0) return;
|
|
19
22
|
let t = await S();
|
|
20
23
|
try {
|
|
21
|
-
let n = [...await
|
|
24
|
+
let n = [...await T(), ...e];
|
|
22
25
|
await a.set(t, n);
|
|
23
26
|
let i = await a.getLogLink(t);
|
|
24
27
|
i && r.info(`📂 Open the error list manually: ${i}`);
|
|
@@ -26,7 +29,7 @@ async function C(e) {
|
|
|
26
29
|
n(e);
|
|
27
30
|
}
|
|
28
31
|
}
|
|
29
|
-
async function
|
|
32
|
+
async function T() {
|
|
30
33
|
try {
|
|
31
34
|
let e = await S();
|
|
32
35
|
return await a.get(e) ?? [];
|
|
@@ -34,7 +37,7 @@ async function w() {
|
|
|
34
37
|
return n(e, { returnValue: [] });
|
|
35
38
|
}
|
|
36
39
|
}
|
|
37
|
-
async function
|
|
40
|
+
async function E() {
|
|
38
41
|
try {
|
|
39
42
|
let e = await S();
|
|
40
43
|
await a.remove(e);
|
|
@@ -42,59 +45,57 @@ async function T() {
|
|
|
42
45
|
n(e);
|
|
43
46
|
}
|
|
44
47
|
}
|
|
45
|
-
async function
|
|
48
|
+
async function D(t) {
|
|
46
49
|
let n = [], i = [], a = "", o = _, s = v, c = y;
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
t.split("\n").forEach((t) => {
|
|
51
|
+
let r = s.exec(t);
|
|
52
|
+
if (r) n.push({
|
|
53
|
+
file: r?.[1] ?? "",
|
|
54
|
+
position: `${r[2]}:${r[3]}`,
|
|
55
|
+
type: r[4] === e.Error ? e.Error : e.Warning,
|
|
56
|
+
message: r?.[5]?.trim() ?? ""
|
|
57
|
+
});
|
|
58
|
+
else if (t.startsWith("/")) a = t.trim();
|
|
49
59
|
else {
|
|
50
|
-
let r = o.exec(
|
|
60
|
+
let r = o.exec(t);
|
|
51
61
|
if (r && a) n.push({
|
|
52
62
|
file: a,
|
|
53
63
|
position: `${r[1]}:${r[2]}`,
|
|
54
|
-
type: r[3] ===
|
|
64
|
+
type: r[3] === e.Error ? e.Error : e.Warning,
|
|
55
65
|
message: r?.[4]?.trim() ?? "",
|
|
56
66
|
rule: r?.[5]?.trim() ?? ""
|
|
57
67
|
});
|
|
58
68
|
else {
|
|
59
|
-
let r =
|
|
60
|
-
|
|
61
|
-
file:
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
-
}
|
|
69
|
+
let r = c.exec(t);
|
|
70
|
+
r ? n.push({
|
|
71
|
+
file: "commitlint",
|
|
72
|
+
type: e.Error,
|
|
73
|
+
message: r?.[1]?.trim() ?? "",
|
|
74
|
+
rule: r?.[2]?.trim() ?? ""
|
|
75
|
+
}) : i.push(t.trim());
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
|
-
}), n.length && await
|
|
78
|
+
}), n.length && await w(n), i.length && (r.warn("Unmatched lines:"), i.forEach((e) => r.info(` ${e}`)));
|
|
78
79
|
}
|
|
79
|
-
async function
|
|
80
|
+
async function O(t) {
|
|
80
81
|
try {
|
|
81
|
-
let n = JSON.parse(
|
|
82
|
-
n.forEach(({ filePath:
|
|
82
|
+
let n = JSON.parse(t), r = [];
|
|
83
|
+
n.forEach(({ filePath: t, messages: n }) => {
|
|
83
84
|
n.forEach(({ severity: n, line: i, column: a, ruleId: o, message: s }) => {
|
|
84
85
|
r.push({
|
|
85
|
-
type: n === 2 ?
|
|
86
|
-
file:
|
|
86
|
+
type: n === 2 ? e.Error : e.Warning,
|
|
87
|
+
file: t,
|
|
87
88
|
position: `${i}:${a}`,
|
|
88
89
|
rule: o,
|
|
89
90
|
message: s
|
|
90
91
|
});
|
|
91
92
|
});
|
|
92
|
-
}), r.length && await
|
|
93
|
+
}), r.length && await w(r);
|
|
93
94
|
} catch {
|
|
94
|
-
await
|
|
95
|
+
await D(t);
|
|
95
96
|
}
|
|
96
97
|
}
|
|
97
|
-
async function
|
|
98
|
+
async function k(e, t = O, n = {}) {
|
|
98
99
|
let i = new AbortController(), a = () => {
|
|
99
100
|
r.warn("Process interrupted. Terminating..."), i.abort(), u.exit(130);
|
|
100
101
|
};
|
|
@@ -120,33 +121,33 @@ async function O(e, t = D, n = {}) {
|
|
|
120
121
|
u.removeListener("SIGINT", a);
|
|
121
122
|
}
|
|
122
123
|
}
|
|
123
|
-
function
|
|
124
|
+
function A(e) {
|
|
124
125
|
return {
|
|
125
126
|
raw: !0,
|
|
126
127
|
cmd: e
|
|
127
128
|
};
|
|
128
129
|
}
|
|
129
|
-
function
|
|
130
|
+
function j(e, t) {
|
|
130
131
|
return t?.isCurrentProject ? `${l} tsx ${s} ${e}` : `${l} ${o} ${e}`;
|
|
131
132
|
}
|
|
132
|
-
function
|
|
133
|
-
return typeof e == "function" ?
|
|
133
|
+
function M(e, t) {
|
|
134
|
+
return typeof e == "function" ? j(e(t), t) : typeof e == "object" && e?.raw === !0 ? e.cmd : typeof e == "string" ? j(e, t) : e;
|
|
134
135
|
}
|
|
135
|
-
async function
|
|
136
|
+
async function N(e) {
|
|
136
137
|
let t = await i({ name: c });
|
|
137
138
|
if (t.success) {
|
|
138
139
|
let n = { isCurrentProject: t.result.isCurrentProject }, r = typeof e == "function" ? e(n) : e;
|
|
139
|
-
return Object.fromEntries(Object.entries(r).map(([e, t]) => [e,
|
|
140
|
+
return Object.fromEntries(Object.entries(r).map(([e, t]) => [e, M(t, n)]));
|
|
140
141
|
}
|
|
141
142
|
}
|
|
142
|
-
async function
|
|
143
|
+
async function P(e, i, a = {}) {
|
|
143
144
|
let o;
|
|
144
145
|
try {
|
|
145
146
|
let n = Date.now();
|
|
146
|
-
r.start(`${
|
|
147
|
-
let
|
|
148
|
-
|
|
149
|
-
}, 1e3), await
|
|
147
|
+
r.start(`${e}`), t().DEBUG ? r.info(`→ ${i}`) : o = setInterval(() => {
|
|
148
|
+
let t = Math.floor((Date.now() - n) / 1e3);
|
|
149
|
+
t > 0 && u.stdout.write(`\r⏳ ${e}... ${t}s`);
|
|
150
|
+
}, 1e3), await k(i, O, a), r.success(`${e} done.`);
|
|
150
151
|
} catch (e) {
|
|
151
152
|
if (a.throwOnError) throw e;
|
|
152
153
|
n(e);
|
|
@@ -155,6 +156,6 @@ async function N(t, i, a = {}) {
|
|
|
155
156
|
}
|
|
156
157
|
}
|
|
157
158
|
//#endregion
|
|
158
|
-
export {
|
|
159
|
+
export { E as clearAllErrorLists, M as formatCommand, T as getStoredErrorLists, A as rawCommand, C as resetCommandCacheForTesting, N as resolveCommands, P as runCommand };
|
|
159
160
|
|
|
160
161
|
//# sourceMappingURL=command.util.js.map
|
|
@@ -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 = /[|&;<>`$(){}[\\]!#~*?]/;\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 * Results are cached after first successful read to avoid redundant I/O.\n *\n * @returns A promise that resolves to the package name or a timestamp string.\n */\nlet _cachedPackageName: string | null = null;\n/** Returns the cached package name, falling back to a timestamp if unavailable. */\nasync function getPackageName() {\n if (_cachedPackageName) {\n return _cachedPackageName;\n }\n\n const pkg = await getPackage();\n\n if (!pkg.success) {\n return Date.now().toString();\n }\n\n _cachedPackageName = pkg.result.name;\n return _cachedPackageName;\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 const logPath = await storage.getLogLink(packageName);\n if (logPath) {\n log.info(`📂 Open the error list manually: ${logPath}`);\n }\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,OAUlB,IAAoC;AAExC,eAAe,IAAiB;AAC5B,KAAI,EACA,Q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AAS;EACrB,IAAM,IAAwB,EAAE,kBAAkB,EAAY,OAAO,kBAAkB,EACjF,IAAW,OAAO,KAAU,aAAa,EAAM,EAAI,GAAG;AAE5D,SAAO,OAAO,YACV,OAAO,QAAQ,EAAS,CAAC,KAAK,CAAC,GAAK,OAAS,CAAC,GAAK,EAAc,GAAK,EAAI,CAAC,CAAC,CAC/E;;;AAeT,eAAsB,EAAW,GAAe,GAAwB,IAAwD,EAAE,EAAE;CAChI,IAAI;AAEJ,KAAI;EACA,IAAM,IAAY,KAAK,KAAK;AAkB5B,EAjBA,EAAI,MAAM,GAAG,IAAQ,EAEjB,GAAQ,CAAC,QACT,EAAI,KAAK,KAAK,IAAU,GAGxB,IAAQ,kBAAkB;GACtB,IAAM,IAAU,KAAK,OAAO,KAAK,KAAK,GAAG,KAAa,IAAK;AAE3D,GAAI,IAAU,KACV,EAAQ,OAAO,MAAM,OAAO,EAAM,MAAM,EAAQ,GAAG;KAExD,IAAK,EAGZ,MAAM,EAAe,GAAS,GAAoB,EAAQ,EAE1D,EAAI,QAAQ,GAAG,EAAM,QAAQ;UAE1B,GAAO;AACV,MAAI,EAAQ,aACR,OAAM;AAEV,IAAW,EAAM;WAEb;AACJ,EAAI,MACA,cAAc,EAAM,EACpB,EAAQ,OAAO,MAAM,WAAW"}
|
|
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 * Results are cached after first successful read to avoid redundant I/O.\n *\n * @returns A promise that resolves to the package name or a timestamp string.\n */\nlet _cachedPackageName: string | null = null;\n/** Returns the cached package name, falling back to a timestamp if unavailable. */\nasync function getPackageName() {\n if (_cachedPackageName) {\n return _cachedPackageName;\n }\n\n const pkg = await getPackage();\n\n if (!pkg.success) {\n return Date.now().toString();\n }\n\n _cachedPackageName = pkg.result.name;\n return _cachedPackageName;\n}\n\n/**\n * Resets the cached package name. For testing only.\n * Call this to force `getPackageName()` to re-read the package.json on the next invocation.\n */\nexport function resetCommandCacheForTesting(): void {\n _cachedPackageName = null;\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 const logPath = await storage.getLogLink(packageName);\n if (logPath) {\n log.info(`📂 Open the error list manually: ${logPath}`);\n }\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 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 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 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 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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awCommand as i,
|
|
3
|
-
export { e as E_CommandType, t as clearAllErrorLists, n as formatCommand, r as getStoredErrorLists, i as rawCommand, a as
|
|
2
|
+
import { clearAllErrorLists as t, formatCommand as n, getStoredErrorLists as r, rawCommand as i, resetCommandCacheForTesting as a, resolveCommands as o, runCommand as s } from "./command.util.js";
|
|
3
|
+
export { e as E_CommandType, t as clearAllErrorLists, n as formatCommand, r as getStoredErrorLists, i as rawCommand, a as resetCommandCacheForTesting, o as resolveCommands, s as runCommand };
|
|
@@ -9,6 +9,7 @@ export interface I_RateLimitOptions {
|
|
|
9
9
|
limit?: number;
|
|
10
10
|
store?: Store;
|
|
11
11
|
skip?: (req: import('express').Request) => boolean | Promise<boolean>;
|
|
12
|
+
keyGenerator?: (req: import('express').Request, res: import('express').Response) => string | Promise<string>;
|
|
12
13
|
}
|
|
13
14
|
export interface I_ExpressOptions {
|
|
14
15
|
isDev?: boolean;
|
|
@@ -20,6 +21,11 @@ export interface I_ExpressOptions {
|
|
|
20
21
|
rateLimit?: false | I_RateLimitOptions;
|
|
21
22
|
/** Route path to scope graphqlUploadExpress middleware (defaults to '/graphql'). */
|
|
22
23
|
uploadPath?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Secret string for cookie-parser. Required for signed cookie verification.
|
|
26
|
+
* Without a secret, `req.signedCookies` will always be empty.
|
|
27
|
+
*/
|
|
28
|
+
cookieSecret?: string;
|
|
23
29
|
}
|
|
24
30
|
export interface I_NestOptions {
|
|
25
31
|
module: Type<object>;
|
|
@@ -30,6 +36,11 @@ export interface I_NestOptions {
|
|
|
30
36
|
jsonLimit?: string;
|
|
31
37
|
trustProxy?: boolean | number | string | string[];
|
|
32
38
|
rateLimit?: false | I_RateLimitOptions;
|
|
39
|
+
/**
|
|
40
|
+
* Secret string for cookie-parser. Required for signed cookie verification.
|
|
41
|
+
* Without a secret, `req.signedCookies` will always be empty.
|
|
42
|
+
*/
|
|
43
|
+
cookieSecret?: string;
|
|
33
44
|
}
|
|
34
45
|
export type T_CorsType = 'node' | 'nest';
|
|
35
46
|
interface I_BaseCorsOptions {
|
|
@@ -14,10 +14,10 @@ import { I_ExpressOptions, I_NestOptions, T_CorsOptions, T_CorsType } from './ex
|
|
|
14
14
|
* @param options.whiteList - Array of allowed origins for CORS requests.
|
|
15
15
|
* @returns CORS options object configured for the specified environment.
|
|
16
16
|
*/
|
|
17
|
-
export declare function createCorsOptions<T extends T_CorsType>({ isDev, whiteList, ...rest }: T_CorsOptions<T>): {
|
|
17
|
+
export declare function createCorsOptions<T extends T_CorsType>({ isDev, whiteList, ...rest }: T_CorsOptions<T>): Omit<T_CorsOptions<T>, "isDev" | "whiteList"> & {
|
|
18
18
|
origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => void;
|
|
19
19
|
credentials: boolean;
|
|
20
|
-
}
|
|
20
|
+
};
|
|
21
21
|
/**
|
|
22
22
|
* Creates a CORS middleware function with the specified configuration.
|
|
23
23
|
* This function creates a CORS middleware that can be used with both Express and NestJS applications,
|
|
@@ -37,10 +37,25 @@ export declare function createCors<T extends T_CorsType>(options: T_CorsOptions<
|
|
|
37
37
|
* with the provided session options including secret, cookie settings, and storage configuration.
|
|
38
38
|
*
|
|
39
39
|
* @remarks
|
|
40
|
-
* **CSRF
|
|
41
|
-
* fully prevent CSRF attacks
|
|
42
|
-
*
|
|
43
|
-
*
|
|
40
|
+
* **CSRF Protection Required:** This middleware sets `SameSite=Lax` by default, which mitigates
|
|
41
|
+
* but does **NOT** fully prevent CSRF attacks. Specifically, `Lax` allows cookies on top-level
|
|
42
|
+
* GET navigations, which can be exploited for state-changing GET endpoints.
|
|
43
|
+
*
|
|
44
|
+
* **Consumer apps MUST add CSRF token validation** for all state-changing routes (POST, PUT,
|
|
45
|
+
* DELETE, PATCH). Recommended libraries:
|
|
46
|
+
* - `csrf-csrf` (double-submit cookie pattern — stateless, recommended)
|
|
47
|
+
* - `csrf-sync` (synchronizer token pattern — requires session store)
|
|
48
|
+
*
|
|
49
|
+
* Example:
|
|
50
|
+
* ```typescript
|
|
51
|
+
* import { doubleCsrf } from 'csrf-csrf';
|
|
52
|
+
* const { doubleCsrfProtection } = doubleCsrf({ getSecret: () => req.session.csrfSecret });
|
|
53
|
+
* app.use(doubleCsrfProtection);
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* **Session Store Warning:** The default `MemoryStore` is not designed for production use:
|
|
57
|
+
* it leaks memory under load and loses all sessions on restart. Configure a persistent
|
|
58
|
+
* store (e.g., `connect-redis`, `connect-mongo`) for production deployments.
|
|
44
59
|
*
|
|
45
60
|
* @param options - Session configuration options including secret, cookie settings, and storage.
|
|
46
61
|
* @returns A session middleware function ready to be used in Express applications.
|
|
@@ -74,3 +89,16 @@ export declare function createExpress(options?: I_ExpressOptions): Application;
|
|
|
74
89
|
*/
|
|
75
90
|
export declare function createNest(options: I_NestOptions): Promise<INestApplication>;
|
|
76
91
|
export { bodyParser, express };
|
|
92
|
+
/**
|
|
93
|
+
* Creates a Content Security Policy (CSP) configuration for Helmet.
|
|
94
|
+
* Provides sensible defaults with presets for common application patterns.
|
|
95
|
+
*
|
|
96
|
+
* @param options - Custom CSP directives to override or extend defaults.
|
|
97
|
+
* @param preset - Pre-configured patterns ('default' or 'graphql').
|
|
98
|
+
* @returns CSP configuration object for Helmet options.
|
|
99
|
+
*/
|
|
100
|
+
export declare function createCSP(options?: Record<string, string[] | string | boolean>, preset?: 'default' | 'graphql'): {
|
|
101
|
+
directives: {
|
|
102
|
+
[x: string]: string | boolean | string[];
|
|
103
|
+
};
|
|
104
|
+
};
|
|
@@ -1,89 +1,114 @@
|
|
|
1
|
-
import e from "
|
|
2
|
-
import t from "
|
|
3
|
-
import
|
|
4
|
-
import r from "
|
|
5
|
-
import i from "
|
|
6
|
-
import a from "
|
|
7
|
-
import o from "
|
|
8
|
-
import s from "
|
|
9
|
-
import c from "
|
|
10
|
-
import
|
|
11
|
-
import u from "
|
|
12
|
-
import d from "
|
|
1
|
+
import { E_Environment as e } from "../../typescript/common.type.js";
|
|
2
|
+
import { log as t } from "../log/log.util.js";
|
|
3
|
+
import n from "node:process";
|
|
4
|
+
import r from "express";
|
|
5
|
+
import { NestFactory as i } from "@nestjs/core";
|
|
6
|
+
import a from "body-parser";
|
|
7
|
+
import o from "compression";
|
|
8
|
+
import s from "cookie-parser";
|
|
9
|
+
import c from "cors";
|
|
10
|
+
import l from "express-rate-limit";
|
|
11
|
+
import u from "express-session";
|
|
12
|
+
import { express as d } from "express-useragent";
|
|
13
|
+
import f from "graphql-upload/graphqlUploadExpress.mjs";
|
|
14
|
+
import p from "helmet";
|
|
13
15
|
//#region src/node/express/express.util.ts
|
|
14
|
-
function
|
|
15
|
-
return
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
function m({ isDev: r, whiteList: i, ...a }) {
|
|
17
|
+
return r && n.env.NODE_ENV === e.PRODUCTION && t.warn("[CORS] WARNING: isDev is true but NODE_ENV is \"production\". CORS restrictions are relaxed. This is likely a misconfiguration."), {
|
|
18
|
+
...a,
|
|
19
|
+
origin: (e, t) => {
|
|
20
|
+
if (r && !e) {
|
|
21
|
+
t(null, !0);
|
|
19
22
|
return;
|
|
20
23
|
}
|
|
21
|
-
e &&
|
|
24
|
+
e && i?.includes(e) ? t(null, !0) : t(/* @__PURE__ */ Error("Not allowed by CORS"), !1);
|
|
22
25
|
},
|
|
23
|
-
credentials: !0
|
|
24
|
-
...r
|
|
26
|
+
credentials: !0
|
|
25
27
|
};
|
|
26
28
|
}
|
|
27
|
-
function
|
|
28
|
-
return
|
|
29
|
+
function h(e) {
|
|
30
|
+
return c(m(e));
|
|
29
31
|
}
|
|
30
|
-
function
|
|
31
|
-
if (!
|
|
32
|
-
!
|
|
33
|
-
let
|
|
32
|
+
function g(r) {
|
|
33
|
+
if (!r.secret) throw Error("Session secret is required. Provide a strong secret string.");
|
|
34
|
+
!r.store && n.env.NODE_ENV === e.PRODUCTION && t.warn("[Session] WARNING: No session store configured in production. The default MemoryStore leaks memory and loses sessions on restart. Use connect-redis, connect-mongo, or another production store.");
|
|
35
|
+
let i = {
|
|
34
36
|
resave: !1,
|
|
35
37
|
saveUninitialized: !1,
|
|
36
38
|
cookie: {
|
|
37
39
|
httpOnly: !0,
|
|
38
40
|
sameSite: "lax",
|
|
39
|
-
secure:
|
|
41
|
+
secure: n.env.NODE_ENV === e.PRODUCTION,
|
|
40
42
|
maxAge: 1440 * 60 * 1e3
|
|
41
43
|
}
|
|
42
44
|
};
|
|
43
|
-
return
|
|
44
|
-
...
|
|
45
|
-
...
|
|
45
|
+
return u({
|
|
46
|
+
...i,
|
|
47
|
+
...r,
|
|
46
48
|
cookie: {
|
|
47
|
-
...
|
|
48
|
-
...
|
|
49
|
+
...i.cookie,
|
|
50
|
+
...r.cookie
|
|
49
51
|
}
|
|
50
52
|
});
|
|
51
53
|
}
|
|
52
|
-
function
|
|
53
|
-
|
|
54
|
-
crossOriginEmbedderPolicy:
|
|
55
|
-
contentSecurityPolicy:
|
|
56
|
-
})),
|
|
57
|
-
windowMs:
|
|
58
|
-
limit:
|
|
54
|
+
function _(e, t = !1, n = "1mb", i = 1, a = {}, c) {
|
|
55
|
+
i && e.set("trust proxy", i), e.use(p({
|
|
56
|
+
crossOriginEmbedderPolicy: t ? !1 : void 0,
|
|
57
|
+
contentSecurityPolicy: t ? !1 : void 0
|
|
58
|
+
})), a !== !1 && e.use(l({
|
|
59
|
+
windowMs: a.windowMs ?? 900 * 1e3,
|
|
60
|
+
limit: a.limit ?? 1e3,
|
|
59
61
|
standardHeaders: !0,
|
|
60
62
|
legacyHeaders: !1,
|
|
61
|
-
...
|
|
62
|
-
...
|
|
63
|
-
|
|
63
|
+
...a.store !== void 0 && { store: a.store },
|
|
64
|
+
...a.skip !== void 0 && { skip: a.skip },
|
|
65
|
+
...a.keyGenerator !== void 0 && { keyGenerator: a.keyGenerator }
|
|
66
|
+
})), e.use(s(c)), e.use(r.json({ limit: n })), e.use(r.urlencoded({
|
|
64
67
|
extended: !0,
|
|
65
|
-
limit:
|
|
66
|
-
})), e.use(
|
|
68
|
+
limit: n
|
|
69
|
+
})), e.use(o()), e.use(d());
|
|
67
70
|
}
|
|
68
|
-
function
|
|
69
|
-
|
|
70
|
-
e.use(`/${
|
|
71
|
+
function v(e, t) {
|
|
72
|
+
t && (Array.isArray(t) ? t : [t]).forEach((t) => {
|
|
73
|
+
e.use(`/${t}`, r.static(t));
|
|
71
74
|
});
|
|
72
75
|
}
|
|
73
|
-
function
|
|
74
|
-
let
|
|
75
|
-
|
|
76
|
-
let
|
|
76
|
+
function y(e) {
|
|
77
|
+
let t = r();
|
|
78
|
+
_(t, e?.isDev, e?.jsonLimit, e?.trustProxy, e?.rateLimit, e?.cookieSecret), v(t, e?.static);
|
|
79
|
+
let n = f({
|
|
77
80
|
maxFileSize: e?.maxFileSize ?? 1e7,
|
|
78
81
|
maxFiles: e?.maxFiles ?? 10
|
|
79
82
|
});
|
|
80
|
-
return
|
|
83
|
+
return t.use(e?.uploadPath ?? "/graphql", n), t;
|
|
84
|
+
}
|
|
85
|
+
async function b(e) {
|
|
86
|
+
let t = await i.create(e.module);
|
|
87
|
+
return _(t.getHttpAdapter().getInstance(), e.isDev, e.jsonLimit, e.trustProxy, e.rateLimit, e.cookieSecret), v(t.getHttpAdapter().getInstance(), e.static), e.filters && t.useGlobalFilters(...e.filters), e.pipes && t.useGlobalPipes(...e.pipes), t;
|
|
81
88
|
}
|
|
82
|
-
|
|
83
|
-
let
|
|
84
|
-
|
|
89
|
+
function x(e, t = "default") {
|
|
90
|
+
let n = {
|
|
91
|
+
defaultSrc: ["'self'"],
|
|
92
|
+
scriptSrc: ["'self'"],
|
|
93
|
+
styleSrc: ["'self'", "'unsafe-inline'"],
|
|
94
|
+
imgSrc: [
|
|
95
|
+
"'self'",
|
|
96
|
+
"data:",
|
|
97
|
+
"https:"
|
|
98
|
+
],
|
|
99
|
+
fontSrc: [
|
|
100
|
+
"'self'",
|
|
101
|
+
"https:",
|
|
102
|
+
"data:"
|
|
103
|
+
],
|
|
104
|
+
connectSrc: ["'self'"]
|
|
105
|
+
};
|
|
106
|
+
return t === "graphql" && (n.scriptSrc?.push("'unsafe-inline'", "'unsafe-eval'", "https://cdn.jsdelivr.net"), n.styleSrc?.push("https://cdn.jsdelivr.net"), n.imgSrc?.push("https://cdn.jsdelivr.net")), { directives: {
|
|
107
|
+
...n,
|
|
108
|
+
...e
|
|
109
|
+
} };
|
|
85
110
|
}
|
|
86
111
|
//#endregion
|
|
87
|
-
export {
|
|
112
|
+
export { a as bodyParser, x as createCSP, h as createCors, m as createCorsOptions, y as createExpress, b as createNest, g as createSession, r as express };
|
|
88
113
|
|
|
89
114
|
//# sourceMappingURL=express.util.js.map
|
|
@@ -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 // Safety net: warn loudly if isDev is mistakenly true in production\n if (isDev && process.env['NODE_ENV'] === 'production') {\n console.warn('[CORS] WARNING: isDev is true but NODE_ENV is \"production\". CORS restrictions are relaxed. This is likely a misconfiguration.');\n }\n\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 * @remarks\n * **CSRF Warning:** This middleware sets `SameSite=Lax` by default, which mitigates but does NOT\n * fully prevent CSRF attacks for non-GET state-changing requests via top-level navigations.\n * Applications should integrate a dedicated CSRF token middleware (e.g., `csrf-csrf` or\n * `csrf-sync`) in addition to this session middleware for complete protection.\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 if (!options.store && process.env['NODE_ENV'] === 'production') {\n console.warn('[Session] WARNING: No session store configured in production. The default MemoryStore leaks memory and loses sessions on restart. Use connect-redis, connect-mongo, or another production store.');\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[] = 1,\n rateLimitOptions: false | import('./express.type.js').I_RateLimitOptions = {},\n) {\n if (trustProxy) {\n app.set('trust proxy', trustProxy);\n }\n\n app.use(\n helmet({\n crossOriginEmbedderPolicy: isDev ? false : undefined,\n contentSecurityPolicy: isDev ? false : undefined,\n }),\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 * @remarks\n * **Requires Express 5.x** — This module uses Express 5 APIs and is not compatible with Express 4.\n * The peer dependency requires `express >= 5.0.0`.\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;AAMrG,QAJI,KAAS,EAAQ,IAAI,aAAgB,gBACr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AAM;EAC7E,CAAC,CACL,EAEL,EAAI,IAAI,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;;AAkBV,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
|
+
{"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 { E_Environment } from '#typescript/index.js';\n\nimport type { I_ExpressOptions, I_NestOptions, T_CorsOptions, T_CorsType } from './express.type.js';\n\nimport { log } from '../log/index.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 // Safety net: warn loudly if isDev is mistakenly true in production\n if (isDev && process.env['NODE_ENV'] === E_Environment.PRODUCTION) {\n log.warn('[CORS] WARNING: isDev is true but NODE_ENV is \"production\". CORS restrictions are relaxed. This is likely a misconfiguration.');\n }\n\n return {\n ...rest,\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 };\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 * @remarks\n * **CSRF Protection Required:** This middleware sets `SameSite=Lax` by default, which mitigates\n * but does **NOT** fully prevent CSRF attacks. Specifically, `Lax` allows cookies on top-level\n * GET navigations, which can be exploited for state-changing GET endpoints.\n *\n * **Consumer apps MUST add CSRF token validation** for all state-changing routes (POST, PUT,\n * DELETE, PATCH). Recommended libraries:\n * - `csrf-csrf` (double-submit cookie pattern — stateless, recommended)\n * - `csrf-sync` (synchronizer token pattern — requires session store)\n *\n * Example:\n * ```typescript\n * import { doubleCsrf } from 'csrf-csrf';\n * const { doubleCsrfProtection } = doubleCsrf({ getSecret: () => req.session.csrfSecret });\n * app.use(doubleCsrfProtection);\n * ```\n *\n * **Session Store Warning:** The default `MemoryStore` is not designed for production use:\n * it leaks memory under load and loses all sessions on restart. Configure a persistent\n * store (e.g., `connect-redis`, `connect-mongo`) for production deployments.\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 if (!options.store && process.env['NODE_ENV'] === E_Environment.PRODUCTION) {\n log.warn('[Session] WARNING: No session store configured in production. The default MemoryStore leaks memory and loses sessions on restart. Use connect-redis, connect-mongo, or another production store.');\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'] === E_Environment.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 * - Rate limiting (configurable, default 1000 req/15min)\n *\n * @remarks\n * **Rate limit store:** The default `MemoryStore` is only suitable for single-process\n * deployments. For multi-process or clustered environments, configure a shared store\n * (e.g., `rate-limit-redis`, `rate-limit-mongo`) via `rateLimitOptions.store`.\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[] = 1,\n rateLimitOptions: false | import('./express.type.js').I_RateLimitOptions = {},\n cookieSecret?: string,\n) {\n if (trustProxy) {\n app.set('trust proxy', trustProxy);\n }\n\n app.use(\n helmet({\n crossOriginEmbedderPolicy: isDev ? false : undefined,\n contentSecurityPolicy: isDev ? false : undefined,\n }),\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 ...(rateLimitOptions.keyGenerator !== undefined && { keyGenerator: rateLimitOptions.keyGenerator }),\n }),\n );\n }\n app.use(cookieParser(cookieSecret));\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 * @remarks\n * **Requires Express 5.x** — This module uses Express 5 APIs and is not compatible with Express 4.\n * The peer dependency requires `express >= 5.0.0`.\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, options?.cookieSecret);\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, options.cookieSecret);\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\n/**\n * Creates a Content Security Policy (CSP) configuration for Helmet.\n * Provides sensible defaults with presets for common application patterns.\n *\n * @param options - Custom CSP directives to override or extend defaults.\n * @param preset - Pre-configured patterns ('default' or 'graphql').\n * @returns CSP configuration object for Helmet options.\n */\nexport function createCSP(\n options?: Record<string, string[] | string | boolean>,\n preset: 'default' | 'graphql' = 'default',\n) {\n const defaultDirectives: Record<string, string[]> = {\n defaultSrc: ['\\'self\\''],\n scriptSrc: ['\\'self\\''],\n styleSrc: ['\\'self\\'', '\\'unsafe-inline\\''],\n imgSrc: ['\\'self\\'', 'data:', 'https:'],\n fontSrc: ['\\'self\\'', 'https:', 'data:'],\n connectSrc: ['\\'self\\''],\n };\n\n if (preset === 'graphql') {\n defaultDirectives['scriptSrc']?.push('\\'unsafe-inline\\'', '\\'unsafe-eval\\'', 'https://cdn.jsdelivr.net');\n defaultDirectives['styleSrc']?.push('https://cdn.jsdelivr.net');\n defaultDirectives['imgSrc']?.push('https://cdn.jsdelivr.net');\n }\n\n return {\n directives: {\n ...defaultDirectives,\n ...options,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiCA,SAAgB,EAAwC,EAAE,UAAO,cAAW,GAAG,KAA0B;AAMrG,QAJI,KAAS,EAAQ,IAAI,aAAgB,EAAc,cACnD,EAAI,KAAK,kIAAgI,EAGtI;EACH,GAAG;EACH,SAAS,GAA4B,MAA2D;AAG5F,OAAI,KAAS,CAAC,GAAQ;AAClB,MAAS,MAAM,GAAK;AACpB;;AAGJ,GAAI,KAAU,GAAW,SAAS,EAAO,GACrC,EAAS,MAAM,GAAK,GAGpB,EAAS,gBAAI,MAAM,sBAAsB,EAAE,GAAM;;EAGzD,aAAa;EAChB;;AAWL,SAAgB,EAAiC,GAA2B;AACxE,QAAO,EAAuB,EAAkB,EAAQ,CAAC;;AAgC7D,SAAgB,EAAc,GAAyC;AACnE,KAAI,CAAC,EAAQ,OACT,OAAU,MAAM,8DAA8D;AAGlF,CAAI,CAAC,EAAQ,SAAS,EAAQ,IAAI,aA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
2
|
-
import { bodyParser as t,
|
|
3
|
-
export { e as Router, t as bodyParser, n as
|
|
2
|
+
import { bodyParser as t, createCSP as n, createCors as r, createCorsOptions as i, createExpress as a, createNest as o, createSession as s, express as c } from "./express.util.js";
|
|
3
|
+
export { e as Router, t as bodyParser, n as createCSP, r as createCors, i as createCorsOptions, a as createExpress, o as createNest, s as createSession, c as express };
|