resolveApiEnvKey.ts
2.16 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
/**
* @file 按优先级链解析 API 环境 key。
*
* P0: 开发者工具本地环境覆盖 → `activeDevApiEnv.ts`
* P1: 已知微信小程序 AppId → 统一映射 test/prod(含 release)
* P2: 未知 AppId 的正式版 → 回退 `.env.production`
* P3: 开发者工具无已知 AppId → `activeDevApiEnv.ts`
* P4: 其他平台 → 回退 `.env` 默认值
*/
import {ACTIVE_DEV_API_ENV} from '@/config/activeDevApiEnv';
import {type ApiEnvKey, resolveEnvKeyFromAppId} from '@/config/apiEnvironments';
import {
type MiniProgramRuntimeContext,
getMiniProgramRuntimeContext,
} from '@/config/getMiniProgramRuntimeContext';
export type ApiEnvResolveSource = 'devtools' | 'build-env' | 'appId' | 'fallback';
export interface ResolvedApiEnvKey {
source: ApiEnvResolveSource;
envKey?: ApiEnvKey;
}
/**
* 根据运行时上下文解析 API 环境(纯函数,便于单元测试)。
*/
export function resolveApiEnvKeyFromContext(
runtime: MiniProgramRuntimeContext,
isDev: boolean,
devtoolsEnvKey: ApiEnvKey = ACTIVE_DEV_API_ENV,
): ResolvedApiEnvKey {
// 开发者工具允许显式覆盖到本地联调地址。
if (runtime.isDevtools && devtoolsEnvKey.startsWith('local-')) {
return {source: 'devtools', envKey: devtoolsEnvKey};
}
// 同一个小程序 AppId 在开发版、体验版和正式版中必须解析到同一环境。
if (runtime.isWeixinMp) {
const envKeyFromAppId = resolveEnvKeyFromAppId(runtime.appId);
if (envKeyFromAppId) {
return {source: 'appId', envKey: envKeyFromAppId};
}
}
// 无法识别 AppId 的正式版才使用构建时 .env.production 作为安全回退。
if (!isDev && runtime.envVersion === 'release') {
return {source: 'build-env'};
}
if (runtime.isDevtools) {
return {source: 'devtools', envKey: devtoolsEnvKey};
}
return {source: 'fallback'};
}
/**
* 解析当前运行时应使用的 API 环境 key。
*/
export function resolveApiEnvKey(): ResolvedApiEnvKey {
return resolveApiEnvKeyFromContext(
getMiniProgramRuntimeContext(),
import.meta.env.DEV,
ACTIVE_DEV_API_ENV,
);
}