@autional/shared 0.1.0-rc.51 → 0.1.0-rc.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autional/shared",
3
- "version": "0.1.0-rc.51",
3
+ "version": "0.1.0-rc.52",
4
4
  "description": "Autional shared layer — API client, auth, types, hooks, utils",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./src/index.ts",
@@ -1,7 +1,7 @@
1
1
  // @vitest-environment jsdom
2
2
  import React from 'react';
3
3
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
4
- import { renderHook, cleanup, waitFor } from '@testing-library/react';
4
+ import { renderHook, cleanup, waitFor, act } from '@testing-library/react';
5
5
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
6
6
 
7
7
  // ============================================================
@@ -54,6 +54,7 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
54
54
  beforeEach(() => {
55
55
  vi.clearAllMocks();
56
56
  resetAuthStore();
57
+ queryClient.clear();
57
58
  mockQueries.perms = { data: undefined, isError: false };
58
59
  mockQueries.tenants = { data: undefined, isError: false };
59
60
  mockProfileAvatar.mockReset();
@@ -62,6 +63,7 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
62
63
 
63
64
  afterEach(() => {
64
65
  cleanup();
66
+ queryClient.clear();
65
67
  resetAuthStore();
66
68
  });
67
69
 
@@ -97,6 +99,18 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
97
99
  expect(result.current).toBe('loading');
98
100
  });
99
101
 
102
+ // P1-2 回归锁(2026-11-08 线上复现):权限/租户两个查询都失败时,
103
+ // 旧实现返回 'loading' ⇒ 状态机永停 bootstrap ⇒ RequireAuth 恒 render null
104
+ // ⇒ 后端 5xx 时整站白屏。必须返回 'error' 让守卫渲染可恢复错误页。
105
+ it('两个 bootstrap 查询都失败 → error(不得 loading)', () => {
106
+ useAuthStore.setState({ accessToken: 'token-xyz' });
107
+ mockQueries.perms = { data: undefined, isError: true };
108
+ mockQueries.tenants = { data: undefined, isError: true };
109
+ const { result } = renderHook(() => useBootstrap(), { wrapper });
110
+ expect(result.current).toBe('error');
111
+ expect(result.current).not.toBe('loading');
112
+ });
113
+
100
114
  // U447:登录响应与 /auth/me 都不含 avatarUrl —— 启动必须补读一次 profile 头像,
101
115
  // 否则换浏览器/新登录后顶栏头像恒为首字母。
102
116
  it('U447:有会话 → 补读 /profile/avatar 并写回认证快照', async () => {
@@ -125,4 +139,51 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
125
139
  await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalled());
126
140
  expect(useAuthStore.getState().user?.avatarUrl).toBeUndefined();
127
141
  });
142
+
143
+ // 首屏 avatar 3 次请求的回归锁:多个消费组件同时调 useBootstrap 时,
144
+ // 同一 userId+tenantId 只允许发一次 GET /profile/avatar。
145
+ it('U447:多个消费组件并发启动 → 头像只请求一次', async () => {
146
+ useAuthStore.setState({
147
+ accessToken: 'token-xyz',
148
+ user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
149
+ permissions: ['user.read'],
150
+ tenants: [{ id: 't1', name: 'demo', role: 'member' }],
151
+ });
152
+ let resolveAvatar!: (v: { avatarUrl: string }) => void;
153
+ mockProfileAvatar.mockImplementation(
154
+ () =>
155
+ new Promise<{ avatarUrl: string }>((resolve) => {
156
+ resolveAvatar = resolve;
157
+ }),
158
+ );
159
+
160
+ renderHook(() => useBootstrap(), { wrapper });
161
+ renderHook(() => useBootstrap(), { wrapper });
162
+
163
+ await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalledTimes(1));
164
+ resolveAvatar({ avatarUrl: 'https://cdn.example.com/b.png' });
165
+ await waitFor(() =>
166
+ expect(useAuthStore.getState().user?.avatarUrl).toBe('https://cdn.example.com/b.png'),
167
+ );
168
+ expect(mockProfileAvatar).toHaveBeenCalledTimes(1);
169
+ });
170
+
171
+ it('切换租户 → 头像重新补读(缓存按 userId+tenantId 隔离)', async () => {
172
+ useAuthStore.setState({
173
+ accessToken: 'token-xyz',
174
+ user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
175
+ currentTenantId: 't1',
176
+ permissions: ['user.read'],
177
+ tenants: [{ id: 't1', name: 'demo', role: 'member' }],
178
+ });
179
+ mockProfileAvatar.mockResolvedValue({ avatarUrl: 'https://cdn.example.com/c.png' });
180
+
181
+ renderHook(() => useBootstrap(), { wrapper });
182
+ await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalledTimes(1));
183
+
184
+ act(() => {
185
+ useAuthStore.setState({ currentTenantId: 't2' });
186
+ });
187
+ await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalledTimes(2));
188
+ });
128
189
  });
