getMiniProgramRuntimeContext.ts
2.08 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
/**
* @file 读取微信小程序运行时上下文(AppId、envVersion、平台)。
*/
export type MiniProgramEnvVersion = 'develop' | 'trial' | 'release' | '';
export interface MiniProgramRuntimeContext {
appId: string;
envVersion: MiniProgramEnvVersion;
platform: string;
isDevtools: boolean;
isWeixinMp: boolean;
}
const TOURIST_APP_ID = 'touristappid';
function emptyContext(): MiniProgramRuntimeContext {
return {
appId: '',
envVersion: '',
platform: '',
isDevtools: false,
isWeixinMp: false,
};
}
function normalizeAppId(appId: string): string {
const normalized = appId?.trim() ?? '';
// touristappid 无法映射环境,留空以回退 activeDevApiEnv / .env
if (normalized === TOURIST_APP_ID) {
return '';
}
return normalized;
}
function normalizeEnvVersion(value: unknown): MiniProgramEnvVersion {
if (value === 'develop' || value === 'trial' || value === 'release') {
return value;
}
return '';
}
/**
* 读取当前微信小程序运行时上下文;非小程序环境或 API 不可用时安全降级。
*/
export function getMiniProgramRuntimeContext(): MiniProgramRuntimeContext {
if (typeof uni === 'undefined') {
return emptyContext();
}
let platform = '';
try {
platform = uni.getSystemInfoSync()?.platform ?? '';
} catch {
platform = '';
}
const isDevtools = platform === 'devtools';
try {
const accountInfo = uni.getAccountInfoSync();
const miniProgram = accountInfo?.miniProgram;
if (!miniProgram) {
return {
...emptyContext(),
platform,
isDevtools,
};
}
return {
appId: normalizeAppId(miniProgram.appId ?? ''),
envVersion: normalizeEnvVersion(miniProgram.envVersion),
platform,
isDevtools,
isWeixinMp: true,
};
} catch {
return {
...emptyContext(),
platform,
isDevtools,
};
}
}