chore: mac打包配置

This commit is contained in:
Wxw-Gu committed 2026-11-01 01:21:00 +08:00
1 parent 84737a7407
commit 915ee73f95
20 files changed
+1170 -58

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
import { app } from 'electron'
import fs from 'node:fs'
import path from 'node:path'
import ffmpegStaticPath from 'ffmpeg-static'
export function resolveBundledFfmpegPath(): string {
if (process.platform === 'darwin' && app.isPackaged) {
const editionFfmpeg = path.join(process.resourcesPath, 'resources', 'ffmpeg', 'ffmpeg')
if (fs.existsSync(editionFfmpeg)) return editionFfmpeg
}
return String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked').trim()
}
+2 -4
View File
@@ -5,7 +5,7 @@ import os from 'os'
import { app } from 'electron'
import { execFile } from 'child_process'
import { Worker } from 'worker_threads'
import ffmpegStaticPath from 'ffmpeg-static'
import { resolveBundledFfmpegPath } from './ffmpeg-path'
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
import { loadSettings } from './services/settings-store'
@@ -78,9 +78,7 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa
const selected = String(selectedPath || '').trim()
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
const staticExecutable = String(ffmpegStaticPath || '')
.replace('app.asar', 'app.asar.unpacked')
.trim()
const staticExecutable = resolveBundledFfmpegPath()
const candidates: FfmpegCandidate[] = [
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
+11
View File
@@ -202,6 +202,7 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
const scope = resolveMsgInsertScopeInput()
if (scope) {
const snapshot = readMsgInsertSwitches(scope)
snapshot.sendCapabilityAvailable = !isMacNativeRuntimeUnavailable()
/* 退群提示的开关状态来自本地设置(事件驱动,不装规则),
* 不是微信库里的 _tm_config。 */
snapshot.switches.group_exit_notice = eventModeStatus(
@@ -213,6 +214,7 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
}
return {
success: false,
sendCapabilityAvailable: !isMacNativeRuntimeUnavailable(),
switches: {
recall_notice: emptyMsgInsertStatus('recall_notice'),
group_exit_notice: eventModeStatus(
@@ -390,6 +392,7 @@ import type {
PersonalWechatSendResult,
PersonalWechatSenderStatus
} from '../shared/personal-wechat'
import { isMacNativeRuntimeUnavailable } from './native-runtime-paths'
import { isTruthyDebugFlag } from '../shared/debug-flags'
import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service'
import type {
@@ -2252,6 +2255,14 @@ app.whenReady().then(async () => {
message: '未知的开关'
}
}
if (isMacNativeRuntimeUnavailable()) {
return {
success: false,
status: emptyMsgInsertStatus(name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'),
errorCode: 'HELPER_NOT_FOUND',
message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响'
}
}
/*
* 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条),
* 不装任何 per-room 规则。所以它的开关只是本地设置:
+90
View File
@@ -0,0 +1,90 @@
import fs from 'node:fs'
import path from 'node:path'
import { app } from 'electron'
import { findResource } from './resource-paths'
export type NativeRuntimeProfile = 'public' | 'native'
const BUILD_MARKER = 'tracememo-build.json'
const RUNTIME_RELATIVE = 'runtime/darwin-arm64'
let cachedProfile: NativeRuntimeProfile | null = null
let cachedMarkerRead = false
function getNativeRuntimeProfile(): NativeRuntimeProfile {
const envProfile = !app.isPackaged ? process.env.TRACEMEMO_RUNTIME_PROFILE : undefined
if (envProfile === 'public' || envProfile === 'native') return envProfile
if (cachedMarkerRead && cachedProfile) return cachedProfile
cachedMarkerRead = true
const marker = findResource(BUILD_MARKER)
if (marker) {
try {
const parsed = JSON.parse(fs.readFileSync(marker, 'utf8')) as { profile?: unknown }
if (parsed.profile === 'public' || parsed.profile === 'native') {
cachedProfile = app.isPackaged ? parsed.profile : 'native'
return cachedProfile
}
} catch {
// Packaged builds fail closed below when the marker cannot be read.
}
}
cachedProfile = app.isPackaged ? 'public' : 'native'
return cachedProfile
}
export function hasMacNativeBundle(): boolean {
return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native'
}
export function isMacNativeRuntimeUnavailable(): boolean {
return process.platform === 'darwin' && !hasMacNativeBundle()
}
export function resolveWcdbLibrary(): string | null {
if (process.platform !== 'darwin') return null
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`)
}
export function resolveWcdbDependency(): string | null {
const library = resolveWcdbLibrary()
if (!library) return null
const dependency = path.join(path.dirname(library), 'libWCDB.dylib')
return fs.existsSync(dependency) ? dependency : null
}
export function resolveWcdbConfigHelper(): string | null {
if (isMacNativeRuntimeUnavailable()) return null
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
return findResource(`wcdb/macos/${arch}/tm-wcdb-config-helper`)
}
export function resolveWechatRuntimeDirectory(): string | null {
if (!hasMacNativeBundle()) return null
const manifest =
findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) ||
(!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null)
return manifest ? path.dirname(manifest) : null
}
export function resolveWechatHost(): string | null {
const directory = resolveWechatRuntimeDirectory()
if (!directory) return null
const candidate = path.join(directory, 'tm-wechat-host')
return fs.existsSync(candidate) ? candidate : null
}
export function resolveWechatDylib(): string | null {
const directory = resolveWechatRuntimeDirectory()
if (!directory) return null
const candidate = path.join(directory, 'libtmwechat.dylib')
return fs.existsSync(candidate) ? candidate : null
}
export function resolveWechatRuntimeManifest(): string | null {
const directory = resolveWechatRuntimeDirectory()
if (!directory) return null
const candidate = path.join(directory, 'runtime-manifest.json')
return fs.existsSync(candidate) ? candidate : null
}
+4
View File
@@ -7,6 +7,10 @@ function unique(values: string[]): string[] {
}
export function getResourceRoots(): string[] {
if (app.isPackaged && process.platform === 'darwin') {
const packagedResources = join(process.resourcesPath || '', 'resources')
return existsSync(packagedResources) ? [packagedResources] : []
}
const appPath = app.getAppPath()
const appPathDir = dirname(appPath)
const execDir = dirname(process.execPath)
@@ -6,7 +6,7 @@ import { join } from 'path'
import { app } from 'electron'
import { appLogger } from '../app-logger'
import { isPackagedRuntime } from '../runtime-mode'
import { isMacNativeRuntimeUnavailable, resolveWechatRuntimeDirectory } from '../native-runtime-paths'
import type {
MacWechatBindResult,
MacWechatBindingStatus,
@@ -180,25 +180,31 @@ class MacWechatRuntimeManager {
wechatRestartRequired: this.wechatRestartRequired,
endpoint: `http://${HOST}:${PORT}`,
port: PORT,
runtimeDir: this.resolveRuntimeDir(),
runtimeDir: this.resolveRuntimeDir() ?? undefined,
error: this.lastError ?? undefined,
binding: this.lastBinding ?? undefined
}
}
private resolveRuntimeDir(): string {
const base = isPackagedRuntime() ? process.resourcesPath : app.getAppPath()
return join(base, 'resources', 'runtime', 'darwin-arm64')
private resolveRuntimeDir(): string | null {
if (isMacNativeRuntimeUnavailable()) return null
const resolved = resolveWechatRuntimeDirectory()
if (resolved) return resolved
if (app.isPackaged) return null
return join(app.getAppPath(), 'resources', 'runtime', 'darwin-arm64')
}
private resolveHostPath(): string {
return join(this.resolveRuntimeDir(), 'tm-wechat-host')
return join(this.resolveRuntimeDir() || '', 'tm-wechat-host')
}
/** Runtime binaries present and executable? Cheap check for the settings UI. */
isRuntimePresent(): boolean {
if (isMacNativeRuntimeUnavailable()) return false
try {
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) return false
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
return true
} catch {
return false
@@ -211,11 +217,22 @@ class MacWechatRuntimeManager {
* online" and "WeChat bound" stay two independent states.
*/
async ensureStarted(): Promise<MacWechatRuntimeSnapshot> {
if (isMacNativeRuntimeUnavailable()) {
this.manifest = null
this.lifecycle = 'stopped'
this.lastError = '当前环境不包含微信发送能力'
return this.getSnapshot()
}
if (this.lifecycle === 'starting') {
return this.getSnapshot()
}
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) {
this.lifecycle = 'stopped'
this.lastError = '暂无发送能力'
return this.getSnapshot()
}
try {
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
appLogger.write({
@@ -517,6 +534,32 @@ class MacWechatRuntimeManager {
* circular import.
*/
async buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
if (isMacNativeRuntimeUnavailable()) {
const message = '当前环境不包含微信发送能力'
return {
state: 'runtime_missing',
platform: 'darwin',
arch: process.arch,
sipDisabled: true,
wechatRunning: false,
endpoint: `http://${HOST}:${PORT}`,
endpointReady: false,
runtimeReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message,
error: message
}
}
/*
* Lazy-start the host from status reads.
*
@@ -534,7 +577,9 @@ class MacWechatRuntimeManager {
/* Self-heal the status card too: if WeChat was restarted, drop the stale
* restartRequired before it is read into the UI as an error. */
try {
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('runtime missing')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
appLogger.write({
@@ -605,6 +650,14 @@ class MacWechatRuntimeManager {
* live WeChat pid again returns attached=false and never double-attaches.
*/
async bind(): Promise<MacWechatBindResult> {
if (isMacNativeRuntimeUnavailable()) {
return {
ok: false,
attached: false,
state: 'runtime_offline',
message: '当前环境不包含微信发送能力'
}
}
if (this.lifecycle !== 'online') {
const snapshot = await this.ensureStarted()
if (snapshot.lifecycle !== 'online') {
@@ -687,6 +740,7 @@ class MacWechatRuntimeManager {
* leave its injected agent inside WeChat and make the next attach hang.
*/
async shutdown(): Promise<void> {
if (isMacNativeRuntimeUnavailable()) return
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
@@ -29,6 +29,7 @@ import { createHash } from 'node:crypto'
import path from 'node:path'
import { findResource } from '../resource-paths'
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
import type { Wcdb4Client } from '../wcdb4-client'
import {
MSG_INSERT_SWITCHES,
@@ -156,6 +157,7 @@ export function emptyMsgInsertStatus(
* 开发态与打包态都靠 findResource 解析,不依赖当前工作目录。
*/
export function resolveHelperPath(): string | null {
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
/*
* 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows),
* 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null,
@@ -640,6 +642,14 @@ export async function applyMsgInsertSwitch(
}
}
if (isMacNativeRuntimeUnavailable()) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'),
errorCode: 'HELPER_NOT_FOUND',
message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响'
}
}
const helperPath = resolveHelperPath()
if (!helperPath) {
return {
@@ -716,6 +726,9 @@ export async function applyMsgInsertSwitch(
export async function reconcileMsgInsertRules(
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
if (isMacNativeRuntimeUnavailable()) {
return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' }
}
const helperPath = resolveHelperPath()
if (!helperPath || !input.databaseKey) {
return {
@@ -12,7 +12,7 @@ import {
} from 'fs'
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, extname, join, sep } from 'path'
import ffmpegStaticPath from 'ffmpeg-static'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { promisify } from 'util'
import type {
PersonalWechatSendRequest,
@@ -64,9 +64,7 @@ function windowsHookHost(port?: unknown): string | null {
export function buildPersonalWechatRuntimePath(): string {
const existing = String(process.env['PATH'] || '')
const bundledFfmpeg = String(ffmpegStaticPath || '')
.replace('app.asar', 'app.asar.unpacked')
.trim()
const bundledFfmpeg = resolveBundledFfmpegPath()
if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
}
@@ -174,7 +172,7 @@ async function detectVoiceDurationMs(filePath: string): Promise<number | undefin
}
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = resolveBundledFfmpegPath()
if (!ffmpegPath || !existsSync(ffmpegPath)) return undefined
let output = ''
try {
@@ -203,7 +201,7 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
return { filePath, durationMs: await detectVoiceDurationMs(filePath), temporary: false }
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = resolveBundledFfmpegPath()
if (!ffmpegPath || !existsSync(ffmpegPath)) {
throw new Error('Windows 语音发送需要可用的 FFmpeg 才能转换为 SILK')
}
+2 -1
View File
@@ -36,6 +36,7 @@
// - macOS 没有"语言包缺失"这一失败模式。
import crypto from 'node:crypto'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { spawn } from 'node:child_process'
import {
SYSTEM_OCR_CACHE_TTL_MS,
@@ -125,7 +126,7 @@ const defaultResolveFfmpegExecutable = (): string => {
const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim()
if (fromEnvironment) return fromEnvironment
try {
const bundled = require('ffmpeg-static') as string | null
const bundled = resolveBundledFfmpegPath()
if (bundled) return bundled
} catch {
// 忽略:退回到 PATH 上的 ffmpeg
@@ -34,6 +34,7 @@ import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { renderLeaveNotificationText } from '../../shared/group-exit-event'
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
import { findResource } from '../resource-paths'
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
export type LocalExitNoticeOutcome =
| 'inserted'
@@ -63,6 +64,7 @@ const HELPER_TIMEOUT_MS = 20_000
const RECENT_LIMIT = 50
function helperPath(): string | null {
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
/* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致:
* Windows 走 wcdb/win32/<arch>/ 且文件名带 .exe。 */
const arch = process.arch === 'x64' ? 'x64' : 'arm64'
@@ -149,6 +151,9 @@ export class WechatLocalExitNoticeService {
}
try {
this.ensureLoaded()
if (isMacNativeRuntimeUnavailable()) {
return this.finish({ ...base, outcome: 'disabled', code: 'SEND_CAPABILITY_UNAVAILABLE' })
}
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
if (!event.eventId || !event.conversationId) {
return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' })
+8 -9
View File
@@ -5,6 +5,7 @@ import crypto from 'crypto'
import { createRequire } from 'module'
import { createConnection, Socket } from 'net'
import { getResourceRoots } from './resource-paths'
import { resolveWcdbLibrary } from './native-runtime-paths'
import { wcdbDebugLog } from './wcdb-debug'
import { looksLikePermissionDenied, PathAccessDeniedError } from './services/path-access-probe'
import type { ImageMessageCountProbe } from '../shared/image-text-index'
@@ -3485,16 +3486,14 @@ export class Wcdb4Client {
}
static resolveNativeLibrary(): string {
const libName =
process.platform === 'darwin'
? 'libwcdb_api.dylib'
: process.platform === 'linux'
? 'libwcdb_api.so'
: 'wcdb_api.dll'
if (process.platform === 'darwin') {
const library = resolveWcdbLibrary()
if (library) return library
throw new Error('找不到当前发行版对应的 WCDB native 库')
}
const libName = process.platform === 'linux' ? 'libwcdb_api.so' : 'wcdb_api.dll'
const platformDir =
process.platform === 'darwin'
? 'macos'
: process.platform === 'win32'
process.platform === 'win32'
? 'win32'
: process.platform
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'