Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(mobile): Android bundle 不再引用 expo-notifications 原生模块 (#1667)
guyong-zapo31cd9f1d8c10
diff --git a/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.ts b/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.tsnew file mode 100644index 0000000000..af2228e354--- /dev/null+++ b/apps/mobile/src/__tests__/nativeNotificationsDecoupling.test.ts@@ -0,0 +1,129 @@+/**+ * Android 与 expo-notifications 原生模块解耦的守门(静态断言 + 面接口对齐)。+ *+ * expo-notifications 的 JS 入口在 **import 期**就 `requireNativeModule(...)`,原生模块+ * 缺失即抛;而 Android 推送从未实现(`isPushSupported()` 只放行 iOS),那颗原生模块只是+ * 把 Firebase Messaging / Installations / DataTransport 与消息权限带进 Android 包。+ * 因此约定:业务代码只经 `@/notifications/nativeNotifications` 访问该 SDK,Android 由+ * `nativeNotifications.android.ts` 顶成空实现,Android bundle 完全不引用真模块。+ *+ * 这两条断言拦的是**运行期才会暴露**的两类回归:+ * 1. 有人在别处直接 import 'expo-notifications' → Android 冷启动崩(typecheck 拦不住);+ * 2. 有人新增 `Notifications.foo()` 调用但没在 Android 替身里补 foo → Android 上+ * `undefined is not a function`。typecheck 已能拦第 2 类(替身按+ * NativeNotificationsApi 收敛),这里再加一道源码级兜底,顺带覆盖 app/ 路由文件。+ */+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it, vi } from 'vitest';++// 真模块拖 react-native 依赖链,node 环境下不可 import;替身只用到 PermissionStatus 枚举。+vi.mock('expo-modules-core', () => ({+ PermissionStatus: { GRANTED: 'granted', UNDETERMINED: 'undetermined', DENIED: 'denied' },+}));++const SRC_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const APP_ROOT = path.resolve(SRC_ROOT, '..', 'app');+const NOTIFICATIONS_DIR = path.join(SRC_ROOT, 'notifications');++/** 唯一允许出现 'expo-notifications' 的两个文件:真接入点与它的纯类型契约。 */+const SDK_ALLOWLIST = new Set([+ path.join(NOTIFICATIONS_DIR, 'nativeNotifications.ts'),+ path.join(NOTIFICATIONS_DIR, 'nativeNotifications.types.ts'),+]);++/**+ * 只认真正的模块引用形态,散文里提到 SDK 名(注释)不算违规。+ *+ * 关键字必须带 `\b`:否则 `perform('expo-notifications')` 之类会把 `form` 当成 `from`+ * 误判。引号两种都收:漏掉一种会让守门在双引号写法下静默失效(漏判比误判更糟)。+ */+const SDK_MODULE_REFERENCE =+ /\b(?:from|import|require)\s*\(?\s*['"]expo-notifications(?:\/[^'"]*)?['"]/;+const NATIVE_NOTIFICATIONS_IMPORT =+ /\b(?:from|import|require)\s*\(?\s*['"](?:\.\/|@\/notifications\/)nativeNotifications['"]/;+const NOTIFICATIONS_MEMBER = /\bNotifications\.([A-Za-z0-9_]+)/g;++function* walkSourceFiles(dir: string): Generator<string> {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name.startsWith('.') || entry.name === '__tests__') {+ continue;+ }+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) yield* walkSourceFiles(full);+ else if (/\.(ts|tsx)$/.test(entry.name) && !entry.name.endsWith('.d.ts')) yield full;+ }+}++function allSourceFiles(): string[] {+ return [...walkSourceFiles(SRC_ROOT), ...walkSourceFiles(APP_ROOT)];+}++describe('Android 不引用 expo-notifications 原生模块', () => {+ // 守门自身的判据要有用例:正则悄悄失配会让上面两条断言变成永绿的假保险。+ it('模块引用正则认得各种写法,且不被散文/相似词误命中', () => {+ for (const violation of [+ "import * as Notifications from 'expo-notifications';",+ 'import * as Notifications from "expo-notifications";',+ "const n = await import('expo-notifications');",+ "require('expo-notifications')",+ "import { setBadgeCountAsync } from 'expo-notifications/build/BadgeModule';",+ ]) {+ expect(SDK_MODULE_REFERENCE.test(violation), violation).toBe(true);+ }+ for (const allowed of [+ '// expo-notifications 的 JS 入口在 import 期就 requireNativeModule(...)',+ "await perform('expo-notifications')", // form ≠ from:词边界必须挡住+ "import * as Notifications from './nativeNotifications';",+ ]) {+ expect(SDK_MODULE_REFERENCE.test(allowed), allowed).toBe(false);+ }++ for (const consumer of [+ "import Notifications from './nativeNotifications';",+ 'import Notifications from "./nativeNotifications";',+ "import Notifications from '@/notifications/nativeNotifications';",+ ]) {+ expect(NATIVE_NOTIFICATIONS_IMPORT.test(consumer), consumer).toBe(true);+ }+ expect(+ NATIVE_NOTIFICATIONS_IMPORT.test("import x from './nativeNotificationsHelper';"),+ ).toBe(false);+ });++ it('除接入点外没有文件直接 import expo-notifications', () => {+ const violations = allSourceFiles().filter(+ (file) =>+ !SDK_ALLOWLIST.has(file) &&+ SDK_MODULE_REFERENCE.test(fs.readFileSync(file, 'utf8')),+ );+ expect(+ violations.map((file) => path.relative(SRC_ROOT, file)),+ '请改用 @/notifications/nativeNotifications(原因见该文件头注)',+ ).toEqual([]);+ });++ it('Android 替身覆盖了业务代码用到的每个成员', async () => {+ const androidStub = (+ await import('@/notifications/nativeNotifications.android')+ ).default as Record<string, unknown>;++ const used = new Set<string>();+ for (const file of allSourceFiles()) {+ const content = fs.readFileSync(file, 'utf8');+ if (!NATIVE_NOTIFICATIONS_IMPORT.test(content)) continue;+ for (const [, member] of content.matchAll(NOTIFICATIONS_MEMBER)) {+ used.add(member);+ }+ }++ // 面接口不为空,避免正则失配导致这条断言空转成永真。+ expect(used.size).toBeGreaterThan(0);+ expect(+ [...used].filter((member) => typeof androidStub[member] !== 'function').sort(),+ '请在 nativeNotifications.android.ts 补上这些成员的 Android 实现',+ ).toEqual([]);+ });+});diff --git a/apps/mobile/src/notifications/PushNotificationsBridge.tsx b/apps/mobile/src/notifications/PushNotificationsBridge.tsxindex 6d813d5e3f..c6ab69c22a 100644--- a/apps/mobile/src/notifications/PushNotificationsBridge.tsx+++ b/apps/mobile/src/notifications/PushNotificationsBridge.tsx@@ -1,7 +1,7 @@-import * as Notifications from 'expo-notifications';import { useRouter } from 'expo-router';import { useEffect, useRef } from 'react';import { useAuth } from '@/auth/AuthContext';+import Notifications from './nativeNotifications';import { parseNotificationDeepLink } from './pushRegistrationModel';import {configureForegroundNotificationBehavior,diff --git a/apps/mobile/src/notifications/nativeNotifications.android.ts b/apps/mobile/src/notifications/nativeNotifications.android.tsnew file mode 100644index 0000000000..0585a4d95e--- /dev/null+++ b/apps/mobile/src/notifications/nativeNotifications.android.ts@@ -0,0 +1,47 @@+import { PermissionStatus } from 'expo-modules-core';++import type { NativeNotificationsApi } from './nativeNotifications.types';++/**+ * Android 的 expo-notifications 替身(Metro 平台扩展在 `platform === 'android'` 时+ * 顶掉 `nativeNotifications.ts`)。+ *+ * 为什么是替身而不是直接用真模块:见 `nativeNotifications.ts` 的说明——真模块在+ * import 期就要求原生模块存在,而 Android 推送从未实现(`isPushSupported()` 只放行+ * iOS),那颗原生模块只是把 Firebase Messaging / Installations / DataTransport 与消息+ * 权限带进包里。本文件让 Android bundle 完全不引用 expo-notifications。+ *+ * 因此这里的实现只需保证「被 import 不炸」:所有真实调用点都在 `isPushSupported()`+ * 之后,正常路径下一个都不会执行到。行为上取最保守语义(权限拒绝、订阅空实现、+ * 无历史通知),而 `getDevicePushTokenAsync` 直接抛——它没有任何合理的假值可返回,+ * 静默返回空串只会把坏数据发到 server 的注册表。+ *+ * 要给 Android 接推送时:实现应该落在本文件(接国内厂商通道或 FCM),而不是把+ * `isPushSupported()` 放开去用真模块——那会把整条 Google 链重新带回来。+ */++const EMPTY_SUBSCRIPTION = { remove: () => {} };++const DENIED: Awaited<+ ReturnType<NativeNotificationsApi['getPermissionsAsync']>+> = {+ status: PermissionStatus.DENIED,+ expires: 'never',+ granted: false,+ canAskAgain: false,+};++const nativeNotifications: NativeNotificationsApi = {+ setNotificationHandler: () => {},+ getPermissionsAsync: async () => DENIED,+ requestPermissionsAsync: async () => DENIED,+ getDevicePushTokenAsync: async () => {+ throw new Error('Push notifications are not supported on Android');+ },+ addPushTokenListener: () => EMPTY_SUBSCRIPTION,+ addNotificationResponseReceivedListener: () => EMPTY_SUBSCRIPTION,+ getLastNotificationResponseAsync: async () => null,+ clearLastNotificationResponseAsync: async () => {},+};++export default nativeNotifications;diff --git a/apps/mobile/src/notifications/nativeNotifications.ts b/apps/mobile/src/notifications/nativeNotifications.tsnew file mode 100644index 0000000000..5d4240954b--- /dev/null+++ b/apps/mobile/src/notifications/nativeNotifications.ts@@ -0,0 +1,25 @@+import * as Notifications from 'expo-notifications';++import type { NativeNotificationsApi } from './nativeNotifications.types';++/**+ * expo-notifications 的接入点(iOS / Web / 单测走本文件;Android 由+ * `nativeNotifications.android.ts` 按 Metro 平台扩展顶掉)。+ *+ * 为什么要这层间接:expo-notifications 的 JS 入口在 **import 期**就+ * `requireNativeModule('ExpoNotificationsEmitter')`(见其+ * `build/NotificationsEmitterModule.native.js`),原生模块缺失即抛。而移动推送只实现了+ * iOS(APNs,见 `pushNotifications.ts` 的 `isPushSupported`),Android 从未走通:+ * 仓内没有 `google-services.json`,拿不到 FCM token,原生模块纯属搭载——却把+ * Firebase Messaging / Installations / DataTransport 与相关消息权限一整条链带进了包。+ *+ * 把 import 收进本模块后,Android bundle 里不会再出现 expo-notifications,+ * 该原生模块可以被安全剥离(是否剥离由出包侧决定,与本层解耦无关)。+ *+ * 与 `platform/appDistribution.ts` 的平台扩展方向相反(那里基础文件是兜底、+ * `.ios.ts` 才是原生):这里基础文件必须是真模块,才能让 iOS、Web 与 node 单测+ * (mock 'expo-notifications')都走真实接线,只有 Android 需要被顶掉。+ */+const nativeNotifications: NativeNotificationsApi = Notifications;++export default nativeNotifications;diff --git a/apps/mobile/src/notifications/nativeNotifications.types.ts b/apps/mobile/src/notifications/nativeNotifications.types.tsnew file mode 100644index 0000000000..ce0d4cbd95--- /dev/null+++ b/apps/mobile/src/notifications/nativeNotifications.types.ts@@ -0,0 +1,19 @@+/**+ * 移动推送真正用到的 expo-notifications 接口面(纯类型,不产生任何运行期 import)。+ *+ * 这里刻意只列**已在用**的成员:Android 侧的实现(`nativeNotifications.android.ts`)+ * 必须逐个补齐,新增调用点时漏补会直接 typecheck 失败,不会静默漏到运行期。+ * 用 `typeof import(...)` 而不是 `import type * as`,保证本文件编译后为空模块,+ * Android bundle 不会因为它而牵进 expo-notifications。+ */+export type NativeNotificationsApi = Pick<+ typeof import('expo-notifications'),+ | 'setNotificationHandler'+ | 'getPermissionsAsync'+ | 'requestPermissionsAsync'+ | 'getDevicePushTokenAsync'+ | 'addPushTokenListener'+ | 'addNotificationResponseReceivedListener'+ | 'getLastNotificationResponseAsync'+ | 'clearLastNotificationResponseAsync'+>;diff --git a/apps/mobile/src/notifications/pushNotifications.ts b/apps/mobile/src/notifications/pushNotifications.tsindex ca692d5d60..880cb7a712 100644--- a/apps/mobile/src/notifications/pushNotifications.ts+++ b/apps/mobile/src/notifications/pushNotifications.ts@@ -1,4 +1,3 @@-import * as Notifications from 'expo-notifications';import AsyncStorage from '@react-native-async-storage/async-storage';import { Platform } from 'react-native';import type { ClientEndpointRegion } from '@cindy/maker-shared/client-endpoints';@@ -10,6 +9,7 @@ import {getMobileEndpointForRealm,loadMobileEndpointsForRealm,} from '@/config/env';+import Notifications from './nativeNotifications';import { buildPushTokenRegistrationBody } from './pushRegistrationModel';/**@@ -19,7 +19,8 @@ import { buildPushTokenRegistrationBody } from './pushRegistrationModel';* - 注册目标是 device-link server 的 PUT /push-token(Bearer 鉴权与 WS 同源);* 关闭开关 / 登出 / 换账号或区域时注销(DELETE,幂等)。* - 仅 iOS(APNs):Android 需 FCM / 国内厂商通道,二期接入(server 侧已预留- * provider='fcm' 字段)。+ * provider='fcm' 字段)。原生模块只在 iOS 存在,所有调用一律经+ * `./nativeNotifications`(Android 由平台扩展顶成空实现,原因见该文件)。* - App 在前台时压掉系统横幅(WS 活着,会话本来就在实时刷新)。*/