sync-mp-apps.mjs
10.9 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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env node
/**
* mp lane 名字真源的消费端。
*
* 唯一真源:apps/mp/manifest.json(定义所有原生小程序 lane 的 dir / displayName / appId / backend)。
* 本脚本依据 manifest 为每个小程序生成 / 同步脚手架(package.json / tsconfig.json / eslint.config.mjs / src/index.ts)。
*
* 用法:
* node scripts/sync-mp-apps.mjs # 新增缺失的 lane、同步包名,不删除多余目录(仅警告)
* node scripts/sync-mp-apps.mjs --prune # 额外删除不在 manifest 中的 apps/mp 子目录(example / manifest 除外)
*
* 改名流程:改 manifest 的 dir -> 跑本脚本(旧目录会告警)-> 加 --prune 清掉旧目录。
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, rmSync, renameSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, '..');
const MP_ROOT = join(ROOT, 'apps', 'mp');
const manifestPath = join(MP_ROOT, 'manifest.json');
const PRUNE = process.argv.includes('--prune');
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
if (!Array.isArray(manifest.apps)) {
console.error('[错误] manifest.json 缺少 apps 数组');
process.exit(1);
}
const apps = manifest.apps;
const wantedDirs = new Set(apps.map((a) => a.dir));
function templatePackageJson(dir) {
return {
name: `@uj/mp-${dir}`,
version: '0.0.0',
private: true,
// 原生小程序入口;lint 只扫 src(工具链不管 mp 业务 js,见根 eslint.config.js 的 ignores)。
// 刻意不写 "type": "module":mp 自带代码与它自己的 node 测试都是 CommonJS 口径
// (utils/lib/*.js 用 module.exports),带上 type 会让这些测试全红,
// 也会让 devtool「构建 npm」看到的清单和源工程不一致。ESLint 配置改用 .mjs 后缀自证 ESM。
main: 'app.js',
scripts: { typecheck: 'tsc --noEmit', lint: 'eslint src' },
dependencies: { '@uj/api-core': 'workspace:*' },
devDependencies: {
'@uj/contracts': 'workspace:*',
'@uj/eslint-config': 'workspace:*',
'@uj/typescript-config': 'workspace:*',
typescript: 'catalog:',
},
};
}
// 同 gen-tsconfig.mjs:extends 不支持 paths 别名,短名只能写
// '@uj/typescript-config/mini-program.json'(需 node_modules/@uj/typescript-config 可解析)。
function templateTsconfig() {
return {
extends: '../../../packages/typescript-config/mini-program.json',
compilerOptions: {
paths: {
'@uj/api-core': ['../../../packages/api-core/src/index.ts'],
'@uj/contracts': ['../../../packages/contracts/src/index.ts'],
},
},
include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.d.ts'],
};
}
function templateEslint() {
return [
"import { mp } from '@uj/eslint-config';",
'',
'// 小程序 lane:禁止引用 web/host 独占运行时(见 @uj/eslint-config 的 mp 预设)。',
'export default mp();',
'',
].join('\n');
}
function templateIndexTs(dir, displayName) {
const gatewayId = `${dir}-backend`;
const signerId = `${dir}-sha1`;
// dir 可能含连字符(如 uj-points),不能直接当 JS 标识符用。
// 转 camelCase 供 const / 函数名使用;id 字符串仍保留原 dir(带连字符,合法)。
const camelDir = dir.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
const capCamel = camelDir.charAt(0).toUpperCase() + camelDir.slice(1);
const L = [];
L.push("import {");
L.push(" createRpcDispatcher,");
L.push(" createWxSender,");
L.push(" createSha1Signer,");
L.push(" registerGateway,");
L.push(" type GatewayStrategy,");
L.push(" type GatewayCredential,");
L.push(" type NormalizedEnvelope,");
L.push(" type RpcCall,");
L.push("} from '@uj/api-core';");
L.push('');
L.push('/**');
L.push(` * ${displayName}(apps/mp lane 脚手架,由 scripts/sync-mp-apps.mjs 依据 apps/mp/manifest.json 生成)。`);
L.push(' *');
L.push(' * 与 web 子应用共用同一套 @uj/api-core 契约,差异只在 transport 一个参数:');
L.push(' * - web 子应用:createHostSender(requestViaHost()) 把请求交回主壳 axios;');
L.push(' * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。');
L.push(' *');
L.push(' * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、');
L.push(' * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx');
L.push(' * 家族、同样用 SHA1,但 timestamp 进原文,故走 createGlsxSha1Signer,两个预设别混用。');
L.push(' *');
L.push(' * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();');
L.push(' * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。');
L.push(' */');
L.push(`export const ${camelDir}Gateway: GatewayStrategy = {`);
L.push(` id: '${gatewayId}',`);
L.push(` // 落点随接入项目而变:scrm 系为 rop-scrm-<dir>/router,dj 系为 rop-dj-<dir>/router。`);
L.push(` router: 'rop-scrm-${dir}/router',`);
L.push(" tokenHeader: 'token',");
L.push(` // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。`);
L.push(` signer: createSha1Signer({ id: '${signerId}' }),`);
L.push(" // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。");
L.push(" fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },");
L.push(' // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。');
L.push(' normalize(body: unknown): NormalizedEnvelope {');
L.push(" if (!body || typeof body !== 'object') return { data: body };");
L.push(' const env = body as Record<string, unknown>;');
L.push(" const code = env['code'];");
L.push(" if (String(code) === '0') return { data: env['data'] };");
L.push(' return {');
L.push(' code: Number(code) || 500,');
L.push(" message: typeof env['message'] === 'string' ? env['message'] : '请求失败',");
L.push(' };');
L.push(' },');
L.push('};');
L.push(`registerGateway(${camelDir}Gateway);`);
L.push('');
L.push('/** 运行时凭据:真实项目从配置中心 / 编译变量注入,本层不留密钥字面量。 */');
L.push('const credentials = new Map<string, GatewayCredential>([');
L.push(` ['${gatewayId}', { origin: 'https://${dir}.example.com', appKey: 'app-key', secret: 'app-secret', version: '1.0', format: 'json' }],`);
L.push(']);');
L.push('');
L.push('const dispatch = createRpcDispatcher({');
L.push(' // 原生小程序 transport:wx.request(非 wujie 环境,可自行发请求)。');
L.push(' sender: createWxSender(),');
L.push(' resolveCredential: (id) => {');
L.push(' const c = credentials.get(id);');
L.push(' if (!c) throw new Error(`未配置网关 ${id} 的凭据`);');
L.push(' return c;');
L.push(' },');
L.push(" resolveToken: () => '',");
L.push(' timeout: 30000,');
L.push('});');
L.push('');
L.push('/** 业务侧调用:只说方法名和参数,不关心对方怎么加签 / 怎么发。 */');
L.push(`export function call${capCamel}<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {`);
L.push(` const call: RpcCall = { gateway: '${gatewayId}', method, params, signed: true };`);
L.push(' return dispatch(call) as Promise<T>;');
L.push('}');
L.push('');
return L.join('\n');
}
let created = 0;
for (const app of apps) {
const { dir, displayName } = app;
if (!dir || !/^[a-z][a-z0-9-]*$/.test(dir)) {
console.error(`[错误] 非法 dir: ${dir}(需小写字母开头,含小写字母/数字/连字符)`);
process.exit(1);
}
const appDir = join(MP_ROOT, dir);
const srcDir = join(appDir, 'src');
mkdirSync(srcDir, { recursive: true });
const pkgPath = join(appDir, 'package.json');
if (existsSync(pkgPath)) {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
const expected = templatePackageJson(dir);
const drift = [];
if (pkg.name !== expected.name) {
pkg.name = expected.name;
drift.push(`name -> ${expected.name}`);
}
// 物理迁入的 lane 带着原工程 package.json 的字段,这里只回收 lane 规范项,不动业务字段。
if ('type' in pkg) {
delete pkg.type;
drift.push('删除 type(mp 代码与其自带测试按 CommonJS 口径)');
}
if (pkg.main !== expected.main) {
pkg.main = expected.main;
drift.push(`main -> ${expected.main}`);
}
for (const [script, command] of Object.entries(expected.scripts)) {
if (pkg.scripts?.[script] !== command) {
pkg.scripts = { ...pkg.scripts, [script]: command };
drift.push(`scripts.${script} -> ${command}`);
}
}
if (drift.length) {
writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
console.log(`同步 ${dir}/package.json: ${drift.join(', ')}`);
}
} else {
writeFileSync(pkgPath, `${JSON.stringify(templatePackageJson(dir), null, 2)}\n`);
console.log(`新建 ${dir}/package.json`);
}
const tsconfigPath = join(appDir, 'tsconfig.json');
if (!existsSync(tsconfigPath)) {
writeFileSync(tsconfigPath, `${JSON.stringify(templateTsconfig(), null, 2)}\n`);
}
const eslintPath = join(appDir, 'eslint.config.mjs');
if (!existsSync(eslintPath)) {
const legacyPath = join(appDir, 'eslint.config.js');
if (existsSync(legacyPath)) {
// lane 不再带 package.json type,.js 会被当 CJS -> 必须换成 .mjs 后缀自证 ESM。
renameSync(legacyPath, eslintPath);
console.log(`重命名 ${dir}/eslint.config.js -> eslint.config.mjs`);
} else {
writeFileSync(eslintPath, templateEslint());
}
}
const indexPath = join(srcDir, 'index.ts');
if (!existsSync(indexPath)) {
writeFileSync(indexPath, templateIndexTs(dir, displayName));
created++;
console.log(`新建 ${dir}/src/index.ts (${displayName})`);
}
}
// 反向校验:磁盘上不在 manifest 的 apps/mp 子目录(排除 example / manifest / 脚本 / node_modules),提示或清理。
const reserved = new Set(['example', 'node_modules']);
const entries = readdirSync(MP_ROOT, { withFileTypes: true });
const stale = entries
.filter((e) => e.isDirectory() && !wantedDirs.has(e.name) && !reserved.has(e.name))
.map((e) => e.name);
for (const s of stale) {
const p = join(MP_ROOT, s);
if (PRUNE) {
rmSync(p, { recursive: true, force: true });
console.log(`[prune] 删除不在 manifest 的 lane: ${s}`);
} else {
console.warn(`[警告] 磁盘存在不在 manifest 的 lane: ${s}(如需删除请加 --prune 重跑)`);
}
}
console.log(`\n完成:manifest 含 ${apps.length} 个小程序,本次新建 ${created} 个 index.ts 脚手架。`);