load-mini-program-source.mjs
3.36 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
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
/**
* @file 以依赖注入方式加载小程序页面或 ES 模块,仅用于迁移行为特征测试。
*/
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { parse } from '@babel/parser'
import generatorModule from '@babel/generator'
const generate = generatorModule.default || generatorModule
const projectRoot = path.resolve(process.cwd())
async function transformSource(relativePath) {
const absolutePath = path.resolve(projectRoot, relativePath)
const relativeToRoot = path.relative(projectRoot, absolutePath)
if (
relativeToRoot === '..' ||
relativeToRoot.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativeToRoot)
) {
throw new Error(`Source must stay inside project: ${relativePath}`)
}
const source = await readFile(absolutePath, 'utf8')
const ast = parse(source, { sourceType: 'module' })
const exportNames = []
const body = []
for (const node of ast.program.body) {
if (node.type === 'ImportDeclaration') continue
if (node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
body.push(node.declaration)
if (node.declaration.type === 'VariableDeclaration') {
for (const declaration of node.declaration.declarations) {
if (declaration.id.type === 'Identifier') exportNames.push(declaration.id.name)
}
} else if (node.declaration.id?.name) {
exportNames.push(node.declaration.id.name)
}
}
for (const specifier of node.specifiers || []) {
exportNames.push(specifier.local.name)
}
continue
}
if (node.type === 'ExportDefaultDeclaration') {
body.push({
type: 'VariableDeclaration',
kind: 'const',
declarations: [{
type: 'VariableDeclarator',
id: { type: 'Identifier', name: '__defaultExport' },
init: node.declaration
}]
})
exportNames.push('__defaultExport')
continue
}
body.push(node)
}
ast.program.body = body
return { code: generate(ast).code, exportNames }
}
/**
* 加载模块的命名导出,import 依赖由调用方显式注入。
* @param {string} relativePath 仓库内模块路径
* @param {Record<string, unknown>} [dependencies] 顶层依赖
* @returns {Promise<Record<string, unknown>>} 模块导出
*/
export async function loadSourceExports(relativePath, dependencies = {}) {
const { code, exportNames } = await transformSource(relativePath)
const names = Object.keys(dependencies)
const values = Object.values(dependencies)
const resultExpression = exportNames
.map(name => `${JSON.stringify(name)}: ${name}`)
.join(',')
return new Function(...names, `${code}\nreturn {${resultExpression}};`)(...values)
}
/**
* 捕获 Page/Component 注册对象,便于直接验证页面编排行为。
* @param {string} relativePath 仓库内页面脚本
* @param {Record<string, unknown>} [dependencies] 页面顶层依赖
* @param {'Page'|'Component'} [registerName] 注册函数名
* @returns {Promise<object>} 页面或组件定义
*/
export async function loadMiniProgramDefinition(
relativePath,
dependencies = {},
registerName = 'Page'
) {
const { code } = await transformSource(relativePath)
let definition
const register = value => {
definition = value
}
const injected = { ...dependencies, [registerName]: register }
new Function(...Object.keys(injected), code)(...Object.values(injected))
if (!definition) throw new Error(`${registerName} was not registered: ${relativePath}`)
return definition
}