This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
es_modules.ts
176 lines (142 loc) · 4.74 KB
/
es_modules.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { basename, dirname, resolve } from 'path'
import { NodeFileTraceReasons } from '@vercel/nft'
import type { FunctionConfig } from '../../../../config.js'
import { FeatureFlags } from '../../../../feature_flags.js'
import { cachedReadFile, FsCache } from '../../../../utils/fs.js'
import { ModuleFormat } from '../../utils/module_format.js'
import { getNodeSupportMatrix } from '../../utils/node_version.js'
import { getPackageJsonIfAvailable, PackageJson } from '../../utils/package_json.js'
import { transpile } from './transpile.js'
const getPatchedESMPackages = async (packages: string[], fsCache: FsCache) => {
const patchedPackages = await Promise.all(packages.map((path) => patchESMPackage(path, fsCache)))
const patchedPackagesMap = new Map<string, string>()
packages.forEach((packagePath, index) => {
patchedPackagesMap.set(packagePath, patchedPackages[index])
})
return patchedPackagesMap
}
const isEntrypointESM = ({
basePath,
esmPaths,
mainFile,
}: {
basePath?: string
esmPaths: Set<string>
mainFile: string
}) => {
const absoluteESMPaths = new Set([...esmPaths].map((path) => resolvePath(path, basePath)))
const entrypointIsESM = absoluteESMPaths.has(mainFile)
return entrypointIsESM
}
const patchESMPackage = async (path: string, fsCache: FsCache) => {
const file = (await cachedReadFile(fsCache, path, 'utf8')) as string
const packageJson: PackageJson = JSON.parse(file)
const patchedPackageJson = {
...packageJson,
type: 'commonjs',
}
return JSON.stringify(patchedPackageJson)
}
export const processESM = async ({
basePath,
config,
esmPaths,
featureFlags,
fsCache,
mainFile,
reasons,
}: {
basePath: string | undefined
config: FunctionConfig
esmPaths: Set<string>
featureFlags: FeatureFlags
fsCache: FsCache
mainFile: string
reasons: NodeFileTraceReasons
}): Promise<{ rewrites?: Map<string, string>; moduleFormat: ModuleFormat }> => {
const entrypointIsESM = isEntrypointESM({ basePath, esmPaths, mainFile })
if (!entrypointIsESM) {
return {
moduleFormat: 'cjs',
}
}
const packageJson = await getPackageJsonIfAvailable(dirname(mainFile))
const nodeSupport = getNodeSupportMatrix(config.nodeVersion)
if (featureFlags.zisi_pure_esm && packageJson.type === 'module' && nodeSupport.esm) {
return {
moduleFormat: 'esm',
}
}
const rewrites = await transpileESM({ basePath, config, esmPaths, fsCache, reasons })
return {
moduleFormat: 'cjs',
rewrites,
}
}
const resolvePath = (relativePath: string, basePath?: string) =>
basePath ? resolve(basePath, relativePath) : resolve(relativePath)
const shouldTranspile = (
path: string,
cache: Map<string, boolean>,
esmPaths: Set<string>,
reasons: NodeFileTraceReasons,
): boolean => {
if (cache.has(path)) {
return cache.get(path) as boolean
}
const reason = reasons.get(path)
// This isn't an expected case, but if the path doesn't exist in `reasons` we
// don't transpile it.
if (reason === undefined) {
cache.set(path, false)
return false
}
const { parents } = reason
const parentPaths = [...parents].filter((parentPath) => parentPath !== path)
// If the path is an entrypoint, we transpile it only if it's an ESM file.
if (parentPaths.length === 0) {
const isESM = esmPaths.has(path)
cache.set(path, isESM)
return isESM
}
// The path should be transpiled if every parent will also be transpiled, or
// if there is no parent.
const shouldTranspilePath = parentPaths.every((parentPath) => shouldTranspile(parentPath, cache, esmPaths, reasons))
cache.set(path, shouldTranspilePath)
return shouldTranspilePath
}
const transpileESM = async ({
basePath,
config,
esmPaths,
fsCache,
reasons,
}: {
basePath: string | undefined
config: FunctionConfig
esmPaths: Set<string>
fsCache: FsCache
reasons: NodeFileTraceReasons
}) => {
const cache: Map<string, boolean> = new Map()
const pathsToTranspile = [...esmPaths].filter((path) => shouldTranspile(path, cache, esmPaths, reasons))
const pathsToTranspileSet = new Set(pathsToTranspile)
const packageJsonPaths: string[] = [...reasons.entries()]
.filter(([path, reason]) => {
if (basename(path) !== 'package.json') {
return false
}
const needsPatch = [...reason.parents].some((parentPath) => pathsToTranspileSet.has(parentPath))
return needsPatch
})
.map(([path]) => (basePath ? resolve(basePath, path) : resolve(path)))
const rewrites = await getPatchedESMPackages(packageJsonPaths, fsCache)
await Promise.all(
pathsToTranspile.map(async (path) => {
const absolutePath = resolvePath(path, basePath)
const transpiled = await transpile(absolutePath, config)
rewrites.set(absolutePath, transpiled)
}),
)
return rewrites
}