@autional/shared 0.1.0-rc.56 → 0.1.0-rc.57

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.
@@ -0,0 +1,328 @@
1
+ /**
2
+ * `fetch` 版 API 客户端 —— 与 axios 版 `createApiClient()` **并存**,供「零运行时依赖」的控制台使用。
3
+ *
4
+ * 背景(docs/CONSOLE-KIT-DECISION.md §4-2):配置中心 / 密钥中心用原生 fetch + 自建错误映射,
5
+ * 与 shared 的 axios client 是两套实现(同一 bug 双写:见决策记录 §2.1)。本客户端只收敛
6
+ * **传输层**(鉴权头、租户头、超时、错误归一、401 续期),不接管业务端点函数 ⇒ 两站可先换
7
+ * 请求层,不动页面。
8
+ *
9
+ * 设计约束(与 axios client 的差异,务必保留):
10
+ * - **默认透传**:不 unwrap `{code,data}` 信封、不做 snake/camel 转换。两站后端通行 snake_case,
11
+ * 且响应形状各异(`{items,total,page}` / 裸对象)。解包与转键用 `unwrap` / `caseConversion` 显式开启。
12
+ * - 额外作用域头(如 `X-App-ID`)经 `getHeaders` 注入,不硬编码。
13
+ * - `credentials: 'omit'`:与 shared axios(`withCredentials:false`)一致 —— 网关跨源不回写 ACAC。
14
+ */
15
+
16
+ /** 归一后的 API 错误(替代各站自建 `ApiError`)。 */
17
+ export class FetchApiError extends Error {
18
+ readonly status: number;
19
+ readonly code: string;
20
+ readonly detail: string;
21
+ readonly body: unknown;
22
+
23
+ constructor(status: number, message: string, code = '', detail = '', body: unknown = null) {
24
+ super(message);
25
+ this.name = 'FetchApiError';
26
+ this.status = status;
27
+ this.code = code;
28
+ this.detail = detail;
29
+ this.body = body;
30
+ }
31
+ }
32
+
33
+ export type FetchQueryValue = string | number | boolean | null | undefined;
34
+
35
+ export interface FetchRequestOptions {
36
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
37
+ query?: Record<string, FetchQueryValue | FetchQueryValue[]>;
38
+ /** 对象 ⇒ JSON.stringify;字符串/Blob/FormData 原样透传。 */
39
+ body?: unknown;
40
+ headers?: Record<string, string>;
41
+ /** 单次覆盖超时(ms)。 */
42
+ timeoutMs?: number;
43
+ signal?: AbortSignal;
44
+ }
45
+
46
+ export interface FetchClientOptions {
47
+ /** 基址(如 `/bff/config/api/v1/admin/config`),与 path 直接拼接。 */
48
+ baseUrl: string;
49
+ /** 取 access token(缺省不注入 Authorization)。 */
50
+ getToken?: () => string | null | undefined;
51
+ /** 取租户 ID(缺省不注入 X-Tenant-ID)。 */
52
+ getTenantId?: () => string | null | undefined;
53
+ /** 额外作用域头(X-App-ID / X-Namespace …),每次请求求值。 */
54
+ getHeaders?: () => Record<string, string>;
55
+ /**
56
+ * 401 回调(跳登录 / 触发全局事件)。
57
+ * **只在「放弃」时调用**:无 refresh、refresh 返回空、或续期后重试仍 401 —— 整个请求最多一次。
58
+ * 可救回的 401 静默续期,不打扰用户。
59
+ */
60
+ onUnauthorized?: (error: FetchApiError) => void;
61
+ /** 401 静默续期:返回新 token 则重试一次;返回 null/抛错则放弃。 */
62
+ refresh?: () => Promise<string | null>;
63
+ /** 默认超时,20s(与两站现状一致)。 */
64
+ timeoutMs?: number;
65
+ /**
66
+ * 解 `{code,data}` 信封(`code != 0` 视为错误,number 与字符串形态都认)。
67
+ * `{code,items}` 列表信封保持原形返回,由调用方取 `items`。默认 false(透传)。
68
+ */
69
+ unwrap?: boolean;
70
+ /** 响应键名归一:`'camel'` = Pascal/snake → camelCase。默认 `'none'`。 */
71
+ caseConversion?: 'none' | 'camel';
72
+ }
73
+
74
+ export interface FetchClient {
75
+ request<T = unknown>(path: string, options?: FetchRequestOptions): Promise<T>;
76
+ get<T = unknown>(path: string, options?: FetchRequestOptions): Promise<T>;
77
+ post<T = unknown>(path: string, body?: unknown, options?: FetchRequestOptions): Promise<T>;
78
+ put<T = unknown>(path: string, body?: unknown, options?: FetchRequestOptions): Promise<T>;
79
+ patch<T = unknown>(path: string, body?: unknown, options?: FetchRequestOptions): Promise<T>;
80
+ delete<T = unknown>(path: string, options?: FetchRequestOptions): Promise<T>;
81
+ }
82
+
83
+ const DEFAULT_TIMEOUT_MS = 20_000;
84
+
85
+ function buildUrl(baseUrl: string, path: string, query?: FetchRequestOptions['query']): string {
86
+ const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost';
87
+ const url = new URL(`${baseUrl}${path}`, origin);
88
+ if (query) {
89
+ for (const [key, value] of Object.entries(query)) {
90
+ if (value === undefined || value === null) continue;
91
+ if (Array.isArray(value)) {
92
+ for (const item of value) {
93
+ if (item === undefined || item === null) continue;
94
+ url.searchParams.append(key, String(item));
95
+ }
96
+ continue;
97
+ }
98
+ url.searchParams.set(key, String(value));
99
+ }
100
+ }
101
+ return url.toString();
102
+ }
103
+
104
+ function toCamelCase(key: string): string {
105
+ return key.replace(/[_-](\w)/g, (_, next: string) => next.toUpperCase());
106
+ }
107
+
108
+ /** 递归把对象的键转 camelCase(仅响应侧,显式开启时使用)。 */
109
+ function camelizeKeys<T>(input: unknown): T {
110
+ if (Array.isArray(input)) return input.map((item) => camelizeKeys(item)) as unknown as T;
111
+ if (!input || typeof input !== 'object' || input instanceof Blob || input instanceof FormData) {
112
+ return input as T;
113
+ }
114
+ const out: Record<string, unknown> = {};
115
+ for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
116
+ out[toCamelCase(key)] = camelizeKeys(value);
117
+ }
118
+ return out as T;
119
+ }
120
+
121
+ interface ProblemBody {
122
+ title?: string;
123
+ detail?: string;
124
+ code?: string | number;
125
+ message?: string;
126
+ status?: number;
127
+ }
128
+
129
+ function toError(status: number, body: unknown, fallbackMessage?: string): FetchApiError {
130
+ const problem = (body && typeof body === 'object' ? body : null) as ProblemBody | null;
131
+ const message =
132
+ problem?.title || problem?.message || fallbackMessage || `HTTP ${status}`;
133
+ const code = problem?.code === undefined || problem.code === null ? '' : String(problem.code);
134
+ const detail = problem?.detail || problem?.message || message;
135
+ return new FetchApiError(status, message, code, detail, body);
136
+ }
137
+
138
+ /**
139
+ * 创建 fetch 客户端。
140
+ *
141
+ * 用法(配置中心形态):
142
+ * ```ts
143
+ * const client = createFetchClient({
144
+ * baseUrl: '/bff/config/api/v1/admin/config',
145
+ * getToken: () => currentSession()?.accessToken,
146
+ * getTenantId: () => currentSession()?.user.tenantId,
147
+ * getHeaders: () => ({ 'X-App-ID': APP_ID }),
148
+ * onUnauthorized: () => window.dispatchEvent(new CustomEvent('config-console:unauthorized')),
149
+ * refresh: () => refreshSession()?.accessToken ?? null,
150
+ * });
151
+ * ```
152
+ */
153
+ export function createFetchClient(options: FetchClientOptions): FetchClient {
154
+ const {
155
+ baseUrl,
156
+ getToken,
157
+ getTenantId,
158
+ getHeaders,
159
+ onUnauthorized,
160
+ refresh,
161
+ timeoutMs = DEFAULT_TIMEOUT_MS,
162
+ unwrap = false,
163
+ caseConversion = 'none',
164
+ } = options;
165
+
166
+ async function send<T>(
167
+ path: string,
168
+ init: FetchRequestOptions,
169
+ retried: boolean,
170
+ tokenOverride?: string | null,
171
+ ): Promise<T> {
172
+ const { method = 'GET', query, body, headers: extraHeaders, timeoutMs: perCall, signal } = init;
173
+ const effectiveTimeout = perCall ?? timeoutMs;
174
+
175
+ const headers: Record<string, string> = { Accept: 'application/json' };
176
+ let payload: BodyInit | undefined;
177
+
178
+ if (body !== undefined && body !== null) {
179
+ if (
180
+ typeof body === 'string' ||
181
+ body instanceof Blob ||
182
+ body instanceof FormData ||
183
+ body instanceof URLSearchParams
184
+ ) {
185
+ payload = body as BodyInit;
186
+ } else {
187
+ payload = JSON.stringify(body);
188
+ headers['Content-Type'] = 'application/json';
189
+ }
190
+ }
191
+
192
+ // 作用域头:显式 headers 优先于自动注入(调用方可覆盖)
193
+ // 续期重试时用续期返回的 token(调用方不一定回写 store);无 token 不注入租户头
194
+ // —— 与 api/client.ts:37-41 同口径(无 token 时 token 里的租户才是唯一权威)。
195
+ const token = tokenOverride ?? getToken?.() ?? null;
196
+ if (token) {
197
+ headers.Authorization = `Bearer ${token}`;
198
+ const tenantId = getTenantId?.() ?? null;
199
+ if (tenantId) headers['X-Tenant-ID'] = tenantId;
200
+ }
201
+ if (getHeaders) Object.assign(headers, getHeaders());
202
+ if (extraHeaders) Object.assign(headers, extraHeaders);
203
+
204
+ // 调用方已取消 ⇒ 直接失败(addEventListener 对"已 abort"的 signal 不会再触发)
205
+ if (signal?.aborted) {
206
+ throw new FetchApiError(0, '请求已取消', 'aborted');
207
+ }
208
+
209
+ const controller = new AbortController();
210
+ let timedOut = false;
211
+ const timer = setTimeout(() => {
212
+ timedOut = true;
213
+ controller.abort();
214
+ }, effectiveTimeout);
215
+ const onAbort = () => controller.abort();
216
+ signal?.addEventListener('abort', onAbort);
217
+
218
+ let response: Response;
219
+ try {
220
+ response = await fetch(buildUrl(baseUrl, path, query), {
221
+ method,
222
+ headers,
223
+ body: payload,
224
+ credentials: 'omit',
225
+ signal: controller.signal,
226
+ });
227
+ } catch (cause) {
228
+ const aborted = (cause as Error)?.name === 'AbortError';
229
+ if (aborted) {
230
+ throw new FetchApiError(
231
+ 0,
232
+ timedOut ? `请求超时(${effectiveTimeout / 1000}s)` : '请求已取消',
233
+ timedOut ? 'timeout' : 'aborted',
234
+ );
235
+ }
236
+ throw new FetchApiError(0, `无法连接服务:${(cause as Error).message}`, 'network_error');
237
+ } finally {
238
+ clearTimeout(timer);
239
+ signal?.removeEventListener('abort', onAbort);
240
+ }
241
+
242
+ // 401:**先**尝试一次静默续期(可救回的 401 不应把用户踢去登录页);
243
+ // 只有在「没有续期能力」或「续期失败 / 重试后仍 401」时才通知 onUnauthorized,
244
+ // 且整个请求生命周期内最多通知一次。
245
+ if (response.status === 401) {
246
+ const unauthorized = toError(401, await safeJson(response), '未授权');
247
+ if (!retried && refresh) {
248
+ let nextToken: string | null = null;
249
+ try {
250
+ nextToken = await refresh();
251
+ } catch {
252
+ nextToken = null;
253
+ }
254
+ if (nextToken) {
255
+ return send<T>(path, init, true, nextToken);
256
+ }
257
+ }
258
+ onUnauthorized?.(unauthorized);
259
+ throw unauthorized;
260
+ }
261
+
262
+ const raw = await safeText(response);
263
+ let parsed: unknown = null;
264
+ if (raw !== '') {
265
+ try {
266
+ parsed = JSON.parse(raw);
267
+ } catch {
268
+ if (response.ok) {
269
+ throw new FetchApiError(response.status, '响应不是合法 JSON', 'invalid_json', raw, raw);
270
+ }
271
+ parsed = raw;
272
+ }
273
+ }
274
+
275
+ if (!response.ok) {
276
+ throw toError(response.status, parsed);
277
+ }
278
+
279
+ let result: unknown = parsed;
280
+ if (unwrap && parsed && typeof parsed === 'object') {
281
+ const envelope = parsed as { code?: unknown; data?: unknown; items?: unknown; message?: string };
282
+ // 业务码:number 0 / 字符串 '0' 视为成功;其余非空值为错误(部分服务把 code 序列化成字符串)
283
+ const code = envelope.code;
284
+ const failedCode =
285
+ (typeof code === 'number' && code !== 0) ||
286
+ (typeof code === 'string' && code !== '' && code !== '0');
287
+ if (failedCode) {
288
+ throw toError(response.status, parsed);
289
+ }
290
+ if ('data' in envelope && envelope.data !== undefined) {
291
+ result = envelope.data;
292
+ }
293
+ // 列表信封(`{items,total,pagination}`):保持原形,由调用方取 items
294
+ }
295
+
296
+ return (caseConversion === 'camel' ? camelizeKeys<T>(result) : result) as T;
297
+ }
298
+
299
+ const request = <T,>(path: string, init: FetchRequestOptions = {}): Promise<T> =>
300
+ send<T>(path, init, false);
301
+
302
+ return {
303
+ request,
304
+ get: (path, init) => request(path, { ...init, method: 'GET' }),
305
+ post: (path, body, init) => request(path, { ...init, method: 'POST', body }),
306
+ put: (path, body, init) => request(path, { ...init, method: 'PUT', body }),
307
+ patch: (path, body, init) => request(path, { ...init, method: 'PATCH', body }),
308
+ delete: (path, init) => request(path, { ...init, method: 'DELETE' }),
309
+ };
310
+ }
311
+
312
+ async function safeText(response: Response): Promise<string> {
313
+ try {
314
+ return await response.text();
315
+ } catch {
316
+ return '';
317
+ }
318
+ }
319
+
320
+ async function safeJson(response: Response): Promise<unknown> {
321
+ const raw = await safeText(response);
322
+ if (!raw) return null;
323
+ try {
324
+ return JSON.parse(raw);
325
+ } catch {
326
+ return raw;
327
+ }
328
+ }
@@ -0,0 +1,144 @@
1
+ // @vitest-environment jsdom
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import {
4
+ configureAuthStore,
5
+ getAuthStore,
6
+ getAuthStorageMode,
7
+ resetAuthStore,
8
+ useAuthStore,
9
+ } from '../store';
10
+ import { createAuthStore, resolveAuthStorage } from '../create-auth-store';
11
+
12
+ const KEY = 'autional-auth-v1';
13
+
14
+ const USER = {
15
+ id: 'usr_1',
16
+ username: 'demo',
17
+ email: 'demo@example.com',
18
+ status: 'active',
19
+ } as never;
20
+
21
+ function clearAll() {
22
+ window.localStorage.clear();
23
+ window.sessionStorage.clear();
24
+ resetAuthStore();
25
+ }
26
+
27
+ describe('createAuthStore —— 存储位置可选', () => {
28
+ beforeEach(() => {
29
+ clearAll();
30
+ });
31
+
32
+ it('默认写 localStorage(既有 9 个消费方行为不变)', () => {
33
+ const store = createAuthStore();
34
+ store.getState().setAuth('access-1', 'refresh-1', USER);
35
+
36
+ expect(window.localStorage.getItem(KEY)).toContain('access-1');
37
+ expect(window.sessionStorage.getItem(KEY)).toBeNull();
38
+ });
39
+
40
+ it("storage: 'session' 只写 sessionStorage(配置中心安全取舍)", () => {
41
+ const store = createAuthStore({ storage: 'session' });
42
+ store.getState().setAuth('access-2', 'refresh-2', USER);
43
+
44
+ expect(window.sessionStorage.getItem(KEY)).toContain('access-2');
45
+ expect(window.localStorage.getItem(KEY)).toBeNull();
46
+ });
47
+
48
+ it('自定义 name 不污染默认键', () => {
49
+ const store = createAuthStore({ storage: 'session', name: 'x-auth-v1' });
50
+ store.getState().setAuth('access-3', 'r', USER);
51
+
52
+ expect(window.sessionStorage.getItem('x-auth-v1')).toContain('access-3');
53
+ expect(window.sessionStorage.getItem(KEY)).toBeNull();
54
+ });
55
+
56
+ it('clearAuth 从所选存储中移除持久化数据', () => {
57
+ const store = createAuthStore({ storage: 'session' });
58
+ store.getState().setAuth('access-4', 'r', USER);
59
+ store.getState().clearAuth();
60
+
61
+ const raw = window.sessionStorage.getItem(KEY) ?? '';
62
+ expect(raw).not.toContain('access-4');
63
+ expect(store.getState().isAuthenticated).toBe(false);
64
+ });
65
+
66
+ it('持久化内容可被同 storage 的新实例回灌', () => {
67
+ const first = createAuthStore({ storage: 'local' });
68
+ first.getState().setAuth('access-5', 'refresh-5', USER);
69
+
70
+ const second = createAuthStore({ storage: 'local' });
71
+ expect(second.getState().accessToken).toBe('access-5');
72
+ expect(second.getState().isAuthenticated).toBe(true);
73
+ });
74
+
75
+ it('存储不可用(getItem/setItem 抛错)不崩,退化为内存', () => {
76
+ const broken = resolveAuthStorage('local');
77
+ const spy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
78
+ throw new Error('QuotaExceededError');
79
+ });
80
+ try {
81
+ expect(() => broken.setItem('k', 'v')).not.toThrow();
82
+ expect(() => broken.getItem('k')).not.toThrow();
83
+ } finally {
84
+ spy.mockRestore();
85
+ }
86
+ });
87
+ });
88
+
89
+ describe('configureAuthStore —— 惰性单例', () => {
90
+ beforeEach(() => {
91
+ clearAll();
92
+ });
93
+
94
+ it('幂等:重复调用返回同一实例', () => {
95
+ const a = configureAuthStore({ storage: 'session' });
96
+ const b = configureAuthStore({ storage: 'session' });
97
+ expect(a).toBe(b);
98
+ expect(getAuthStore()).toBe(a);
99
+ });
100
+
101
+ it("configure 在首次访问前生效:storage = 'session'", () => {
102
+ configureAuthStore({ storage: 'session' });
103
+ expect(getAuthStorageMode()).toBe('session');
104
+ useAuthStore.getState().setAuth('access-6', 'r', USER);
105
+
106
+ expect(window.sessionStorage.getItem(KEY)).toContain('access-6');
107
+ expect(window.localStorage.getItem(KEY)).toBeNull();
108
+ });
109
+
110
+ it('未 configure ⇒ 默认 local(不是 session)', () => {
111
+ expect(getAuthStorageMode()).toBe('local');
112
+ getAuthStore().getState().setAuth('access-7', 'r', USER);
113
+ expect(window.localStorage.getItem(KEY)).toContain('access-7');
114
+ });
115
+
116
+ it('导入 store 模块不提前建实例(否则先 configure 也会退化为 local)', async () => {
117
+ vi.resetModules();
118
+ // 模拟站点入口顺序:先 import(不得有副作用),再 configure,再写入
119
+ const fresh = await import('../store');
120
+ fresh.configureAuthStore({ storage: 'session' });
121
+ fresh.useAuthStore.getState().setAuth('access-early', 'r', USER);
122
+
123
+ expect(fresh.getAuthStorageMode()).toBe('session');
124
+ expect(window.sessionStorage.getItem(KEY)).toContain('access-early');
125
+ expect(window.localStorage.getItem(KEY)).toBeNull();
126
+ });
127
+
128
+ it('persist API 透传是惰性的(取用才建实例,不在模块求值期求值)', async () => {
129
+ vi.resetModules();
130
+ const fresh = await import('../store');
131
+ // 访问 persist 之前不得创建实例:configure 仍应生效
132
+ expect(typeof Object.getOwnPropertyDescriptor(fresh.useAuthStore, 'persist')?.get).toBe('function');
133
+ fresh.configureAuthStore({ storage: 'session' });
134
+ const persist = (fresh.useAuthStore as unknown as { persist?: { rehydrate?: unknown } }).persist;
135
+ expect(persist).toBeTruthy();
136
+ expect(fresh.getAuthStorageMode()).toBe('session');
137
+ });
138
+
139
+ it('兼容旧调用点:hook 形状 + getState/setState 静态方法都可用', () => {
140
+ useAuthStore.setState({ accessToken: 'access-8' });
141
+ expect(useAuthStore.getState().accessToken).toBe('access-8');
142
+ expect(typeof useAuthStore.subscribe).toBe('function');
143
+ });
144
+ });