loadMiniProgramApi.mjs
2.04 KB
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
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const repositoryRoot = fileURLToPath(new URL('../../../', import.meta.url))
const requestImportPattern =
/import\s+api\s+from\s+['"]~\/utils\/request\/request\.js['"];?/
const abnormalFlowImportPattern =
/import\s+\*\s+as\s+abnormalFlowApi\s+from\s+['"]\.\/abnormalFlowDeclaration\.js['"];?/
const exportsPattern = /module\.exports\s*=/
const replaceRequired = (source, pattern, replacement, label) => {
if (!pattern.test(source)) {
throw new Error(`Unable to transform mini-program API module: missing ${label}`)
}
return source.replace(pattern, replacement)
}
export async function loadMiniProgramApi(relativePath, requestSpy) {
if (!requestSpy || typeof requestSpy.post !== 'function') {
throw new TypeError('requestSpy.post must be a function')
}
const resolved = path.resolve(repositoryRoot, relativePath)
const relative = path.relative(repositoryRoot, resolved)
if (relative.startsWith('..') || path.isAbsolute(relative)) {
throw new Error(`API source must be inside repository: ${relativePath}`)
}
const spyKey = `__orderLifecycleApiSpy_${Date.now()}_${Math.random()
.toString(36)
.slice(2)}`
let source = await readFile(resolved, 'utf8')
source = replaceRequired(
source,
requestImportPattern,
`const api = globalThis[${JSON.stringify(spyKey)}]`,
'request import'
)
if (abnormalFlowImportPattern.test(source)) {
source = source.replace(
abnormalFlowImportPattern,
'const abnormalFlowApi = Object.create(null)'
)
}
source = replaceRequired(
source,
exportsPattern,
'export default',
'module.exports assignment'
)
source += `\n//# sourceURL=${relativePath.replaceAll('\\', '/')}?spy=${spyKey}\n`
globalThis[spyKey] = requestSpy
try {
const encoded = Buffer.from(source, 'utf8').toString('base64')
const module = await import(`data:text/javascript;base64,${encoded}`)
return module.default
} finally {
delete globalThis[spyKey]
}
}