@@ -1,6 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import { useEffect } from 'react';
4
+ import { useQueryClient } from '@tanstack/react-query';
4
5
  import { useAuthStore } from '../auth/store';
5
6
  import { AuthService } from '../auth/service';
6
7
  import { usePermissionsQuery, useTenantsQuery } from '../auth/auth-queries';
@@ -52,13 +53,24 @@ export function useBootstrap(): BootstrapState {
52
53
  // 失败静默(展示层回落首字母,不影响任何业务流程)。
53
54
  // 用动态 import 引生成客户端:generated/api 反向 import '@autional/shared',
54
55
  // 静态导入会在包入口形成循环,动态导入等入口初始化完再求值。
56
+ // React Query 负责去重与缓存:同一 userId+tenantId 并发/重复挂载只发一次请求(5 分钟缓存)。
57
+ const queryClient = useQueryClient();
58
+ const userId = useAuthStore((s) => s.user?.id);
55
59
  useEffect(() => {
56
60
  if (!hasToken) return;
57
61
  let cancelled = false;
58
- void import('../generated/api')
59
- .then(({ profileAvatar }) => profileAvatar())
60
- .then((res) => {
61
- const avatarUrl = ((res as { avatarUrl?: string } | undefined)?.avatarUrl ?? '').trim();
62
+ void queryClient
63
+ .fetchQuery({
64
+ queryKey: ['profile-avatar', userId ?? '', currentTenantId ?? ''],
65
+ queryFn: async () => {
66
+ const { profileAvatar } = await import('../generated/api');
67
+ const res = await profileAvatar();
68
+ return ((res as { avatarUrl?: string } | undefined)?.avatarUrl ?? '').trim() || null;
69
+ },
70
+ staleTime: 5 * 60_000,
71
+ retry: false, // 头像失败静默,不重试
72
+ })
73
+ .then((avatarUrl) => {
62
74
  if (cancelled || !avatarUrl) return;
63
75
  const current = useAuthStore.getState().user;
64
76
  if (current && current.avatarUrl !== avatarUrl) {
@@ -71,7 +83,7 @@ export function useBootstrap(): BootstrapState {
71
83
  return () => {
72
84
  cancelled = true;
73
85
  };
74
- }, [hasToken]);
86
+ }, [hasToken, userId, currentTenantId, queryClient]);
75
87
 
76
88
  // 无会话 = 无数据可引导:返回 'idle',登录交棒由 RequireAuth/守卫决策(见上)。
77
89
  // 不得返回 'loading':Layout 消费者(platform-console)以 bootstrap==='loading'
@@ -90,10 +102,13 @@ export function useBootstrap(): BootstrapState {
90
102
  return 'ready';
91
103
  }
92
104
 
93
- // 两个请求都失败 — keep reporting loading to prevent re-render loops
94
- // (OAuth PKCE or BFF redirect will resolve the page before error matters)
105
+ // 两个请求都失败 —— 语义是「启动失败」,不是「仍在加载」。
106
+ // 旧实现返回 'loading'(原注释:防重渲染循环),使状态机永停 bootstrap、
107
+ // RequireAuth 恒 render null ⇒ 后端 5xx 时整站白屏(P1-2,2026-11-08 线上复现:
108
+ // 四个 bootstrap 接口全 500 → #root 只剩空容器,无提示/无重试)。
109
+ // 返回 'error' 是稳定值(不会抖动),由 RequireAuth 渲染可恢复错误页。
95
110
  if (permsQuery.isError && tentsQuery.isError) {
96
- return 'loading';
111
+ return 'error';
97
112
  }
98
113
 
99
114
  // 等待中