Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 2x 2x 2x 2x 5x 3x 3x 5x 1x 1x 6x 6x 6x 4x 4x 4x 4x 4x 4x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 5x 4x 4x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 5x 4x 12x 3x 1x 12x 12x 1x 1x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 1x 1x 1x 1x 3x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* ChemPal background service worker.
*
* Required by Manifest V3 for the extension to participate in the Chrome
* extension lifecycle (install / update events) and to provide a discoverable
* entry point for Playwright-driven end-to-end tests, which identify the loaded
* extension by its service-worker URL.
*
* Bundled as a self-contained IIFE (see `serviceWorkerBuildPlugin` in
* vite.config.ts) so it can share TypeScript constants like {@link CACHE} with
* the app while remaining a single classic script that works as both a Chrome
* MV3 worker and a Firefox background script.
* @module serviceWorker
* @source
*/
import { defaultSettings, extension } from '@/../config.json';
import { CACHE, MESSAGE_TYPE } from '@/constants/common';
import { trackInstallOrUpgrade } from '@/helpers/analytics';
import { installErrorCapture } from '@/helpers/errorBuffer';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('service-worker');
/**
* Context-menu item id for the "Search selection in ChemPal" entry.
* @category Background
* @source
*/
export const CONTEXT_MENU_ID = 'chempal-search-selection';
/**
* Full-tab view URL; `?view=tab` is recognized by the app (see utils/displayContext.ts).
* @category Background
* @source
*/
export const TAB_VIEW_PATH = 'index.html?view=tab';
// Capture background-context errors into the shared ring buffer so they can be
// attached to a bug report opened from the UI.
installErrorCapture();
chrome.runtime.onInstalled.addListener(({ reason, previousVersion }) => {
if (reason === chrome.runtime.OnInstalledReason.INSTALL) {
logger.info('ChemPal installed');
// Seed the review-prompt record with an exact install date. Raw chrome.storage
// (not cstorage) for the same reason as the writes below: compression is off and
// the app-side decoder passes non-envelope values through unchanged.
void chrome.storage.local.set({
[CACHE.REVIEW_PROMPT]: {
installedAt: Date.now(),
searchCount: 0,
totalResults: 0,
dismissCount: 0,
},
});
} else if (reason === chrome.runtime.OnInstalledReason.UPDATE) {
// Reloading an unpacked extension fires onInstalled with reason "update" and
// previousVersion equal to the version already running. That's a dev reload, not
// an upgrade — and clearing UPDATE_PENDING here would silently drop a genuinely
// staged update the UI is still meant to prompt for.
if (previousVersion === __APP_VERSION__) return;
logger.info('ChemPal updated');
// The staged update just landed; drop the record so the UI doesn't keep
// prompting for a version that is now running.
void chrome.storage.local.remove(CACHE.UPDATE_PENDING);
}
});
// Report installs and version upgrades. Its own listener rather than a branch in
// the one above, matching how the rest of this file registers one onInstalled
// listener per concern. Awaited (not bare-voided) because two storage reads
// precede the send; Chrome doesn't await the returned promise, but the worker is
// reliably awake during install/update and trackEvent swallows all failures.
chrome.runtime.onInstalled.addListener(async (details) => {
await trackInstallOrUpgrade(details.reason, details.previousVersion);
});
// Registering this listener is what *defers* the update: with no listener Chrome
// applies a staged Web Store update the moment the extension goes idle, which
// would tear down an in-flight search. Instead we record it and let the UI offer
// a reload. Optional-chained because Firefox has no onUpdateAvailable.
chrome.runtime.onUpdateAvailable?.addListener(({ version }) => {
// Raw chrome.storage rather than cstorage for the same reason as the
// context-menu write below: storage compression is off, and the app-side
// decoder passes non-envelope values through unchanged.
void chrome.storage.local.set({
[CACHE.UPDATE_PENDING]: { version, detectedAt: Date.now() },
});
});
/**
* Focuses the extension tab already open at `url`, or opens a new one. Mirrors
* findExtensionTab/openExtensionTab in src/utils/displayContext.ts.
* @param url - The full extension URL to open or focus.
* @returns A promise that resolves once the tab has been opened or focused.
* @source
*/
async function openOrFocusExtensionTab(url: string): Promise<void> {
const tabs = await chrome.tabs.query({});
const existing = tabs.find((tab) => tab.url === url || tab.pendingUrl === url);
if (existing?.id != null) {
await chrome.tabs.update(existing.id, { active: true });
if (existing.windowId != null) {
await chrome.windows.update(existing.windowId, { focused: true });
}
} else {
await chrome.tabs.create({ url, active: true });
}
}
/**
* Seeds the pending-search inbox the app already consumes, then opens or focuses
* the full-tab view. Shared entry point for the "Search selection" context menu
* and the omnibox keyword. Raw (uncompressed) values are fine: the app's storage
* layer (utils/storage.ts decodeValue) passes non-LZ-envelope values through
* unchanged. No-ops when the trimmed query is empty.
* @param rawQuery - The user-entered text to search for; trimmed internally.
* @returns A promise that resolves once the search is seeded and the view opened.
* @source
*/
async function seedSearchAndOpen(rawQuery: string): Promise<void> {
const query = rawQuery.trim();
if (!query) return;
await chrome.storage.session.set({
[CACHE.QUERY]: query,
[CACHE.SEARCH_IS_NEW_SEARCH]: true,
});
await openOrFocusExtensionTab(chrome.runtime.getURL(TAB_VIEW_PATH));
}
/**
* (Re)creates the "Search selection" context-menu item. `removeAll` runs first
* so install/update/startup never double-adds it. The MV3 worker is ephemeral,
* so this is invoked on both `onInstalled` and `onStartup`.
* @source
*/
function createContextMenu(): void {
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: CONTEXT_MENU_ID,
title: chrome.i18n.getMessage('context_menu_search_selection'),
contexts: ['selection'],
});
});
}
chrome.runtime.onInstalled.addListener(createContextMenu);
chrome.runtime.onStartup.addListener(createContextMenu);
chrome.contextMenus.onClicked.addListener(async (info) => {
if (info.menuItemId !== CONTEXT_MENU_ID) return;
await seedSearchAndOpen(info.selectionText ?? '');
});
// Address-bar keyword search: typing "chem <query>" (the manifest `omnibox`
// keyword) runs a ChemPal search directly, without opening the popup first.
chrome.omnibox.setDefaultSuggestion({
description: chrome.i18n.getMessage('omnibox_default_suggestion'),
});
chrome.omnibox.onInputEntered.addListener(async (text) => {
await seedSearchAndOpen(text);
});
// Toolbar-icon behavior. The `openInTab` user setting decides whether clicking
// the toolbar icon shows the popup (default) or opens ChemPal in a full tab.
// We enforce it by toggling the action popup: clearing the popup makes clicks
// fire chrome.action.onClicked (below) instead of opening index.html as a popup.
//
// Settings live in chrome.storage.local under CACHE.USER_SETTINGS. Compression is
// disabled (config.json storage.useStorageCompression=false), so the value is the plain
// object; an LZ envelope ({__lz}) would be unreadable here, so that case falls
// back to the shipped default. The fallback must match the config.json default the
// UI hydrates with — otherwise a fresh profile (no persisted user_settings) shows the
// toggle on while the action still opens a popup.
/** Shipped default for the open-in-tab toolbar behavior (config.json defaultSettings). */
const DEFAULT_OPEN_IN_TAB = Boolean(defaultSettings.display?.openInTab);
/**
* Reads the `openInTab` user setting from storage, falling back to the shipped
* config.json default ({@link DEFAULT_OPEN_IN_TAB}) when it's unset, unreadable, or
* an unexpected shape. An explicitly persisted value always wins.
* @returns `true` when the toolbar icon should open the full-tab view.
* @source
*/
async function readOpenInTab(): Promise<boolean> {
try {
const stored: Record<string, unknown> = await chrome.storage.local.get(CACHE.USER_SETTINGS);
const settings = stored[CACHE.USER_SETTINGS];
if (typeof settings !== 'object' || settings === null) return DEFAULT_OPEN_IN_TAB;
if (!('display' in settings)) return DEFAULT_OPEN_IN_TAB;
const { display } = settings;
return typeof display === 'object' && display !== null && 'openInTab' in display
? Boolean(display.openInTab)
: DEFAULT_OPEN_IN_TAB;
} catch (error) {
logger.warn(`Failed to read openInTab setting: ${getErrorMessage(error)}`, { error });
return DEFAULT_OPEN_IN_TAB;
}
}
/**
* Applies the current `openInTab` setting to the toolbar action. An empty popup
* makes clicks fire `chrome.action.onClicked`; `index.html` restores the popup.
* @returns A promise that resolves once the action popup has been updated.
* @source
*/
async function applyActionBehavior(): Promise<void> {
const openInTab = await readOpenInTab();
await chrome.action.setPopup({ popup: openInTab ? '' : 'index.html' });
}
// The setPopup state resets to the manifest default on browser restart, so
// re-apply on startup as well as install/update.
chrome.runtime.onInstalled.addListener(applyActionBehavior);
chrome.runtime.onStartup.addListener(applyActionBehavior);
/** Public "ChemPal Feedback" Google Form opened when the extension is uninstalled. */
const FEEDBACK_FORM_URL = extension.feedbackFormUrl;
/**
* Points the browser's uninstall URL at the feedback form, so removing ChemPal
* opens the form in a new tab. Re-applied on install and startup because the MV3
* worker is ephemeral and the setting doesn't survive a browser restart.
* Optional-chained because it's guarded for engines without the API (Firefox
* does support it). No user data is ever placed in the URL.
* @returns Nothing.
* @source
*/
function applyUninstallUrl(): void {
if (!FEEDBACK_FORM_URL) return;
void chrome.runtime.setUninstallURL?.(FEEDBACK_FORM_URL);
}
chrome.runtime.onInstalled.addListener(applyUninstallUrl);
chrome.runtime.onStartup.addListener(applyUninstallUrl);
// Re-apply whenever the user toggles the setting in the settings panel.
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local' && changes[CACHE.USER_SETTINGS]) {
void applyActionBehavior();
}
});
// Fires only while the popup is cleared (openInTab on). Open/focus the full tab.
chrome.action.onClicked.addListener(() => {
void openOrFocusExtensionTab(chrome.runtime.getURL(TAB_VIEW_PATH));
});
/** Message the background fetch proxy accepts; mirrors src/helpers/backgroundFetch.ts. */
interface BackgroundFetchRequest {
type: typeof MESSAGE_TYPE.BACKGROUND_FETCH;
url: string;
init?: RequestInit;
}
/**
* Type-guard narrowing an unknown runtime message to a {@link BackgroundFetchRequest}.
* @param message - The value received by the `chrome.runtime.onMessage` listener.
* @returns `true` when `message` is a background-fetch request.
* @source
*/
function isBackgroundFetchRequest(message: unknown): message is BackgroundFetchRequest {
return (
typeof message === 'object' &&
message !== null &&
Reflect.get(message, 'type') === MESSAGE_TYPE.BACKGROUND_FETCH &&
typeof Reflect.get(message, 'url') === 'string'
);
}
// Generic fetch proxy. Extension pages are subject to page CORS for
// cross-origin requests, but the background service worker is not (given matching
// host_permissions). Any context can run a request here by sending a
// BackgroundFetchRequest and gets back a serialized response (Response objects
// aren't structured-cloneable):
//
// { ok, status, statusText, headers: Record<string,string>, body: string }
// | { error: string }
//
// The client side lives in src/helpers/backgroundFetch.ts.
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (!isBackgroundFetchRequest(message)) {
return; // Not ours — leave the channel for other listeners.
}
void (async () => {
try {
const response = await fetch(message.url, message.init ?? {});
const body = await response.text();
const headers: Record<string, string> = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
sendResponse({
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers,
body,
});
} catch (error) {
sendResponse({ error: error instanceof Error ? error.message : String(error) });
}
})();
return true; // Keep the message channel open for the async sendResponse.
});
|