[backend] fix: 修复异常处理和类型转换问题

This commit is contained in:
xsl
2026-01-26 11:53:40 +08:00
parent 7ccc2a6ac6
commit 83e05bf85f
28639 changed files with 2506458 additions and 93 deletions
+379 -1
View File
@@ -2280,4 +2280,382 @@ function findExports(code) {
for (const declaredExport of declaredExports) {
if (/^export\s+(?:async\s+)?function/.test(declaredExport.code)) {
continue;
}
}
const extraNamesStr = declaredExport.extraNames;
if (extraNamesStr) {
const extraNames = matchAll(
/({.*?})|(\[.*?])|(,\s*(?<name>\w+))/g,
extraNamesStr,
{}
).map((m) => m.name).filter(Boolean);
declaredExport.names = [declaredExport.name, ...extraNames];
}
delete declaredExport.extraNames;
}
const namedExports = normalizeNamedExports(
matchAll(EXPORT_NAMED_RE, code, {
type: "named"
})
);
const destructuredExports = matchAll(
EXPORT_NAMED_DESTRUCT,
code,
{ type: "named" }
);
for (const namedExport of destructuredExports) {
namedExport.exports = namedExport.exports1 || namedExport.exports2;
namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map(
(name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim()
);
}
const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, {
type: "default",
name: "default"
});
const defaultClassExports = matchAll(EXPORT_DEFAULT_CLASS_RE, code, {
type: "declaration"
});
const starExports = matchAll(EXPORT_STAR_RE, code, {
type: "star"
});
const exports = normalizeExports([
...declaredExports,
...namedExports,
...destructuredExports,
...defaultExport,
...defaultClassExports,
...starExports
]);
if (exports.length === 0) {
return [];
}
const exportLocations = _tryGetLocations(code, "export");
if (exportLocations && exportLocations.length === 0) {
return [];
}
return (
// Filter false positive export matches
_filterStatement(exportLocations, exports).filter((exp, index, exports2) => {
const nextExport = exports2[index + 1];
return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
})
);
}
function findTypeExports(code) {
const declaredExports = matchAll(
EXPORT_DECAL_TYPE_RE,
code,
{ type: "declaration" }
);
const namedExports = normalizeNamedExports(
matchAll(EXPORT_NAMED_TYPE_RE, code, {
type: "named"
})
);
const exports = normalizeExports([
...declaredExports,
...namedExports
]);
if (exports.length === 0) {
return [];
}
const exportLocations = _tryGetLocations(code, "export");
if (exportLocations && exportLocations.length === 0) {
return [];
}
return (
// Filter false positive export matches
_filterStatement(exportLocations, exports).filter((exp, index, exports2) => {
const nextExport = exports2[index + 1];
return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
})
);
}
function normalizeExports(exports) {
for (const exp of exports) {
if (!exp.name && exp.names && exp.names.length === 1) {
exp.name = exp.names[0];
}
if (exp.name === "default" && exp.type !== "default") {
exp._type = exp.type;
exp.type = "default";
}
if (!exp.names && exp.name) {
exp.names = [exp.name];
}
if (exp.type === "declaration" && exp.declaration) {
exp.declarationType = exp.declaration.replace(
/^declare\s*/,
""
);
}
}
return exports;
}
function normalizeNamedExports(namedExports) {
for (const namedExport of namedExports) {
namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim());
}
return namedExports;
}
function findExportNames(code) {
return findExports(code).flatMap((exp) => exp.names).filter(Boolean);
}
async function resolveModuleExportNames(id, options) {
const url = await resolvePath(id, options);
const code = await loadURL(url);
const exports = findExports(code);
const exportNames = new Set(
exports.flatMap((exp) => exp.names).filter(Boolean)
);
for (const exp of exports) {
if (exp.type !== "star" || !exp.specifier) {
continue;
}
const subExports = await resolveModuleExportNames(exp.specifier, {
...options,
url
});
for (const subExport of subExports) {
exportNames.add(subExport);
}
}
return [...exportNames];
}
function _filterStatement(locations, statements) {
return statements.filter((exp) => {
return !locations || locations.some((location) => {
return exp.start <= location.start && exp.end >= location.end;
});
});
}
function _tryGetLocations(code, label) {
try {
return _getLocations(code, label);
} catch {
}
}
function _getLocations(code, label) {
const tokens = acorn.tokenizer(code, {
ecmaVersion: "latest",
sourceType: "module",
allowHashBang: true,
allowAwaitOutsideFunction: true,
allowImportExportEverywhere: true
});
const locations = [];
for (const token of tokens) {
if (token.type.label === label) {
locations.push({
start: token.start,
end: token.end
});
}
}
return locations;
}
function createCommonJS(url) {
const __filename = fileURLToPath(url);
const __dirname = path.dirname(__filename);
let _nativeRequire;
const getNativeRequire = () => {
if (!_nativeRequire) {
_nativeRequire = node_module.createRequire(url);
}
return _nativeRequire;
};
function require(id) {
return getNativeRequire()(id);
}
require.resolve = function requireResolve(id, options) {
return getNativeRequire().resolve(id, options);
};
return {
__filename,
__dirname,
require
};
}
function interopDefault(sourceModule, opts = {}) {
if (!isObject(sourceModule) || !("default" in sourceModule)) {
return sourceModule;
}
const defaultValue = sourceModule.default;
if (defaultValue === void 0 || defaultValue === null) {
return sourceModule;
}
const _defaultType = typeof defaultValue;
if (_defaultType !== "object" && !(_defaultType === "function" && !opts.preferNamespace)) {
return opts.preferNamespace ? sourceModule : defaultValue;
}
for (const key in sourceModule) {
try {
if (!(key in defaultValue)) {
Object.defineProperty(defaultValue, key, {
enumerable: key !== "default",
configurable: key !== "default",
get() {
return sourceModule[key];
}
});
}
} catch {
}
}
return defaultValue;
}
const EVAL_ESM_IMPORT_RE = /(?<=import .* from ["'])[^"']+(?=["'])|(?<=export .* from ["'])[^"']+(?=["'])|(?<=import\s*["'])[^"']+(?=["'])|(?<=import\s*\(["'])[^"']+(?=["']\))/g;
async function loadModule(id, options = {}) {
const url = await resolve(id, options);
const code = await loadURL(url);
return evalModule(code, { ...options, url });
}
async function evalModule(code, options = {}) {
const transformed = await transformModule(code, options);
const dataURL = toDataURL(transformed);
return import(dataURL).catch((error) => {
error.stack = error.stack.replace(
new RegExp(dataURL, "g"),
options.url || "_mlly_eval_"
);
throw error;
});
}
function transformModule(code, options = {}) {
if (options.url && options.url.endsWith(".json")) {
return Promise.resolve("export default " + code);
}
if (options.url) {
code = code.replace(/import\.meta\.url/g, `'${options.url}'`);
}
return Promise.resolve(code);
}
async function resolveImports(code, options) {
const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]);
if (imports.length === 0) {
return code;
}
const uniqueImports = [...new Set(imports)];
const resolved = /* @__PURE__ */ new Map();
await Promise.all(
uniqueImports.map(async (id) => {
let url = await resolve(id, options);
if (url.endsWith(".json")) {
const code2 = await loadURL(url);
url = toDataURL(await transformModule(code2, { url }));
}
resolved.set(id, url);
})
);
const re = new RegExp(
uniqueImports.map((index) => `(?:${index})`).join("|"),
"g"
);
return code.replace(re, (id) => resolved.get(id));
}
const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
const CJS_RE = /(?:[\s;]|^)(?:module\.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
function hasESMSyntax(code, opts = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
return ESM_RE.test(code);
}
function hasCJSSyntax(code, opts = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
return CJS_RE.test(code);
}
function detectSyntax(code, opts = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
const hasESM = hasESMSyntax(code, {});
const hasCJS = hasCJSSyntax(code, {});
return {
hasESM,
hasCJS,
isMixed: hasESM && hasCJS
};
}
const validNodeImportDefaults = {
allowedProtocols: ["node", "file", "data"]
};
async function isValidNodeImport(id, _options = {}) {
if (isNodeBuiltin(id)) {
return true;
}
const options = { ...validNodeImportDefaults, ..._options };
const proto = getProtocol(id);
if (proto && !options.allowedProtocols?.includes(proto)) {
return false;
}
if (proto === "data") {
return true;
}
const resolvedPath = await resolvePath(id, options);
const extension = pathe.extname(resolvedPath);
if (BUILTIN_EXTENSIONS.has(extension)) {
return true;
}
if (extension !== ".js") {
return false;
}
const package_ = await pkgTypes.readPackageJSON(resolvedPath).catch(() => {
});
if (package_?.type === "module") {
return true;
}
if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(resolvedPath)) {
return false;
}
const code = options.code || await fs.promises.readFile(resolvedPath, "utf8").catch(() => {
}) || "";
return !hasESMSyntax(code, { stripComments: options.stripComments });
}
exports.DYNAMIC_IMPORT_RE = DYNAMIC_IMPORT_RE;
exports.ESM_STATIC_IMPORT_RE = ESM_STATIC_IMPORT_RE;
exports.EXPORT_DECAL_RE = EXPORT_DECAL_RE;
exports.EXPORT_DECAL_TYPE_RE = EXPORT_DECAL_TYPE_RE;
exports.createCommonJS = createCommonJS;
exports.createResolve = createResolve;
exports.detectSyntax = detectSyntax;
exports.evalModule = evalModule;
exports.fileURLToPath = fileURLToPath;
exports.findDynamicImports = findDynamicImports;
exports.findExportNames = findExportNames;
exports.findExports = findExports;
exports.findStaticImports = findStaticImports;
exports.findTypeExports = findTypeExports;
exports.findTypeImports = findTypeImports;
exports.getProtocol = getProtocol;
exports.hasCJSSyntax = hasCJSSyntax;
exports.hasESMSyntax = hasESMSyntax;
exports.interopDefault = interopDefault;
exports.isNodeBuiltin = isNodeBuiltin;
exports.isValidNodeImport = isValidNodeImport;
exports.loadModule = loadModule;
exports.loadURL = loadURL;
exports.lookupNodeModuleSubpath = lookupNodeModuleSubpath;
exports.normalizeid = normalizeid;
exports.parseNodeModulePath = parseNodeModulePath;
exports.parseStaticImport = parseStaticImport;
exports.parseTypeImport = parseTypeImport;
exports.pathToFileURL = pathToFileURL;
exports.resolve = resolve;
exports.resolveImports = resolveImports;
exports.resolveModuleExportNames = resolveModuleExportNames;
exports.resolvePath = resolvePath;
exports.resolvePathSync = resolvePathSync;
exports.resolveSync = resolveSync;
exports.sanitizeFilePath = sanitizeFilePath;
exports.sanitizeURIComponent = sanitizeURIComponent;
exports.toDataURL = toDataURL;
exports.transformModule = transformModule;