subapp.ts
4.4 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
import {
busEvents,
type RemoteRequestFn,
type SessionSnapshot,
type SubAppProps,
} from '@uj/contracts';
/**
* wujie 注入到 iframe 的运行时对象。
* 这里刻意不写 declare global:子应用自己的 wujie.d.ts 会声明 window.$wujie,
* 两边重复声明容易在类型合并时打架。局部断言即可。
*/
interface WujieBus {
$on: (event: string, handler: (...args: unknown[]) => void) => void;
$off: (event: string, handler: (...args: unknown[]) => void) => void;
$emit: (event: string, ...args: unknown[]) => void;
}
interface WujieRuntime {
bus?: WujieBus;
props?: Record<string, unknown>;
}
export function wujieRuntime(): WujieRuntime | undefined {
if (typeof window === 'undefined') return undefined;
return (window as unknown as { $wujie?: WujieRuntime }).$wujie;
}
export function isInWujie(): boolean {
return Boolean((window as unknown as { __POWERED_BY_WUJIE__?: boolean }).__POWERED_BY_WUJIE__);
}
export function shortName(): string {
const props = wujieRuntime()?.props;
return typeof props?.['shortName'] === 'string' ? (props['shortName'] as string) : '';
}
export function subappBus(): WujieBus | undefined {
return wujieRuntime()?.bus;
}
/** 会话真源:localStorage。wujie 的 iframe 是同源 srcdoc,天然读得到主壳写的那一份。 */
export function readSession(): SessionSnapshot | null {
try {
const raw = localStorage.getItem('session');
if (!raw) return null;
const s = JSON.parse(raw) as SessionSnapshot;
if (!s.token || (s.expireAt && new Date(s.expireAt).getTime() <= Date.now())) return null;
return s;
} catch {
return null;
}
}
/** 权限按钮的唯一依据:与老项目 getUserPermCodes() 同源。 */
export function readPermCodes(): string[] {
const fromSession = readSession()?.permCodes;
if (Array.isArray(fromSession) && fromSession.length) return fromSession;
try {
const raw = localStorage.getItem('uj-auth-user-info');
const info = raw ? (JSON.parse(raw) as { permCodes?: unknown }) : null;
return Array.isArray(info?.permCodes)
? info.permCodes.filter((c): c is string => typeof c === 'string')
: [];
} catch {
return [];
}
}
/** 页面级判定:三段兜底,与 host 的 AccessProvider.can() 逐条对齐。 */
export function canByPoints(points: Set<string>, resource: string): boolean {
if (points.has(resource)) return true;
if (points.has(`${resource}:manage`)) return true;
return [...points].some((p) => p.startsWith(`${resource}:`));
}
/** 按钮级判定:严格命中,无兜底,必须与后端码逐字符一致。 */
export function canPointByPoints(points: Set<string>, point: string): boolean {
return points.has(point);
}
/** 首屏页名:只认 wujie 注入的 props.page;独立运行时回退到 URL 末段。 */
export function readInitialPage(): string {
const fromProps = wujieRuntime()?.props?.['page'];
if (typeof fromProps === 'string') return fromProps;
if (typeof window !== 'undefined') {
return window.location.pathname.split('/').filter(Boolean).pop() ?? '';
}
return '';
}
/**
* 唯一的后端出入口。
* 独立运行(非 wujie)时明确抛错而不是静默返回 undefined —— 子应用单独起 dev server
* 时看到的是一句人话,而不是「接口没反应」这种最难查的故障。
*/
export function requestViaHost(): RemoteRequestFn {
const fn = wujieRuntime()?.props?.['request'];
if (typeof fn !== 'function') {
return () =>
Promise.reject(
new Error(
'未检测到主壳注入的 props.request。子应用的所有请求必须由主壳代理;请用 pnpm dev 从主壳入口访问,或检查 startApp 的 props。',
),
);
}
return fn as RemoteRequestFn;
}
/** 取完整 props(缺字段时补默认值,便于子应用独立调试)。 */
export function subAppProps(): SubAppProps {
const raw = (wujieRuntime()?.props ?? {}) as Partial<SubAppProps>;
return {
request: requestViaHost(),
session: readSession(),
permCodes: readPermCodes(),
theme: (raw.theme as Record<string, unknown>) ?? {},
page: readInitialPage(),
navigate:
typeof raw.navigate === 'function'
? raw.navigate
: (path: string) => {
const bus = subappBus();
const name = shortName();
if (bus && name) bus.$emit(busEvents(name).navigateHost, path);
},
shortName: shortName(),
};
}