refactor: extract shared types + safe chrome wrappers into src/lib

- src/lib/types.ts: message contract (both ANALYZE_TEXT shapes preserved),
  config/response types, storage-key constants.
- src/lib/messaging.ts: single safeStorageGet/safeStorageSet/safeSendMessage/
  isExtensionValid implementation replacing the three divergent copies in
  Options, Popup, and content. Content script keeps its refresh-toast
  behavior via an onContextInvalidated callback.
- New '@lib' import alias (wxt force-overwrites '~' and '@' to srcDir, so
  those cannot point at ./src); wired in wxt.config, tsconfig, vitest.
- tests/unit/messaging.test.ts: 14 unit tests over the wrappers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
john kevin asprec
2026-07-14 21:33:56 +08:00
parent 04a4a2dc99
commit 324cfcc486
10 changed files with 303 additions and 124 deletions

68
src/lib/messaging.ts Normal file
View File

@@ -0,0 +1,68 @@
// Single implementation of the "safe" chrome API wrappers shared by every
// context. All of them guard against the extension context being invalidated
// (extension reloaded/updated while a page, popup, or options view is open),
// which otherwise throws from any chrome.* call.
export function isExtensionValid(): boolean {
try {
return typeof chrome !== 'undefined' && !!chrome.runtime?.id;
} catch {
return false;
}
}
export function safeStorageGet(
keys: string[],
callback: (result: Record<string, any>) => void,
storage: chrome.storage.StorageArea = chrome.storage.local,
): void {
try {
if (!isExtensionValid()) return;
storage.get(keys, callback);
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
}
export function safeStorageSet(
data: Record<string, unknown>,
callback?: () => void,
storage: chrome.storage.StorageArea = chrome.storage.local,
): void {
try {
if (!isExtensionValid()) return;
if (callback) {
storage.set(data, callback);
} else {
storage.set(data);
}
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
}
// Sends a message to the background worker. Returns null (never throws) when
// the extension context is gone or the send fails. `onContextInvalidated` lets
// UI contexts react (e.g. the content script shows a "please refresh" toast).
export async function safeSendMessage<T = any>(
message: Record<string, unknown>,
onContextInvalidated?: () => void,
): Promise<T | null> {
if (!isExtensionValid()) {
onContextInvalidated?.();
return null;
}
try {
return await chrome.runtime.sendMessage(message);
} catch (err) {
if (
String(err).includes('Extension context invalidated') ||
String(err).includes('message channel closed')
) {
onContextInvalidated?.();
} else {
console.warn('LexAI: sendMessage failed', err);
}
return null;
}
}

54
src/lib/types.ts Normal file
View File

@@ -0,0 +1,54 @@
// Shared types and constants for all extension contexts (background, content,
// options, popup). This is the single source of truth for the message contract
// and the storage schema.
export interface AnalyzePayload {
text: string;
action: string;
style?: string;
}
export interface LexAIConfig {
provider?: string;
apiKey?: string; // legacy plaintext key — kept for backward compat until migrated
apiKeyEnc?: string; // base64(nonce + secretbox ciphertext)
encKey?: string; // base64 32-byte secretbox key
model?: string;
}
export interface LexAIResponse {
result?: string;
error?: string;
}
// Storage keys the background worker reads when resolving provider config.
export const CONFIG_STORAGE_KEYS = ['provider', 'apiKey', 'apiKeyEnc', 'encKey', 'model'] as const;
// ─── Message contract ─────────────────────────────────────────────────────────
// ANALYZE_TEXT intentionally supports BOTH shapes:
// { type, payload: { text, action, style } } (content script, popup)
// { type, text, action, style } (flat/legacy)
// The background handler normalizes; both must keep working.
export interface AnalyzeTextMessage {
type: 'ANALYZE_TEXT';
payload?: AnalyzePayload;
text?: string;
action?: string;
style?: string;
}
export interface CopyAsMessage {
type: 'COPY_AS';
text: string;
format: string;
}
export interface ListModelsMessage {
type: 'LIST_MODELS';
provider?: string;
// Freshly typed key not yet saved — preferred over the stored key when present.
apiKey?: string;
}
export type LexAIMessage = AnalyzeTextMessage | CopyAsMessage | ListModelsMessage;