mirror of
https://git.zavage.net/Zavage-Software/search-with-chatgpt-powered-by-openai-extension.git
synced 2026-08-31 22:20:47 -06:00
feat: add settings defaults and validation with unit tests
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
// Single source of truth for the settings shape and their defaults.
|
||||
// Defaults reproduce the extension's pre-1.1 behaviour exactly: an empty model
|
||||
// and both toggles off mean the only URL parameter sent is `q`.
|
||||
|
||||
export const OPEN_IN_VALUES = ["new-tab", "background-tab", "new-window"];
|
||||
|
||||
export const DEFAULT_SETTINGS = {
|
||||
model: "",
|
||||
temporaryChat: false,
|
||||
webSearch: false,
|
||||
openIn: "new-tab",
|
||||
promptTemplate: "{query}",
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { DEFAULT_SETTINGS, OPEN_IN_VALUES } from "./defaults.js";
|
||||
|
||||
// Pure. Layers stored values over the defaults, dropping unknown keys and
|
||||
// falling back on wrong types or out-of-range values. A fresh or signed-out
|
||||
// profile returns {} from storage, which yields the defaults.
|
||||
export function mergeSettings(stored) {
|
||||
const merged = { ...DEFAULT_SETTINGS };
|
||||
if (stored === null || typeof stored !== "object") {
|
||||
return merged;
|
||||
}
|
||||
if (typeof stored.model === "string") {
|
||||
merged.model = stored.model;
|
||||
}
|
||||
if (typeof stored.temporaryChat === "boolean") {
|
||||
merged.temporaryChat = stored.temporaryChat;
|
||||
}
|
||||
if (typeof stored.webSearch === "boolean") {
|
||||
merged.webSearch = stored.webSearch;
|
||||
}
|
||||
if (OPEN_IN_VALUES.includes(stored.openIn)) {
|
||||
merged.openIn = stored.openIn;
|
||||
}
|
||||
if (typeof stored.promptTemplate === "string") {
|
||||
merged.promptTemplate = stored.promptTemplate;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
// storage.sync works with no Mozilla account (it behaves as local storage and
|
||||
// syncs later if the user signs in), so no capability probe is needed. Any
|
||||
// rejection falls back to defaults rather than blocking the user's action.
|
||||
// Firefox sanitises all non-quota backend errors to a single generic string, so
|
||||
// there is nothing useful to branch on.
|
||||
export async function load() {
|
||||
try {
|
||||
const stored = await browser.storage.sync.get(Object.keys(DEFAULT_SETTINGS));
|
||||
return mergeSettings(stored);
|
||||
} catch {
|
||||
return mergeSettings(null);
|
||||
}
|
||||
}
|
||||
|
||||
export async function save(partial) {
|
||||
await browser.storage.sync.set(partial);
|
||||
}
|
||||
Reference in New Issue
Block a user