forked from unjs/mlly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syntax.ts
125 lines (103 loc) 路 3.16 KB
/
syntax.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import { promises as fsp } from "node:fs";
import { extname } from "pathe";
import { readPackageJSON } from "pkg-types";
import { ResolveOptions, resolvePath } from "./resolve";
import { isNodeBuiltin, getProtocol } from "./utils";
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 = new Set([".mjs", ".cjs", ".node", ".wasm"]);
export type DetectSyntaxOptions = { stripComments?: boolean };
export function hasESMSyntax(
code: string,
opts: DetectSyntaxOptions = {},
): boolean {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
return ESM_RE.test(code);
}
export function hasCJSSyntax(
code: string,
opts: DetectSyntaxOptions = {},
): boolean {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
return CJS_RE.test(code);
}
export function detectSyntax(code: string, opts: DetectSyntaxOptions = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
// We strip comments once hence not passing opts down to hasESMSyntax and hasCJSSyntax
const hasESM = hasESMSyntax(code, {});
const hasCJS = hasCJSSyntax(code, {});
return {
hasESM,
hasCJS,
isMixed: hasESM && hasCJS,
};
}
export interface ValidNodeImportOptions extends ResolveOptions {
/**
* The contents of the import, which may be analyzed to see if it contains
* CJS or ESM syntax as a last step in checking whether it is a valid import.
*/
code?: string;
/**
* Protocols that are allowed as valid node imports.
*
* Default: ['node', 'file', 'data']
*/
allowedProtocols?: Array<string>;
/**
* Whether to strip comments from the code before checking for ESM syntax.
*
* Default: false
*/
stripComments?: boolean;
}
const validNodeImportDefaults: ValidNodeImportOptions = {
allowedProtocols: ["node", "file", "data"],
};
export async function isValidNodeImport(
id: string,
_options: ValidNodeImportOptions = {},
): Promise<boolean> {
if (isNodeBuiltin(id)) {
return true;
}
const options = { ...validNodeImportDefaults, ..._options };
const proto = getProtocol(id);
if (proto && !options.allowedProtocols?.includes(proto)) {
return false;
}
// node is already validated by isNodeBuiltin and file will be normalized by resolvePath
if (proto === "data") {
return true;
}
const resolvedPath = await resolvePath(id, options);
const extension = extname(resolvedPath);
if (BUILTIN_EXTENSIONS.has(extension)) {
return true;
}
if (extension !== ".js") {
return false;
}
const package_ = await readPackageJSON(resolvedPath).catch(() => {});
// @ts-ignore
if (package_?.type === "module") {
return true;
}
if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(resolvedPath)) {
return false;
}
const code =
options.code ||
(await fsp.readFile(resolvedPath, "utf8").catch(() => {})) ||
"";
return !hasESMSyntax(code, { stripComments: options.stripComments });
}