Commit bc376f43 by liimin

feat: api-core SHA1/多transport 扩展 + JS 产物;mp lane 基建(名字真源+sync+护栏)

- api-core:新增 sha1/crypto、createSha1Signer(secret 前后包裹+全签+大写,与原生
  mp sign.js 字节级一致)、createWxSender/UniSender/FetchSender/AutoSender、
  GatewayStrategy.fixedParams(dispatcher 签名前并入);tsup 出 CJS+ESM+dts
  供原生小程序构建 npm 消费(miniprogram 字段指 dist/index.cjs)
- mp lane 基建:apps/mp/manifest.json 名字唯一真源(usedcar/sales/store/points,
  含 source gitlab 仓与 backend 家族提示);scripts/sync-mp-apps.mjs 消费端
  (--prune 清旧 lane;dir 含连字符时派生 camelCase 标识符修非法命名 bug);
  4 个 lane 脚手架(createWxSender+createSha1Signer+fixedParams)
- typescript-config/mini-program.json + eslint mp() 预设;check-boundaries 双 lane
  护栏(mp 禁引 platform-core/web-*/wujie)
- 根 eslint ignores:apps/mp/**/*.js(原生 mp 代码归 devtool 管,工具链只查 src/)、
  temp/**(已 gitignore 的暂存目录此前被 lint:all 误扫,顺手修复)
1 parent 644bd133
import { mp } from '@uj/eslint-config';
// 小程序 lane:禁止引用 web/host 独占运行时(见 @uj/eslint-config 的 mp 预设)。
export default mp();
{
"name": "@uj/mp-example",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint ."
},
"dependencies": {
"@uj/api-core": "workspace:*"
},
"devDependencies": {
"@uj/contracts": "workspace:*",
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"typescript": "catalog:"
}
}
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
type NormalizedEnvelope,
type RpcCall,
} from '@uj/api-core';
/**
* 原生小程序接入示例(apps/mp lane 的样板)。
*
* 与 web 子应用共用同一套 @uj/api-core 契约,差异只在 transport 一个参数:
* - web 子应用:createHostSender(requestViaHost()) 把请求交回主壳 axios;
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同算法。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
*/
export const demoGateway: GatewayStrategy = {
id: 'demo-backend',
// 落点随接入项目而变:scrm 系为 rop-scrm-<dir>/router,dj 系为 rop-dj-<dir>/router。
router: 'rop-scrm-demo/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'demo-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
normalize(body: unknown): NormalizedEnvelope {
if (!body || typeof body !== 'object') return { data: body };
const env = body as Record<string, unknown>;
const code = env['code'];
if (String(code) === '0') return { data: env['data'] };
return {
code: Number(code) || 500,
message: typeof env['message'] === 'string' ? env['message'] : '请求失败',
};
},
};
registerGateway(demoGateway);
/** 运行时凭据:真实项目从配置中心 / 编译变量注入,本层不留密钥字面量。 */
const credentials = new Map<string, GatewayCredential>([
['demo-backend', { origin: 'https://demo.example.com', appKey: 'app-key', secret: 'app-secret', version: '1.0', format: 'json' }],
]);
const dispatch = createRpcDispatcher({
// 原生小程序 transport:wx.request(非 wujie 环境,可自行发请求)。
sender: createWxSender(),
resolveCredential: (id) => {
const c = credentials.get(id);
if (!c) throw new Error(`未配置网关 ${id} 的凭据`);
return c;
},
resolveToken: () => '',
timeout: 30000,
});
/** 业务侧调用:只说方法名和参数,不关心对方怎么加签 / 怎么发。 */
export function callDemo<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {
const call: RpcCall = { gateway: 'demo-backend', method, params, signed: true };
return dispatch(call) as Promise<T>;
}
{
"extends": "../../../packages/typescript-config/mini-program.json",
"compilerOptions": {
"baseUrl": ".",
"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"]
}
{
"note": "【mp lane 名字唯一真源】这里定义所有原生小程序 lane 的目录名与元信息。dir 同时决定目录名 apps/mp/<dir> 与包名 @uj/mp-<dir>。名字已定稿(2026-11-06 超人拍板),后续若需改名改本文件的 dir / displayName / appId / backend / source 字段,再跑 `pnpm mp:sync` 即可重建脚手架(`--prune` 清旧目录)。`source` 字段记录该 lane 真实代码来自哪个 GitLab 仓库,供物理迁入时对照;`backend` 为后端家族提示,精确的 scrm/dj project 码在物理迁移真实请求层时再落定。",
"apps": [
{
"dir": "usedcar",
"displayName": "二手车 / 车精品小程序",
"appId": "wx_usedcar_PLACEHOLDER",
"backend": "saas_plus 家族(dj-car-boutique-work-wechat);双后端 scrm + dj,project 码待物理迁移时确认",
"source": "dj-car-boutique-work-wechat"
},
{
"dir": "sales",
"displayName": "车生活小程序(SCRM)",
"appId": "wx_sales_PLACEHOLDER",
"backend": "glsx SCRM(miniprogram-scrm-carlife,已依赖 glsx-common-sdk)",
"source": "miniprogram-scrm-carlife"
},
{
"dir": "store",
"displayName": "门店助手小程序",
"appId": "wx_store_PLACEHOLDER",
"backend": "saas_plus 家族(store-assistant-assemble);双后端 scrm + dj(djSecretKey)",
"source": "store-assistant-assemble"
},
{
"dir": "points",
"displayName": "积分商城小程序",
"appId": "wx_points_PLACEHOLDER",
"backend": "scrm-shopmall(points-mall,单后端,与 web points 同构)",
"source": "points-mall"
}
]
}
import { mp } from '@uj/eslint-config';
// 小程序 lane:禁止引用 web/host 独占运行时(见 @uj/eslint-config 的 mp 预设)。
export default mp();
{
"name": "@uj/mp-sales",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint ."
},
"dependencies": {
"@uj/api-core": "workspace:*"
},
"devDependencies": {
"@uj/contracts": "workspace:*",
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"typescript": "catalog:"
}
}
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
type NormalizedEnvelope,
type RpcCall,
} from '@uj/api-core';
/**
* 车生活小程序(SCRM)(apps/mp lane 脚手架,由 scripts/sync-mp-apps.mjs 依据 apps/mp/manifest.json 生成)。
*
* 与 web 子应用共用同一套 @uj/api-core 契约,差异只在 transport 一个参数:
* - web 子应用:createHostSender(requestViaHost()) 把请求交回主壳 axios;
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
*/
export const salesGateway: GatewayStrategy = {
id: 'sales-backend',
// 落点随接入项目而变:scrm 系为 rop-scrm-<dir>/router,dj 系为 rop-dj-<dir>/router。
router: 'rop-scrm-sales/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'sales-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
normalize(body: unknown): NormalizedEnvelope {
if (!body || typeof body !== 'object') return { data: body };
const env = body as Record<string, unknown>;
const code = env['code'];
if (String(code) === '0') return { data: env['data'] };
return {
code: Number(code) || 500,
message: typeof env['message'] === 'string' ? env['message'] : '请求失败',
};
},
};
registerGateway(salesGateway);
/** 运行时凭据:真实项目从配置中心 / 编译变量注入,本层不留密钥字面量。 */
const credentials = new Map<string, GatewayCredential>([
['sales-backend', { origin: 'https://sales.example.com', appKey: 'app-key', secret: 'app-secret', version: '1.0', format: 'json' }],
]);
const dispatch = createRpcDispatcher({
// 原生小程序 transport:wx.request(非 wujie 环境,可自行发请求)。
sender: createWxSender(),
resolveCredential: (id) => {
const c = credentials.get(id);
if (!c) throw new Error(`未配置网关 ${id} 的凭据`);
return c;
},
resolveToken: () => '',
timeout: 30000,
});
/** 业务侧调用:只说方法名和参数,不关心对方怎么加签 / 怎么发。 */
export function callSales<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {
const call: RpcCall = { gateway: 'sales-backend', method, params, signed: true };
return dispatch(call) as Promise<T>;
}
{
"extends": "../../../packages/typescript-config/mini-program.json",
"compilerOptions": {
"baseUrl": ".",
"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"
]
}
import { mp } from '@uj/eslint-config';
// 小程序 lane:禁止引用 web/host 独占运行时(见 @uj/eslint-config 的 mp 预设)。
export default mp();
{
"name": "@uj/mp-store",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint ."
},
"dependencies": {
"@uj/api-core": "workspace:*"
},
"devDependencies": {
"@uj/contracts": "workspace:*",
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"typescript": "catalog:"
}
}
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
type NormalizedEnvelope,
type RpcCall,
} from '@uj/api-core';
/**
* 门店助手小程序(apps/mp lane 脚手架,由 scripts/sync-mp-apps.mjs 依据 apps/mp/manifest.json 生成)。
*
* 与 web 子应用共用同一套 @uj/api-core 契约,差异只在 transport 一个参数:
* - web 子应用:createHostSender(requestViaHost()) 把请求交回主壳 axios;
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
*/
export const storeGateway: GatewayStrategy = {
id: 'store-backend',
// 落点随接入项目而变:scrm 系为 rop-scrm-<dir>/router,dj 系为 rop-dj-<dir>/router。
router: 'rop-scrm-store/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'store-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
normalize(body: unknown): NormalizedEnvelope {
if (!body || typeof body !== 'object') return { data: body };
const env = body as Record<string, unknown>;
const code = env['code'];
if (String(code) === '0') return { data: env['data'] };
return {
code: Number(code) || 500,
message: typeof env['message'] === 'string' ? env['message'] : '请求失败',
};
},
};
registerGateway(storeGateway);
/** 运行时凭据:真实项目从配置中心 / 编译变量注入,本层不留密钥字面量。 */
const credentials = new Map<string, GatewayCredential>([
['store-backend', { origin: 'https://store.example.com', appKey: 'app-key', secret: 'app-secret', version: '1.0', format: 'json' }],
]);
const dispatch = createRpcDispatcher({
// 原生小程序 transport:wx.request(非 wujie 环境,可自行发请求)。
sender: createWxSender(),
resolveCredential: (id) => {
const c = credentials.get(id);
if (!c) throw new Error(`未配置网关 ${id} 的凭据`);
return c;
},
resolveToken: () => '',
timeout: 30000,
});
/** 业务侧调用:只说方法名和参数,不关心对方怎么加签 / 怎么发。 */
export function callStore<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {
const call: RpcCall = { gateway: 'store-backend', method, params, signed: true };
return dispatch(call) as Promise<T>;
}
{
"extends": "../../../packages/typescript-config/mini-program.json",
"compilerOptions": {
"baseUrl": ".",
"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"
]
}
import { mp } from '@uj/eslint-config';
// 小程序 lane:禁止引用 web/host 独占运行时(见 @uj/eslint-config 的 mp 预设)。
export default mp();
{
"name": "@uj/mp-usedcar",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint ."
},
"dependencies": {
"@uj/api-core": "workspace:*"
},
"devDependencies": {
"@uj/contracts": "workspace:*",
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"typescript": "catalog:"
}
}
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
type NormalizedEnvelope,
type RpcCall,
} from '@uj/api-core';
/**
* 二手车 / 车精品小程序(apps/mp lane 脚手架,由 scripts/sync-mp-apps.mjs 依据 apps/mp/manifest.json 生成)。
*
* 与 web 子应用共用同一套 @uj/api-core 契约,差异只在 transport 一个参数:
* - web 子应用:createHostSender(requestViaHost()) 把请求交回主壳 axios;
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
*/
export const usedcarGateway: GatewayStrategy = {
id: 'usedcar-backend',
// 落点随接入项目而变:scrm 系为 rop-scrm-<dir>/router,dj 系为 rop-dj-<dir>/router。
router: 'rop-scrm-usedcar/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'usedcar-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
normalize(body: unknown): NormalizedEnvelope {
if (!body || typeof body !== 'object') return { data: body };
const env = body as Record<string, unknown>;
const code = env['code'];
if (String(code) === '0') return { data: env['data'] };
return {
code: Number(code) || 500,
message: typeof env['message'] === 'string' ? env['message'] : '请求失败',
};
},
};
registerGateway(usedcarGateway);
/** 运行时凭据:真实项目从配置中心 / 编译变量注入,本层不留密钥字面量。 */
const credentials = new Map<string, GatewayCredential>([
['usedcar-backend', { origin: 'https://usedcar.example.com', appKey: 'app-key', secret: 'app-secret', version: '1.0', format: 'json' }],
]);
const dispatch = createRpcDispatcher({
// 原生小程序 transport:wx.request(非 wujie 环境,可自行发请求)。
sender: createWxSender(),
resolveCredential: (id) => {
const c = credentials.get(id);
if (!c) throw new Error(`未配置网关 ${id} 的凭据`);
return c;
},
resolveToken: () => '',
timeout: 30000,
});
/** 业务侧调用:只说方法名和参数,不关心对方怎么加签 / 怎么发。 */
export function callUsedcar<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {
const call: RpcCall = { gateway: 'usedcar-backend', method, params, signed: true };
return dispatch(call) as Promise<T>;
}
{
"extends": "../../../packages/typescript-config/mini-program.json",
"compilerOptions": {
"baseUrl": ".",
"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"
]
}
......@@ -9,7 +9,7 @@ import { app } from '@uj/eslint-config';
*/
export default [
{
ignores: ['**/dist/**', '**/node_modules/**', '**/.turbo/**', '**/coverage/**', '.release/**'],
ignores: ['**/dist/**', '**/node_modules/**', '**/.turbo/**', '**/coverage/**', '.release/**', '**/temp/**', '**/apps/mp/**/*.js'],
},
...app(),
];
......@@ -38,6 +38,7 @@
"release:prune": "node scripts/release/release-prune.mjs",
"sync": "node scripts/sync-from-uj-store.mjs",
"gen:tsconfig": "node scripts/gen-tsconfig.mjs",
"mp:sync": "node scripts/sync-mp-apps.mjs",
"verify": "node scripts/check-boundaries.mjs && node scripts/reconcile.mjs && pnpm typecheck && pnpm lint && pnpm lint:all && pnpm format:check",
"ci": "pnpm verify && pnpm build"
},
......
......@@ -3,9 +3,24 @@
"version": "0.0.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"miniprogram": "./dist/index.cjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.cjs"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"lint": "eslint . --max-warnings=0",
"typecheck": "tsc --noEmit"
},
......@@ -14,6 +29,7 @@
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"eslint": "catalog:",
"tsup": "catalog:",
"typescript": "catalog:"
}
}
......@@ -150,3 +150,96 @@ export async function hmacSha256(message: string, secret: string): Promise<strin
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* SHA1(RFC 3174)。
*
* 原生小程序(points-mall / store-assistant / business-assistant / scrm-carlife)的 RPC 网关
* 走 SHA1 加签(`sha1(secret + 拼接原文 + secret).toUpperCase()`),与 web points 子应用的
* MD5 网关是**两套不同算法**——同一网关家族、不同端用不同摘要。为不让 mp 重新造轮子,这里
* 提供零依赖纯实现,与 MD5 共用 `toUtf8Bytes`,并已用 RFC 3174 测试向量核对。
*/
function leftRotate32(value: number, amount: number): number {
return ((value << amount) | (value >>> (32 - amount))) >>> 0;
}
function toHexBigEndian(word: number): string {
return (word >>> 0).toString(16).padStart(8, '0');
}
export function sha1(input: string): string {
const bytes = toUtf8Bytes(input);
const bitLen = bytes.length * 8;
bytes.push(0x80);
while (bytes.length % 64 !== 56) bytes.push(0);
// 64 位大端长度;本场景 message 远小于 2^32 位,高 32 位恒为 0。
const hi = Math.floor(bitLen / 2 ** 32);
const lo = bitLen >>> 0;
bytes.push(
(hi >>> 24) & 0xff,
(hi >>> 16) & 0xff,
(hi >>> 8) & 0xff,
hi & 0xff,
(lo >>> 24) & 0xff,
(lo >>> 16) & 0xff,
(lo >>> 8) & 0xff,
lo & 0xff,
);
let h0 = 0x67452301;
let h1 = 0xefcdab89;
let h2 = 0x98badcfe;
let h3 = 0x10325476;
let h4 = 0xc3d2e1f0;
const w = new Array<number>(80);
for (let i = 0; i < bytes.length; i += 64) {
for (let j = 0; j < 16; j += 1) {
const p = i + j * 4;
w[j] =
((bytes[p]! << 24) |
(bytes[p + 1]! << 16) |
(bytes[p + 2]! << 8) |
bytes[p + 3]!) >>>
0;
}
for (let j = 16; j < 80; j += 1) {
w[j] = leftRotate32(w[j - 3]! ^ w[j - 8]! ^ w[j - 14]! ^ w[j - 16]!, 1);
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
for (let j = 0; j < 80; j += 1) {
let f: number;
let k: number;
if (j < 20) {
f = (b & c) | (~b & d);
k = 0x5a827999;
} else if (j < 40) {
f = b ^ c ^ d;
k = 0x6ed9eba1;
} else if (j < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdc;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6;
}
const temp = (leftRotate32(a, 5) + f + e + k + w[j]!) | 0;
e = d;
d = c;
c = leftRotate32(b, 30);
b = a;
a = temp >>> 0;
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
}
return [h0, h1, h2, h3, h4].map(toHexBigEndian).join('');
}
......@@ -52,7 +52,12 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) {
const credential = resolveCredential(call.gateway);
const needsSign = call.signed !== false;
const body: Record<string, unknown> = { ...call.params, method: call.method };
// 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;签名与请求体都基于这份有效参数。
const effectiveParams: Record<string, unknown> = {
...strategy.fixedParams,
...call.params,
};
const body: Record<string, unknown> = { ...effectiveParams, method: call.method };
if (needsSign) {
if (!credential.secret) {
throw new Error(
......@@ -62,7 +67,7 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) {
const signFields = await Promise.resolve(
strategy.signer.fields({
method: call.method,
params: call.params,
params: effectiveParams,
timestamp: Date.now(),
appKey: credential.appKey,
secret: credential.secret,
......
......@@ -24,10 +24,11 @@ export {
} from './senders';
export type { HostRequestConfig, HostSendFn } from './senders';
// 签名策略适配:通用工厂 + MD5 / HMAC / none 三种预设,算法可注入。
// 签名策略适配:通用工厂 + MD5 / SHA1 / HMAC / none 四种预设,算法可注入。
export {
createSigner,
createMd5Signer,
createSha1Signer,
createHmacSigner,
createNoneSigner,
} from './signers';
......@@ -41,4 +42,4 @@ export type {
} from './signers';
// 摘要 / MAC 算法 helper(供自定义 Signer 注入,例如 mp 侧引 crypto-js 实现同步 HMAC)。
export { md5, hmacSha256 } from './crypto';
export { md5, sha1, hmacSha256 } from './crypto';
import { hmacSha256, md5 } from './crypto';
import { hmacSha256, md5, sha1 } from './crypto';
import type { Signer, SignInput } from './types';
/**
......@@ -18,12 +18,14 @@ export type SignFieldNames = Partial<
export interface SignerOptions {
/** 策略 id(用于排查 / 区分算法)。 */
id?: string;
/** 摘要 / MAC 算法。内置 'md5' | 'hmac-sha256',或传函数自定义。 */
algorithm: SignAlgorithm | 'md5' | 'hmac-sha256';
/** 摘要 / MAC 算法。内置 'md5' | 'hmac-sha256' | 'sha1',或传函数自定义。 */
algorithm: SignAlgorithm | 'md5' | 'hmac-sha256' | 'sha1';
/** secret 包裹方式:both=`${secret}${body}${secret}` / prefix / suffix / none。默认 'none'。 */
secretWrap?: 'both' | 'prefix' | 'suffix' | 'none';
/** 是否把 appKey/format/method/timestamp/v 并进(除 params 外)。默认 true。 */
includeDefaults?: boolean;
/** 在 includeDefaults 为真时,剔除其中不需要的字段(mp 的 ROP/SHA1 方案不用 timestamp)。 */
excludeDefaults?: Array<'appKey' | 'format' | 'method' | 'timestamp' | 'version'>;
/** 系统字段输出名映射(默认 appKey/format/method/timestamp/v/sign)。 */
fieldNames?: SignFieldNames;
/** 值序列化(默认 glsx 风格:字符串原样、数/布尔 String、其它 JSON.stringify)。 */
......@@ -54,6 +56,7 @@ const DEFAULT_FIELD_NAMES = {
function resolveAlgorithm(algo: SignerOptions['algorithm']): SignAlgorithm {
if (algo === 'md5') return (message) => md5(message);
if (algo === 'hmac-sha256') return (message, secret) => hmacSha256(message, secret);
if (algo === 'sha1') return (message) => sha1(message);
return algo;
}
......@@ -83,6 +86,7 @@ export function createSigner(options: SignerOptions): Signer {
algorithm,
secretWrap = 'none',
includeDefaults = true,
excludeDefaults = [],
fieldNames = {},
canonicalize = DEFAULT_CANONICALIZE,
uppercase = false,
......@@ -90,6 +94,7 @@ export function createSigner(options: SignerOptions): Signer {
} = options;
const algo = resolveAlgorithm(algorithm);
const names = { ...DEFAULT_FIELD_NAMES, ...fieldNames };
const excluded = new Set(excludeDefaults);
return {
id,
......@@ -98,11 +103,11 @@ export function createSigner(options: SignerOptions): Signer {
const ignored = new Set(exclude ?? []);
const picked: Record<string, unknown> = {};
if (includeDefaults) {
picked[names.appKey] = appKey;
picked[names.format] = format;
picked[names.method] = method;
picked[names.timestamp] = timestamp;
picked[names.version] = version;
if (!excluded.has('appKey')) picked[names.appKey] = appKey;
if (!excluded.has('format')) picked[names.format] = format;
if (!excluded.has('method')) picked[names.method] = method;
if (!excluded.has('timestamp')) picked[names.timestamp] = timestamp;
if (!excluded.has('version')) picked[names.version] = version;
}
if (includeParams) {
for (const [key, value] of Object.entries(params)) {
......@@ -119,6 +124,7 @@ export function createSigner(options: SignerOptions): Signer {
const signValue = await algo(wrapSecret(body, secret, secretWrap), secret);
const out: Record<string, unknown> = {};
for (const key of [names.appKey, names.format, names.method, names.timestamp, names.version]) {
if (excluded.has(key as 'appKey' | 'format' | 'method' | 'timestamp' | 'version')) continue;
if (picked[key] !== undefined) out[key] = picked[key];
}
out[names.sign] = uppercase ? signValue.toUpperCase() : signValue;
......@@ -141,6 +147,26 @@ export function createMd5Signer(options: { id?: string; uppercase?: boolean } =
});
}
/**
* SHA1 加签预设(原生小程序 ROP 方案):secret 前后包裹、`appKey/format/method/v` 进原文 +
* params 全签(mp 会把 locale / source / sessionId 放进 params,一并参与签名)、不挂 timestamp
* (mp 用 v 而非时间戳)、输出 sign 大写。
*
* 与 web points 子应用的 MD5 网关同属一个后端家族,但**算法是 SHA1**——两套不同摘要并存,
* 故这里独立预设,不让 mp 复用 web 的 MD5 signer。原文拼接使用默认 glsx 风格(扁平参数下与
* mp 的 qs 拼接等价;仅当参数含嵌套对象 / 数组时才可能分叉,那种情况可改用 qs 或自定义 canonicalize)。
*/
export function createSha1Signer(options: { id?: string; uppercase?: boolean } = {}): Signer {
return createSigner({
id: options.id ?? 'glsx-sha1',
algorithm: 'sha1',
secretWrap: 'both',
includeDefaults: true,
excludeDefaults: ['timestamp'],
uppercase: options.uppercase ?? true,
});
}
/** 输出头名(glsk 风格:X-App-Id / X-Nonce / X-Timestamp / X-Sign)。 */
export type HmacHeaderNames = Partial<Record<'appId' | 'nonce' | 'timestamp' | 'sign', string>>;
......
......@@ -66,6 +66,11 @@ export interface GatewayStrategy {
signer: Signer;
/** 返回值映射:把该系统的响应包归一成主壳拦截器认得的形状 */
normalize(body: unknown): NormalizedEnvelope;
/**
* 该网关每次请求都固定携带、且参与签名的常量参数(如 mp 的 locale='zh_CN' / source='dj-wechat')。
* dispatcher 在签名前把它并入业务参数;业务调用时可再覆盖同名字段。
*/
fixedParams?: Record<string, unknown>;
}
/** 网关运行时凭据(通用形状;具体取值来自各域的 .env / 配置中心注入)。 */
......
import { defineConfig } from 'tsup';
/**
* api-core 是唯一需要「出 JS 产物」的包:web 子应用走源码 alias(不消费 dist),
* 但原生小程序「构建 npm」只能吃编译后的 CommonJS / 带 main/miniprogram 入口的包,
* 所以这里把纯 TS 源打成单文件 bundle。
*
* - format: ['cjs', 'esm'] —— WeChat 构建 npm 偏好 CJS(走 main / miniprogram),
* web / node 可走 ESM(走 module)。
* - dts: true —— 顺手产出类型声明,供 TS 消费者(不影响 mp 的 JS 消费)。
* - external: ['@uj/contracts'] —— HttpMethod 是 type-only 导入,运行期零耦合;
* 显式 external 让 dts 仅保留类型引用,不把 workspace 包打进 bundle。
* - 本包零运行时依赖,bundle 完全自包含。
*/
export default defineConfig({
entry: ['src/index.ts'],
format: ['cjs', 'esm'],
dts: true,
clean: true,
target: 'es2018',
sourcemap: true,
external: ['@uj/contracts'],
});
......@@ -63,4 +63,74 @@ export const app = (options = {}) =>
prettier,
);
/**
* 小程序 lane 的 ESLint(flat) 配置(原生微信小程序,非 web、非 React DOM)。
*
* 与 app() 的区别:
* - 不加载 react-hooks / react-refresh(原生 mp 用 wxml,不写 JSX 组件树);
* - 注入 wx / uni / App / Page / Component / getApp 等小程序全局;
* - 硬性禁止引用 web/host 独占运行时(platform-core / platform-sdk / vite-config / @uj/web-* / wujie),
* 因为小程序自带 wx.request,不经主壳 props.request 代理,也不跑 vite 构建。
* 小程序复用 @uj/api-core(createWxSender + 各类 Signer),但不得反向耦合 web lane。
*/
export const mp = () =>
tseslint.config(
{ ignores: ['dist/**', 'node_modules/**'] },
js.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.{ts,tsx,js,mjs}'],
languageOptions: {
globals: {
...globals.node,
wx: 'readonly',
uni: 'readonly',
App: 'readonly',
Page: 'readonly',
Component: 'readonly',
getApp: 'readonly',
getCurrentPages: 'readonly',
},
},
},
{
files: ['**/*.{ts,tsx}'],
rules: {
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
],
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@uj/platform-core', '@uj/platform-core/*'],
message:
'小程序禁止引用 host 独占运行时(axios/RSA/PEM)。请改用 @uj/api-core(createWxSender)。',
},
{
group: ['@uj/platform-sdk', '@uj/platform-sdk/*'],
message: '小程序不经由主壳 props.request,请勿引用 web 子应用 SDK @uj/platform-sdk。',
},
{
group: ['@uj/vite-config', '@uj/vite-config/*'],
message: '小程序不跑 vite 构建,请勿引用 @uj/vite-config。',
},
{
group: ['@uj/web-*'],
message: '小程序不得直接依赖 web 子应用 / 主壳包(@uj/web-*)。',
},
{
group: ['wujie'],
message: '小程序无 wujie 微前端容器,请勿直接 import wujie。',
},
],
},
],
},
},
prettier,
);
export default app();
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"noEmit": true
}
}
......@@ -5,7 +5,8 @@
"type": "module",
"exports": {
"./react-app.json": "./react-app.json",
"./react-lib.json": "./react-lib.json"
"./react-lib.json": "./react-lib.json",
"./mini-program.json": "./mini-program.json"
},
"devDependencies": {
"typescript": "catalog:"
......
......@@ -63,6 +63,9 @@ catalogs:
# vitest 2.x 只依赖 vite ^5,会和 vite 6 装出两份 vite,
# 导致插件拿到 vite 5 的 Plugin 类型;3.x 可复用同一份 vite(genesis 踩过一次)。
vitest: ^3.2.4
# 仅 api-core 用的打包器:把 TS 源打成单文件 ESM+CJS+ d.ts,
# 供原生小程序「构建 npm」消费(web 子应用仍走源码 alias,不受影响)。
tsup: ^8.3.6
# --- Lint / 格式 ---
eslint: ^9.19.0
......
......@@ -5,16 +5,22 @@ import { fileURLToPath } from 'node:url';
/**
* 架构边界闸门(CI 必跑)。
*
* ESLint 只能看 import 语句,看不住配置与全局变量;这里从磁盘事实复查四条硬约束:
* 1. 子应用不得引用 @uj/platform-core(host 独占运行时)
* 2. 子应用不得出现 PEM 虚拟模块 / 签名密钥 env(请求层不下放)
* 3. 子应用 vite.config 不得挂 /api 代理或读密钥
* 4. 子应用不得直接 import wujie core(应只用 window.$wujie)
* 本仓库有两条独立技术栈,护栏分别设置:
* - web lane(apps/web):主壳 + wujie 微前端子应用,受下方「web 子应用」四条硬约束;
* - mp lane(apps/mp):原生小程序,自带 wx.request,不经主壳代理,受「小程序」护栏约束。
*
* 这四条任何一条破了,症状都不是编译错误,而是「登录 10011」「两份签名状态」
* ESLint 只能看 import 语句,看不住配置与全局变量;这里从磁盘事实复查硬约束:
* 【web 子应用】不得:引用 @uj/platform-core(host 独占运行时)/ 出现 PEM 虚拟模块或签名密钥
* env(请求层不下放)/ vite.config 挂 /api 代理或读密钥 / 直接 import wujie core /
* 运行时 import axios / 跨子应用依赖 @uj/web-*。
* 【小程序】不得:反向引用 web/host 独占运行时(platform-core / platform-sdk / vite-config /
* @uj/web-* / wujie)—— 小程序复用 @uj/api-core(createWxSender),但不耦合 web lane。
*
* 这些约束任何一条破了,症状都不是编译错误,而是「登录 10011」「两份签名状态」
* 「两份 Context」这类运行时故障,必须静态拦住。
*/
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
// web lane:主壳 + wujie 子应用。小程序 lane 在 apps/mp,单独处理,不混入本扫描根。
const SUBAPPS_ROOT = path.join(ROOT, 'apps', 'web', 'subapps');
const errors = [];
const warnings = [];
......@@ -96,6 +102,59 @@ for (const appDir of subappDirs) {
}
}
// ---------------------------------------------------------------------------
// 小程序 lane(apps/mp):与 web 子应用是两条独立技术栈,分别设护栏。
// web 子应用的「请求层不下放」规则不适用于 mp(mp 自带 wx.request,不经主壳代理),
// 但 mp 也不得反向耦合 web/host 独占运行时(axios/RSA/PEM/vite/wujie/主壳子应用包)。
// 这条护栏保证「mp 引入 @uj/api-core 复用请求/签名适配」不会退化成「mp 偷偷引 web 运行时」。
// ---------------------------------------------------------------------------
const MP_ROOT = path.join(ROOT, 'apps', 'mp');
const MP_RULES = [
{
id: 'host-runtime',
re: /@uj\/platform-core/,
message: '小程序引用了 host 独占运行时 @uj/platform-core;请改用 @uj/api-core(createWxSender)。',
},
{
id: 'web-sdk',
re: /@uj\/platform-sdk/,
message: '小程序不经由主壳 props.request,请勿引用 web 子应用 SDK @uj/platform-sdk。',
},
{
id: 'web-build',
re: /@uj\/vite-config/,
message: '小程序不跑 vite 构建,请勿引用 @uj/vite-config。',
},
{
id: 'cross-lane',
re: /@uj\/web-/,
message: '小程序不得直接依赖 web 子应用 / 主壳包(@uj/web-*)。',
},
{
id: 'wujie-core',
re: /from\s+['"]wujie['"]/,
message: '小程序无 wujie 微前端容器,请勿直接 import wujie。',
},
];
if (fs.existsSync(MP_ROOT)) {
const mpDirs = fs
.readdirSync(MP_ROOT, { withFileTypes: true })
.filter((e) => e.isDirectory())
.map((e) => path.join(MP_ROOT, e.name));
for (const appDir of mpDirs) {
const files = collect(path.join(appDir, 'src'), ['.ts', '.tsx']);
for (const file of files) {
const text = fs.readFileSync(file, 'utf8');
const rel = path.relative(ROOT, file).split(path.sep).join('/');
for (const rule of MP_RULES) {
if (rule.re.test(text)) errors.push(`[${rule.id}] ${rel}: ${rule.message}`);
}
}
}
console.log(`[boundaries] 扫描 ${mpDirs.length} 个小程序`);
}
// 反向检查:只有 shell 允许读 PEM 虚拟模块。
const shellConfig = path.join(ROOT, 'apps/web/shell/vite.config.ts');
if (fs.existsSync(shellConfig)) {
......
#!/usr/bin/env node
/**
* mp lane 名字真源的消费端。
*
* 唯一真源:apps/mp/manifest.json(定义所有原生小程序 lane 的 dir / displayName / appId / backend)。
* 本脚本依据 manifest 为每个小程序生成 / 同步脚手架(package.json / tsconfig.json / eslint.config.js / 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 } 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,
type: 'module',
scripts: { typecheck: 'tsc --noEmit', lint: 'eslint .' },
dependencies: { '@uj/api-core': 'workspace:*' },
devDependencies: {
'@uj/contracts': 'workspace:*',
'@uj/eslint-config': 'workspace:*',
'@uj/typescript-config': 'workspace:*',
typescript: 'catalog:',
},
};
}
function templateTsconfig() {
return {
extends: '../../../packages/typescript-config/mini-program.json',
compilerOptions: {
baseUrl: '.',
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 全签),与 web points 子应用的 MD5 网关是两套不同');
L.push(' * 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。');
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');
const expectedName = `@uj/mp-${dir}`;
if (existsSync(pkgPath)) {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
if (pkg.name !== expectedName) {
pkg.name = expectedName;
writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
console.log(`同步 name -> ${expectedName} (${dir})`);
}
} 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.js');
if (!existsSync(eslintPath)) {
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 脚手架。`);
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!