mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-07 04:03:49 +10:30
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d35ee91d90 | ||
|
|
545069aa88 | ||
|
|
9dfe38a483 | ||
|
|
364db59d17 | ||
|
|
06777702fa | ||
|
|
8df7edcb75 |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
export default {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
testEnvironment: 'jsdom',
|
||||
roots: ['<rootDir>/src'],
|
||||
testMatch: [
|
||||
'**/__tests__/**/*.ts',
|
||||
|
||||
@@ -108,7 +108,6 @@
|
||||
"semver": "^7.7.1",
|
||||
"sortablejs": "^1.15.6",
|
||||
"svelte": "^5.46.4",
|
||||
"svelte-hero-icons": "^5.2.0",
|
||||
"webextension-polyfill": "^0.12.0"
|
||||
},
|
||||
"overrides": {
|
||||
|
||||
@@ -19,10 +19,6 @@ import {
|
||||
registerGoogleCalendarMessageHandlers,
|
||||
registerOutlookCalendarMessageHandlers,
|
||||
} from "./background/calendarBackground";
|
||||
import {
|
||||
handleAiModCreatorMessage,
|
||||
registerAiModCreatorStreaming,
|
||||
} from "./background/aiModCreator";
|
||||
|
||||
/**
|
||||
* Session-only dev-mode override of the content API base.
|
||||
@@ -529,13 +525,6 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
cloudFavorite: handleCloudFavorite,
|
||||
cloudSettingsUpload: handleCloudSettingsUpload,
|
||||
cloudSettingsDownload: handleCloudSettingsDownload,
|
||||
aiModCreator: (request, sendResponse, sender) =>
|
||||
handleAiModCreatorMessage(
|
||||
request,
|
||||
sender ?? {},
|
||||
sendResponse,
|
||||
isTrustedSender,
|
||||
),
|
||||
cloudSettingsPoll: () => {
|
||||
void runCloudSettingsPoll();
|
||||
return false;
|
||||
@@ -584,7 +573,6 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
|
||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||
registerAiModCreatorStreaming(isTrustedSender);
|
||||
initCalendarBackground();
|
||||
|
||||
browser.runtime.onMessage.addListener(
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
AI_MOD_CREATOR_MESSAGE_TYPE,
|
||||
createAiModCreatorService,
|
||||
formatOpenRouterError,
|
||||
handleAiModCreatorMessage,
|
||||
} from "./aiModCreator";
|
||||
import type { SelectedElementContext } from "@/plugins/built-in/aiModCreator/types";
|
||||
|
||||
const context: SelectedElementContext = {
|
||||
route: "assessments",
|
||||
rootSelector: "#selected",
|
||||
request: "Round this card",
|
||||
userContext: "Assessment summary",
|
||||
selectedHtml: '<section id="selected">Assessment</section>',
|
||||
domCatalog: [
|
||||
{
|
||||
selector: ":scope",
|
||||
tag: "section",
|
||||
classes: [],
|
||||
parentSelector: null,
|
||||
siblingIndex: 0,
|
||||
siblingCount: 1,
|
||||
layout: { display: "block" },
|
||||
},
|
||||
],
|
||||
tagName: "section",
|
||||
dimensions: { width: 400, height: 200 },
|
||||
computedStyle: { color: "rgb(0, 0, 0)" },
|
||||
};
|
||||
|
||||
describe("AI mod OpenRouter background service", () => {
|
||||
it("stores the key locally and reports only whether it exists", async () => {
|
||||
const service = createAiModCreatorService({
|
||||
fetchImpl: jest.fn(),
|
||||
now: () => 1_000,
|
||||
});
|
||||
|
||||
await service.saveKey(" sk-or-v1-test-key-123456 ");
|
||||
await expect(service.getKeyStatus()).resolves.toEqual({ configured: true });
|
||||
expect(await browser.storage.local.get("aiModCreator.openRouterApiKey")).toEqual({
|
||||
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||
});
|
||||
|
||||
await service.clearKey();
|
||||
await expect(service.getKeyStatus()).resolves.toEqual({ configured: false });
|
||||
});
|
||||
|
||||
it("calls the free model with json_object output and provider fallbacks", async () => {
|
||||
await browser.storage.local.set({
|
||||
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||
});
|
||||
const fetchImpl = jest.fn(async (_url: string, init?: RequestInit) => {
|
||||
const body = JSON.parse(String(init?.body));
|
||||
expect(body).toMatchObject({
|
||||
model: "minimax/minimax-m2.7:free",
|
||||
provider: { allow_fallbacks: true },
|
||||
response_format: { type: "json_object" },
|
||||
});
|
||||
expect(init?.headers).toMatchObject({
|
||||
Authorization: "Bearer sk-or-v1-test-key-123456",
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: JSON.stringify({
|
||||
name: "Rounded card",
|
||||
description: "Rounds the selected card.",
|
||||
operations: [
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "border-radius",
|
||||
value: "12px",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
});
|
||||
const service = createAiModCreatorService({
|
||||
fetchImpl,
|
||||
now: () => 10_000,
|
||||
});
|
||||
|
||||
await expect(service.generate(context)).resolves.toMatchObject({
|
||||
name: "Rounded card",
|
||||
operations: [{ type: "setStyle", property: "border-radius" }],
|
||||
});
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
expect.objectContaining({ method: "POST" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries without structured output when OpenRouter routing fails", async () => {
|
||||
await browser.storage.local.set({
|
||||
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||
});
|
||||
const fetchImpl = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message:
|
||||
"No endpoints found that can handle the requested parameters.",
|
||||
},
|
||||
}),
|
||||
{ status: 404 },
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: JSON.stringify({
|
||||
name: "Fallback mod",
|
||||
description: "Generated without structured output.",
|
||||
operations: [{ type: "hide", selector: ":scope .meta" }],
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
const service = createAiModCreatorService({
|
||||
fetchImpl,
|
||||
now: () => 10_000,
|
||||
});
|
||||
|
||||
await expect(service.generate(context)).resolves.toMatchObject({
|
||||
name: "Fallback mod",
|
||||
});
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
const firstBody = JSON.parse(String(fetchImpl.mock.calls[0][1]?.body));
|
||||
const secondBody = JSON.parse(String(fetchImpl.mock.calls[1][1]?.body));
|
||||
expect(firstBody.response_format).toEqual({ type: "json_object" });
|
||||
expect(secondBody.response_format).toBeUndefined();
|
||||
});
|
||||
|
||||
it("streams partial recipe content and token usage", async () => {
|
||||
await browser.storage.local.set({
|
||||
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||
});
|
||||
const json = JSON.stringify({
|
||||
name: "Streamed mod",
|
||||
description: "Generated incrementally",
|
||||
operations: [{ type: "hide", selector: ":scope .metadata" }],
|
||||
});
|
||||
const first = json.slice(0, 35);
|
||||
const second = json.slice(35);
|
||||
const streamBody = [
|
||||
`data: ${JSON.stringify({ choices: [{ delta: { reasoning_details: [{}] } }] })}\n\n`,
|
||||
`data: ${JSON.stringify({ choices: [{ delta: { content: first } }] })}\n\n`,
|
||||
`data: ${JSON.stringify({ choices: [{ delta: { content: second } }], usage: { prompt_tokens: 20, completion_tokens: 30 } })}\n\n`,
|
||||
"data: [DONE]\n\n",
|
||||
].join("");
|
||||
const service = createAiModCreatorService({
|
||||
fetchImpl: jest.fn(async () =>
|
||||
new Response(streamBody, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/event-stream" },
|
||||
}),
|
||||
),
|
||||
now: () => 20_000,
|
||||
});
|
||||
const progress: unknown[] = [];
|
||||
|
||||
await expect(
|
||||
service.streamGenerate(context, (update) => progress.push(update)),
|
||||
).resolves.toMatchObject({ name: "Streamed mod" });
|
||||
expect(progress).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ type: "status", text: "Connecting to MiniMax M2.7 (free)…" },
|
||||
{ type: "status", text: "Model is reasoning…" },
|
||||
{ type: "content", text: first },
|
||||
{
|
||||
type: "usage",
|
||||
promptTokens: 20,
|
||||
completionTokens: 30,
|
||||
},
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("surfaces stream rate-limit errors with actionable guidance", async () => {
|
||||
await browser.storage.local.set({
|
||||
"aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456",
|
||||
});
|
||||
const streamBody = [
|
||||
": OPENROUTER PROCESSING\n\n",
|
||||
`data: ${JSON.stringify({
|
||||
error: {
|
||||
code: 429,
|
||||
message: "Provider returned error",
|
||||
metadata: { error_type: "rate_limit_exceeded" },
|
||||
},
|
||||
})}\n\n`,
|
||||
].join("");
|
||||
const service = createAiModCreatorService({
|
||||
fetchImpl: jest.fn(async () =>
|
||||
new Response(streamBody, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/event-stream" },
|
||||
}),
|
||||
),
|
||||
now: () => 20_000,
|
||||
});
|
||||
|
||||
await expect(service.streamGenerate(context, () => {})).rejects.toThrow(
|
||||
/Rate limit reached for MiniMax M2\.7 \(free\)/,
|
||||
);
|
||||
});
|
||||
|
||||
it("formats free-tier rate-limit guidance", () => {
|
||||
expect(
|
||||
formatOpenRouterError(
|
||||
{
|
||||
code: 429,
|
||||
message: "Provider returned error",
|
||||
metadata: { error_type: "rate_limit_exceeded" },
|
||||
},
|
||||
"minimax/minimax-m2.7:free",
|
||||
),
|
||||
).toMatch(/switch model/i);
|
||||
});
|
||||
|
||||
it("rejects missing keys, oversized input, throttling, and provider errors", async () => {
|
||||
const service = createAiModCreatorService({
|
||||
fetchImpl: jest.fn(),
|
||||
now: () => 1_000,
|
||||
});
|
||||
await expect(service.generate(context)).rejects.toThrow("API key");
|
||||
|
||||
await service.saveKey("sk-or-v1-test-key-123456");
|
||||
await expect(
|
||||
service.generate({ ...context, request: "x".repeat(2_001) }),
|
||||
).rejects.toThrow("too long");
|
||||
|
||||
const failingService = createAiModCreatorService({
|
||||
fetchImpl: jest.fn(async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message: "Free model rate limit reached",
|
||||
code: 429,
|
||||
metadata: { error_type: "rate_limit_exceeded" },
|
||||
},
|
||||
}),
|
||||
{ status: 429 },
|
||||
),
|
||||
),
|
||||
now: () => 10_000,
|
||||
});
|
||||
await expect(failingService.generate(context)).rejects.toThrow(
|
||||
/Rate limit reached for MiniMax M2\.7 \(free\)/,
|
||||
);
|
||||
await expect(failingService.generate(context)).rejects.toThrow(
|
||||
/Please wait \d+s/,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects untrusted runtime message senders", () => {
|
||||
const sendResponse = jest.fn();
|
||||
const handled = handleAiModCreatorMessage(
|
||||
{
|
||||
type: AI_MOD_CREATOR_MESSAGE_TYPE,
|
||||
action: "status",
|
||||
},
|
||||
{ id: "another-extension" } as browser.Runtime.MessageSender,
|
||||
sendResponse,
|
||||
() => false,
|
||||
);
|
||||
|
||||
expect(handled).toBe(false);
|
||||
expect(sendResponse).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
error: "Unauthorized sender",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,738 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
buildAiModMessages,
|
||||
} from "@/plugins/built-in/aiModCreator/prompt";
|
||||
import {
|
||||
formatRecipeValidationError,
|
||||
parseGeneratedModDraft,
|
||||
} from "@/plugins/built-in/aiModCreator/recipeSchema";
|
||||
import { aiModLog } from "@/plugins/built-in/aiModCreator/logger";
|
||||
import {
|
||||
DEFAULT_OPENROUTER_MODEL_ID,
|
||||
getModelOption,
|
||||
validateModelId,
|
||||
} from "@/plugins/built-in/aiModCreator/models";
|
||||
import {
|
||||
OPENROUTER_API_KEY_STORAGE_KEY,
|
||||
OPENROUTER_MODEL_STORAGE_KEY,
|
||||
} from "@/plugins/built-in/aiModCreator/storage";
|
||||
import {
|
||||
executeAdvancedMod,
|
||||
getAdvancedScriptSupport,
|
||||
stopAdvancedMod,
|
||||
} from "./aiModUserScripts";
|
||||
import type {
|
||||
GenerationProgress,
|
||||
GeneratedModDraft,
|
||||
KeyStatus,
|
||||
SelectedElementContext,
|
||||
StoredModRecipe,
|
||||
} from "@/plugins/built-in/aiModCreator/types";
|
||||
|
||||
export const AI_MOD_CREATOR_MESSAGE_TYPE = "aiModCreator";
|
||||
export const OPENROUTER_MODEL_ID = DEFAULT_OPENROUTER_MODEL_ID;
|
||||
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
|
||||
const MIN_GENERATION_INTERVAL_MS = 5_000;
|
||||
const ROUTING_ERROR_PATTERN =
|
||||
/no endpoints found|can handle the requested parameters/i;
|
||||
|
||||
type ResponseFormatMode = "json_object" | "none";
|
||||
|
||||
type StorageArea = Pick<
|
||||
browser.Storage.StorageArea,
|
||||
"get" | "set" | "remove"
|
||||
>;
|
||||
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
||||
type SendResponse = (response: unknown) => void;
|
||||
type TrustCheck = (sender?: browser.Runtime.MessageSender) => boolean;
|
||||
|
||||
function validateApiKey(value: unknown): string {
|
||||
if (typeof value !== "string") throw new Error("API key is required");
|
||||
const key = value.trim();
|
||||
if (key.length < 16 || key.length > 512) {
|
||||
throw new Error("API key must be between 16 and 512 characters");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function validateContext(value: unknown): SelectedElementContext {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error("Selected element context is required");
|
||||
}
|
||||
const context = value as SelectedElementContext;
|
||||
const limits: Array<[keyof SelectedElementContext, number]> = [
|
||||
["route", 256],
|
||||
["rootSelector", 1_000],
|
||||
["request", 2_000],
|
||||
["userContext", 4_000],
|
||||
["selectedHtml", 24_000],
|
||||
["ancestorHtml", 6_000],
|
||||
["tagName", 80],
|
||||
];
|
||||
for (const [key, limit] of limits) {
|
||||
const field = context[key];
|
||||
if (field === undefined) continue;
|
||||
if (typeof field !== "string") throw new Error(`${key} must be text`);
|
||||
if (field.length > limit) throw new Error(`${key} is too long`);
|
||||
}
|
||||
if (!Array.isArray(context.domCatalog)) {
|
||||
throw new Error("domCatalog is required");
|
||||
}
|
||||
if (context.domCatalog.length > 100) {
|
||||
throw new Error("domCatalog must contain at most 100 entries");
|
||||
}
|
||||
for (const entry of context.domCatalog) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
throw new Error("domCatalog entries must be objects");
|
||||
}
|
||||
if (typeof entry.selector !== "string" || entry.selector.length > 500) {
|
||||
throw new Error("domCatalog selector is invalid");
|
||||
}
|
||||
if (typeof entry.tag !== "string" || entry.tag.length > 80) {
|
||||
throw new Error("domCatalog tag is invalid");
|
||||
}
|
||||
if (
|
||||
entry.layout &&
|
||||
(typeof entry.layout !== "object" ||
|
||||
Array.isArray(entry.layout) ||
|
||||
Object.keys(entry.layout).length > 24)
|
||||
) {
|
||||
throw new Error("domCatalog layout summary is invalid");
|
||||
}
|
||||
for (const countKey of ["rowCount", "columnCount", "itemCount"] as const) {
|
||||
const count = entry[countKey];
|
||||
if (count === undefined) continue;
|
||||
if (!Number.isFinite(count) || count < 0 || count > 10_000) {
|
||||
throw new Error(`domCatalog ${countKey} is invalid`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (context.parentChain !== undefined) {
|
||||
if (!Array.isArray(context.parentChain)) {
|
||||
throw new Error("parentChain must be an array");
|
||||
}
|
||||
if (context.parentChain.length > 3) {
|
||||
throw new Error("parentChain must contain at most 3 entries");
|
||||
}
|
||||
for (const entry of context.parentChain) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
throw new Error("parentChain entries must be objects");
|
||||
}
|
||||
if (typeof entry.tag !== "string" || entry.tag.length > 80) {
|
||||
throw new Error("parentChain tag is invalid");
|
||||
}
|
||||
if (!Array.isArray(entry.classes) || entry.classes.length > 8) {
|
||||
throw new Error("parentChain classes are invalid");
|
||||
}
|
||||
for (const className of entry.classes) {
|
||||
if (typeof className !== "string" || className.length > 80) {
|
||||
throw new Error("parentChain class name is invalid");
|
||||
}
|
||||
}
|
||||
if (
|
||||
!entry.layout ||
|
||||
typeof entry.layout !== "object" ||
|
||||
Array.isArray(entry.layout) ||
|
||||
Object.keys(entry.layout).length > 24
|
||||
) {
|
||||
throw new Error("parentChain layout summary is invalid");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (context.structuralHints !== undefined) {
|
||||
const hints = context.structuralHints;
|
||||
if (!hints || typeof hints !== "object" || Array.isArray(hints)) {
|
||||
throw new Error("structuralHints must be an object");
|
||||
}
|
||||
if (typeof hints.hasTable !== "boolean" || typeof hints.hasList !== "boolean") {
|
||||
throw new Error("structuralHints flags are invalid");
|
||||
}
|
||||
if (!Array.isArray(hints.primaryClasses) || hints.primaryClasses.length > 8) {
|
||||
throw new Error("structuralHints primaryClasses are invalid");
|
||||
}
|
||||
for (const className of hints.primaryClasses) {
|
||||
if (typeof className !== "string" || className.length > 80) {
|
||||
throw new Error("structuralHints class name is invalid");
|
||||
}
|
||||
}
|
||||
for (const countKey of ["rowCount", "columnCount", "itemCount"] as const) {
|
||||
const count = hints[countKey];
|
||||
if (count === undefined) continue;
|
||||
if (!Number.isFinite(count) || count < 0 || count > 10_000) {
|
||||
throw new Error(`structuralHints ${countKey} is invalid`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!context.request.trim()) throw new Error("Change request is required");
|
||||
if (
|
||||
!context.dimensions ||
|
||||
!Number.isFinite(context.dimensions.width) ||
|
||||
!Number.isFinite(context.dimensions.height)
|
||||
) {
|
||||
throw new Error("Element dimensions are invalid");
|
||||
}
|
||||
if (
|
||||
!context.computedStyle ||
|
||||
typeof context.computedStyle !== "object" ||
|
||||
Array.isArray(context.computedStyle) ||
|
||||
Object.keys(context.computedStyle).length > 20
|
||||
) {
|
||||
throw new Error("Computed style summary is invalid");
|
||||
}
|
||||
return {
|
||||
...context,
|
||||
dimensions: { ...context.dimensions },
|
||||
computedStyle: { ...context.computedStyle },
|
||||
domCatalog: context.domCatalog.map((entry) => ({
|
||||
...entry,
|
||||
classes: [...entry.classes],
|
||||
layout: { ...entry.layout },
|
||||
})),
|
||||
...(context.parentChain
|
||||
? {
|
||||
parentChain: context.parentChain.map((entry) => ({
|
||||
...entry,
|
||||
classes: [...entry.classes],
|
||||
layout: { ...entry.layout },
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(context.structuralHints
|
||||
? {
|
||||
structuralHints: {
|
||||
...context.structuralHints,
|
||||
primaryClasses: [...context.structuralHints.primaryClasses],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function responseContent(payload: unknown): string {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("OpenRouter returned an invalid response");
|
||||
}
|
||||
const choices = (payload as { choices?: unknown }).choices;
|
||||
if (!Array.isArray(choices) || choices.length === 0) {
|
||||
throw new Error("OpenRouter returned no choices");
|
||||
}
|
||||
const content = (
|
||||
choices[0] as { message?: { content?: unknown } }
|
||||
).message?.content;
|
||||
if (typeof content === "string") return content;
|
||||
if (Array.isArray(content)) {
|
||||
const combined = content
|
||||
.map((part) =>
|
||||
part &&
|
||||
typeof part === "object" &&
|
||||
"text" in part &&
|
||||
typeof part.text === "string"
|
||||
? part.text
|
||||
: "",
|
||||
)
|
||||
.join("");
|
||||
if (combined) return combined;
|
||||
}
|
||||
throw new Error("OpenRouter returned no generated recipe");
|
||||
}
|
||||
|
||||
async function providerError(
|
||||
response: Response,
|
||||
modelId: string,
|
||||
): Promise<string> {
|
||||
const fallback = `OpenRouter request failed (${response.status})`;
|
||||
try {
|
||||
const payload = (await response.json()) as {
|
||||
error?: { message?: unknown; code?: number; metadata?: { error_type?: string } } | string;
|
||||
};
|
||||
if (typeof payload.error === "string") {
|
||||
return formatOpenRouterError({ message: payload.error }, modelId);
|
||||
}
|
||||
if (payload.error && typeof payload.error === "object") {
|
||||
return formatOpenRouterError(payload.error, modelId);
|
||||
}
|
||||
} catch {
|
||||
// Use the status-only fallback without exposing response content.
|
||||
}
|
||||
if (response.status === 429) {
|
||||
return formatOpenRouterError({ code: 429 }, modelId);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
type OpenRouterErrorShape = {
|
||||
code?: number;
|
||||
message?: string;
|
||||
metadata?: { error_type?: string };
|
||||
};
|
||||
|
||||
export function formatOpenRouterError(
|
||||
error: OpenRouterErrorShape | undefined,
|
||||
modelId: string,
|
||||
): string {
|
||||
if (!error) return "OpenRouter request failed";
|
||||
|
||||
const errorType = error.metadata?.error_type;
|
||||
const message = typeof error.message === "string" ? error.message : "";
|
||||
const isRateLimit =
|
||||
error.code === 429 ||
|
||||
errorType === "rate_limit_exceeded" ||
|
||||
/rate limit/i.test(message);
|
||||
|
||||
if (isRateLimit) {
|
||||
const model = getModelOption(modelId);
|
||||
const tierHint =
|
||||
model?.tier === "free"
|
||||
? "Free models share strict provider limits — wait 1–2 minutes or switch model in the creator panel."
|
||||
: "Wait a minute and try again.";
|
||||
return `Rate limit reached for ${model?.label ?? modelId}. ${tierHint}`;
|
||||
}
|
||||
|
||||
return message || "OpenRouter request failed";
|
||||
}
|
||||
|
||||
function openRouterRequestBody(
|
||||
context: SelectedElementContext,
|
||||
stream: boolean,
|
||||
formatMode: ResponseFormatMode,
|
||||
modelId: string,
|
||||
): Record<string, unknown> {
|
||||
const body: Record<string, unknown> = {
|
||||
model: modelId,
|
||||
messages: buildAiModMessages(context),
|
||||
temperature: 0.2,
|
||||
max_tokens: 8_000,
|
||||
stream,
|
||||
provider: {
|
||||
allow_fallbacks: true,
|
||||
},
|
||||
};
|
||||
|
||||
if (formatMode === "json_object") {
|
||||
body.response_format = { type: "json_object" };
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
function openRouterRequestInit(
|
||||
apiKey: string,
|
||||
context: SelectedElementContext,
|
||||
stream: boolean,
|
||||
formatMode: ResponseFormatMode,
|
||||
modelId: string,
|
||||
): RequestInit {
|
||||
return {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"HTTP-Referer": "https://betterseqta.org",
|
||||
"X-Title": "BetterSEQTA+ AI Mod Creator",
|
||||
},
|
||||
body: JSON.stringify(
|
||||
openRouterRequestBody(context, stream, formatMode, modelId),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function isRoutingError(message: string): boolean {
|
||||
return ROUTING_ERROR_PATTERN.test(message);
|
||||
}
|
||||
|
||||
function parseValidatedDraft(
|
||||
content: string | GeneratedModDraft,
|
||||
): GeneratedModDraft {
|
||||
try {
|
||||
return parseGeneratedModDraft(content);
|
||||
} catch (error) {
|
||||
throw new Error(formatRecipeValidationError(error));
|
||||
}
|
||||
}
|
||||
|
||||
async function requestGeneratedDraft(
|
||||
fetchImpl: FetchLike,
|
||||
apiKey: string,
|
||||
context: SelectedElementContext,
|
||||
stream: boolean,
|
||||
modelId: string,
|
||||
onProgress?: (progress: GenerationProgress) => void,
|
||||
): Promise<GeneratedModDraft> {
|
||||
const modes: ResponseFormatMode[] = ["json_object", "none"];
|
||||
let lastError = "OpenRouter request failed";
|
||||
const modelLabel = getModelOption(modelId)?.label ?? modelId;
|
||||
|
||||
for (const [index, mode] of modes.entries()) {
|
||||
if (index > 0) {
|
||||
aiModLog.warn("background", "Retrying OpenRouter request", { mode, lastError });
|
||||
onProgress?.({
|
||||
type: "status",
|
||||
text: "Retrying with a simpler OpenRouter request…",
|
||||
});
|
||||
} else if (stream) {
|
||||
onProgress?.({ type: "status", text: `Connecting to ${modelLabel}…` });
|
||||
}
|
||||
|
||||
aiModLog.info("background", "Sending OpenRouter request", {
|
||||
mode,
|
||||
stream,
|
||||
model: modelId,
|
||||
route: context.route,
|
||||
rootSelector: context.rootSelector,
|
||||
});
|
||||
|
||||
const response = await fetchImpl(
|
||||
OPENROUTER_URL,
|
||||
openRouterRequestInit(apiKey, context, stream, mode, modelId),
|
||||
);
|
||||
if (response.ok) {
|
||||
aiModLog.info("background", "OpenRouter request succeeded", {
|
||||
mode,
|
||||
stream,
|
||||
status: response.status,
|
||||
});
|
||||
if (stream) {
|
||||
return consumeOpenRouterStream(
|
||||
response,
|
||||
modelId,
|
||||
onProgress ?? (() => {}),
|
||||
);
|
||||
}
|
||||
const payload = await response.json();
|
||||
const content = responseContent(payload);
|
||||
aiModLog.debug("background", "OpenRouter non-stream content", content);
|
||||
return parseValidatedDraft(content);
|
||||
}
|
||||
|
||||
lastError = await providerError(response, modelId);
|
||||
aiModLog.warn("background", "OpenRouter request failed", {
|
||||
mode,
|
||||
stream,
|
||||
status: response.status,
|
||||
error: lastError,
|
||||
});
|
||||
if (!isRoutingError(lastError)) break;
|
||||
}
|
||||
|
||||
throw new Error(lastError);
|
||||
}
|
||||
|
||||
async function consumeOpenRouterStream(
|
||||
response: Response,
|
||||
modelId: string,
|
||||
onProgress: (progress: GenerationProgress) => void,
|
||||
): Promise<GeneratedModDraft> {
|
||||
if (!response.body) throw new Error("OpenRouter returned an empty stream");
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let generatedContent = "";
|
||||
let reasoningStarted = false;
|
||||
|
||||
const processEvent = (event: string) => {
|
||||
const data = event
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.startsWith("data:"))
|
||||
.map((line) => line.slice(5).trim())
|
||||
.join("");
|
||||
if (!data || data === "[DONE]") return;
|
||||
|
||||
const chunk = JSON.parse(data) as {
|
||||
error?: OpenRouterErrorShape;
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string | null;
|
||||
reasoning_details?: unknown[];
|
||||
};
|
||||
error?: OpenRouterErrorShape;
|
||||
}>;
|
||||
usage?: {
|
||||
prompt_tokens?: number;
|
||||
completion_tokens?: number;
|
||||
};
|
||||
};
|
||||
const streamError = chunk.error ?? chunk.choices?.[0]?.error;
|
||||
if (streamError) {
|
||||
aiModLog.warn("background", "OpenRouter stream error chunk", streamError);
|
||||
throw new Error(formatOpenRouterError(streamError, modelId));
|
||||
}
|
||||
|
||||
const delta = chunk.choices?.[0]?.delta;
|
||||
if (Array.isArray(delta?.reasoning_details) && !reasoningStarted) {
|
||||
reasoningStarted = true;
|
||||
onProgress({ type: "status", text: "Model is reasoning…" });
|
||||
}
|
||||
if (typeof delta?.content === "string" && delta.content) {
|
||||
generatedContent += delta.content;
|
||||
onProgress({ type: "content", text: delta.content });
|
||||
}
|
||||
if (chunk.usage) {
|
||||
onProgress({
|
||||
type: "usage",
|
||||
promptTokens: chunk.usage.prompt_tokens,
|
||||
completionTokens: chunk.usage.completion_tokens,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
buffer += decoder.decode(value, { stream: !done });
|
||||
const events = buffer.split(/\r?\n\r?\n/);
|
||||
buffer = events.pop() ?? "";
|
||||
for (const event of events) processEvent(event);
|
||||
if (done) break;
|
||||
}
|
||||
if (buffer.trim()) processEvent(buffer);
|
||||
aiModLog.debug("background", "Completed OpenRouter stream", {
|
||||
contentLength: generatedContent.length,
|
||||
preview: generatedContent.slice(0, 500),
|
||||
});
|
||||
return parseValidatedDraft(generatedContent);
|
||||
}
|
||||
|
||||
export function createAiModCreatorService(
|
||||
dependencies: {
|
||||
storage?: StorageArea;
|
||||
fetchImpl?: FetchLike;
|
||||
now?: () => number;
|
||||
} = {},
|
||||
) {
|
||||
const storage = dependencies.storage ?? browser.storage.local;
|
||||
const fetchImpl = dependencies.fetchImpl ?? fetch;
|
||||
const now = dependencies.now ?? Date.now;
|
||||
let inFlight = false;
|
||||
let lastGenerationAt = Number.NEGATIVE_INFINITY;
|
||||
|
||||
const getStoredKey = async (): Promise<string | null> => {
|
||||
const result = await storage.get(OPENROUTER_API_KEY_STORAGE_KEY);
|
||||
const value = result[OPENROUTER_API_KEY_STORAGE_KEY];
|
||||
return typeof value === "string" && value.length > 0 ? value : null;
|
||||
};
|
||||
|
||||
const getStoredModelId = async (): Promise<string> => {
|
||||
const result = await storage.get(OPENROUTER_MODEL_STORAGE_KEY);
|
||||
const value = result[OPENROUTER_MODEL_STORAGE_KEY];
|
||||
if (typeof value === "string" && value.length > 0) {
|
||||
try {
|
||||
return validateModelId(value);
|
||||
} catch {
|
||||
aiModLog.warn("background", "Ignoring invalid stored model id", value);
|
||||
}
|
||||
}
|
||||
return DEFAULT_OPENROUTER_MODEL_ID;
|
||||
};
|
||||
|
||||
const beginGeneration = () => {
|
||||
const currentTime = now();
|
||||
if (inFlight) {
|
||||
throw new Error("A generation is already in progress");
|
||||
}
|
||||
if (currentTime - lastGenerationAt < MIN_GENERATION_INTERVAL_MS) {
|
||||
const waitSeconds = Math.ceil(
|
||||
(MIN_GENERATION_INTERVAL_MS - (currentTime - lastGenerationAt)) / 1000,
|
||||
);
|
||||
throw new Error(
|
||||
`Please wait ${waitSeconds}s before generating another mod`,
|
||||
);
|
||||
}
|
||||
inFlight = true;
|
||||
lastGenerationAt = currentTime;
|
||||
};
|
||||
|
||||
return {
|
||||
async saveKey(apiKey: unknown): Promise<void> {
|
||||
await storage.set({
|
||||
[OPENROUTER_API_KEY_STORAGE_KEY]: validateApiKey(apiKey),
|
||||
});
|
||||
},
|
||||
|
||||
async clearKey(): Promise<void> {
|
||||
await storage.remove(OPENROUTER_API_KEY_STORAGE_KEY);
|
||||
},
|
||||
|
||||
async getKeyStatus(): Promise<KeyStatus> {
|
||||
return { configured: (await getStoredKey()) !== null };
|
||||
},
|
||||
|
||||
async getModelSettings() {
|
||||
return { modelId: await getStoredModelId() };
|
||||
},
|
||||
|
||||
async saveModel(modelId: unknown): Promise<void> {
|
||||
await storage.set({
|
||||
[OPENROUTER_MODEL_STORAGE_KEY]: validateModelId(modelId),
|
||||
});
|
||||
aiModLog.info("background", "Saved OpenRouter model", modelId);
|
||||
},
|
||||
|
||||
async generate(input: unknown): Promise<GeneratedModDraft> {
|
||||
const context = validateContext(input);
|
||||
const apiKey = await getStoredKey();
|
||||
if (!apiKey) throw new Error("OpenRouter API key is not configured");
|
||||
const modelId = await getStoredModelId();
|
||||
beginGeneration();
|
||||
|
||||
try {
|
||||
return await requestGeneratedDraft(
|
||||
fetchImpl,
|
||||
apiKey,
|
||||
context,
|
||||
false,
|
||||
modelId,
|
||||
);
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
},
|
||||
|
||||
async streamGenerate(
|
||||
input: unknown,
|
||||
onProgress: (progress: GenerationProgress) => void,
|
||||
): Promise<GeneratedModDraft> {
|
||||
const context = validateContext(input);
|
||||
const apiKey = await getStoredKey();
|
||||
if (!apiKey) throw new Error("OpenRouter API key is not configured");
|
||||
const modelId = await getStoredModelId();
|
||||
beginGeneration();
|
||||
|
||||
try {
|
||||
return await requestGeneratedDraft(
|
||||
fetchImpl,
|
||||
apiKey,
|
||||
context,
|
||||
true,
|
||||
modelId,
|
||||
onProgress,
|
||||
);
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const defaultService = createAiModCreatorService();
|
||||
|
||||
export function handleAiModCreatorMessage(
|
||||
request: {
|
||||
type?: string;
|
||||
action?: string;
|
||||
apiKey?: unknown;
|
||||
context?: unknown;
|
||||
recipe?: unknown;
|
||||
id?: unknown;
|
||||
modelId?: unknown;
|
||||
},
|
||||
sender: browser.Runtime.MessageSender,
|
||||
sendResponse: SendResponse,
|
||||
isTrustedSender: TrustCheck,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
|
||||
const action = request.action;
|
||||
aiModLog.debug("background", "Handling message", {
|
||||
action,
|
||||
tabId: sender.tab?.id,
|
||||
senderId: sender.id,
|
||||
});
|
||||
void (async () => {
|
||||
try {
|
||||
let data: unknown;
|
||||
if (action === "saveKey") {
|
||||
await defaultService.saveKey(request.apiKey);
|
||||
} else if (action === "clearKey") {
|
||||
await defaultService.clearKey();
|
||||
} else if (action === "status") {
|
||||
data = await defaultService.getKeyStatus();
|
||||
} else if (action === "getModel") {
|
||||
data = await defaultService.getModelSettings();
|
||||
} else if (action === "saveModel") {
|
||||
await defaultService.saveModel(request.modelId);
|
||||
} else if (action === "advancedSupport") {
|
||||
data = getAdvancedScriptSupport();
|
||||
} else if (action === "generate") {
|
||||
data = await defaultService.generate(request.context);
|
||||
} else if (action === "executeAdvanced") {
|
||||
if (sender.tab?.id === undefined) {
|
||||
throw new Error("Advanced scripts require a SEQTA browser tab");
|
||||
}
|
||||
const { devMode } = await browser.storage.local.get("devMode");
|
||||
if (devMode !== true) {
|
||||
throw new Error("Advanced scripts are available only in developer mode");
|
||||
}
|
||||
await executeAdvancedMod(
|
||||
request.recipe as StoredModRecipe,
|
||||
sender.tab.id,
|
||||
);
|
||||
} else if (action === "stopAdvanced") {
|
||||
if (sender.tab?.id === undefined || typeof request.id !== "string") {
|
||||
throw new Error("Advanced script id or tab is missing");
|
||||
}
|
||||
await stopAdvancedMod(request.id, sender.tab.id);
|
||||
} else {
|
||||
throw new Error("Unsupported AI Mod Creator action");
|
||||
}
|
||||
sendResponse({ success: true, data });
|
||||
aiModLog.debug("background", "Message handled", { action });
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "AI request failed";
|
||||
aiModLog.error("background", "Message failed", { action, error: message });
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function registerAiModCreatorStreaming(
|
||||
isTrustedSender: TrustCheck,
|
||||
): void {
|
||||
browser.runtime.onConnect.addListener((port) => {
|
||||
if (port.name !== "aiModCreator.stream") return;
|
||||
if (!isTrustedSender(port.sender)) {
|
||||
port.postMessage({ type: "error", error: "Unauthorized sender" });
|
||||
port.disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
let started = false;
|
||||
port.onMessage.addListener((message: unknown) => {
|
||||
if (started) return;
|
||||
started = true;
|
||||
const context =
|
||||
message && typeof message === "object" && "context" in message
|
||||
? (message as { context?: unknown }).context
|
||||
: undefined;
|
||||
aiModLog.info("background", "Starting streamed generation");
|
||||
void defaultService
|
||||
.streamGenerate(context, (progress) => {
|
||||
port.postMessage({ type: "progress", progress });
|
||||
})
|
||||
.then((draft) => {
|
||||
aiModLog.info("background", "Streamed generation complete", {
|
||||
name: draft.name,
|
||||
operationCount: draft.operations.length,
|
||||
});
|
||||
port.postMessage({ type: "done", draft });
|
||||
port.disconnect();
|
||||
})
|
||||
.catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "AI streaming failed";
|
||||
aiModLog.error("background", "Streamed generation failed", message);
|
||||
port.postMessage({
|
||||
type: "error",
|
||||
error: message,
|
||||
});
|
||||
port.disconnect();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import { buildExecutionSource } from "./aiModUserScripts";
|
||||
import type { StoredModRecipe } from "@/plugins/built-in/aiModCreator/types";
|
||||
|
||||
const baseRecipe: StoredModRecipe = {
|
||||
schemaVersion: 1,
|
||||
id: "mod-test",
|
||||
enabled: true,
|
||||
route: "welcome",
|
||||
rootSelector: "#titlebar",
|
||||
name: "Test mod",
|
||||
description: "Test",
|
||||
operations: [],
|
||||
advancedScript: `
|
||||
const house = select('.userInfohouse');
|
||||
if (!house) throw new Error('Missing .userInfohouse inside selected root');
|
||||
return () => {};
|
||||
`,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
};
|
||||
|
||||
describe("advanced user script injection source", () => {
|
||||
it("does not declare select twice in the generated runtime", () => {
|
||||
const source = buildExecutionSource(baseRecipe);
|
||||
expect(source.match(/\bconst select\b/g)?.length).toBe(1);
|
||||
expect(source.match(/\bconst selectAll\b/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it("throws when the selected root is missing", () => {
|
||||
const source = buildExecutionSource(baseRecipe);
|
||||
expect(source).toContain("AI mod root not found on this page");
|
||||
});
|
||||
});
|
||||
@@ -1,290 +0,0 @@
|
||||
import {
|
||||
SAFE_ATTRIBUTE_NAMES,
|
||||
SAFE_INSERT_TAGS,
|
||||
SAFE_STYLE_PROPERTIES,
|
||||
validateStoredRecipes,
|
||||
} from "@/plugins/built-in/aiModCreator/recipeSchema";
|
||||
import { assertAdvancedScriptSafe } from "@/plugins/built-in/aiModCreator/scriptSafety";
|
||||
import type { StoredModRecipe } from "@/plugins/built-in/aiModCreator/types";
|
||||
|
||||
interface UserScriptsApi {
|
||||
configureWorld(details: {
|
||||
worldId: string;
|
||||
csp: string;
|
||||
messaging: boolean;
|
||||
}): Promise<void>;
|
||||
execute(details: {
|
||||
target: { tabId: number; allFrames: boolean };
|
||||
worldId: string;
|
||||
world: "USER_SCRIPT";
|
||||
injectImmediately: boolean;
|
||||
js: Array<{ code: string }>;
|
||||
}): Promise<unknown>;
|
||||
}
|
||||
|
||||
const USER_SCRIPT_CSP = [
|
||||
"default-src 'none'",
|
||||
"script-src 'self' 'unsafe-inline'",
|
||||
"connect-src 'none'",
|
||||
"img-src 'none'",
|
||||
"media-src 'none'",
|
||||
"font-src 'none'",
|
||||
"object-src 'none'",
|
||||
"frame-src 'none'",
|
||||
"child-src 'none'",
|
||||
"form-action 'none'",
|
||||
"base-uri 'none'",
|
||||
].join("; ");
|
||||
|
||||
function getUserScriptsApi(): UserScriptsApi {
|
||||
const globalApis = globalThis as unknown as {
|
||||
chrome?: { userScripts?: UserScriptsApi };
|
||||
browser?: { userScripts?: UserScriptsApi };
|
||||
};
|
||||
const api =
|
||||
globalApis.chrome?.userScripts ?? globalApis.browser?.userScripts;
|
||||
if (!api?.execute || !api.configureWorld) {
|
||||
throw new Error(
|
||||
"Advanced scripts require Chrome User Scripts support.",
|
||||
);
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
export const ADVANCED_SCRIPT_SETUP_INSTRUCTIONS = [
|
||||
"Open chrome://extensions",
|
||||
"Find BetterSEQTA+ and open Details",
|
||||
'Enable "Allow User Scripts"',
|
||||
"Reload this SEQTA tab, then enable the mod again",
|
||||
].join("\n");
|
||||
|
||||
export function getAdvancedScriptSupport(): {
|
||||
supported: boolean;
|
||||
reason?: string;
|
||||
instructions?: string;
|
||||
} {
|
||||
try {
|
||||
getUserScriptsApi();
|
||||
return { supported: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
supported: false,
|
||||
reason:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Advanced scripts are unavailable in this browser",
|
||||
instructions: ADVANCED_SCRIPT_SETUP_INSTRUCTIONS,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function worldId(id: string): string {
|
||||
return `bsplus-${id}`.slice(0, 256);
|
||||
}
|
||||
|
||||
export function buildExecutionSource(recipe: StoredModRecipe): string {
|
||||
const script = assertAdvancedScriptSafe(recipe.advancedScript);
|
||||
const config = JSON.stringify({
|
||||
id: recipe.id,
|
||||
route: recipe.route,
|
||||
rootSelector: recipe.rootSelector,
|
||||
allowedAttributes: SAFE_ATTRIBUTE_NAMES,
|
||||
allowedStyles: SAFE_STYLE_PROPERTIES,
|
||||
allowedTags: SAFE_INSERT_TAGS,
|
||||
});
|
||||
|
||||
return `(() => {
|
||||
"use strict";
|
||||
const config = ${config};
|
||||
const registryKey = Symbol.for("betterseqta.aiModRuntime");
|
||||
const registry = globalThis[registryKey] ?? (globalThis[registryKey] = new Map());
|
||||
const previousCleanup = registry.get(config.id);
|
||||
if (typeof previousCleanup === "function") previousCleanup();
|
||||
|
||||
const route = (location.hash.split("?page=/")[1] ?? "").split(/[/?#]/)[0];
|
||||
if (config.route && route !== config.route) {
|
||||
throw new Error("AI mod route mismatch: expected " + config.route + " but page is " + route);
|
||||
}
|
||||
const root = document.querySelector(config.rootSelector);
|
||||
if (!(root instanceof HTMLElement)) {
|
||||
throw new Error("AI mod root not found on this page: " + config.rootSelector);
|
||||
}
|
||||
|
||||
const cleanups = [];
|
||||
const remember = (cleanup) => {
|
||||
if (typeof cleanup === "function") cleanups.push(cleanup);
|
||||
return cleanup;
|
||||
};
|
||||
const insideRoot = (element) =>
|
||||
element instanceof Element && (element === root || root.contains(element));
|
||||
const requireInsideRoot = (element) => {
|
||||
if (!insideRoot(element)) throw new Error("AI mod attempted to leave its selected root");
|
||||
return element;
|
||||
};
|
||||
const query = (selector = ":scope") =>
|
||||
selector === ":scope" ? root : root.querySelector(selector);
|
||||
const queryAll = (selector = ":scope") =>
|
||||
selector === ":scope" ? [root] : Array.from(root.querySelectorAll(selector));
|
||||
|
||||
const bsplus = Object.freeze({
|
||||
root,
|
||||
select: query,
|
||||
selectAll: queryAll,
|
||||
onCleanup: remember,
|
||||
setText(element, text) {
|
||||
requireInsideRoot(element);
|
||||
const previous = element.textContent;
|
||||
element.textContent = String(text);
|
||||
remember(() => { element.textContent = previous; });
|
||||
return element;
|
||||
},
|
||||
setStyle(element, property, value) {
|
||||
requireInsideRoot(element);
|
||||
if (!config.allowedStyles.includes(property)) throw new Error("Unsupported style property");
|
||||
const previous = element.style.getPropertyValue(property);
|
||||
const priority = element.style.getPropertyPriority(property);
|
||||
element.style.setProperty(property, String(value).replace(/\\s*!important\\s*$/i, "").trim(), "important");
|
||||
remember(() => previous
|
||||
? element.style.setProperty(property, previous, priority)
|
||||
: element.style.removeProperty(property));
|
||||
return element;
|
||||
},
|
||||
setAttribute(element, name, value) {
|
||||
requireInsideRoot(element);
|
||||
if (!config.allowedAttributes.includes(name)) throw new Error("Unsupported attribute");
|
||||
const hadAttribute = element.hasAttribute(name);
|
||||
const previous = element.getAttribute(name);
|
||||
element.setAttribute(name, String(value));
|
||||
remember(() => hadAttribute
|
||||
? element.setAttribute(name, previous ?? "")
|
||||
: element.removeAttribute(name));
|
||||
return element;
|
||||
},
|
||||
create(tag, text, parent = root) {
|
||||
requireInsideRoot(parent);
|
||||
if (!config.allowedTags.includes(tag)) throw new Error("Unsupported element tag");
|
||||
const element = document.createElement(tag);
|
||||
element.textContent = String(text);
|
||||
parent.append(element);
|
||||
remember(() => element.remove());
|
||||
return element;
|
||||
},
|
||||
on(element, event, handler, options) {
|
||||
requireInsideRoot(element);
|
||||
element.addEventListener(event, handler, options);
|
||||
remember(() => element.removeEventListener(event, handler, options));
|
||||
},
|
||||
observe(element, callback, options = { childList: true, subtree: true }) {
|
||||
requireInsideRoot(element);
|
||||
const observer = new MutationObserver(callback);
|
||||
observer.observe(element, options);
|
||||
remember(() => observer.disconnect());
|
||||
return observer;
|
||||
},
|
||||
});
|
||||
|
||||
const select = bsplus.select;
|
||||
const selectAll = bsplus.selectAll;
|
||||
|
||||
let disposed = false;
|
||||
const cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
for (const callback of cleanups.reverse()) {
|
||||
try { callback(); } catch (error) { console.warn("[BetterSEQTA+ AI Mod] Cleanup failed", error); }
|
||||
}
|
||||
registry.delete(config.id);
|
||||
};
|
||||
|
||||
try {
|
||||
const userCleanup = (() => {
|
||||
${script}
|
||||
})();
|
||||
remember(userCleanup);
|
||||
registry.set(config.id, cleanup);
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
cleanup();
|
||||
throw error;
|
||||
}
|
||||
})();`;
|
||||
}
|
||||
|
||||
function buildStopSource(id: string): string {
|
||||
return `(() => {
|
||||
const registry = globalThis[Symbol.for("betterseqta.aiModRuntime")];
|
||||
const cleanup = registry?.get(${JSON.stringify(id)});
|
||||
if (typeof cleanup === "function") cleanup();
|
||||
})();`;
|
||||
}
|
||||
|
||||
async function configureWorld(api: UserScriptsApi, id: string): Promise<void> {
|
||||
try {
|
||||
await api.configureWorld({
|
||||
worldId: worldId(id),
|
||||
csp: USER_SCRIPT_CSP,
|
||||
messaging: false,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Could not configure the isolated script world: ${
|
||||
error instanceof Error ? error.message : "browser rejected it"
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeSource(
|
||||
api: UserScriptsApi,
|
||||
id: string,
|
||||
tabId: number,
|
||||
source: string,
|
||||
): Promise<void> {
|
||||
await configureWorld(api, id);
|
||||
const results = (await api.execute({
|
||||
target: { tabId, allFrames: false },
|
||||
world: "USER_SCRIPT",
|
||||
worldId: worldId(id),
|
||||
injectImmediately: true,
|
||||
js: [{ code: source }],
|
||||
})) as Array<{ result?: unknown; error?: unknown }> | undefined;
|
||||
|
||||
const injectionError = results?.find((entry) => entry.error)?.error;
|
||||
if (injectionError) {
|
||||
throw new Error(
|
||||
injectionError instanceof Error
|
||||
? injectionError.message
|
||||
: String(injectionError),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function executeAdvancedMod(
|
||||
input: StoredModRecipe,
|
||||
tabId: number,
|
||||
): Promise<void> {
|
||||
const support = getAdvancedScriptSupport();
|
||||
if (!support.supported) {
|
||||
throw new Error(
|
||||
`${support.reason ?? "Advanced scripts are unavailable"}\n\n${support.instructions ?? ADVANCED_SCRIPT_SETUP_INSTRUCTIONS}`,
|
||||
);
|
||||
}
|
||||
const [recipe] = validateStoredRecipes([input]);
|
||||
if (!recipe.advancedScript) return;
|
||||
await executeSource(
|
||||
getUserScriptsApi(),
|
||||
recipe.id,
|
||||
tabId,
|
||||
buildExecutionSource(recipe),
|
||||
);
|
||||
}
|
||||
|
||||
export async function stopAdvancedMod(
|
||||
id: string,
|
||||
tabId: number,
|
||||
): Promise<void> {
|
||||
const support = getAdvancedScriptSupport();
|
||||
if (!support.supported) return;
|
||||
if (!/^[A-Za-z0-9_-]{1,160}$/.test(id)) throw new Error("Invalid mod id");
|
||||
await executeSource(getUserScriptsApi(), id, tabId, buildStopSource(id));
|
||||
}
|
||||
+304
-6
@@ -772,11 +772,6 @@ html.bsplus-custom-title-pending #title > :not(#bsplus-title-root),
|
||||
background-image: none !important;
|
||||
}
|
||||
|
||||
> #bsplus-sidebar-root.drilling .sub ul .bsplus-sidebar-item,
|
||||
> #bsplus-sidebar-root.drilling .sub ul .bsplus-sidebar-item * {
|
||||
pointer-events: auto !important;
|
||||
}
|
||||
|
||||
> #bsplus-sidebar-root > li.hasChildren.bsplus-active > label,
|
||||
> #bsplus-sidebar-root.drilling > li.hasChildren > label {
|
||||
pointer-events: none !important;
|
||||
@@ -3849,18 +3844,320 @@ div.day-empty {
|
||||
.userInfo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-top: 4px;
|
||||
padding: 4px 0;
|
||||
}
|
||||
.userInfoText {
|
||||
text-align: end;
|
||||
padding: 2px 0;
|
||||
}
|
||||
.userInfoName {
|
||||
margin: 0 !important;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.userInfoCode {
|
||||
margin: 0 !important;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.userInfoNameRow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 6px;
|
||||
}
|
||||
.userInfoDetails {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 2px;
|
||||
}
|
||||
.userInfoHouseWrap {
|
||||
display: inline-block;
|
||||
margin: 0 8px;
|
||||
text-align: center;
|
||||
}
|
||||
.userInfoHouseWrap .userInfohouse {
|
||||
display: block;
|
||||
margin: 0 !important;
|
||||
padding: 0 6px !important;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.userInfoHouseWrap .bsplus-founder-badge-slot {
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.userInfoHouseWrap .bsplus-founder-badge-slot[hidden],
|
||||
.bsplus-founder-badge-slot[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar {
|
||||
display: block;
|
||||
width: 100%;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__glass,
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__content {
|
||||
width: 100%;
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__content {
|
||||
justify-content: center;
|
||||
padding: 0 6px;
|
||||
gap: 0;
|
||||
min-height: 0;
|
||||
height: auto;
|
||||
font-size: 15px;
|
||||
line-height: normal;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.28),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.16),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__label {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: center;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar:focus-visible .bsplus-founder-badge__content {
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.28),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.16),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.12),
|
||||
0 0 0 2px var(--theme-primary, #f97316),
|
||||
0 0 0 4px rgba(249, 115, 22, 0.35);
|
||||
}
|
||||
.legacy-root .bsplus-founder-badge,
|
||||
.legacy-root .bsplus-founder-badge-actions .bsplus-cal-btn {
|
||||
background: transparent !important;
|
||||
}
|
||||
.legacy-root .bsplus-founder-badge::after,
|
||||
.legacy-root .bsplus-founder-badge-actions .bsplus-cal-btn::after {
|
||||
display: none !important;
|
||||
content: none !important;
|
||||
}
|
||||
.legacy-root .bsplus-founder-badge-actions .bsplus-cal-btn--ghost {
|
||||
background: color-mix(in srgb, var(--text-primary, #111) 8%, transparent) !important;
|
||||
}
|
||||
.legacy-root .bsplus-founder-badge-actions .bsplus-cal-btn--ghost:hover {
|
||||
background: color-mix(in srgb, var(--text-primary, #111) 14%, transparent) !important;
|
||||
}
|
||||
.legacy-root .bsplus-founder-badge-actions .bsplus-cal-btn--primary {
|
||||
background: var(--better-main, #3b82f6) !important;
|
||||
}
|
||||
.bsplus-founder-badge {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
vertical-align: middle;
|
||||
cursor: pointer;
|
||||
font-family: var(--betterseqta-font-family, Rubik), sans-serif !important;
|
||||
transition: transform 0.2s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.bsplus-founder-badge--hero {
|
||||
border-radius: 12px;
|
||||
}
|
||||
.bsplus-founder-badge:hover {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
.bsplus-founder-badge:focus {
|
||||
outline: none;
|
||||
}
|
||||
.bsplus-founder-badge:focus-visible .bsplus-founder-badge__glass {
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.78),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.52),
|
||||
inset 0 2px 8px rgba(255, 255, 255, 0.14),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.08),
|
||||
0 0 0 2px var(--theme-primary, #f97316),
|
||||
0 0 0 4px rgba(249, 115, 22, 0.35);
|
||||
}
|
||||
.bsplus-founder-badge__glass {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
overflow: hidden;
|
||||
border-radius: inherit;
|
||||
background: var(--badge-base, #1e293b);
|
||||
}
|
||||
.bsplus-founder-badge__blobs {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
background:
|
||||
radial-gradient(ellipse 72% 68% at 18% 42%, var(--badge-blob-a), transparent 72%),
|
||||
radial-gradient(ellipse 68% 62% at 82% 58%, var(--badge-blob-b), transparent 70%),
|
||||
radial-gradient(ellipse 64% 56% at 50% 88%, var(--badge-blob-c), transparent 68%);
|
||||
filter: blur(1px);
|
||||
}
|
||||
.bsplus-founder-badge__content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 0 10px;
|
||||
min-height: 22px;
|
||||
border-radius: inherit;
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
line-height: 22px;
|
||||
letter-spacing: 0.01em;
|
||||
font-family: inherit;
|
||||
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.22);
|
||||
backdrop-filter: blur(14px) saturate(1.3);
|
||||
-webkit-backdrop-filter: blur(14px) saturate(1.3);
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.78),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.52),
|
||||
inset 0 2px 8px rgba(255, 255, 255, 0.14),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
.bsplus-founder-badge--hero .bsplus-founder-badge__content {
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
min-height: auto;
|
||||
font-size: 14px;
|
||||
line-height: 1.2;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
.bsplus-founder-badge--hero .bsplus-founder-badge__glass {
|
||||
background: transparent;
|
||||
}
|
||||
.bsplus-founder-badge__icon {
|
||||
flex-shrink: 0;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
opacity: 0.95;
|
||||
}
|
||||
.bsplus-founder-badge--hero .bsplus-founder-badge__icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
.bsplus-founder-badge-hero {
|
||||
position: relative;
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
margin: 0 auto;
|
||||
width: 90%;
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
|
||||
background: var(--badge-base, #0f172a);
|
||||
}
|
||||
.bsplus-founder-badge-hero__blobs {
|
||||
position: absolute;
|
||||
inset: -22%;
|
||||
pointer-events: none;
|
||||
background:
|
||||
radial-gradient(ellipse 72% 62% at 18% 34%, var(--badge-blob-a), transparent 76%),
|
||||
radial-gradient(ellipse 68% 58% at 82% 42%, var(--badge-blob-b), transparent 74%),
|
||||
radial-gradient(ellipse 74% 64% at 52% 88%, var(--badge-blob-c), transparent 76%),
|
||||
radial-gradient(ellipse 78% 68% at 48% 52%, var(--badge-blob-b), transparent 78%);
|
||||
filter: blur(10px);
|
||||
}
|
||||
.bsplus-founder-badge-hero__vignette {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
background: radial-gradient(ellipse at center, transparent 34%, rgba(0, 0, 0, 0.62) 100%);
|
||||
opacity: 0.84;
|
||||
}
|
||||
.bsplus-founder-badge-hero__stage {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.bsplus-founder-badge-hero__stage .bsplus-founder-badge {
|
||||
pointer-events: auto;
|
||||
}
|
||||
.whatsnewTextContainer.bsplus-founder-badge-body p {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 1.2rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.whatsnewTextContainer.bsplus-founder-badge-body a {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.bsplus-founder-badge-signup {
|
||||
margin: 0 0 1rem !important;
|
||||
padding: 0.55rem 0.75rem;
|
||||
border-radius: 0.6rem;
|
||||
border: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent);
|
||||
background: color-mix(in srgb, var(--text-primary) 5%, transparent);
|
||||
font-size: 1rem !important;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.bsplus-founder-badge-header {
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
|
||||
h1,
|
||||
p {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
.bsplus-founder-badge-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn {
|
||||
padding: 8px 14px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn:focus-visible {
|
||||
outline: none;
|
||||
box-shadow:
|
||||
0 0 0 2px var(--background-primary, #fff),
|
||||
0 0 0 4px var(--better-main, #3b82f6);
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn--ghost {
|
||||
background: color-mix(in srgb, var(--text-primary, #111) 8%, transparent);
|
||||
color: var(--text-primary, #111);
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn--ghost:hover {
|
||||
background: color-mix(in srgb, var(--text-primary, #111) 14%, transparent);
|
||||
transform: scale(1.02);
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn--primary {
|
||||
background: var(--better-main, #3b82f6);
|
||||
color: #fff;
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn--primary:hover {
|
||||
filter: brightness(1.06);
|
||||
transform: scale(1.02);
|
||||
}
|
||||
.bsplus-founder-badge-actions .bsplus-cal-btn:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
.userInfosvg {
|
||||
width: 50px;
|
||||
@@ -3903,6 +4200,7 @@ div.day-empty {
|
||||
color: var(--text-primary);
|
||||
background: var(--auto-background);
|
||||
outline: solid 1px black;
|
||||
text-align: center;
|
||||
}
|
||||
.DarkLightButton {
|
||||
right: 145px !important;
|
||||
|
||||
@@ -283,9 +283,14 @@
|
||||
|
||||
const applyDestination = (destination: SettingsDestination) => {
|
||||
activePage = destination.page;
|
||||
if (destination.page === "settings" && destination.section) {
|
||||
settingsSearch = "";
|
||||
activeSection = destination.section;
|
||||
if (destination.page === "settings") {
|
||||
if (destination.section) {
|
||||
settingsSearch = "";
|
||||
activeSection = destination.section;
|
||||
}
|
||||
if (destination.search) {
|
||||
settingsSearch = destination.search;
|
||||
}
|
||||
} else if (destination.page === "themes" && destination.view) {
|
||||
activeThemeView = destination.view === "store" ? "theme-store" : "theme-settings";
|
||||
} else if (destination.page === "backgrounds" && destination.view) {
|
||||
|
||||
@@ -173,6 +173,27 @@
|
||||
return !q || parts.some((part) => part?.toLowerCase().includes(q));
|
||||
};
|
||||
|
||||
const founderBadgeSetting = {
|
||||
title: "Titlebar founder badge",
|
||||
description: "Show your Cloud founder badge in the SEQTA titlebar",
|
||||
} as const;
|
||||
|
||||
const showCloudCardHeader = $derived(
|
||||
matchesSearch("BetterSEQTA Cloud", "Account & sync"),
|
||||
);
|
||||
|
||||
const showFounderBadgeSetting = $derived(
|
||||
matchesSearch(
|
||||
founderBadgeSetting.title,
|
||||
founderBadgeSetting.description,
|
||||
"founder badge",
|
||||
"titlebar",
|
||||
"founder",
|
||||
),
|
||||
);
|
||||
|
||||
const showCloudAccountCard = $derived(showCloudCardHeader || showFounderBadgeSetting);
|
||||
|
||||
const pluginHit = (plugin: Plugin) =>
|
||||
matchesSearch(plugin.name, plugin.description, ...Object.values(plugin.settings).flatMap((s) => [s.title, s.description]));
|
||||
|
||||
@@ -214,9 +235,10 @@
|
||||
props: {}
|
||||
})}
|
||||
|
||||
{#if matchesSearch("BetterSEQTA Cloud", "Account & sync")}
|
||||
{#if showCloudAccountCard}
|
||||
<div class="border-none">
|
||||
<div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
|
||||
{#if showCloudCardHeader}
|
||||
<div class="flex justify-between items-center px-5 py-4">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-xl font-bold">BetterSEQTA Cloud</h2>
|
||||
@@ -226,9 +248,28 @@
|
||||
<CloudHeader alwaysShowUserName onClick={showCloudPanel} />
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="px-3 pb-3">
|
||||
<div class="px-3 pb-3" class:pt-3={!showCloudCardHeader}>
|
||||
{#if showCloudCardHeader}
|
||||
<CloudSettingsSync showDisclaimer={(onConfirm, onCancel) => showDisclaimer(onConfirm, onCancel, "Restore from cloud?", "This will replace your local settings with the cloud backup. Continue?")} />
|
||||
{/if}
|
||||
{#if showFounderBadgeSetting}
|
||||
{@render Setting({
|
||||
title: founderBadgeSetting.title,
|
||||
description: founderBadgeSetting.description,
|
||||
id: 17,
|
||||
Component: Switch,
|
||||
props: {
|
||||
state: $settingsState.showTitlebarFounderBadge !== false,
|
||||
onChange: (isOn: boolean) => (settingsState.showTitlebarFounderBadge = isOn),
|
||||
},
|
||||
})}
|
||||
{/if}
|
||||
</div>
|
||||
{:else if showFounderBadgeSetting}
|
||||
<div class="px-5 pb-4 text-sm text-zinc-600 dark:text-zinc-400">
|
||||
Sign in to Cloud first.
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"64": "resources/icons/icon-64.png"
|
||||
}
|
||||
},
|
||||
"permissions": ["tabs", "notifications", "storage", "identity", "alarms", "userScripts"],
|
||||
"permissions": ["tabs", "notifications", "storage", "identity", "alarms"],
|
||||
"host_permissions": [
|
||||
"https://newsapi.org/",
|
||||
"https://betterseqta.org/",
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
<script lang="ts">
|
||||
type TabId = "create" | "mods" | "settings";
|
||||
|
||||
let {
|
||||
tabs,
|
||||
activeTab = $bindable("create" as TabId),
|
||||
disabled = false,
|
||||
}: {
|
||||
tabs: { id: TabId; label: string }[];
|
||||
activeTab?: TabId;
|
||||
disabled?: boolean;
|
||||
} = $props();
|
||||
|
||||
const activeIndex = $derived(
|
||||
Math.max(
|
||||
0,
|
||||
tabs.findIndex((tab) => tab.id === activeTab),
|
||||
),
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="tab-nav" aria-label="Creator sections">
|
||||
<div class="tab-track" role="tablist">
|
||||
<div
|
||||
class="tab-indicator"
|
||||
style="width: {100 / tabs.length}%; transform: translateX({activeIndex * 100}%)"
|
||||
aria-hidden="true"
|
||||
></div>
|
||||
{#each tabs as tab (tab.id)}
|
||||
<button
|
||||
type="button"
|
||||
class="tab-button accent-ring"
|
||||
role="tab"
|
||||
aria-selected={activeTab === tab.id}
|
||||
disabled={disabled}
|
||||
onclick={() => (activeTab = tab.id)}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.tab-nav {
|
||||
padding: 12px 16px 0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.tab-track {
|
||||
position: relative;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.tab-indicator {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 100%;
|
||||
border-radius: 9999px;
|
||||
background: linear-gradient(
|
||||
to top right,
|
||||
rgb(56 55 61 / 0.8),
|
||||
rgb(56 55 61)
|
||||
);
|
||||
opacity: 0.45;
|
||||
pointer-events: none;
|
||||
transition: transform 380ms cubic-bezier(0.34, 1.45, 0.64, 1);
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.tab-button {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border: 0;
|
||||
border-radius: 9999px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font-size: inherit;
|
||||
font-weight: 600;
|
||||
transition: opacity 180ms ease;
|
||||
}
|
||||
|
||||
.tab-button[aria-selected="true"] {
|
||||
color: #f4f4f5;
|
||||
}
|
||||
|
||||
.tab-button[aria-selected="false"] {
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.tab-button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.tab-indicator {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,326 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { tick } from "svelte";
|
||||
import { fade, fly } from "svelte/transition";
|
||||
import LoadingSpinnerMini from "./LoadingSpinnerMini.svelte";
|
||||
|
||||
let {
|
||||
status = "",
|
||||
tokenUsage = "",
|
||||
streamChunks = [],
|
||||
error = "",
|
||||
onBack,
|
||||
}: {
|
||||
status?: string;
|
||||
tokenUsage?: string;
|
||||
streamChunks?: string[];
|
||||
error?: string;
|
||||
onBack: () => void;
|
||||
} = $props();
|
||||
|
||||
let streamContainer = $state<HTMLElement | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (streamChunks.length === 0 || !streamContainer) return;
|
||||
void tick().then(() => {
|
||||
streamContainer?.scrollTo({
|
||||
top: streamContainer.scrollHeight,
|
||||
behavior: "smooth",
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="generating-view"
|
||||
aria-live="polite"
|
||||
aria-busy={!error}
|
||||
>
|
||||
{#if error}
|
||||
<div
|
||||
class="error-card"
|
||||
role="alert"
|
||||
in:fly={{ y: 10, duration: 420, easing: (t) => 1 + 0.36 * Math.pow(t - 1, 3) + 0.22 * Math.pow(t - 1, 2) }}
|
||||
>
|
||||
<p class="error-title">Generation failed</p>
|
||||
<p class="error-message">{error}</p>
|
||||
<button class="secondary-button w-full accent-ring" type="button" onclick={onBack}>
|
||||
Go back and try again
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="generating-header">
|
||||
<LoadingSpinnerMini />
|
||||
<div class="min-w-0">
|
||||
<h3 class="generating-title">Generating mod recipe</h3>
|
||||
{#key status}
|
||||
<p class="generating-status" in:fade={{ duration: 280 }}>
|
||||
{status || "Connecting to model…"}
|
||||
</p>
|
||||
{/key}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="generating-meta">
|
||||
<span class="pulse-dot" aria-hidden="true"></span>
|
||||
<span class="meta-label">Streaming response</span>
|
||||
{#if tokenUsage}
|
||||
<span class="token-badge" in:fly={{ y: 6, duration: 280 }}>
|
||||
{tokenUsage}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div
|
||||
bind:this={streamContainer}
|
||||
class="stream-panel"
|
||||
data-testid="generation-stream"
|
||||
>
|
||||
{#if streamChunks.length === 0}
|
||||
<div class="stream-placeholder" in:fade={{ duration: 320 }}>
|
||||
<span class="skeleton-line"></span>
|
||||
<span class="skeleton-line skeleton-line--short"></span>
|
||||
<span class="skeleton-line skeleton-line--medium"></span>
|
||||
</div>
|
||||
{:else}
|
||||
<pre class="stream-output">
|
||||
{#each streamChunks as chunk, index (index)}
|
||||
<span class="stream-chunk" in:fly={{ y: 8, duration: 220, delay: 16 }}>
|
||||
{chunk}
|
||||
</span>
|
||||
{/each}
|
||||
<span class="stream-cursor" aria-hidden="true"></span>
|
||||
</pre>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.generating-view {
|
||||
display: flex;
|
||||
min-height: 320px;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.generating-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.generating-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
color: #f4f4f5;
|
||||
}
|
||||
|
||||
.generating-status {
|
||||
margin-top: 2px;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
color: rgba(244, 244, 245, 0.62);
|
||||
}
|
||||
|
||||
.generating-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: rgba(244, 244, 245, 0.52);
|
||||
}
|
||||
|
||||
.pulse-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 9999px;
|
||||
background: var(--better-main, #8b5cf6);
|
||||
animation: pulse-dot 1.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.token-badge {
|
||||
margin-left: auto;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 9999px;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
text-transform: none;
|
||||
color: rgba(244, 244, 245, 0.82);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.stream-panel {
|
||||
flex: 1;
|
||||
min-height: 220px;
|
||||
max-height: 360px;
|
||||
overflow: auto;
|
||||
padding: 14px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 12px;
|
||||
background:
|
||||
linear-gradient(180deg, rgb(255 255 255 / 0.03) 0%, transparent 100%),
|
||||
rgb(0 0 0 / 0.35);
|
||||
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.04);
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
.stream-panel::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.stream-panel::-webkit-scrollbar-thumb {
|
||||
border-radius: 9999px;
|
||||
background: rgb(255 255 255 / 0.14);
|
||||
}
|
||||
|
||||
.stream-placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.skeleton-line {
|
||||
display: block;
|
||||
height: 10px;
|
||||
border-radius: 9999px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgb(255 255 255 / 0.06) 0%,
|
||||
rgb(255 255 255 / 0.12) 50%,
|
||||
rgb(255 255 255 / 0.06) 100%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: skeleton-shimmer 1.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.skeleton-line--short {
|
||||
width: 55%;
|
||||
}
|
||||
|
||||
.skeleton-line--medium {
|
||||
width: 78%;
|
||||
}
|
||||
|
||||
.stream-output {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.55;
|
||||
color: #e4e4e7;
|
||||
}
|
||||
|
||||
.stream-chunk {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.stream-cursor {
|
||||
display: inline-block;
|
||||
width: 2px;
|
||||
height: 1em;
|
||||
margin-left: 1px;
|
||||
vertical-align: text-bottom;
|
||||
background: var(--better-main, #8b5cf6);
|
||||
animation: cursor-blink 1s step-end infinite;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 20px;
|
||||
border: 1px solid rgb(248 113 113 / 0.4);
|
||||
border-radius: 12px;
|
||||
background: rgb(127 29 29 / 0.28);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
|
||||
.error-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: rgb(252 165 165);
|
||||
}
|
||||
|
||||
.error-message {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.6;
|
||||
color: rgb(254 202 202);
|
||||
}
|
||||
|
||||
.secondary-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 10px;
|
||||
font-size: 0.775rem;
|
||||
font-weight: 600;
|
||||
color: inherit;
|
||||
background: rgb(255 255 255 / 0.05);
|
||||
transition: all 220ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
|
||||
.secondary-button:hover {
|
||||
transform: scale(1.03);
|
||||
border-color: rgb(96 165 250 / 0.28);
|
||||
}
|
||||
|
||||
.secondary-button:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
@keyframes pulse-dot {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.45;
|
||||
transform: scale(0.85);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes skeleton-shimmer {
|
||||
0% {
|
||||
background-position: 200% 0;
|
||||
}
|
||||
|
||||
100% {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes cursor-blink {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.pulse-dot,
|
||||
.skeleton-line,
|
||||
.stream-cursor {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,42 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
let { children }: { children: Snippet } = $props();
|
||||
</script>
|
||||
|
||||
<div class="bk-skin">
|
||||
<div class="bk-skin__vignette" aria-hidden="true"></div>
|
||||
<div class="bk-skin__content">
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.bk-skin {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
color: #f4f4f5;
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
#010101 0%,
|
||||
#040404 50%,
|
||||
#080808 100%
|
||||
);
|
||||
}
|
||||
|
||||
.bk-skin__vignette {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: radial-gradient(
|
||||
ellipse at center,
|
||||
transparent 40%,
|
||||
rgb(0 0 0 / 0.55) 100%
|
||||
);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bk-skin__content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
</style>
|
||||
@@ -1,74 +0,0 @@
|
||||
<script lang="ts">
|
||||
import loadingSpinner from "@/seqta/ui/loading-spinner.html?raw";
|
||||
</script>
|
||||
|
||||
<div class="bk-spinner-mini" aria-hidden="true">
|
||||
{@html loadingSpinner}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.bk-spinner-mini {
|
||||
position: relative;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex-shrink: 0;
|
||||
color: var(--better-main, #8b5cf6);
|
||||
}
|
||||
|
||||
.bk-spinner-mini :global(.svg) {
|
||||
transform-origin: center center;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
backface-visibility: hidden;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.bk-spinner-mini :global(.logo) {
|
||||
transform: translate3d(-50%, -50%, 0);
|
||||
z-index: 2;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.bk-spinner-mini :global(.big-circle) {
|
||||
margin: -38px;
|
||||
width: 76px;
|
||||
height: 76px;
|
||||
animation: bk-spin 3s linear infinite;
|
||||
}
|
||||
|
||||
.bk-spinner-mini :global(.small-circle) {
|
||||
margin: -29px;
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
animation: bk-spin-reverse 3s linear infinite;
|
||||
}
|
||||
|
||||
.bk-spinner-mini :global(.outer-circle) {
|
||||
margin: -46px;
|
||||
width: 92px;
|
||||
height: 92px;
|
||||
animation: bk-spin 4.5s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes bk-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes bk-spin-reverse {
|
||||
to {
|
||||
transform: rotate(-360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bk-spinner-mini :global(.big-circle),
|
||||
.bk-spinner-mini :global(.small-circle),
|
||||
.bk-spinner-mini :global(.outer-circle) {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,32 +0,0 @@
|
||||
<script lang="ts">
|
||||
let { size = 20 }: { size?: number } = $props();
|
||||
</script>
|
||||
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden="true"
|
||||
class="mod-creator-icon"
|
||||
>
|
||||
<path
|
||||
d="M12 2L13.09 8.26L19 7L14.74 12L19 17L13.09 15.74L12 22L10.91 15.74L5 17L9.26 12L5 7L10.91 8.26L12 2Z"
|
||||
fill="currentColor"
|
||||
opacity="0.95"
|
||||
/>
|
||||
<path
|
||||
d="M18 3L18.6 5.4L21 6L18.6 6.6L18 9L17.4 6.6L15 6L17.4 5.4L18 3Z"
|
||||
fill="currentColor"
|
||||
opacity="0.75"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<style>
|
||||
.mod-creator-icon {
|
||||
display: block;
|
||||
flex-shrink: 0;
|
||||
color: currentColor;
|
||||
}
|
||||
</style>
|
||||
@@ -1,81 +0,0 @@
|
||||
/** @jest-environment jsdom */
|
||||
/**
|
||||
* Unit-test runtime only. Production advanced mods run through the background
|
||||
* User Scripts API because page/content CSP blocks eval/new Function.
|
||||
*/
|
||||
import { runAdvancedMod, stopAdvancedMod } from "./advancedModRuntime";
|
||||
import type { StoredModRecipe } from "./types";
|
||||
|
||||
describe("advanced mod runtime", () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
stopAdvancedMod("test-mod");
|
||||
});
|
||||
|
||||
it("runs an advanced script scoped to the selected root", () => {
|
||||
document.body.innerHTML = `
|
||||
<div id="root">
|
||||
<p class="label">House</p>
|
||||
<p class="target">ID</p>
|
||||
</div>
|
||||
`;
|
||||
const root = document.getElementById("root")!;
|
||||
const label = root.querySelector(".label")!;
|
||||
const target = root.querySelector(".target")!;
|
||||
|
||||
const recipe: StoredModRecipe = {
|
||||
schemaVersion: 1,
|
||||
id: "test-mod",
|
||||
enabled: true,
|
||||
route: "",
|
||||
rootSelector: "#root",
|
||||
name: "Move label",
|
||||
description: "Moves label next to target",
|
||||
operations: [],
|
||||
advancedScript: `
|
||||
const label = select('.label');
|
||||
const target = select('.target');
|
||||
target.parentNode.insertBefore(label, target);
|
||||
return () => {
|
||||
root.prepend(label);
|
||||
};
|
||||
`,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
};
|
||||
|
||||
runAdvancedMod(recipe);
|
||||
expect(target.previousElementSibling).toBe(label);
|
||||
|
||||
stopAdvancedMod("test-mod");
|
||||
expect(root.firstElementChild).toBe(label);
|
||||
});
|
||||
|
||||
it("stops a previously started mod before restarting it", () => {
|
||||
document.body.innerHTML = `<div id="root"><span class="badge">Y11HA</span></div>`;
|
||||
const recipe: StoredModRecipe = {
|
||||
schemaVersion: 1,
|
||||
id: "test-mod",
|
||||
enabled: true,
|
||||
route: "",
|
||||
rootSelector: "#root",
|
||||
name: "Hide badge",
|
||||
description: "Hides badge",
|
||||
operations: [],
|
||||
advancedScript: `
|
||||
const badge = select('.badge');
|
||||
badge.hidden = true;
|
||||
return () => { badge.hidden = false; };
|
||||
`,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
};
|
||||
|
||||
runAdvancedMod(recipe);
|
||||
expect(document.querySelector(".badge")).toHaveProperty("hidden", true);
|
||||
runAdvancedMod(recipe);
|
||||
expect(document.querySelector(".badge")).toHaveProperty("hidden", true);
|
||||
stopAdvancedMod("test-mod");
|
||||
expect(document.querySelector(".badge")).toHaveProperty("hidden", false);
|
||||
});
|
||||
});
|
||||
@@ -1,210 +0,0 @@
|
||||
import {
|
||||
SAFE_ATTRIBUTE_NAMES,
|
||||
SAFE_INSERT_TAGS,
|
||||
SAFE_STYLE_PROPERTIES,
|
||||
normalizeStyleProperty,
|
||||
} from "./recipeSchema";
|
||||
import { assertAdvancedScriptSafe } from "./scriptSafety";
|
||||
import { applyModStyleProperty, restoreModStyleProperty } from "./modStyle";
|
||||
import { aiModLog } from "./logger";
|
||||
import type { StoredModRecipe } from "./types";
|
||||
|
||||
/**
|
||||
* Test-only runtime. Production uses background User Scripts injection because
|
||||
* SEQTA's CSP blocks eval/new Function inside content scripts.
|
||||
*/
|
||||
|
||||
const REGISTRY_KEY = Symbol.for("betterseqta.aiModRuntime");
|
||||
type Cleanup = () => void;
|
||||
|
||||
function getRegistry(): Map<string, Cleanup> {
|
||||
const globalScope = globalThis as typeof globalThis & {
|
||||
[key: symbol]: Map<string, Cleanup> | undefined;
|
||||
};
|
||||
if (!globalScope[REGISTRY_KEY]) {
|
||||
globalScope[REGISTRY_KEY] = new Map();
|
||||
}
|
||||
return globalScope[REGISTRY_KEY]!;
|
||||
}
|
||||
|
||||
function currentRoute(): string {
|
||||
return (window.location.hash.split("?page=/")[1] ?? "").split(/[/?#]/)[0];
|
||||
}
|
||||
|
||||
function createBsplus(root: HTMLElement, cleanups: Cleanup[]) {
|
||||
const remember = (cleanup: unknown) => {
|
||||
if (typeof cleanup === "function") cleanups.push(cleanup as Cleanup);
|
||||
return cleanup;
|
||||
};
|
||||
const insideRoot = (element: Element) =>
|
||||
element === root || root.contains(element);
|
||||
const requireInsideRoot = (element: Element) => {
|
||||
if (!insideRoot(element)) {
|
||||
throw new Error("AI mod attempted to leave its selected root");
|
||||
}
|
||||
return element;
|
||||
};
|
||||
const select = (selector = ":scope") =>
|
||||
selector === ":scope"
|
||||
? root
|
||||
: root.querySelector<HTMLElement>(selector);
|
||||
const selectAll = (selector = ":scope") =>
|
||||
selector === ":scope"
|
||||
? [root]
|
||||
: Array.from(root.querySelectorAll<HTMLElement>(selector));
|
||||
|
||||
return Object.freeze({
|
||||
root,
|
||||
select,
|
||||
selectAll,
|
||||
onCleanup: remember,
|
||||
setText(element: HTMLElement, text: string) {
|
||||
requireInsideRoot(element);
|
||||
const previous = element.textContent;
|
||||
element.textContent = String(text);
|
||||
remember(() => {
|
||||
element.textContent = previous;
|
||||
});
|
||||
return element;
|
||||
},
|
||||
setStyle(element: HTMLElement, property: string, value: string) {
|
||||
requireInsideRoot(element);
|
||||
const normalizedProperty = normalizeStyleProperty(property);
|
||||
if (!SAFE_STYLE_PROPERTIES.includes(normalizedProperty as never)) {
|
||||
throw new Error("Unsupported style property");
|
||||
}
|
||||
const snapshot = applyModStyleProperty(
|
||||
element,
|
||||
normalizedProperty,
|
||||
String(value),
|
||||
true,
|
||||
);
|
||||
remember(() =>
|
||||
restoreModStyleProperty(element, normalizedProperty, snapshot),
|
||||
);
|
||||
return element;
|
||||
},
|
||||
setAttribute(element: HTMLElement, name: string, value: string) {
|
||||
requireInsideRoot(element);
|
||||
if (!SAFE_ATTRIBUTE_NAMES.includes(name as never)) {
|
||||
throw new Error("Unsupported attribute");
|
||||
}
|
||||
const hadAttribute = element.hasAttribute(name);
|
||||
const previous = element.getAttribute(name);
|
||||
element.setAttribute(name, String(value));
|
||||
remember(() =>
|
||||
hadAttribute
|
||||
? element.setAttribute(name, previous ?? "")
|
||||
: element.removeAttribute(name),
|
||||
);
|
||||
return element;
|
||||
},
|
||||
create(tag: string, text: string, parent: HTMLElement = root) {
|
||||
requireInsideRoot(parent);
|
||||
if (!SAFE_INSERT_TAGS.includes(tag as never)) {
|
||||
throw new Error("Unsupported element tag");
|
||||
}
|
||||
const element = document.createElement(tag);
|
||||
element.textContent = String(text);
|
||||
parent.append(element);
|
||||
remember(() => element.remove());
|
||||
return element;
|
||||
},
|
||||
on(
|
||||
element: HTMLElement,
|
||||
event: string,
|
||||
handler: EventListenerOrEventListenerObject,
|
||||
options?: boolean | AddEventListenerOptions,
|
||||
) {
|
||||
requireInsideRoot(element);
|
||||
element.addEventListener(event, handler, options);
|
||||
remember(() => element.removeEventListener(event, handler, options));
|
||||
},
|
||||
observe(
|
||||
element: HTMLElement,
|
||||
callback: MutationCallback,
|
||||
options: MutationObserverInit = { childList: true, subtree: true },
|
||||
) {
|
||||
requireInsideRoot(element);
|
||||
const observer = new MutationObserver(callback);
|
||||
observer.observe(element, options);
|
||||
remember(() => observer.disconnect());
|
||||
return observer;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function runAdvancedMod(recipe: StoredModRecipe): void {
|
||||
if (!recipe.advancedScript) return;
|
||||
|
||||
stopAdvancedMod(recipe.id);
|
||||
const script = assertAdvancedScriptSafe(recipe.advancedScript);
|
||||
|
||||
if (recipe.route && currentRoute() !== recipe.route) {
|
||||
aiModLog.debug("runtime", `Skipped mod ${recipe.id} on route ${currentRoute()}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const root = document.querySelector(recipe.rootSelector);
|
||||
if (!(root instanceof HTMLElement)) {
|
||||
throw new Error(
|
||||
`Selected root not found on this page: ${recipe.rootSelector}`,
|
||||
);
|
||||
}
|
||||
|
||||
const cleanups: Cleanup[] = [];
|
||||
const bsplus = createBsplus(root, cleanups);
|
||||
const select = bsplus.select;
|
||||
const selectAll = bsplus.selectAll;
|
||||
let disposed = false;
|
||||
|
||||
const cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
for (const callback of cleanups.reverse()) {
|
||||
try {
|
||||
callback();
|
||||
} catch (error) {
|
||||
aiModLog.warn("runtime", `Cleanup failed for mod ${recipe.id}`, error);
|
||||
}
|
||||
}
|
||||
getRegistry().delete(recipe.id);
|
||||
};
|
||||
|
||||
try {
|
||||
const runner = new Function(
|
||||
"root",
|
||||
"bsplus",
|
||||
"select",
|
||||
"selectAll",
|
||||
`"use strict"; return (() => { ${script} })();`,
|
||||
) as (
|
||||
root: HTMLElement,
|
||||
bsplus: ReturnType<typeof createBsplus>,
|
||||
select: typeof bsplus.select,
|
||||
selectAll: typeof bsplus.selectAll,
|
||||
) => unknown;
|
||||
|
||||
const userCleanup = runner(root, bsplus, select, selectAll);
|
||||
if (typeof userCleanup === "function") {
|
||||
cleanups.push(userCleanup as Cleanup);
|
||||
}
|
||||
getRegistry().set(recipe.id, cleanup);
|
||||
aiModLog.info("runtime", `Started advanced mod ${recipe.id}`, recipe.name);
|
||||
} catch (error) {
|
||||
cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function stopAdvancedMod(id: string): void {
|
||||
const cleanup = getRegistry().get(id);
|
||||
if (typeof cleanup === "function") {
|
||||
cleanup();
|
||||
aiModLog.info("runtime", `Stopped advanced mod ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function isAdvancedModRuntimeAvailable(): boolean {
|
||||
return typeof document !== "undefined" && typeof Function !== "undefined";
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { unmount } from "svelte";
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import renderSvelte from "@/interface/main";
|
||||
import { syncPageThemeToElement } from "@/interface/utils/syncPageTheme";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import FloatingModCreator from "./FloatingModCreator.svelte";
|
||||
import { ModRuntime } from "./modRuntime";
|
||||
import { createCreatorServices } from "./services";
|
||||
import { AI_MODS_STORAGE_KEY, loadStoredMods } from "./storage";
|
||||
import { aiModLog } from "./logger";
|
||||
|
||||
const HOST_ATTRIBUTE = "data-bsplus-ai-mod-creator-host";
|
||||
|
||||
async function mountCreator(): Promise<() => void> {
|
||||
document.querySelector(`[${HOST_ATTRIBUTE}]`)?.remove();
|
||||
|
||||
const host = document.createElement("div");
|
||||
host.setAttribute(HOST_ATTRIBUTE, "");
|
||||
Object.assign(host.style, {
|
||||
position: "fixed",
|
||||
right: "0",
|
||||
bottom: "0",
|
||||
width: "0",
|
||||
height: "0",
|
||||
zIndex: "2147483647",
|
||||
});
|
||||
document.body.appendChild(host);
|
||||
syncPageThemeToElement(host);
|
||||
|
||||
const shadow = host.attachShadow({ mode: "open" });
|
||||
const services = createCreatorServices();
|
||||
const app = renderSvelte(
|
||||
FloatingModCreator,
|
||||
shadow,
|
||||
{ services },
|
||||
"content",
|
||||
);
|
||||
|
||||
const runtime = new ModRuntime();
|
||||
runtime.start();
|
||||
let activeAdvancedScripts = new Map<string, number>();
|
||||
|
||||
const currentRoute = () => {
|
||||
const path = window.location.hash.split("?page=/")[1] ?? "";
|
||||
return path.split(/[/?#]/)[0];
|
||||
};
|
||||
|
||||
const syncMods = async () => {
|
||||
const mods = await loadStoredMods();
|
||||
aiModLog.debug("plugin", "Syncing stored mods", {
|
||||
count: mods.length,
|
||||
route: currentRoute(),
|
||||
});
|
||||
runtime.setRecipes(mods);
|
||||
const route = currentRoute();
|
||||
const nextAdvanced = mods.filter(
|
||||
(mod) =>
|
||||
mod.enabled &&
|
||||
Boolean(mod.advancedScript) &&
|
||||
(!mod.route || mod.route === route),
|
||||
);
|
||||
const nextIds = new Set(nextAdvanced.map((mod) => mod.id));
|
||||
|
||||
await Promise.all(
|
||||
[...activeAdvancedScripts.keys()]
|
||||
.filter((id) => !nextIds.has(id))
|
||||
.map((id) =>
|
||||
services.stopAdvancedScript(id).catch((error) => {
|
||||
aiModLog.warn("plugin", `Failed to stop AI mod ${id}`, error);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
for (const mod of nextAdvanced) {
|
||||
if (activeAdvancedScripts.get(mod.id) === mod.updatedAt) continue;
|
||||
try {
|
||||
await services.executeAdvancedScript(mod);
|
||||
aiModLog.info("plugin", `Started advanced mod ${mod.id}`);
|
||||
} catch (error) {
|
||||
aiModLog.warn("plugin", `Failed to execute advanced AI mod ${mod.id}`, error);
|
||||
}
|
||||
}
|
||||
activeAdvancedScripts = new Map(
|
||||
nextAdvanced.map((mod) => [mod.id, mod.updatedAt]),
|
||||
);
|
||||
};
|
||||
|
||||
await syncMods();
|
||||
|
||||
const onStorageChanged = (
|
||||
changes: Record<string, browser.Storage.StorageChange>,
|
||||
areaName: string,
|
||||
) => {
|
||||
if (areaName !== "local" || !changes[AI_MODS_STORAGE_KEY]) return;
|
||||
void syncMods();
|
||||
};
|
||||
browser.storage.onChanged.addListener(onStorageChanged);
|
||||
window.addEventListener("hashchange", syncMods);
|
||||
|
||||
const themeObserver = new MutationObserver(() => syncPageThemeToElement(host));
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["class", "style"],
|
||||
});
|
||||
|
||||
const syncTheme = () => syncPageThemeToElement(host);
|
||||
settingsState.register("DarkMode", syncTheme);
|
||||
settingsState.register("selectedColor", syncTheme);
|
||||
|
||||
return () => {
|
||||
settingsState.unregister("DarkMode", syncTheme);
|
||||
settingsState.unregister("selectedColor", syncTheme);
|
||||
themeObserver.disconnect();
|
||||
browser.storage.onChanged.removeListener(onStorageChanged);
|
||||
window.removeEventListener("hashchange", syncMods);
|
||||
for (const id of activeAdvancedScripts.keys()) {
|
||||
void services.stopAdvancedScript(id).catch((error) => {
|
||||
console.warn(`[BetterSEQTA+] Failed to stop AI mod ${id}:`, error);
|
||||
});
|
||||
}
|
||||
activeAdvancedScripts = new Map();
|
||||
runtime.stop();
|
||||
unmount(app);
|
||||
host.remove();
|
||||
};
|
||||
}
|
||||
|
||||
const aiModCreatorPlugin: Plugin = {
|
||||
id: "ai-mod-creator",
|
||||
name: "AI Mod Creator",
|
||||
description:
|
||||
"Developer-only local creator for safe, declarative BetterSEQTA+ page mods.",
|
||||
version: "0.1.0",
|
||||
settings: {},
|
||||
beta: true,
|
||||
run: async () => {
|
||||
let cleanup: (() => void) | null = null;
|
||||
let generation = 0;
|
||||
|
||||
const syncEnabledState = async () => {
|
||||
const currentGeneration = ++generation;
|
||||
if (!settingsState.devMode) {
|
||||
cleanup?.();
|
||||
cleanup = null;
|
||||
return;
|
||||
}
|
||||
if (cleanup) return;
|
||||
const nextCleanup = await mountCreator();
|
||||
if (
|
||||
currentGeneration !== generation ||
|
||||
!settingsState.devMode
|
||||
) {
|
||||
nextCleanup();
|
||||
return;
|
||||
}
|
||||
cleanup = nextCleanup;
|
||||
};
|
||||
|
||||
const onDevModeChanged = () => void syncEnabledState();
|
||||
settingsState.register("devMode", onDevModeChanged);
|
||||
await syncEnabledState();
|
||||
|
||||
return () => {
|
||||
generation += 1;
|
||||
settingsState.unregister("devMode", onDevModeChanged);
|
||||
cleanup?.();
|
||||
cleanup = null;
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default aiModCreatorPlugin;
|
||||
@@ -1,34 +0,0 @@
|
||||
const PREFIX = "[BetterSEQTA+ AI Mod Creator]";
|
||||
|
||||
function serialize(value: unknown): unknown {
|
||||
if (value instanceof Error) {
|
||||
return { name: value.name, message: value.message, stack: value.stack };
|
||||
}
|
||||
if (typeof value === "string" && value.length > 4_000) {
|
||||
return `${value.slice(0, 4_000)}… (${value.length} chars)`;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export const aiModLog = {
|
||||
debug(scope: string, ...details: unknown[]) {
|
||||
console.debug(PREFIX, scope, ...details.map(serialize));
|
||||
},
|
||||
info(scope: string, ...details: unknown[]) {
|
||||
console.info(PREFIX, scope, ...details.map(serialize));
|
||||
},
|
||||
warn(scope: string, ...details: unknown[]) {
|
||||
console.warn(PREFIX, scope, ...details.map(serialize));
|
||||
},
|
||||
error(scope: string, ...details: unknown[]) {
|
||||
console.error(PREFIX, scope, ...details.map(serialize));
|
||||
},
|
||||
group(scope: string, label: string, fn: () => void) {
|
||||
console.groupCollapsed(`${PREFIX} ${scope} · ${label}`);
|
||||
try {
|
||||
fn();
|
||||
} finally {
|
||||
console.groupEnd();
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -1,200 +0,0 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
import { applyModRecipe, ModRuntime } from "./modRuntime";
|
||||
import type { StoredModRecipe } from "./types";
|
||||
|
||||
function recipe(
|
||||
operations: StoredModRecipe["operations"],
|
||||
overrides: Partial<StoredModRecipe> = {},
|
||||
): StoredModRecipe {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: "mod-1",
|
||||
name: "Test mod",
|
||||
description: "Test",
|
||||
enabled: true,
|
||||
route: "assessments",
|
||||
rootSelector: "#selected",
|
||||
operations,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("safe AI mod runtime", () => {
|
||||
beforeEach(() => {
|
||||
window.location.hash = "#?page=/assessments";
|
||||
document.body.innerHTML = `
|
||||
<section id="selected" aria-label="Old label">
|
||||
<h2 class="title">Old title</h2>
|
||||
<p class="description">One old old</p>
|
||||
</section>
|
||||
<p id="outside">Outside</p>
|
||||
`;
|
||||
});
|
||||
|
||||
it("applies the supported standard-library operations", () => {
|
||||
const cleanup = applyModRecipe(
|
||||
recipe([
|
||||
{
|
||||
type: "setText",
|
||||
selector: ":scope .title",
|
||||
text: "New title",
|
||||
},
|
||||
{
|
||||
type: "replaceText",
|
||||
selector: ":scope .description",
|
||||
search: "old",
|
||||
replacement: "new",
|
||||
all: true,
|
||||
},
|
||||
{
|
||||
type: "setAttribute",
|
||||
selector: ":scope",
|
||||
name: "aria-label",
|
||||
value: "New label",
|
||||
},
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "border-radius",
|
||||
value: "12px",
|
||||
},
|
||||
{
|
||||
type: "addClass",
|
||||
selector: ":scope",
|
||||
className: "custom-card",
|
||||
},
|
||||
{
|
||||
type: "hide",
|
||||
selector: ":scope .description",
|
||||
},
|
||||
{
|
||||
type: "insertText",
|
||||
selector: ":scope",
|
||||
position: "append",
|
||||
tag: "span",
|
||||
text: "Generated note",
|
||||
className: "note",
|
||||
},
|
||||
]),
|
||||
document,
|
||||
);
|
||||
|
||||
const selected = document.querySelector<HTMLElement>("#selected")!;
|
||||
expect(selected.querySelector(".title")?.textContent).toBe("New title");
|
||||
expect(selected.querySelector(".description")?.textContent).toBe(
|
||||
"One new new",
|
||||
);
|
||||
expect(selected.querySelector<HTMLElement>(".description")?.style.display).toBe(
|
||||
"none",
|
||||
);
|
||||
expect(
|
||||
selected.querySelector<HTMLElement>(".description")?.style.getPropertyPriority(
|
||||
"display",
|
||||
),
|
||||
).toBe("important");
|
||||
expect(selected.getAttribute("aria-label")).toBe("New label");
|
||||
expect(selected.style.borderRadius).toBe("12px");
|
||||
expect(selected.style.getPropertyPriority("border-radius")).toBe("important");
|
||||
expect(selected.classList.contains("custom-card")).toBe(true);
|
||||
expect(selected.querySelector(".note")?.textContent).toBe("Generated note");
|
||||
|
||||
cleanup();
|
||||
expect(selected.querySelector(".title")?.textContent).toBe("Old title");
|
||||
expect(selected.querySelector(".description")?.textContent).toBe(
|
||||
"One old old",
|
||||
);
|
||||
expect(selected.querySelector<HTMLElement>(".description")?.style.display).toBe(
|
||||
"",
|
||||
);
|
||||
expect(selected.getAttribute("aria-label")).toBe("Old label");
|
||||
expect(selected.style.borderRadius).toBe("");
|
||||
expect(selected.classList.contains("custom-card")).toBe(false);
|
||||
expect(selected.querySelector(".note")).toBeNull();
|
||||
});
|
||||
|
||||
it("never changes nodes outside the captured root", () => {
|
||||
const cleanup = applyModRecipe(
|
||||
recipe([{ type: "setText", selector: ":scope #outside", text: "Changed" }]),
|
||||
document,
|
||||
);
|
||||
|
||||
expect(document.querySelector("#outside")?.textContent).toBe("Outside");
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("applies setStyle with important priority to beat page CSS caps", () => {
|
||||
window.location.hash = "#?page=/news";
|
||||
document.body.innerHTML = `
|
||||
<div class="home-root" id="selected">
|
||||
<div class="home-container">News</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const cleanup = applyModRecipe(
|
||||
recipe(
|
||||
[
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope > div.home-container",
|
||||
property: "max-width",
|
||||
value: "100%",
|
||||
},
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope > div.home-container",
|
||||
property: "width",
|
||||
value: "100%",
|
||||
},
|
||||
],
|
||||
{ route: "news" },
|
||||
),
|
||||
document,
|
||||
);
|
||||
|
||||
const container = document.querySelector<HTMLElement>(".home-container")!;
|
||||
expect(container.style.getPropertyValue("max-width")).toBe("100%");
|
||||
expect(container.style.getPropertyPriority("max-width")).toBe("important");
|
||||
expect(container.style.getPropertyValue("width")).toBe("100%");
|
||||
expect(container.style.getPropertyPriority("width")).toBe("important");
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it("reconciles enabled recipes after a SPA remount and restores on stop", async () => {
|
||||
jest.useFakeTimers();
|
||||
const runtime = new ModRuntime(document, () => "assessments");
|
||||
runtime.start();
|
||||
runtime.setRecipes(
|
||||
recipe([{ type: "setText", selector: ":scope .title", text: "Changed" }]),
|
||||
);
|
||||
expect(document.querySelector(".title")?.textContent).toBe("Changed");
|
||||
|
||||
document.querySelector("#selected")!.outerHTML =
|
||||
'<section id="selected"><h2 class="title">Remounted</h2></section>';
|
||||
await Promise.resolve();
|
||||
jest.runOnlyPendingTimers();
|
||||
expect(document.querySelector(".title")?.textContent).toBe("Changed");
|
||||
|
||||
runtime.stop();
|
||||
expect(document.querySelector(".title")?.textContent).toBe("Remounted");
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it("applies only enabled recipes matching the current route", () => {
|
||||
const runtime = new ModRuntime(document, () => "courses");
|
||||
runtime.start();
|
||||
runtime.setRecipes([
|
||||
recipe([{ type: "setText", selector: ":scope .title", text: "Wrong" }]),
|
||||
recipe(
|
||||
[{ type: "setText", selector: ":scope .title", text: "Disabled" }],
|
||||
{ id: "mod-2", route: "courses", enabled: false },
|
||||
),
|
||||
]);
|
||||
|
||||
expect(document.querySelector(".title")?.textContent).toBe("Old title");
|
||||
runtime.stop();
|
||||
});
|
||||
});
|
||||
@@ -1,228 +0,0 @@
|
||||
import { validateStoredRecipes } from "./recipeSchema";
|
||||
import {
|
||||
applyModStyleProperty,
|
||||
restoreModStyleProperty,
|
||||
} from "./modStyle";
|
||||
import type { ModOperation, StoredModRecipe } from "./types";
|
||||
type Cleanup = () => void;
|
||||
|
||||
function targetsFor(
|
||||
root: HTMLElement,
|
||||
selector: string,
|
||||
): HTMLElement[] {
|
||||
if (selector === ":scope") return [root];
|
||||
try {
|
||||
return [...root.querySelectorAll<HTMLElement>(selector)];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function applyOperation(
|
||||
root: HTMLElement,
|
||||
operation: ModOperation,
|
||||
modId: string,
|
||||
): Cleanup[] {
|
||||
const cleanups: Cleanup[] = [];
|
||||
for (const element of targetsFor(root, operation.selector)) {
|
||||
switch (operation.type) {
|
||||
case "setText":
|
||||
case "replaceText": {
|
||||
const previous = element.textContent;
|
||||
if (operation.type === "setText") {
|
||||
element.textContent = operation.text;
|
||||
} else if (operation.all) {
|
||||
element.textContent = (previous ?? "").split(operation.search).join(
|
||||
operation.replacement,
|
||||
);
|
||||
} else {
|
||||
element.textContent = (previous ?? "").replace(
|
||||
operation.search,
|
||||
operation.replacement,
|
||||
);
|
||||
}
|
||||
cleanups.push(() => {
|
||||
element.textContent = previous;
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "setAttribute": {
|
||||
const hadAttribute = element.hasAttribute(operation.name);
|
||||
const previous = element.getAttribute(operation.name);
|
||||
element.setAttribute(operation.name, operation.value);
|
||||
cleanups.push(() => {
|
||||
if (hadAttribute && previous !== null) {
|
||||
element.setAttribute(operation.name, previous);
|
||||
} else {
|
||||
element.removeAttribute(operation.name);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "setStyle": {
|
||||
const important = operation.important !== false;
|
||||
const snapshot = applyModStyleProperty(
|
||||
element,
|
||||
operation.property,
|
||||
operation.value,
|
||||
important,
|
||||
);
|
||||
cleanups.push(() => {
|
||||
restoreModStyleProperty(element, operation.property, snapshot);
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "addClass":
|
||||
case "removeClass": {
|
||||
const hadClass = element.classList.contains(operation.className);
|
||||
element.classList.toggle(
|
||||
operation.className,
|
||||
operation.type === "addClass",
|
||||
);
|
||||
cleanups.push(() => {
|
||||
element.classList.toggle(operation.className, hadClass);
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "hide":
|
||||
case "show": {
|
||||
const previous = element.style.getPropertyValue("display");
|
||||
const priority = element.style.getPropertyPriority("display");
|
||||
if (operation.type === "hide") {
|
||||
element.style.setProperty("display", "none", "important");
|
||||
} else {
|
||||
element.style.removeProperty("display");
|
||||
}
|
||||
cleanups.push(() => {
|
||||
if (previous) {
|
||||
element.style.setProperty("display", previous, priority);
|
||||
} else {
|
||||
element.style.removeProperty("display");
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "insertText": {
|
||||
if (
|
||||
element === root &&
|
||||
(operation.position === "before" || operation.position === "after")
|
||||
) {
|
||||
break;
|
||||
}
|
||||
const inserted = document.createElement(operation.tag);
|
||||
inserted.textContent = operation.text;
|
||||
inserted.dataset.bsplusAiMod = modId;
|
||||
if (operation.className) inserted.classList.add(operation.className);
|
||||
if (operation.position === "before") {
|
||||
element.before(inserted);
|
||||
} else if (operation.position === "after") {
|
||||
element.after(inserted);
|
||||
} else if (operation.position === "prepend") {
|
||||
element.prepend(inserted);
|
||||
} else {
|
||||
element.append(inserted);
|
||||
}
|
||||
cleanups.push(() => inserted.remove());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return cleanups;
|
||||
}
|
||||
|
||||
export function applyModRecipe(
|
||||
input: StoredModRecipe,
|
||||
documentRef: Document = document,
|
||||
): Cleanup {
|
||||
const [recipe] = validateStoredRecipes([input]);
|
||||
let root: HTMLElement | null = null;
|
||||
try {
|
||||
root = documentRef.querySelector<HTMLElement>(recipe.rootSelector);
|
||||
} catch {
|
||||
return () => {};
|
||||
}
|
||||
if (!root) return () => {};
|
||||
|
||||
const cleanups = recipe.operations.flatMap((operation) =>
|
||||
applyOperation(root!, operation, recipe.id),
|
||||
);
|
||||
return () => {
|
||||
for (const cleanup of [...cleanups].reverse()) cleanup();
|
||||
};
|
||||
}
|
||||
|
||||
export class ModRuntime {
|
||||
private recipes: StoredModRecipe[] = [];
|
||||
private cleanups: Cleanup[] = [];
|
||||
private observer: MutationObserver | null = null;
|
||||
private reconcileTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private running = false;
|
||||
|
||||
constructor(
|
||||
private readonly documentRef: Document = document,
|
||||
private readonly getRoute: () => string = () => {
|
||||
const route = window.location.hash.split("?page=/")[1] ?? "";
|
||||
return route.split(/[/?#]/)[0];
|
||||
},
|
||||
) {}
|
||||
|
||||
start(): void {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.observer = new MutationObserver(() => this.scheduleReconcile());
|
||||
this.observe();
|
||||
window.addEventListener("hashchange", this.handleRouteChange);
|
||||
this.reconcile();
|
||||
}
|
||||
|
||||
setRecipes(input: StoredModRecipe | StoredModRecipe[]): void {
|
||||
this.recipes = validateStoredRecipes(
|
||||
Array.isArray(input) ? input : [input],
|
||||
);
|
||||
if (this.running) this.reconcile();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.running = false;
|
||||
if (this.reconcileTimer) clearTimeout(this.reconcileTimer);
|
||||
this.reconcileTimer = null;
|
||||
this.observer?.disconnect();
|
||||
this.observer = null;
|
||||
window.removeEventListener("hashchange", this.handleRouteChange);
|
||||
this.clearAppliedMods();
|
||||
}
|
||||
|
||||
private readonly handleRouteChange = () => this.scheduleReconcile();
|
||||
|
||||
private observe(): void {
|
||||
if (!this.observer || !this.documentRef.body) return;
|
||||
this.observer.observe(this.documentRef.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleReconcile(): void {
|
||||
if (!this.running || this.reconcileTimer) return;
|
||||
this.reconcileTimer = setTimeout(() => {
|
||||
this.reconcileTimer = null;
|
||||
this.reconcile();
|
||||
}, 40);
|
||||
}
|
||||
|
||||
private clearAppliedMods(): void {
|
||||
for (const cleanup of [...this.cleanups].reverse()) cleanup();
|
||||
this.cleanups = [];
|
||||
}
|
||||
|
||||
private reconcile(): void {
|
||||
if (!this.running) return;
|
||||
this.observer?.disconnect();
|
||||
this.clearAppliedMods();
|
||||
const route = this.getRoute();
|
||||
this.cleanups = this.recipes
|
||||
.filter((recipe) => recipe.enabled && recipe.route === route)
|
||||
.map((recipe) => applyModRecipe(recipe, this.documentRef));
|
||||
this.observe();
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
import {
|
||||
applyModStyleProperty,
|
||||
restoreModStyleProperty,
|
||||
stripStyleImportantSuffix,
|
||||
} from "./modStyle";
|
||||
|
||||
describe("modStyle", () => {
|
||||
it("strips trailing !important from values", () => {
|
||||
expect(stripStyleImportantSuffix("100% !important")).toBe("100%");
|
||||
expect(stripStyleImportantSuffix("100% !IMPORTANT")).toBe("100%");
|
||||
});
|
||||
|
||||
it("applies styles with important priority by default", () => {
|
||||
const element = document.createElement("div");
|
||||
const snapshot = applyModStyleProperty(element, "max-width", "100%");
|
||||
expect(element.style.getPropertyValue("max-width")).toBe("100%");
|
||||
expect(element.style.getPropertyPriority("max-width")).toBe("important");
|
||||
restoreModStyleProperty(element, "max-width", snapshot);
|
||||
expect(element.style.getPropertyValue("max-width")).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
/** Apply mod styles with priority over BetterSEQTA page CSS. */
|
||||
export function stripStyleImportantSuffix(value: string): string {
|
||||
return value.replace(/\s*!important\s*$/i, "").trim();
|
||||
}
|
||||
|
||||
export interface ModStyleSnapshot {
|
||||
previous: string;
|
||||
priority: string;
|
||||
}
|
||||
|
||||
export function applyModStyleProperty(
|
||||
element: HTMLElement,
|
||||
property: string,
|
||||
value: string,
|
||||
important = true,
|
||||
): ModStyleSnapshot {
|
||||
const previous = element.style.getPropertyValue(property);
|
||||
const priority = element.style.getPropertyPriority(property);
|
||||
element.style.setProperty(
|
||||
property,
|
||||
stripStyleImportantSuffix(value),
|
||||
important ? "important" : "",
|
||||
);
|
||||
return { previous, priority };
|
||||
}
|
||||
|
||||
export function restoreModStyleProperty(
|
||||
element: HTMLElement,
|
||||
property: string,
|
||||
snapshot: ModStyleSnapshot,
|
||||
): void {
|
||||
if (snapshot.previous) {
|
||||
element.style.setProperty(property, snapshot.previous, snapshot.priority);
|
||||
} else {
|
||||
element.style.removeProperty(property);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
export const DEFAULT_OPENROUTER_MODEL_ID = "minimax/minimax-m2.7:free";
|
||||
|
||||
export interface AiModModelOption {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
tier: "free" | "paid";
|
||||
}
|
||||
|
||||
export const AI_MOD_MODEL_OPTIONS: readonly AiModModelOption[] = [
|
||||
{
|
||||
id: "minimax/minimax-m2.7:free",
|
||||
label: "MiniMax M2.7 (free)",
|
||||
description:
|
||||
"Best free option for agentic DOM mods. Separate provider rate limits apply.",
|
||||
tier: "free",
|
||||
},
|
||||
{
|
||||
id: "minimax/minimax-m3:free",
|
||||
label: "MiniMax M3 (free)",
|
||||
description: "Alternate free MiniMax with GMICloud rate limits.",
|
||||
tier: "free",
|
||||
},
|
||||
{
|
||||
id: "google/gemma-3-27b-it:free",
|
||||
label: "Gemma 3 27B (free)",
|
||||
description: "Free Google model; useful when MiniMax free tiers are busy.",
|
||||
tier: "free",
|
||||
},
|
||||
{
|
||||
id: "meta-llama/llama-3.3-70b-instruct:free",
|
||||
label: "Llama 3.3 70B (free)",
|
||||
description: "Free Meta model with broader availability.",
|
||||
tier: "free",
|
||||
},
|
||||
{
|
||||
id: "minimax/minimax-m3",
|
||||
label: "MiniMax M3 (paid)",
|
||||
description: "Paid tier with much higher rate limits.",
|
||||
tier: "paid",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const ALLOWED_OPENROUTER_MODEL_IDS = new Set(
|
||||
AI_MOD_MODEL_OPTIONS.map((option) => option.id),
|
||||
);
|
||||
|
||||
export function validateModelId(value: unknown): string {
|
||||
if (typeof value !== "string") {
|
||||
throw new Error("Model id is required");
|
||||
}
|
||||
const modelId = value.trim();
|
||||
if (!ALLOWED_OPENROUTER_MODEL_IDS.has(modelId)) {
|
||||
throw new Error("Unsupported OpenRouter model");
|
||||
}
|
||||
return modelId;
|
||||
}
|
||||
|
||||
export function getModelOption(modelId: string): AiModModelOption | undefined {
|
||||
return AI_MOD_MODEL_OPTIONS.find((option) => option.id === modelId);
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
import { buildSelectedElementContext } from "./pageContext";
|
||||
|
||||
describe("selected element context", () => {
|
||||
it("sends only the selected subtree and redacts active content and values", () => {
|
||||
document.body.innerHTML = `
|
||||
<div id="outside">Never include me</div>
|
||||
<section id="selected" onclick="steal()" data-session="secret">
|
||||
<input value="student@example.test" placeholder="Email">
|
||||
<a href="https://example.test/token?secret=1">Assessment details</a>
|
||||
<script>window.secret = "bad"</script>
|
||||
<p>Selected text</p>
|
||||
</section>
|
||||
`;
|
||||
const selected = document.querySelector<HTMLElement>("#selected")!;
|
||||
|
||||
const context = buildSelectedElementContext(selected, {
|
||||
route: "assessments",
|
||||
rootSelector: "#selected",
|
||||
request: "Make this clearer",
|
||||
userContext: "This is an assessment card.",
|
||||
});
|
||||
|
||||
expect(context.selectedHtml).toContain("Selected text");
|
||||
expect(context.selectedHtml).not.toContain("Never include me");
|
||||
expect(context.selectedHtml).not.toContain("student@example.test");
|
||||
expect(context.selectedHtml).not.toContain("onclick");
|
||||
expect(context.selectedHtml).not.toContain("data-session");
|
||||
expect(context.selectedHtml).not.toContain("<script");
|
||||
expect(context.selectedHtml).not.toContain("secret=1");
|
||||
expect(context.domCatalog.length).toBeGreaterThan(0);
|
||||
expect(context.domCatalog[0]).toMatchObject({
|
||||
selector: ":scope",
|
||||
tag: "section",
|
||||
});
|
||||
expect(context).toMatchObject({
|
||||
route: "assessments",
|
||||
rootSelector: "#selected",
|
||||
request: "Make this clearer",
|
||||
userContext: "This is an assessment card.",
|
||||
tagName: "section",
|
||||
});
|
||||
});
|
||||
|
||||
it("includes parent context and a layout catalog for nested structures", () => {
|
||||
document.body.innerHTML = `
|
||||
<div class="titlebar">
|
||||
<div class="userInfo">
|
||||
<div class="userInfoText" style="display: flex; flex-direction: column; align-items: flex-end;">
|
||||
<div style="display: flex; align-items: center;">
|
||||
<p class="userInfohouse userInfoCode">Y11HA</p>
|
||||
<p class="userInfoName">Jaxon Lewis-Wilson</p>
|
||||
</div>
|
||||
<p class="userInfoCode">15845 // 33804833</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
const selected = document.querySelector<HTMLElement>(".userInfoText")!;
|
||||
|
||||
const context = buildSelectedElementContext(selected, {
|
||||
route: "welcome",
|
||||
rootSelector: ".userInfoText",
|
||||
request: "Move house next to ID",
|
||||
userContext: "",
|
||||
});
|
||||
|
||||
expect(context.ancestorHtml).toContain("userInfo");
|
||||
expect(context.selectedHtml).toContain('display: flex');
|
||||
expect(context.domCatalog).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
tag: "p",
|
||||
classes: ["userInfoCode"],
|
||||
directText: "15845 // 33804833",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
tag: "p",
|
||||
classes: expect.arrayContaining(["userInfohouse", "userInfoCode"]),
|
||||
directText: "Y11HA",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
context.domCatalog.find((entry) => entry.selector === ":scope")?.layout,
|
||||
).toMatchObject({
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "flex-end",
|
||||
});
|
||||
});
|
||||
|
||||
it("caps all user-controlled fields", () => {
|
||||
const selected = document.createElement("div");
|
||||
selected.textContent = "x".repeat(30_000);
|
||||
document.body.appendChild(selected);
|
||||
|
||||
const context = buildSelectedElementContext(selected, {
|
||||
route: "r".repeat(2_000),
|
||||
rootSelector: "#selected",
|
||||
request: "q".repeat(5_000),
|
||||
userContext: "c".repeat(8_000),
|
||||
});
|
||||
|
||||
expect(context.selectedHtml.length).toBeLessThanOrEqual(24_000);
|
||||
expect(context.route.length).toBeLessThanOrEqual(256);
|
||||
expect(context.request.length).toBeLessThanOrEqual(2_000);
|
||||
expect(context.userContext.length).toBeLessThanOrEqual(4_000);
|
||||
expect(context.domCatalog.length).toBeLessThanOrEqual(100);
|
||||
});
|
||||
|
||||
it("captures only a small allowlisted computed-style summary", () => {
|
||||
const selected = document.createElement("div");
|
||||
selected.style.color = "rgb(1, 2, 3)";
|
||||
selected.style.backgroundColor = "rgb(4, 5, 6)";
|
||||
selected.style.backgroundImage = "url(https://example.test/pixel)";
|
||||
document.body.appendChild(selected);
|
||||
|
||||
const context = buildSelectedElementContext(selected, {
|
||||
route: "",
|
||||
rootSelector: "div",
|
||||
request: "Restyle",
|
||||
userContext: "",
|
||||
});
|
||||
|
||||
expect(context.computedStyle).toMatchObject({
|
||||
color: "rgb(1, 2, 3)",
|
||||
backgroundColor: "rgb(4, 5, 6)",
|
||||
});
|
||||
expect(context.computedStyle).not.toHaveProperty("backgroundImage");
|
||||
});
|
||||
|
||||
it("includes parent chain summaries for placement context", () => {
|
||||
document.body.innerHTML = `
|
||||
<div class="titlebar" style="display: flex; align-items: center;">
|
||||
<div class="userInfo" style="display: flex;">
|
||||
<div class="userInfoText" style="display: flex; flex-direction: column;">
|
||||
<p class="userInfoCode">15845</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
const selected = document.querySelector<HTMLElement>(".userInfoText")!;
|
||||
|
||||
const context = buildSelectedElementContext(selected, {
|
||||
route: "welcome",
|
||||
rootSelector: ".userInfoText",
|
||||
request: "Reorder items",
|
||||
userContext: "",
|
||||
});
|
||||
|
||||
expect(context.parentChain).toEqual([
|
||||
expect.objectContaining({
|
||||
tag: "div",
|
||||
classes: ["userInfo"],
|
||||
layout: expect.objectContaining({ display: "flex" }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
tag: "div",
|
||||
classes: ["titlebar"],
|
||||
layout: expect.objectContaining({
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(context.structuralHints).toMatchObject({
|
||||
hasTable: false,
|
||||
hasList: false,
|
||||
primaryClasses: ["userInfoText"],
|
||||
});
|
||||
});
|
||||
|
||||
it("includes table and list structure counts in root catalog and hints", () => {
|
||||
document.body.innerHTML = `
|
||||
<table class="assessmentTable">
|
||||
<tr><th>Name</th><th>Grade</th><th>Due</th></tr>
|
||||
<tr><td>Essay</td><td>A</td><td>Mon</td></tr>
|
||||
<tr><td>Quiz</td><td>B</td><td>Tue</td></tr>
|
||||
</table>
|
||||
`;
|
||||
const table = document.querySelector<HTMLElement>(".assessmentTable")!;
|
||||
|
||||
const tableContext = buildSelectedElementContext(table, {
|
||||
route: "assessments",
|
||||
rootSelector: ".assessmentTable",
|
||||
request: "Highlight header row",
|
||||
userContext: "",
|
||||
});
|
||||
|
||||
expect(
|
||||
tableContext.domCatalog.find((entry) => entry.selector === ":scope"),
|
||||
).toMatchObject({
|
||||
rowCount: 3,
|
||||
columnCount: 3,
|
||||
});
|
||||
expect(tableContext.structuralHints).toMatchObject({
|
||||
hasTable: true,
|
||||
hasList: false,
|
||||
rowCount: 3,
|
||||
columnCount: 3,
|
||||
primaryClasses: ["assessmentTable"],
|
||||
});
|
||||
|
||||
document.body.innerHTML = `
|
||||
<ul class="taskList">
|
||||
<li>Task one</li>
|
||||
<li>Task two</li>
|
||||
<li>Task three</li>
|
||||
</ul>
|
||||
`;
|
||||
const list = document.querySelector<HTMLElement>(".taskList")!;
|
||||
|
||||
const listContext = buildSelectedElementContext(list, {
|
||||
route: "tasks",
|
||||
rootSelector: ".taskList",
|
||||
request: "Bold first item",
|
||||
userContext: "",
|
||||
});
|
||||
|
||||
expect(
|
||||
listContext.domCatalog.find((entry) => entry.selector === ":scope"),
|
||||
).toMatchObject({
|
||||
itemCount: 3,
|
||||
});
|
||||
expect(listContext.structuralHints).toMatchObject({
|
||||
hasTable: false,
|
||||
hasList: true,
|
||||
itemCount: 3,
|
||||
primaryClasses: ["taskList"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,291 +0,0 @@
|
||||
import { buildScopeRelativeSelector } from "./selection";
|
||||
import type {
|
||||
DomElementSummary,
|
||||
ParentChainSummary,
|
||||
SelectedElementContext,
|
||||
StructuralHints,
|
||||
} from "./types";
|
||||
|
||||
const HTML_LIMIT = 24_000;
|
||||
const ANCESTOR_HTML_LIMIT = 6_000;
|
||||
const REQUEST_LIMIT = 2_000;
|
||||
const USER_CONTEXT_LIMIT = 4_000;
|
||||
const ROUTE_LIMIT = 256;
|
||||
const DOM_CATALOG_LIMIT = 100;
|
||||
const DIRECT_TEXT_LIMIT = 120;
|
||||
const PARENT_CHAIN_LIMIT = 3;
|
||||
const CLASS_LIMIT = 8;
|
||||
|
||||
const COMPUTED_STYLE_PROPERTIES = [
|
||||
["color", "color"],
|
||||
["backgroundColor", "background-color"],
|
||||
["display", "display"],
|
||||
["flexDirection", "flex-direction"],
|
||||
["alignItems", "align-items"],
|
||||
["justifyContent", "justify-content"],
|
||||
["gap", "gap"],
|
||||
["flexWrap", "flex-wrap"],
|
||||
["fontSize", "font-size"],
|
||||
["fontWeight", "font-weight"],
|
||||
["padding", "padding"],
|
||||
["margin", "margin"],
|
||||
["border", "border"],
|
||||
["borderRadius", "border-radius"],
|
||||
["width", "width"],
|
||||
["height", "height"],
|
||||
["textAlign", "text-align"],
|
||||
["opacity", "opacity"],
|
||||
] as const;
|
||||
|
||||
const ALLOWED_INLINE_STYLE =
|
||||
/^(display|flex|align-items|justify-content|gap|flex-direction|flex-wrap|text-align|padding|margin|border-radius|opacity|font-size|font-weight|width|height|background-color|color)$/i;
|
||||
|
||||
function cap(value: string, maxLength: number): string {
|
||||
return value.trim().slice(0, maxLength);
|
||||
}
|
||||
|
||||
function sanitizeInlineStyle(value: string): string {
|
||||
return value
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => {
|
||||
if (!part.includes(":")) return false;
|
||||
const name = part.split(":")[0]?.trim() ?? "";
|
||||
return (
|
||||
ALLOWED_INLINE_STYLE.test(name) &&
|
||||
!/url\s*\(|expression\s*\(|javascript\s*:/i.test(part)
|
||||
);
|
||||
})
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
function sanitizeClone(element: HTMLElement): HTMLElement {
|
||||
const clone = element.cloneNode(true) as HTMLElement;
|
||||
clone
|
||||
.querySelectorAll(
|
||||
"script,style,noscript,iframe,object,embed,link,meta,template",
|
||||
)
|
||||
.forEach((node) => node.remove());
|
||||
|
||||
const nodes = [clone, ...clone.querySelectorAll<HTMLElement>("*")];
|
||||
for (const node of nodes) {
|
||||
for (const attribute of [...node.attributes]) {
|
||||
const name = attribute.name.toLowerCase();
|
||||
if (
|
||||
name.startsWith("on") ||
|
||||
name.startsWith("data-") ||
|
||||
[
|
||||
"action",
|
||||
"checked",
|
||||
"formaction",
|
||||
"href",
|
||||
"selected",
|
||||
"src",
|
||||
"srcset",
|
||||
"value",
|
||||
].includes(name)
|
||||
) {
|
||||
node.removeAttribute(attribute.name);
|
||||
continue;
|
||||
}
|
||||
if (name === "style") {
|
||||
const sanitizedStyle = sanitizeInlineStyle(attribute.value);
|
||||
if (sanitizedStyle) node.setAttribute("style", sanitizedStyle);
|
||||
else node.removeAttribute("style");
|
||||
}
|
||||
}
|
||||
}
|
||||
return clone;
|
||||
}
|
||||
|
||||
function computedStyleSummary(element: HTMLElement): Record<string, string> {
|
||||
const style = getComputedStyle(element);
|
||||
return Object.fromEntries(
|
||||
COMPUTED_STYLE_PROPERTIES.map(([outputName, cssName]) => [
|
||||
outputName,
|
||||
style.getPropertyValue(cssName) ||
|
||||
(style as unknown as Record<string, string>)[outputName] ||
|
||||
"",
|
||||
]).filter(([, value]) => value.length > 0),
|
||||
);
|
||||
}
|
||||
|
||||
function directText(element: HTMLElement): string | undefined {
|
||||
const chunks: string[] = [];
|
||||
for (const node of element.childNodes) {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
const text = node.textContent?.replace(/\s+/g, " ").trim() ?? "";
|
||||
if (text) chunks.push(text);
|
||||
}
|
||||
}
|
||||
if (chunks.length === 0) return undefined;
|
||||
return cap(chunks.join(" "), DIRECT_TEXT_LIMIT);
|
||||
}
|
||||
|
||||
function classSummary(element: HTMLElement): string[] {
|
||||
return [...element.classList].slice(0, CLASS_LIMIT);
|
||||
}
|
||||
|
||||
function findTable(element: HTMLElement): HTMLTableElement | null {
|
||||
if (element instanceof HTMLTableElement) return element;
|
||||
return element.querySelector("table");
|
||||
}
|
||||
|
||||
function findList(element: HTMLElement): HTMLUListElement | HTMLOListElement | null {
|
||||
if (element instanceof HTMLUListElement || element instanceof HTMLOListElement) {
|
||||
return element;
|
||||
}
|
||||
return element.querySelector("ul, ol");
|
||||
}
|
||||
|
||||
function tableMetrics(
|
||||
element: HTMLElement,
|
||||
): { rowCount: number; columnCount: number } | null {
|
||||
const table = findTable(element);
|
||||
if (!table) return null;
|
||||
|
||||
const rows = [...table.querySelectorAll("tr")];
|
||||
const columnCount = rows.reduce((max, row) => {
|
||||
const cells = row.querySelectorAll("td, th").length;
|
||||
return Math.max(max, cells);
|
||||
}, 0);
|
||||
|
||||
return { rowCount: rows.length, columnCount };
|
||||
}
|
||||
|
||||
function listMetrics(element: HTMLElement): { itemCount: number } | null {
|
||||
const list = findList(element);
|
||||
if (!list) return null;
|
||||
return { itemCount: list.querySelectorAll(":scope > li").length };
|
||||
}
|
||||
|
||||
function buildStructuralHints(element: HTMLElement): StructuralHints {
|
||||
const table = tableMetrics(element);
|
||||
const list = listMetrics(element);
|
||||
|
||||
return {
|
||||
hasTable: table !== null,
|
||||
hasList: list !== null,
|
||||
...(table ? table : {}),
|
||||
...(list ? list : {}),
|
||||
primaryClasses: classSummary(element),
|
||||
};
|
||||
}
|
||||
|
||||
function buildParentChain(element: HTMLElement): ParentChainSummary[] {
|
||||
const chain: ParentChainSummary[] = [];
|
||||
let current = element.parentElement;
|
||||
|
||||
while (
|
||||
current &&
|
||||
current !== document.body &&
|
||||
current !== document.documentElement &&
|
||||
chain.length < PARENT_CHAIN_LIMIT
|
||||
) {
|
||||
chain.push({
|
||||
tag: current.tagName.toLowerCase(),
|
||||
classes: classSummary(current),
|
||||
layout: computedStyleSummary(current),
|
||||
});
|
||||
current = current.parentElement;
|
||||
}
|
||||
|
||||
return chain;
|
||||
}
|
||||
|
||||
function rootStructureSummary(
|
||||
root: HTMLElement,
|
||||
): Pick<DomElementSummary, "rowCount" | "columnCount" | "itemCount"> {
|
||||
const table = tableMetrics(root);
|
||||
const list = listMetrics(root);
|
||||
return {
|
||||
...(table ?? {}),
|
||||
...(list ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildDomCatalog(root: HTMLElement): DomElementSummary[] {
|
||||
const nodes = [root, ...root.querySelectorAll<HTMLElement>("*")].slice(
|
||||
0,
|
||||
DOM_CATALOG_LIMIT,
|
||||
);
|
||||
|
||||
return nodes.map((node) => {
|
||||
const parent = node.parentElement;
|
||||
const parentSelector =
|
||||
parent && root.contains(parent)
|
||||
? buildScopeRelativeSelector(root, parent)
|
||||
: node === root
|
||||
? null
|
||||
: ":scope";
|
||||
const siblings = parent
|
||||
? [...parent.children].filter((child) => child instanceof HTMLElement)
|
||||
: [root];
|
||||
|
||||
const summary: DomElementSummary = {
|
||||
selector: buildScopeRelativeSelector(root, node),
|
||||
tag: node.tagName.toLowerCase(),
|
||||
classes: classSummary(node),
|
||||
...(directText(node) ? { directText: directText(node) } : {}),
|
||||
parentSelector,
|
||||
siblingIndex: siblings.indexOf(node),
|
||||
siblingCount: siblings.length,
|
||||
layout: computedStyleSummary(node),
|
||||
};
|
||||
|
||||
if (node === root) {
|
||||
Object.assign(summary, rootStructureSummary(root));
|
||||
}
|
||||
|
||||
return summary;
|
||||
});
|
||||
}
|
||||
|
||||
function buildAncestorContext(root: HTMLElement): { ancestorHtml?: string } {
|
||||
const parent = root.parentElement;
|
||||
if (
|
||||
!parent ||
|
||||
parent === document.body ||
|
||||
parent === document.documentElement
|
||||
) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
ancestorHtml: sanitizeClone(parent).outerHTML.slice(0, ANCESTOR_HTML_LIMIT),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSelectedElementContext(
|
||||
element: HTMLElement,
|
||||
input: {
|
||||
route: string;
|
||||
rootSelector: string;
|
||||
request: string;
|
||||
userContext: string;
|
||||
},
|
||||
): SelectedElementContext {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const sanitized = sanitizeClone(element);
|
||||
const ancestor = buildAncestorContext(element);
|
||||
const parentChain = buildParentChain(element);
|
||||
const structuralHints = buildStructuralHints(element);
|
||||
|
||||
return {
|
||||
route: cap(input.route, ROUTE_LIMIT),
|
||||
rootSelector: cap(input.rootSelector, 1_000),
|
||||
request: cap(input.request, REQUEST_LIMIT),
|
||||
userContext: cap(input.userContext, USER_CONTEXT_LIMIT),
|
||||
selectedHtml: sanitized.outerHTML.slice(0, HTML_LIMIT),
|
||||
domCatalog: buildDomCatalog(element),
|
||||
...(ancestor.ancestorHtml ? { ancestorHtml: ancestor.ancestorHtml } : {}),
|
||||
...(parentChain.length > 0 ? { parentChain } : {}),
|
||||
structuralHints,
|
||||
tagName: element.tagName.toLowerCase(),
|
||||
dimensions: {
|
||||
width: Math.round(rect.width),
|
||||
height: Math.round(rect.height),
|
||||
},
|
||||
computedStyle: computedStyleSummary(element),
|
||||
};
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
import {
|
||||
SAFE_ATTRIBUTE_NAMES,
|
||||
SAFE_INSERT_POSITIONS,
|
||||
SAFE_INSERT_TAGS,
|
||||
SAFE_STYLE_PROPERTIES,
|
||||
} from "./recipeSchema";
|
||||
import type { SelectedElementContext } from "./types";
|
||||
|
||||
const operationSchemas = [
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector", "text"],
|
||||
properties: {
|
||||
type: { const: "setText" },
|
||||
selector: { type: "string" },
|
||||
text: { type: "string" },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector", "search", "replacement"],
|
||||
properties: {
|
||||
type: { const: "replaceText" },
|
||||
selector: { type: "string" },
|
||||
search: { type: "string" },
|
||||
replacement: { type: "string" },
|
||||
all: { type: "boolean" },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector", "name", "value"],
|
||||
properties: {
|
||||
type: { const: "setAttribute" },
|
||||
selector: { type: "string" },
|
||||
name: { type: "string", enum: SAFE_ATTRIBUTE_NAMES },
|
||||
value: { type: "string" },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector", "property", "value"],
|
||||
properties: {
|
||||
type: { const: "setStyle" },
|
||||
selector: { type: "string" },
|
||||
property: { type: "string", enum: SAFE_STYLE_PROPERTIES },
|
||||
value: { type: "string" },
|
||||
},
|
||||
},
|
||||
...(["addClass", "removeClass"] as const).map((type) => ({
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector", "className"],
|
||||
properties: {
|
||||
type: { const: type },
|
||||
selector: { type: "string" },
|
||||
className: { type: "string" },
|
||||
},
|
||||
})),
|
||||
...(["hide", "show"] as const).map((type) => ({
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector"],
|
||||
properties: {
|
||||
type: { const: type },
|
||||
selector: { type: "string" },
|
||||
},
|
||||
})),
|
||||
{
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["type", "selector", "position", "tag", "text"],
|
||||
properties: {
|
||||
type: { const: "insertText" },
|
||||
selector: { type: "string" },
|
||||
position: { type: "string", enum: SAFE_INSERT_POSITIONS },
|
||||
tag: { type: "string", enum: SAFE_INSERT_TAGS },
|
||||
text: { type: "string" },
|
||||
className: { type: "string" },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const AI_MOD_RESPONSE_JSON_SCHEMA = {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["name", "description", "operations"],
|
||||
properties: {
|
||||
name: { type: "string", minLength: 1, maxLength: 120 },
|
||||
description: { type: "string", maxLength: 500 },
|
||||
operations: {
|
||||
type: "array",
|
||||
minItems: 0,
|
||||
maxItems: 30,
|
||||
items: { oneOf: operationSchemas },
|
||||
},
|
||||
advancedScript: {
|
||||
type: "string",
|
||||
minLength: 1,
|
||||
maxLength: 20_000,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function buildAiModMessages(context: SelectedElementContext) {
|
||||
const allowedStyleProperties = SAFE_STYLE_PROPERTIES.join(", ");
|
||||
|
||||
return [
|
||||
{
|
||||
role: "system",
|
||||
content: `You create advanced BetterSEQTA+ DOM mods.
|
||||
Return only a valid JSON object with keys: name, description, operations, and optionally advancedScript.
|
||||
Each operation must be an object with a string "type" field and a "selector" field.
|
||||
Supported type values: setText, replaceText, setAttribute, setStyle, addClass, removeClass, hide, show, insertText.
|
||||
operations may be an empty array when advancedScript alone implements the requested change.
|
||||
|
||||
setStyle rules:
|
||||
- Use kebab-case property names only (e.g. "flex-wrap", not "flexWrap").
|
||||
- Allowed properties: ${allowedStyleProperties}
|
||||
- Do not use background-image, transform, animation, or any property not in the allowed list.
|
||||
- setStyle operations automatically override BetterSEQTA page CSS (including rules with !important). Target constraining ancestors, not only leaf nodes — e.g. for full-width news cards set max-width, width, margin, and padding on :scope > div.home-container (BS+ caps it at 1050px), not only on .NewsArticle children.
|
||||
|
||||
Example (full-width layout — override BS+ container cap):
|
||||
{"name":"Full-width news","description":"Expands home container to viewport width","operations":[{"type":"setStyle","selector":":scope > div.home-container","property":"max-width","value":"100%"},{"type":"setStyle","selector":":scope > div.home-container","property":"width","value":"100%"},{"type":"setStyle","selector":":scope > div.home-container","property":"margin-left","value":"0"},{"type":"setStyle","selector":":scope > div.home-container","property":"margin-right","value":"0"}]}
|
||||
|
||||
Example (simple style):
|
||||
{"name":"Rounded card","description":"Adds rounded corners","operations":[{"type":"setStyle","selector":":scope","property":"border-radius","value":"12px"}]}
|
||||
|
||||
Example (flex row layout):
|
||||
{"name":"Flex toolbar","description":"Lays out children in a horizontal row","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"flex"},{"type":"setStyle","selector":":scope","property":"align-items","value":"center"},{"type":"setStyle","selector":":scope","property":"gap","value":"8px"},{"type":"setStyle","selector":":scope","property":"flex-wrap","value":"wrap"}]}
|
||||
|
||||
Example (CSS grid layout):
|
||||
{"name":"Grid cards","description":"Displays children in a responsive grid","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"grid"},{"type":"setStyle","selector":":scope","property":"grid-template-columns","value":"repeat(auto-fill, minmax(200px, 1fr))"},{"type":"setStyle","selector":":scope","property":"gap","value":"12px"}]}
|
||||
|
||||
Example (table to grid — convert a table container to grid while keeping child cells):
|
||||
{"name":"Table as grid","description":"Replaces table layout with CSS grid on the wrapper","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"grid"},{"type":"setStyle","selector":":scope","property":"grid-template-columns","value":"repeat(3, 1fr)"},{"type":"setStyle","selector":":scope","property":"gap","value":"8px"},{"type":"setStyle","selector":":scope tr","property":"display","value":"contents"},{"type":"setStyle","selector":":scope td, :scope th","property":"display","value":"block"}]}
|
||||
For table-to-grid mods, target the table or tbody with display:grid and use display:contents on tr rows so td/th become direct grid items. Use advancedScript when row/column reordering or cell merging is required.
|
||||
|
||||
Advanced-only example:
|
||||
{"name":"Reorder header","description":"Moves child nodes","operations":[],"advancedScript":"return () => {};"}
|
||||
Every selector must be ":scope" or begin with ":scope " / ":scope>" so it stays inside the user's selected root.
|
||||
Use domCatalog for exact relative selectors, sibling order, and computed layout on each node.
|
||||
Use parentChain to understand how the selected root is nested inside parent containers.
|
||||
Use structuralHints (hasTable, rowCount, columnCount, hasList, itemCount, primaryClasses) for table/list/grid transforms.
|
||||
Use ancestorHtml to see how the selected root sits inside its parent container.
|
||||
Use selectedHtml for full subtree markup including preserved inline layout styles.
|
||||
Select the smallest page area that actually contains the elements you need to change. Do not select BetterSEQTA+ overlay UI; select the underlying SEQTA content instead.
|
||||
When moving elements, preserve BetterSEQTA+ styling: prefer flex rows with align-items:center, gap, inline-block badges, var(--text-primary), var(--auto-background), and transparent/theme borders over solid black boxes.
|
||||
If required elements are missing inside root, throw an Error explaining which selector failed.
|
||||
Use operations for simple reversible changes and advancedScript for richer JavaScript behavior.
|
||||
advancedScript runs with root, bsplus, and shorthand helpers select(selector) / selectAll(selector) in scope.
|
||||
The helper library provides select(selector), selectAll(selector), setText(element,text), setStyle(element,property,value), setAttribute(element,name,value), create(tag,text,parent), on(element,event,handler), observe(element,callback,options), and onCleanup(callback).
|
||||
You may call select() directly or use bsplus.select().
|
||||
The advancedScript body must return a cleanup function and should use bsplus helpers so disabling the mod restores the page.
|
||||
Never use network APIs, extension APIs, browser storage, cookies, navigation, raw HTML markup, eval, dynamic imports, workers, programmatic clicks/submits, src/href assignments, or unbounded loops.
|
||||
You may clear a container with element.innerHTML = '' before moving existing nodes, but never assign HTML strings or use outerHTML/insertAdjacentHTML.
|
||||
Prefer appendChild, insertBefore, replaceChildren, cloneNode, remove, and textContent for DOM changes.
|
||||
Direct DOM APIs are allowed for advanced layout and interaction work, but keep every change within root and register cleanup.
|
||||
Prefer the smallest set of reversible operations. Do not invent page content that is not requested.
|
||||
For insertText, "before" and "after" may only target descendants, not :scope itself.`,
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: `Create a mod for this explicitly selected page area:\n${JSON.stringify(
|
||||
context,
|
||||
null,
|
||||
2,
|
||||
)}`,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
@@ -1,267 +0,0 @@
|
||||
import {
|
||||
createStoredRecipe,
|
||||
extractJsonFromModelText,
|
||||
normalizeStyleProperty,
|
||||
parseGeneratedModDraft,
|
||||
parseStoredRecipes,
|
||||
} from "./recipeSchema";
|
||||
|
||||
describe("AI mod recipe validation", () => {
|
||||
const validDraft = {
|
||||
name: "Calmer assessment card",
|
||||
description: "Makes the selected card easier to scan.",
|
||||
operations: [
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "border-radius",
|
||||
value: "16px",
|
||||
},
|
||||
{
|
||||
type: "setText",
|
||||
selector: ":scope .title",
|
||||
text: "Upcoming assessment",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("accepts a safe generated draft and creates a stored recipe", () => {
|
||||
const draft = parseGeneratedModDraft(JSON.stringify(validDraft));
|
||||
const recipe = createStoredRecipe(draft, {
|
||||
rootSelector: "#assessment-42",
|
||||
route: "assessments",
|
||||
now: 1_700_000_000_000,
|
||||
id: "mod-1",
|
||||
});
|
||||
|
||||
expect(recipe).toMatchObject({
|
||||
schemaVersion: 1,
|
||||
id: "mod-1",
|
||||
enabled: false,
|
||||
rootSelector: "#assessment-42",
|
||||
route: "assessments",
|
||||
name: validDraft.name,
|
||||
createdAt: 1_700_000_000_000,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "script-like attribute",
|
||||
operation: {
|
||||
type: "setAttribute",
|
||||
selector: ":scope",
|
||||
name: "onclick",
|
||||
value: "alert(1)",
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "network-capable CSS",
|
||||
operation: {
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "background-image",
|
||||
value: "url(https://attacker.invalid/pixel)",
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "selector escaping the selected root",
|
||||
operation: {
|
||||
type: "hide",
|
||||
selector: "body",
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "raw executable operation",
|
||||
operation: {
|
||||
type: "javascript",
|
||||
code: "document.cookie",
|
||||
},
|
||||
},
|
||||
])("rejects $label", ({ operation }) => {
|
||||
expect(() =>
|
||||
parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
...validDraft,
|
||||
operations: [operation],
|
||||
}),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("extracts JSON from fenced model output", () => {
|
||||
const json = JSON.stringify(validDraft);
|
||||
expect(parseGeneratedModDraft(`\`\`\`json\n${json}\n\`\`\``)).toMatchObject({
|
||||
name: validDraft.name,
|
||||
});
|
||||
expect(extractJsonFromModelText(`Here is the mod:\n${json}`)).toBe(json);
|
||||
});
|
||||
|
||||
it("normalizes common model operation shapes", () => {
|
||||
expect(
|
||||
parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
name: "Aliased mod",
|
||||
description: "Uses alternate field names",
|
||||
operations: [
|
||||
{
|
||||
setStyle: {
|
||||
target: ":scope",
|
||||
styleProperty: "border-radius",
|
||||
styleValue: "12px",
|
||||
},
|
||||
},
|
||||
{
|
||||
action: "hide",
|
||||
element: ":scope .meta",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
name: "Aliased mod",
|
||||
operations: [
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "border-radius",
|
||||
value: "12px",
|
||||
},
|
||||
{ type: "hide", selector: ":scope .meta" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["flexWrap", "flex-wrap"],
|
||||
["alignItems", "align-items"],
|
||||
["gridTemplateColumns", "grid-template-columns"],
|
||||
["flexDirection", "flex-direction"],
|
||||
["overflowX", "overflow-x"],
|
||||
["zIndex", "z-index"],
|
||||
["whiteSpace", "white-space"],
|
||||
["border-radius", "border-radius"],
|
||||
])("normalizes style property %s to %s", (input, expected) => {
|
||||
expect(normalizeStyleProperty(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("accepts camelCase style properties from the model", () => {
|
||||
expect(
|
||||
parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
name: "Flex layout",
|
||||
description: "Uses camelCase property names",
|
||||
operations: [
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "flexWrap",
|
||||
value: "wrap",
|
||||
},
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "alignItems",
|
||||
value: "center",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
operations: [
|
||||
{ type: "setStyle", property: "flex-wrap", value: "wrap" },
|
||||
{ type: "setStyle", property: "align-items", value: "center" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts newly allowed layout style properties", () => {
|
||||
expect(
|
||||
parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
name: "Grid layout",
|
||||
description: "CSS grid on selected root",
|
||||
operations: [
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "display",
|
||||
value: "grid",
|
||||
},
|
||||
{
|
||||
type: "setStyle",
|
||||
selector: ":scope",
|
||||
property: "grid-template-columns",
|
||||
value: "repeat(3, 1fr)",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).operations,
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("accepts advancedScript-only mods with no declarative operations", () => {
|
||||
const draft = parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
name: "House next to ID",
|
||||
description: "Moves house info beside the user ID",
|
||||
operations: [],
|
||||
advancedScript:
|
||||
"const house = bsplus.select(':scope .userInfohouse'); return () => {};",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(draft.operations).toEqual([]);
|
||||
expect(draft.advancedScript).toContain("bsplus.select");
|
||||
});
|
||||
|
||||
it("rejects mods with neither operations nor advancedScript", () => {
|
||||
expect(() =>
|
||||
parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
name: "Empty mod",
|
||||
description: "Does nothing",
|
||||
operations: [],
|
||||
}),
|
||||
),
|
||||
).toThrow("at least one operation or an advancedScript");
|
||||
});
|
||||
|
||||
it("rejects oversized or non-JSON model output", () => {
|
||||
expect(() => parseGeneratedModDraft("not json")).toThrow();
|
||||
expect(() =>
|
||||
parseGeneratedModDraft(
|
||||
JSON.stringify({
|
||||
...validDraft,
|
||||
name: "x".repeat(121),
|
||||
}),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("validates every imported recipe before returning any", () => {
|
||||
const recipe = createStoredRecipe(
|
||||
parseGeneratedModDraft(JSON.stringify(validDraft)),
|
||||
{
|
||||
rootSelector: "#assessment-42",
|
||||
route: "assessments",
|
||||
now: 1,
|
||||
id: "mod-1",
|
||||
},
|
||||
);
|
||||
|
||||
expect(parseStoredRecipes(JSON.stringify([recipe]))).toEqual([recipe]);
|
||||
expect(() =>
|
||||
parseStoredRecipes(
|
||||
JSON.stringify([
|
||||
recipe,
|
||||
{
|
||||
...recipe,
|
||||
id: "bad",
|
||||
operations: [{ type: "hide", selector: "html" }],
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,666 +0,0 @@
|
||||
import {
|
||||
AI_MOD_SCHEMA_VERSION,
|
||||
type GeneratedModDraft,
|
||||
type ModOperation,
|
||||
type SafeAttributeName,
|
||||
type SafeStyleProperty,
|
||||
type StoredModRecipe,
|
||||
} from "./types";
|
||||
import { assertAdvancedScriptSafe } from "./scriptSafety";
|
||||
import { aiModLog } from "./logger";
|
||||
import { stripStyleImportantSuffix } from "./modStyle";
|
||||
|
||||
export const SAFE_STYLE_PROPERTIES: readonly SafeStyleProperty[] = [
|
||||
"align-items",
|
||||
"align-self",
|
||||
"aspect-ratio",
|
||||
"background",
|
||||
"background-color",
|
||||
"border",
|
||||
"border-color",
|
||||
"border-radius",
|
||||
"border-style",
|
||||
"border-width",
|
||||
"bottom",
|
||||
"box-shadow",
|
||||
"color",
|
||||
"cursor",
|
||||
"display",
|
||||
"flex",
|
||||
"flex-direction",
|
||||
"flex-grow",
|
||||
"flex-shrink",
|
||||
"flex-wrap",
|
||||
"font-size",
|
||||
"font-weight",
|
||||
"gap",
|
||||
"grid-template-columns",
|
||||
"height",
|
||||
"justify-content",
|
||||
"left",
|
||||
"letter-spacing",
|
||||
"line-height",
|
||||
"margin",
|
||||
"margin-bottom",
|
||||
"margin-left",
|
||||
"margin-right",
|
||||
"margin-top",
|
||||
"max-height",
|
||||
"max-width",
|
||||
"min-height",
|
||||
"min-width",
|
||||
"object-fit",
|
||||
"opacity",
|
||||
"order",
|
||||
"overflow",
|
||||
"overflow-x",
|
||||
"overflow-y",
|
||||
"padding",
|
||||
"padding-bottom",
|
||||
"padding-left",
|
||||
"padding-right",
|
||||
"padding-top",
|
||||
"position",
|
||||
"right",
|
||||
"text-align",
|
||||
"text-decoration",
|
||||
"top",
|
||||
"vertical-align",
|
||||
"white-space",
|
||||
"width",
|
||||
"z-index",
|
||||
] as const;
|
||||
|
||||
const SAFE_STYLE_PROPERTY_SET = new Set<string>(SAFE_STYLE_PROPERTIES);
|
||||
|
||||
/** Converts camelCase CSS property names to kebab-case (e.g. flexWrap -> flex-wrap). */
|
||||
export function normalizeStyleProperty(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed.includes("-") && /[A-Z]/.test(trimmed)) {
|
||||
return trimmed
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1-$2")
|
||||
.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
|
||||
.toLowerCase();
|
||||
}
|
||||
return trimmed.toLowerCase();
|
||||
}
|
||||
|
||||
export const SAFE_ATTRIBUTE_NAMES: readonly SafeAttributeName[] = [
|
||||
"aria-label",
|
||||
"aria-description",
|
||||
"aria-hidden",
|
||||
"placeholder",
|
||||
"role",
|
||||
"title",
|
||||
] as const;
|
||||
|
||||
export const SAFE_INSERT_TAGS = [
|
||||
"div",
|
||||
"span",
|
||||
"p",
|
||||
"button",
|
||||
"label",
|
||||
] as const;
|
||||
export const SAFE_INSERT_POSITIONS = [
|
||||
"before",
|
||||
"after",
|
||||
"prepend",
|
||||
"append",
|
||||
] as const;
|
||||
|
||||
const OPERATION_TYPES = new Set([
|
||||
"setText",
|
||||
"replaceText",
|
||||
"setAttribute",
|
||||
"setStyle",
|
||||
"addClass",
|
||||
"removeClass",
|
||||
"hide",
|
||||
"show",
|
||||
"insertText",
|
||||
]);
|
||||
const CLASS_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
|
||||
const UNSAFE_STYLE_VALUE =
|
||||
/(?:url\s*\(|expression\s*\(|javascript\s*:|@import|[{};]|<\/?style)/i;
|
||||
|
||||
const TYPE_ALIASES: Record<string, string> = {
|
||||
settext: "setText",
|
||||
set_text: "setText",
|
||||
replacetext: "replaceText",
|
||||
replace_text: "replaceText",
|
||||
setattribute: "setAttribute",
|
||||
set_attribute: "setAttribute",
|
||||
setstyle: "setStyle",
|
||||
set_style: "setStyle",
|
||||
style: "setStyle",
|
||||
addclass: "addClass",
|
||||
add_class: "addClass",
|
||||
removeclass: "removeClass",
|
||||
remove_class: "removeClass",
|
||||
inserttext: "insertText",
|
||||
insert_text: "insertText",
|
||||
hidden: "hide",
|
||||
visible: "show",
|
||||
};
|
||||
|
||||
function describeValue(value: unknown): string {
|
||||
if (value === null) return "null";
|
||||
if (value === undefined) return "undefined";
|
||||
if (Array.isArray(value)) return `array(${value.length})`;
|
||||
if (typeof value === "object") {
|
||||
const preview = JSON.stringify(value);
|
||||
return `object ${preview.length > 160 ? `${preview.slice(0, 160)}…` : preview}`;
|
||||
}
|
||||
return `${typeof value}: ${String(value).slice(0, 120)}`;
|
||||
}
|
||||
|
||||
function coerceString(value: unknown): string | null {
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
if (typeof value === "number" || typeof value === "boolean") {
|
||||
return String(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeOperationType(value: unknown): string | null {
|
||||
const direct = coerceString(value);
|
||||
if (direct) {
|
||||
if (OPERATION_TYPES.has(direct)) return direct;
|
||||
const compact = direct.replace(/[\s_-]+/g, "").toLowerCase();
|
||||
const alias = TYPE_ALIASES[compact] ?? TYPE_ALIASES[direct.toLowerCase()];
|
||||
if (alias) return alias;
|
||||
}
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
const record = value as Record<string, unknown>;
|
||||
return normalizeOperationType(
|
||||
record.type ?? record.name ?? record.action ?? record.op,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function unwrapKeyedOperation(
|
||||
operation: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
if (operation.type || operation.action || operation.op) return operation;
|
||||
|
||||
const keys = Object.keys(operation).filter((key) => {
|
||||
const normalized = normalizeOperationType(key);
|
||||
return normalized !== null;
|
||||
});
|
||||
if (keys.length !== 1) return operation;
|
||||
|
||||
const type = normalizeOperationType(keys[0]);
|
||||
const payload = operation[keys[0]];
|
||||
if (!type || !payload || typeof payload !== "object" || Array.isArray(payload)) {
|
||||
return operation;
|
||||
}
|
||||
|
||||
return {
|
||||
type,
|
||||
...(payload as Record<string, unknown>),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeOperationRecord(
|
||||
value: unknown,
|
||||
index: number,
|
||||
): Record<string, unknown> {
|
||||
if (typeof value === "string") {
|
||||
throw new Error(
|
||||
`Operation #${index + 1} must be an object, received string: ${value.slice(0, 120)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const operation = asRecord(value, `Operation #${index + 1}`);
|
||||
const unwrapped = unwrapKeyedOperation(operation);
|
||||
const type = normalizeOperationType(
|
||||
unwrapped.type ?? unwrapped.action ?? unwrapped.op ?? unwrapped.operation,
|
||||
);
|
||||
if (!type) {
|
||||
throw new Error(
|
||||
`Operation #${index + 1} has an invalid type (received ${describeValue(
|
||||
unwrapped.type ?? unwrapped.action ?? unwrapped.op,
|
||||
)}). Expected one of: ${[...OPERATION_TYPES].join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const selector =
|
||||
unwrapped.selector ??
|
||||
unwrapped.target ??
|
||||
unwrapped.element ??
|
||||
unwrapped.query ??
|
||||
":scope";
|
||||
|
||||
return {
|
||||
...unwrapped,
|
||||
type,
|
||||
selector,
|
||||
...(unwrapped.className === undefined && unwrapped.class !== undefined
|
||||
? { className: unwrapped.class }
|
||||
: {}),
|
||||
...(unwrapped.property === undefined &&
|
||||
(unwrapped.styleProperty !== undefined || unwrapped.cssProperty !== undefined)
|
||||
? {
|
||||
property: unwrapped.styleProperty ?? unwrapped.cssProperty,
|
||||
}
|
||||
: {}),
|
||||
...(unwrapped.text === undefined && unwrapped.content !== undefined
|
||||
? { text: unwrapped.content }
|
||||
: {}),
|
||||
...(unwrapped.value === undefined && unwrapped.styleValue !== undefined
|
||||
? { value: unwrapped.styleValue }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeDraftShape(value: unknown): unknown {
|
||||
const draft = asRecord(value, "Generated mod");
|
||||
let operations = draft.operations;
|
||||
|
||||
if (operations && typeof operations === "object" && !Array.isArray(operations)) {
|
||||
operations = Object.values(operations as Record<string, unknown>);
|
||||
aiModLog.warn(
|
||||
"recipeSchema",
|
||||
"Normalized operations object into an array",
|
||||
operations,
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(operations)) {
|
||||
throw new Error("Generated mod operations must be a list");
|
||||
}
|
||||
|
||||
return {
|
||||
...draft,
|
||||
operations: operations.map(normalizeOperationRecord),
|
||||
};
|
||||
}
|
||||
|
||||
function asRecord(value: unknown, label: string): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error(`${label} must be an object`);
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function boundedString(
|
||||
value: unknown,
|
||||
label: string,
|
||||
maxLength: number,
|
||||
allowEmpty = false,
|
||||
): string {
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`${label} must be text (received ${describeValue(value)})`);
|
||||
}
|
||||
const result = value.trim();
|
||||
if (!allowEmpty && result.length === 0) throw new Error(`${label} is required`);
|
||||
if (result.length > maxLength) {
|
||||
throw new Error(`${label} is too long (maximum ${maxLength} characters)`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function validateRelativeSelector(value: unknown): string {
|
||||
const selector = boundedString(value, "Operation selector", 500);
|
||||
if (
|
||||
selector !== ":scope" &&
|
||||
!selector.startsWith(":scope ") &&
|
||||
!selector.startsWith(":scope>")
|
||||
) {
|
||||
throw new Error("Operation selectors must stay inside :scope");
|
||||
}
|
||||
if (selector.includes(",") || /(?:^|\s)(?:html|body|:root)(?:\s|$)/i.test(selector)) {
|
||||
throw new Error("Operation selector may not escape the selected root");
|
||||
}
|
||||
return selector;
|
||||
}
|
||||
|
||||
function validateClassName(value: unknown): string {
|
||||
const className = boundedString(value, "Class name", 64);
|
||||
if (!CLASS_NAME_PATTERN.test(className)) {
|
||||
throw new Error("Class name contains unsupported characters");
|
||||
}
|
||||
return className;
|
||||
}
|
||||
|
||||
function validateOperation(value: unknown): ModOperation {
|
||||
const operation = asRecord(value, "Operation");
|
||||
const type = boundedString(operation.type, "Operation type", 40);
|
||||
if (!OPERATION_TYPES.has(type)) {
|
||||
throw new Error(`Unsupported operation type: ${type}`);
|
||||
}
|
||||
const selector = validateRelativeSelector(operation.selector);
|
||||
|
||||
switch (type) {
|
||||
case "setText":
|
||||
return {
|
||||
type,
|
||||
selector,
|
||||
text: boundedString(operation.text, "Text", 2_000, true),
|
||||
};
|
||||
case "replaceText":
|
||||
return {
|
||||
type,
|
||||
selector,
|
||||
search: boundedString(operation.search, "Search text", 500),
|
||||
replacement: boundedString(
|
||||
operation.replacement,
|
||||
"Replacement text",
|
||||
2_000,
|
||||
true,
|
||||
),
|
||||
...(operation.all === true ? { all: true } : {}),
|
||||
};
|
||||
case "setAttribute": {
|
||||
const name = boundedString(operation.name, "Attribute name", 40);
|
||||
if (!SAFE_ATTRIBUTE_NAMES.includes(name as SafeAttributeName)) {
|
||||
throw new Error(`Unsafe attribute: ${name}`);
|
||||
}
|
||||
return {
|
||||
type,
|
||||
selector,
|
||||
name: name as SafeAttributeName,
|
||||
value: boundedString(operation.value, "Attribute value", 1_000, true),
|
||||
};
|
||||
}
|
||||
case "setStyle": {
|
||||
const rawProperty = boundedString(operation.property, "Style property", 60);
|
||||
const property = normalizeStyleProperty(rawProperty);
|
||||
if (!SAFE_STYLE_PROPERTY_SET.has(property)) {
|
||||
throw new Error(`Unsafe style property: ${rawProperty}`);
|
||||
}
|
||||
const styleValue = stripStyleImportantSuffix(
|
||||
boundedString(operation.value, "Style value", 200, true),
|
||||
);
|
||||
if (UNSAFE_STYLE_VALUE.test(styleValue)) {
|
||||
throw new Error("Style value contains unsafe content");
|
||||
}
|
||||
const important =
|
||||
operation.important === undefined
|
||||
? undefined
|
||||
: operation.important === true;
|
||||
return {
|
||||
type,
|
||||
selector,
|
||||
property: property as SafeStyleProperty,
|
||||
value: styleValue,
|
||||
...(important === undefined ? {} : { important }),
|
||||
};
|
||||
}
|
||||
case "addClass":
|
||||
case "removeClass":
|
||||
return {
|
||||
type,
|
||||
selector,
|
||||
className: validateClassName(operation.className),
|
||||
};
|
||||
case "hide":
|
||||
case "show":
|
||||
return { type, selector };
|
||||
case "insertText": {
|
||||
const position = boundedString(operation.position, "Insert position", 20);
|
||||
const tag = boundedString(operation.tag, "Insert tag", 20);
|
||||
if (!SAFE_INSERT_POSITIONS.includes(position as never)) {
|
||||
throw new Error(`Unsafe insert position: ${position}`);
|
||||
}
|
||||
if (!SAFE_INSERT_TAGS.includes(tag as never)) {
|
||||
throw new Error(`Unsafe insert tag: ${tag}`);
|
||||
}
|
||||
return {
|
||||
type,
|
||||
selector,
|
||||
position: position as "before" | "after" | "prepend" | "append",
|
||||
tag: tag as "div" | "span" | "p" | "button" | "label",
|
||||
text: boundedString(operation.text, "Inserted text", 2_000, true),
|
||||
...(operation.className === undefined
|
||||
? {}
|
||||
: { className: validateClassName(operation.className) }),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Unsupported operation");
|
||||
}
|
||||
|
||||
function describeOperationPreview(value: unknown): string {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return "unknown operation";
|
||||
}
|
||||
const operation = value as Record<string, unknown>;
|
||||
const type =
|
||||
operation.type ??
|
||||
operation.action ??
|
||||
operation.op ??
|
||||
Object.keys(operation).find((key) => normalizeOperationType(key) !== null) ??
|
||||
"unknown";
|
||||
const selector =
|
||||
operation.selector ??
|
||||
operation.target ??
|
||||
operation.element ??
|
||||
operation.query ??
|
||||
":scope";
|
||||
return `${String(type)} → ${String(selector).slice(0, 80)}`;
|
||||
}
|
||||
|
||||
export function formatRecipeValidationError(error: unknown): string {
|
||||
const base =
|
||||
error instanceof Error ? error.message : "Recipe validation failed";
|
||||
if (base.startsWith("Recipe validation failed:")) {
|
||||
return base;
|
||||
}
|
||||
|
||||
const suggestions: string[] = [];
|
||||
const unsafeStyle = base.match(/Unsafe style property:\s*(.+)/i);
|
||||
if (unsafeStyle) {
|
||||
const property = unsafeStyle[1].trim();
|
||||
suggestions.push(
|
||||
`"${property}" is not allowed. Supported style properties include ${SAFE_STYLE_PROPERTIES.slice(0, 10).join(", ")}, and more.`,
|
||||
);
|
||||
suggestions.push(
|
||||
"For layout changes, try display, flex-wrap, align-items, justify-content, gap, or grid-template-columns.",
|
||||
);
|
||||
}
|
||||
if (/Unsafe attribute:/i.test(base)) {
|
||||
suggestions.push(
|
||||
`Allowed attributes: ${SAFE_ATTRIBUTE_NAMES.join(", ")}.`,
|
||||
);
|
||||
}
|
||||
if (/selectors must stay inside :scope/i.test(base)) {
|
||||
suggestions.push(
|
||||
'Selectors must start with :scope (for example ":scope" or ":scope .child").',
|
||||
);
|
||||
}
|
||||
if (/invalid JSON/i.test(base)) {
|
||||
suggestions.push("Try regenerating the mod or switching to a different model.");
|
||||
}
|
||||
if (/at least one operation/i.test(base)) {
|
||||
suggestions.push(
|
||||
"Describe a concrete DOM change such as hiding an element, changing color, or rounding corners.",
|
||||
);
|
||||
}
|
||||
if (/Unsupported operation type:/i.test(base)) {
|
||||
suggestions.push(
|
||||
"Supported operations: setText, replaceText, setAttribute, setStyle, addClass, removeClass, hide, show, insertText.",
|
||||
);
|
||||
}
|
||||
|
||||
if (suggestions.length === 0) {
|
||||
return `Recipe validation failed: ${base}`;
|
||||
}
|
||||
|
||||
return `Recipe validation failed: ${base} — ${suggestions.join(" ")}`;
|
||||
}
|
||||
|
||||
function validateDraft(value: unknown): GeneratedModDraft {
|
||||
const normalized = normalizeDraftShape(value);
|
||||
const draft = asRecord(normalized, "Generated mod");
|
||||
if (!Array.isArray(draft.operations)) {
|
||||
throw new Error("Generated mod operations must be a list");
|
||||
}
|
||||
if (draft.operations.length > 30) {
|
||||
throw new Error("Generated mod may contain at most 30 operations");
|
||||
}
|
||||
|
||||
const operations = draft.operations.map((operation, index) => {
|
||||
try {
|
||||
return validateOperation(operation);
|
||||
} catch (cause) {
|
||||
const detail =
|
||||
cause instanceof Error ? cause.message : "Invalid operation";
|
||||
throw new Error(
|
||||
`Operation #${index + 1} (${describeOperationPreview(operation)}): ${detail}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
const advancedScript =
|
||||
draft.advancedScript === undefined ||
|
||||
(typeof draft.advancedScript === "string" &&
|
||||
draft.advancedScript.trim().length === 0)
|
||||
? undefined
|
||||
: assertAdvancedScriptSafe(draft.advancedScript);
|
||||
|
||||
if (operations.length === 0 && !advancedScript) {
|
||||
throw new Error(
|
||||
"Generated mod must include at least one operation or an advancedScript",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
name: boundedString(draft.name, "Mod name", 120),
|
||||
description: boundedString(
|
||||
draft.description,
|
||||
"Mod description",
|
||||
500,
|
||||
true,
|
||||
),
|
||||
operations,
|
||||
...(advancedScript === undefined ? {} : { advancedScript }),
|
||||
};
|
||||
}
|
||||
|
||||
export function extractJsonFromModelText(text: string): string {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed.startsWith("{")) return trimmed;
|
||||
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
||||
if (fenced?.[1]) return fenced[1].trim();
|
||||
const start = trimmed.indexOf("{");
|
||||
const end = trimmed.lastIndexOf("}");
|
||||
if (start >= 0 && end > start) return trimmed.slice(start, end + 1);
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function parseGeneratedModDraft(
|
||||
input: string | GeneratedModDraft,
|
||||
): GeneratedModDraft {
|
||||
let parsed: unknown;
|
||||
if (typeof input === "string") {
|
||||
const normalized = extractJsonFromModelText(input);
|
||||
if (normalized.length > 50_000) {
|
||||
throw new Error("Generated response is too large");
|
||||
}
|
||||
try {
|
||||
parsed = JSON.parse(normalized);
|
||||
} catch {
|
||||
aiModLog.error("recipeSchema", "Model returned invalid JSON", normalized);
|
||||
throw new Error("The model returned invalid JSON");
|
||||
}
|
||||
} else {
|
||||
parsed = input;
|
||||
}
|
||||
|
||||
try {
|
||||
const draft = validateDraft(parsed);
|
||||
aiModLog.info("recipeSchema", "Validated generated mod draft", {
|
||||
name: draft.name,
|
||||
operationCount: draft.operations.length,
|
||||
hasAdvancedScript: Boolean(draft.advancedScript),
|
||||
});
|
||||
return draft;
|
||||
} catch (error) {
|
||||
aiModLog.error("recipeSchema", "Recipe validation failed", {
|
||||
parsed,
|
||||
error,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function createStoredRecipe(
|
||||
draft: GeneratedModDraft,
|
||||
input: {
|
||||
rootSelector: string;
|
||||
route: string;
|
||||
now?: number;
|
||||
id?: string;
|
||||
},
|
||||
): StoredModRecipe {
|
||||
const validated = validateDraft(draft);
|
||||
const now = input.now ?? Date.now();
|
||||
const generatedId =
|
||||
input.id ??
|
||||
globalThis.crypto?.randomUUID?.() ??
|
||||
`mod-${now}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
return validateStoredRecipe({
|
||||
...validated,
|
||||
schemaVersion: AI_MOD_SCHEMA_VERSION,
|
||||
id: generatedId,
|
||||
enabled: false,
|
||||
route: input.route,
|
||||
rootSelector: input.rootSelector,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
function validateStoredRecipe(value: unknown): StoredModRecipe {
|
||||
const recipe = asRecord(value, "Stored mod");
|
||||
if (recipe.schemaVersion !== AI_MOD_SCHEMA_VERSION) {
|
||||
throw new Error("Unsupported mod schema version");
|
||||
}
|
||||
const draft = validateDraft(recipe);
|
||||
const id = boundedString(recipe.id, "Mod id", 160);
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(id)) {
|
||||
throw new Error("Mod id contains unsupported characters");
|
||||
}
|
||||
const rootSelector = boundedString(recipe.rootSelector, "Root selector", 1_000);
|
||||
if (/^(?:html|body|:root|\*)$/i.test(rootSelector)) {
|
||||
throw new Error("Root selector is too broad");
|
||||
}
|
||||
const createdAt = Number(recipe.createdAt);
|
||||
const updatedAt = Number(recipe.updatedAt);
|
||||
if (!Number.isFinite(createdAt) || !Number.isFinite(updatedAt)) {
|
||||
throw new Error("Mod timestamps are invalid");
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
schemaVersion: AI_MOD_SCHEMA_VERSION,
|
||||
id,
|
||||
enabled: recipe.enabled === true,
|
||||
route: boundedString(recipe.route, "Route", 256, true),
|
||||
rootSelector,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseStoredRecipes(json: string): StoredModRecipe[] {
|
||||
if (json.length > 500_000) throw new Error("Import file is too large");
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(json);
|
||||
} catch {
|
||||
throw new Error("Import file is not valid JSON");
|
||||
}
|
||||
if (!Array.isArray(parsed)) throw new Error("Import must contain a mod list");
|
||||
if (parsed.length > 100) throw new Error("At most 100 mods can be imported");
|
||||
return parsed.map(validateStoredRecipe);
|
||||
}
|
||||
|
||||
export function validateStoredRecipes(value: unknown): StoredModRecipe[] {
|
||||
return parseStoredRecipes(JSON.stringify(value));
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { assertAdvancedScriptSafe } from "./scriptSafety";
|
||||
|
||||
describe("advanced AI mod script safeguards", () => {
|
||||
it("allows advanced DOM code with cleanup", () => {
|
||||
expect(() =>
|
||||
assertAdvancedScriptSafe(`
|
||||
const cards = bsplus.selectAll(":scope .card");
|
||||
for (const card of cards) {
|
||||
bsplus.setStyle(card, "border-radius", "16px");
|
||||
bsplus.on(card, "click", () => card.classList.toggle("expanded"));
|
||||
}
|
||||
const observer = bsplus.observe(root, () => console.info("changed"));
|
||||
return () => observer.disconnect();
|
||||
`),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("allows clearing containers with empty innerHTML during DOM moves", () => {
|
||||
expect(() =>
|
||||
assertAdvancedScriptSafe(`
|
||||
const wrapper = bsplus.select(".search-trigger-wrapper");
|
||||
wrapper.innerHTML = '';
|
||||
wrapper.appendChild(anchor);
|
||||
return () => {};
|
||||
`),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["network requests", `fetch("https://attacker.invalid")`],
|
||||
["extension APIs", `chrome.storage.local.get(null)`],
|
||||
["page storage", `localStorage.getItem("token")`],
|
||||
["cookies", `document.cookie`],
|
||||
["dynamic evaluation", `eval("alert(1)")`],
|
||||
["script injection", `element.innerHTML = "<script>alert(1)</script>"`],
|
||||
["non-empty innerHTML", `wrapper.innerHTML = "<div></div>"`],
|
||||
["innerHTML append", `wrapper.innerHTML += "<span></span>"`],
|
||||
["navigation", `location.href = "https://attacker.invalid"`],
|
||||
["unbounded loops", `while (true) {}`],
|
||||
])("rejects %s", (_label, script) => {
|
||||
expect(() => assertAdvancedScriptSafe(script)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
const MAX_SCRIPT_LENGTH = 20_000;
|
||||
|
||||
const BLOCKED_PATTERNS: ReadonlyArray<{
|
||||
pattern: RegExp;
|
||||
reason: string;
|
||||
}> = [
|
||||
{
|
||||
pattern:
|
||||
/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|RTCPeerConnection|sendBeacon)\b/i,
|
||||
reason: "network access",
|
||||
},
|
||||
{
|
||||
pattern: /\b(?:chrome|browser)\s*\./i,
|
||||
reason: "extension API access",
|
||||
},
|
||||
{
|
||||
pattern:
|
||||
/\b(?:localStorage|sessionStorage|indexedDB|caches|cookieStore)\b/i,
|
||||
reason: "browser storage access",
|
||||
},
|
||||
{ pattern: /\bdocument\s*\.\s*cookie\b/i, reason: "cookie access" },
|
||||
{
|
||||
pattern:
|
||||
/\b(?:eval|Function|AsyncFunction|GeneratorFunction|importScripts|Worker|SharedWorker)\s*\(/i,
|
||||
reason: "dynamic code execution",
|
||||
},
|
||||
{ pattern: /\bimport\s*\(/i, reason: "dynamic imports" },
|
||||
{
|
||||
pattern: /\b(?:globalThis|top|parent|opener)\b/i,
|
||||
reason: "cross-world access",
|
||||
},
|
||||
{
|
||||
pattern: /\b(?:location|history)\s*(?:\.|\[|=)/i,
|
||||
reason: "navigation",
|
||||
},
|
||||
{
|
||||
pattern: /\bwindow\s*\.\s*(?:open|postMessage)\s*\(/i,
|
||||
reason: "cross-window messaging",
|
||||
},
|
||||
{
|
||||
pattern: /\.(?:src|srcset|href|action|formAction)\s*=/i,
|
||||
reason: "network-capable DOM properties",
|
||||
},
|
||||
{
|
||||
pattern:
|
||||
/\.setAttribute\s*\(\s*["'`](?:src|srcset|href|action|formaction|style|on[^"'`]*)["'`]/i,
|
||||
reason: "unsafe DOM attributes",
|
||||
},
|
||||
{
|
||||
pattern: /\.(?:outerHTML|insertAdjacentHTML)\b/i,
|
||||
reason: "raw HTML injection",
|
||||
},
|
||||
{
|
||||
pattern: /<\s*(?:script|iframe|object|embed|link|meta|form)\b/i,
|
||||
reason: "active HTML",
|
||||
},
|
||||
{
|
||||
pattern: /\.(?:submit|requestSubmit|click)\s*\(/i,
|
||||
reason: "programmatic page actions",
|
||||
},
|
||||
{
|
||||
pattern: /\b(?:while\s*\(\s*true\s*\)|for\s*\(\s*;\s*;\s*\))/i,
|
||||
reason: "unbounded loops",
|
||||
},
|
||||
{
|
||||
pattern: /(?:__proto__|prototype\s*\[|constructor\s*\.\s*constructor)/i,
|
||||
reason: "prototype escape",
|
||||
},
|
||||
];
|
||||
|
||||
const EMPTY_STRING_LITERAL = /^['"`]\s*['"`]$/;
|
||||
|
||||
function assertNoUnsafeInnerHtml(script: string): void {
|
||||
for (const match of script.matchAll(/\.innerHTML\s*=\s*([^;\n]+)/g)) {
|
||||
if (!EMPTY_STRING_LITERAL.test(match[1].trim())) {
|
||||
throw new Error("Advanced script blocked: raw HTML injection");
|
||||
}
|
||||
}
|
||||
if (/\.innerHTML\s*\+=/.test(script)) {
|
||||
throw new Error("Advanced script blocked: raw HTML injection");
|
||||
}
|
||||
}
|
||||
|
||||
export function assertAdvancedScriptSafe(value: unknown): string {
|
||||
if (typeof value !== "string") throw new Error("Advanced script must be text");
|
||||
const script = value.trim();
|
||||
if (!script) throw new Error("Advanced script is empty");
|
||||
if (script.length > MAX_SCRIPT_LENGTH) {
|
||||
throw new Error(
|
||||
`Advanced script is too long (maximum ${MAX_SCRIPT_LENGTH} characters)`,
|
||||
);
|
||||
}
|
||||
assertNoUnsafeInnerHtml(script);
|
||||
for (const { pattern, reason } of BLOCKED_PATTERNS) {
|
||||
if (pattern.test(script)) {
|
||||
throw new Error(`Advanced script blocked: ${reason}`);
|
||||
}
|
||||
}
|
||||
return script;
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
import {
|
||||
createStableSelector,
|
||||
startElementSelection,
|
||||
} from "./selection";
|
||||
|
||||
describe("AI mod element selection", () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = `
|
||||
<main>
|
||||
<section class="cards">
|
||||
<article class="assessment card"><h2>First</h2></article>
|
||||
<article class="assessment card" data-testid="target"><h2>Second</h2></article>
|
||||
</section>
|
||||
</main>
|
||||
`;
|
||||
});
|
||||
|
||||
it("prefers a unique id or test attribute", () => {
|
||||
const target = document.querySelector<HTMLElement>("[data-testid=target]")!;
|
||||
expect(createStableSelector(target)).toBe('[data-testid="target"]');
|
||||
|
||||
target.id = "assessment:42";
|
||||
expect(createStableSelector(target)).toBe("#assessment\\:42");
|
||||
});
|
||||
|
||||
it("falls back to a unique structural selector", () => {
|
||||
const target = document.querySelectorAll<HTMLElement>("article")[1];
|
||||
target.removeAttribute("data-testid");
|
||||
|
||||
const selector = createStableSelector(target);
|
||||
expect(document.querySelector(selector)).toBe(target);
|
||||
expect(document.querySelectorAll(selector)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("captures a clicked page element without activating it", () => {
|
||||
const onSelect = jest.fn();
|
||||
const onCancel = jest.fn();
|
||||
const target = document.querySelector<HTMLElement>("[data-testid=target]")!;
|
||||
const clickSpy = jest.fn();
|
||||
target.addEventListener("click", clickSpy);
|
||||
|
||||
const stop = startElementSelection({ onSelect, onCancel });
|
||||
target.dispatchEvent(
|
||||
new MouseEvent("click", { bubbles: true, cancelable: true }),
|
||||
);
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(target);
|
||||
expect(clickSpy).not.toHaveBeenCalled();
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
expect(document.querySelector("[data-bsplus-ai-selection-overlay]")).toBeNull();
|
||||
stop();
|
||||
});
|
||||
|
||||
it("cancels with Escape and removes the overlay", () => {
|
||||
const onCancel = jest.fn();
|
||||
const stop = startElementSelection({
|
||||
onSelect: jest.fn(),
|
||||
onCancel,
|
||||
});
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
expect(document.querySelector("[data-bsplus-ai-selection-overlay]")).toBeNull();
|
||||
stop();
|
||||
});
|
||||
});
|
||||
@@ -1,185 +0,0 @@
|
||||
const PREFERRED_ATTRIBUTES = ["data-testid", "data-id", "name"] as const;
|
||||
|
||||
function isUnique(selector: string, documentRef: Document): boolean {
|
||||
try {
|
||||
return documentRef.querySelectorAll(selector).length === 1;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function escapeCss(value: string): string {
|
||||
const escaped = value.replace(/([^\w-])/g, "\\$1");
|
||||
if (/^-?\d/.test(escaped)) {
|
||||
const firstDigit = escaped.startsWith("-") ? escaped[1] : escaped[0];
|
||||
const prefixLength = escaped.startsWith("-") ? 2 : 1;
|
||||
return `${escaped.startsWith("-") ? "-" : ""}\\3${firstDigit} ${escaped.slice(prefixLength)}`;
|
||||
}
|
||||
return escaped;
|
||||
}
|
||||
|
||||
function elementSegment(element: Element): string {
|
||||
const tag = element.tagName.toLowerCase();
|
||||
const stableClasses = [...element.classList]
|
||||
.filter((className) => /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(className))
|
||||
.slice(0, 2);
|
||||
let segment = `${tag}${stableClasses
|
||||
.map((className) => `.${escapeCss(className)}`)
|
||||
.join("")}`;
|
||||
|
||||
const parent = element.parentElement;
|
||||
if (parent) {
|
||||
const sameTag = [...parent.children].filter(
|
||||
(sibling) => sibling.tagName === element.tagName,
|
||||
);
|
||||
if (sameTag.length > 1) {
|
||||
segment += `:nth-of-type(${sameTag.indexOf(element) + 1})`;
|
||||
}
|
||||
}
|
||||
return segment;
|
||||
}
|
||||
|
||||
export function createStableSelector(
|
||||
element: Element,
|
||||
documentRef: Document = document,
|
||||
): string {
|
||||
if (element.id) {
|
||||
const byId = `#${escapeCss(element.id)}`;
|
||||
if (isUnique(byId, documentRef)) return byId;
|
||||
}
|
||||
|
||||
for (const attribute of PREFERRED_ATTRIBUTES) {
|
||||
const value = element.getAttribute(attribute);
|
||||
if (!value || value.length > 160) continue;
|
||||
const selector = `[${attribute}="${escapeCss(value)}"]`;
|
||||
if (isUnique(selector, documentRef)) return selector;
|
||||
}
|
||||
|
||||
const segments: string[] = [];
|
||||
let current: Element | null = element;
|
||||
while (current && current !== documentRef.documentElement) {
|
||||
segments.unshift(elementSegment(current));
|
||||
const selector = segments.join(" > ");
|
||||
if (isUnique(selector, documentRef)) return selector;
|
||||
current = current.parentElement;
|
||||
}
|
||||
|
||||
const selector = segments.join(" > ");
|
||||
if (!selector || !isUnique(selector, documentRef)) {
|
||||
throw new Error("Could not create a stable selector for this element");
|
||||
}
|
||||
return selector;
|
||||
}
|
||||
|
||||
export function buildScopeRelativeSelector(
|
||||
root: HTMLElement,
|
||||
target: Element,
|
||||
): string {
|
||||
if (target === root) return ":scope";
|
||||
if (!root.contains(target)) {
|
||||
throw new Error("Cannot build a selector outside the selected root");
|
||||
}
|
||||
const segments: string[] = [];
|
||||
let current: Element | null = target;
|
||||
while (current && current !== root) {
|
||||
segments.unshift(elementSegment(current));
|
||||
current = current.parentElement;
|
||||
}
|
||||
return segments.length > 0 ? `:scope > ${segments.join(" > ")}` : ":scope";
|
||||
}
|
||||
|
||||
export interface ElementSelectionOptions {
|
||||
onSelect: (element: HTMLElement) => void;
|
||||
onCancel: () => void;
|
||||
ignoredRoot?: Node | null;
|
||||
}
|
||||
|
||||
function eventElement(event: Event): HTMLElement | null {
|
||||
for (const item of event.composedPath()) {
|
||||
if (item instanceof HTMLElement) return item;
|
||||
}
|
||||
return event.target instanceof HTMLElement ? event.target : null;
|
||||
}
|
||||
|
||||
export function startElementSelection({
|
||||
onSelect,
|
||||
onCancel,
|
||||
ignoredRoot,
|
||||
}: ElementSelectionOptions): () => void {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.dataset.bsplusAiSelectionOverlay = "";
|
||||
Object.assign(overlay.style, {
|
||||
position: "fixed",
|
||||
pointerEvents: "none",
|
||||
zIndex: "2147483647",
|
||||
border: "2px solid var(--better-main, #8b5cf6)",
|
||||
borderRadius: "6px",
|
||||
background: "color-mix(in srgb, var(--better-main, #8b5cf6) 14%, transparent)",
|
||||
boxShadow: "0 0 0 1px rgba(255,255,255,.7)",
|
||||
display: "none",
|
||||
transition: "left 60ms, top 60ms, width 60ms, height 60ms",
|
||||
});
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
let active = true;
|
||||
const isIgnored = (element: HTMLElement) =>
|
||||
element === overlay ||
|
||||
ignoredRoot === element ||
|
||||
Boolean(ignoredRoot?.contains(element)) ||
|
||||
Boolean(
|
||||
ignoredRoot instanceof HTMLElement &&
|
||||
ignoredRoot.shadowRoot?.contains(element),
|
||||
);
|
||||
|
||||
const updateOverlay = (element: HTMLElement) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
Object.assign(overlay.style, {
|
||||
display: "block",
|
||||
left: `${rect.left}px`,
|
||||
top: `${rect.top}px`,
|
||||
width: `${rect.width}px`,
|
||||
height: `${rect.height}px`,
|
||||
});
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
document.removeEventListener("pointermove", onPointerMove, true);
|
||||
document.removeEventListener("click", onClick, true);
|
||||
document.removeEventListener("keydown", onKeyDown, true);
|
||||
overlay.remove();
|
||||
};
|
||||
|
||||
const onPointerMove = (event: PointerEvent) => {
|
||||
const element = eventElement(event);
|
||||
if (!element || isIgnored(element)) {
|
||||
overlay.style.display = "none";
|
||||
return;
|
||||
}
|
||||
updateOverlay(element);
|
||||
};
|
||||
|
||||
const onClick = (event: MouseEvent) => {
|
||||
const element = eventElement(event);
|
||||
if (!element || isIgnored(element)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
cleanup();
|
||||
onSelect(element);
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
cleanup();
|
||||
onCancel();
|
||||
};
|
||||
|
||||
document.addEventListener("pointermove", onPointerMove, true);
|
||||
document.addEventListener("click", onClick, true);
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
return cleanup;
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
formatRecipeValidationError,
|
||||
parseGeneratedModDraft,
|
||||
} from "./recipeSchema";
|
||||
import { aiModLog } from "./logger";
|
||||
import {
|
||||
deleteStoredMod,
|
||||
exportStoredMods,
|
||||
importStoredMods,
|
||||
loadStoredMods,
|
||||
setStoredModEnabled,
|
||||
upsertStoredMod,
|
||||
} from "./storage";
|
||||
import type {
|
||||
AdvancedScriptSupport,
|
||||
CreatorServices,
|
||||
GeneratedModDraft,
|
||||
GenerationProgress,
|
||||
KeyStatus,
|
||||
ModelSettings,
|
||||
SelectedElementContext,
|
||||
} from "./types";
|
||||
|
||||
const AI_MOD_CREATOR_MESSAGE_TYPE = "aiModCreator";
|
||||
|
||||
interface MessageResponse {
|
||||
success?: boolean;
|
||||
data?: unknown;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
async function sendBackgroundMessage(
|
||||
action: string,
|
||||
payload: Record<string, unknown> = {},
|
||||
): Promise<unknown> {
|
||||
aiModLog.debug("services", `Sending background message: ${action}`, payload);
|
||||
const response = (await browser.runtime.sendMessage({
|
||||
type: AI_MOD_CREATOR_MESSAGE_TYPE,
|
||||
action,
|
||||
...payload,
|
||||
})) as MessageResponse | undefined;
|
||||
if (!response?.success) {
|
||||
const error =
|
||||
typeof response?.error === "string"
|
||||
? response.error
|
||||
: "AI Mod Creator background service is unavailable";
|
||||
aiModLog.error("services", `Background message failed: ${action}`, error);
|
||||
throw new Error(error);
|
||||
}
|
||||
aiModLog.debug("services", `Background message succeeded: ${action}`, response.data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
function streamGeneration(
|
||||
context: SelectedElementContext,
|
||||
onProgress?: (progress: GenerationProgress) => void,
|
||||
) {
|
||||
return new Promise<ReturnType<typeof parseGeneratedModDraft>>(
|
||||
(resolve, reject) => {
|
||||
aiModLog.info("services", "Opening streaming generation port", {
|
||||
route: context.route,
|
||||
rootSelector: context.rootSelector,
|
||||
request: context.request,
|
||||
});
|
||||
const port = browser.runtime.connect({ name: "aiModCreator.stream" });
|
||||
let settled = false;
|
||||
port.onMessage.addListener(
|
||||
(message: {
|
||||
type?: string;
|
||||
progress?: GenerationProgress;
|
||||
draft?: unknown;
|
||||
error?: unknown;
|
||||
}) => {
|
||||
if (message.type === "progress" && message.progress) {
|
||||
aiModLog.debug("services", "Stream progress", message.progress);
|
||||
onProgress?.(message.progress);
|
||||
} else if (message.type === "done") {
|
||||
settled = true;
|
||||
aiModLog.info("services", "Stream completed", message.draft);
|
||||
try {
|
||||
resolve(parseGeneratedModDraft(message.draft as GeneratedModDraft));
|
||||
} catch (error) {
|
||||
const formatted = formatRecipeValidationError(error);
|
||||
aiModLog.error("services", "Failed to validate streamed draft", {
|
||||
draft: message.draft,
|
||||
error: formatted,
|
||||
});
|
||||
reject(new Error(formatted));
|
||||
}
|
||||
} else if (message.type === "error") {
|
||||
settled = true;
|
||||
const errorMessage =
|
||||
typeof message.error === "string"
|
||||
? message.error
|
||||
: "AI streaming failed";
|
||||
aiModLog.error("services", "Stream error from background", errorMessage);
|
||||
reject(new Error(errorMessage));
|
||||
}
|
||||
},
|
||||
);
|
||||
port.onDisconnect.addListener(() => {
|
||||
if (!settled) {
|
||||
aiModLog.error("services", "Streaming port disconnected early");
|
||||
reject(new Error("AI streaming connection closed"));
|
||||
}
|
||||
});
|
||||
port.postMessage({ context });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function createCreatorServices(): CreatorServices {
|
||||
return {
|
||||
async getKeyStatus() {
|
||||
const data = await sendBackgroundMessage("status");
|
||||
if (
|
||||
!data ||
|
||||
typeof data !== "object" ||
|
||||
typeof (data as KeyStatus).configured !== "boolean"
|
||||
) {
|
||||
throw new Error("Invalid API key status response");
|
||||
}
|
||||
return { configured: (data as KeyStatus).configured };
|
||||
},
|
||||
async getModelSettings() {
|
||||
const data = await sendBackgroundMessage("getModel");
|
||||
if (
|
||||
!data ||
|
||||
typeof data !== "object" ||
|
||||
typeof (data as ModelSettings).modelId !== "string"
|
||||
) {
|
||||
throw new Error("Invalid model settings response");
|
||||
}
|
||||
return { modelId: (data as ModelSettings).modelId };
|
||||
},
|
||||
async saveModel(modelId) {
|
||||
await sendBackgroundMessage("saveModel", { modelId });
|
||||
},
|
||||
async getAdvancedScriptSupport() {
|
||||
const data = await sendBackgroundMessage("advancedSupport");
|
||||
if (
|
||||
!data ||
|
||||
typeof data !== "object" ||
|
||||
typeof (data as AdvancedScriptSupport).supported !== "boolean"
|
||||
) {
|
||||
throw new Error("Invalid advanced script support response");
|
||||
}
|
||||
return data as AdvancedScriptSupport;
|
||||
},
|
||||
async openExtensionSettings() {
|
||||
const extensionId = browser.runtime.id;
|
||||
await browser.tabs.create({
|
||||
url: `chrome://extensions/?id=${extensionId}`,
|
||||
});
|
||||
},
|
||||
async saveKey(apiKey) {
|
||||
await sendBackgroundMessage("saveKey", { apiKey });
|
||||
},
|
||||
async clearKey() {
|
||||
await sendBackgroundMessage("clearKey");
|
||||
},
|
||||
async generate(context, onProgress) {
|
||||
return streamGeneration(context, onProgress);
|
||||
},
|
||||
loadMods: loadStoredMods,
|
||||
saveMod: upsertStoredMod,
|
||||
setModEnabled: setStoredModEnabled,
|
||||
deleteMod: deleteStoredMod,
|
||||
importMods: importStoredMods,
|
||||
exportMods: exportStoredMods,
|
||||
async executeAdvancedScript(recipe) {
|
||||
aiModLog.info("services", "Requesting advanced mod via background", recipe.id);
|
||||
await sendBackgroundMessage("executeAdvanced", { recipe });
|
||||
},
|
||||
async stopAdvancedScript(id) {
|
||||
aiModLog.info("services", "Stopping advanced mod via background", id);
|
||||
await sendBackgroundMessage("stopAdvanced", { id });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import {
|
||||
deleteStoredMod,
|
||||
exportStoredMods,
|
||||
importStoredMods,
|
||||
loadStoredMods,
|
||||
setStoredModEnabled,
|
||||
upsertStoredMod,
|
||||
} from "./storage";
|
||||
import type { StoredModRecipe } from "./types";
|
||||
|
||||
const storedRecipe: StoredModRecipe = {
|
||||
schemaVersion: 1,
|
||||
id: "mod-1",
|
||||
name: "Test",
|
||||
description: "Test mod",
|
||||
enabled: false,
|
||||
route: "assessments",
|
||||
rootSelector: "#selected",
|
||||
operations: [{ type: "hide", selector: ":scope" }],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
};
|
||||
|
||||
describe("AI mod local storage", () => {
|
||||
it("immutably inserts, updates, toggles, and deletes recipes", async () => {
|
||||
await upsertStoredMod(storedRecipe);
|
||||
expect(await loadStoredMods()).toEqual([storedRecipe]);
|
||||
|
||||
await setStoredModEnabled("mod-1", true);
|
||||
expect((await loadStoredMods())[0]).toMatchObject({
|
||||
id: "mod-1",
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
await upsertStoredMod({ ...storedRecipe, name: "Updated" });
|
||||
expect((await loadStoredMods())[0].name).toBe("Updated");
|
||||
|
||||
await deleteStoredMod("mod-1");
|
||||
expect(await loadStoredMods()).toEqual([]);
|
||||
});
|
||||
|
||||
it("round-trips validated import/export JSON", async () => {
|
||||
await upsertStoredMod(storedRecipe);
|
||||
const exported = await exportStoredMods();
|
||||
|
||||
await browser.storage.local.clear?.();
|
||||
const imported = await importStoredMods(exported);
|
||||
|
||||
expect(imported).toEqual([storedRecipe]);
|
||||
expect(await loadStoredMods()).toEqual([storedRecipe]);
|
||||
});
|
||||
|
||||
it("does not overwrite storage when an import is invalid", async () => {
|
||||
await upsertStoredMod(storedRecipe);
|
||||
|
||||
await expect(
|
||||
importStoredMods(
|
||||
JSON.stringify([
|
||||
{
|
||||
...storedRecipe,
|
||||
operations: [{ type: "javascript", code: "alert(1)" }],
|
||||
},
|
||||
]),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(await loadStoredMods()).toEqual([storedRecipe]);
|
||||
});
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { parseStoredRecipes, validateStoredRecipes } from "./recipeSchema";
|
||||
import type { StoredModRecipe } from "./types";
|
||||
|
||||
export const AI_MODS_STORAGE_KEY = "aiModCreator.mods";
|
||||
export const OPENROUTER_API_KEY_STORAGE_KEY =
|
||||
"aiModCreator.openRouterApiKey";
|
||||
export const OPENROUTER_MODEL_STORAGE_KEY = "aiModCreator.openRouterModelId";
|
||||
|
||||
async function writeStoredMods(
|
||||
recipes: StoredModRecipe[],
|
||||
): Promise<StoredModRecipe[]> {
|
||||
const validated = validateStoredRecipes(recipes);
|
||||
await browser.storage.local.set({ [AI_MODS_STORAGE_KEY]: validated });
|
||||
return validated;
|
||||
}
|
||||
|
||||
export async function loadStoredMods(): Promise<StoredModRecipe[]> {
|
||||
const result = await browser.storage.local.get(AI_MODS_STORAGE_KEY);
|
||||
const stored = result[AI_MODS_STORAGE_KEY];
|
||||
if (stored === undefined) return [];
|
||||
try {
|
||||
return validateStoredRecipes(stored);
|
||||
} catch (error) {
|
||||
console.error("[BetterSEQTA+] Ignoring invalid locally stored AI mods:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function upsertStoredMod(
|
||||
recipe: StoredModRecipe,
|
||||
): Promise<StoredModRecipe[]> {
|
||||
const [validated] = validateStoredRecipes([recipe]);
|
||||
const existing = await loadStoredMods();
|
||||
const next = existing.some((item) => item.id === validated.id)
|
||||
? existing.map((item) => (item.id === validated.id ? validated : item))
|
||||
: [...existing, validated];
|
||||
return writeStoredMods(next);
|
||||
}
|
||||
|
||||
export async function setStoredModEnabled(
|
||||
id: string,
|
||||
enabled: boolean,
|
||||
): Promise<StoredModRecipe[]> {
|
||||
const existing = await loadStoredMods();
|
||||
const next = existing.map((item) =>
|
||||
item.id === id ? { ...item, enabled, updatedAt: Date.now() } : item,
|
||||
);
|
||||
return writeStoredMods(next);
|
||||
}
|
||||
|
||||
export async function deleteStoredMod(
|
||||
id: string,
|
||||
): Promise<StoredModRecipe[]> {
|
||||
const existing = await loadStoredMods();
|
||||
return writeStoredMods(existing.filter((item) => item.id !== id));
|
||||
}
|
||||
|
||||
export async function exportStoredMods(): Promise<string> {
|
||||
return JSON.stringify(await loadStoredMods(), null, 2);
|
||||
}
|
||||
|
||||
export async function importStoredMods(
|
||||
json: string,
|
||||
): Promise<StoredModRecipe[]> {
|
||||
const imported = parseStoredRecipes(json);
|
||||
return writeStoredMods(imported);
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
export const AI_MOD_SCHEMA_VERSION = 1 as const;
|
||||
|
||||
export type SafeStyleProperty =
|
||||
| "align-items"
|
||||
| "align-self"
|
||||
| "aspect-ratio"
|
||||
| "background"
|
||||
| "background-color"
|
||||
| "border"
|
||||
| "border-color"
|
||||
| "border-radius"
|
||||
| "border-style"
|
||||
| "border-width"
|
||||
| "bottom"
|
||||
| "box-shadow"
|
||||
| "color"
|
||||
| "cursor"
|
||||
| "display"
|
||||
| "flex"
|
||||
| "flex-direction"
|
||||
| "flex-grow"
|
||||
| "flex-shrink"
|
||||
| "flex-wrap"
|
||||
| "font-size"
|
||||
| "font-weight"
|
||||
| "gap"
|
||||
| "grid-template-columns"
|
||||
| "height"
|
||||
| "justify-content"
|
||||
| "left"
|
||||
| "letter-spacing"
|
||||
| "line-height"
|
||||
| "margin"
|
||||
| "margin-bottom"
|
||||
| "margin-left"
|
||||
| "margin-right"
|
||||
| "margin-top"
|
||||
| "max-height"
|
||||
| "max-width"
|
||||
| "min-height"
|
||||
| "min-width"
|
||||
| "object-fit"
|
||||
| "opacity"
|
||||
| "order"
|
||||
| "overflow"
|
||||
| "overflow-x"
|
||||
| "overflow-y"
|
||||
| "padding"
|
||||
| "padding-bottom"
|
||||
| "padding-left"
|
||||
| "padding-right"
|
||||
| "padding-top"
|
||||
| "position"
|
||||
| "right"
|
||||
| "text-align"
|
||||
| "text-decoration"
|
||||
| "top"
|
||||
| "vertical-align"
|
||||
| "white-space"
|
||||
| "width"
|
||||
| "z-index";
|
||||
|
||||
export type SafeAttributeName =
|
||||
| "aria-label"
|
||||
| "aria-description"
|
||||
| "aria-hidden"
|
||||
| "placeholder"
|
||||
| "role"
|
||||
| "title";
|
||||
|
||||
interface OperationBase {
|
||||
selector: string;
|
||||
}
|
||||
|
||||
export interface SetTextOperation extends OperationBase {
|
||||
type: "setText";
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ReplaceTextOperation extends OperationBase {
|
||||
type: "replaceText";
|
||||
search: string;
|
||||
replacement: string;
|
||||
all?: boolean;
|
||||
}
|
||||
|
||||
export interface SetAttributeOperation extends OperationBase {
|
||||
type: "setAttribute";
|
||||
name: SafeAttributeName;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface SetStyleOperation extends OperationBase {
|
||||
type: "setStyle";
|
||||
property: SafeStyleProperty;
|
||||
value: string;
|
||||
/** When true (default), beats BetterSEQTA stylesheet rules including !important. */
|
||||
important?: boolean;
|
||||
}
|
||||
|
||||
export interface AddClassOperation extends OperationBase {
|
||||
type: "addClass";
|
||||
className: string;
|
||||
}
|
||||
|
||||
export interface RemoveClassOperation extends OperationBase {
|
||||
type: "removeClass";
|
||||
className: string;
|
||||
}
|
||||
|
||||
export interface HideOperation extends OperationBase {
|
||||
type: "hide";
|
||||
}
|
||||
|
||||
export interface ShowOperation extends OperationBase {
|
||||
type: "show";
|
||||
}
|
||||
|
||||
export interface InsertTextOperation extends OperationBase {
|
||||
type: "insertText";
|
||||
position: "before" | "after" | "prepend" | "append";
|
||||
tag: "div" | "span" | "p" | "button" | "label";
|
||||
text: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export type ModOperation =
|
||||
| SetTextOperation
|
||||
| ReplaceTextOperation
|
||||
| SetAttributeOperation
|
||||
| SetStyleOperation
|
||||
| AddClassOperation
|
||||
| RemoveClassOperation
|
||||
| HideOperation
|
||||
| ShowOperation
|
||||
| InsertTextOperation;
|
||||
|
||||
export interface GeneratedModDraft {
|
||||
name: string;
|
||||
description: string;
|
||||
operations: ModOperation[];
|
||||
advancedScript?: string;
|
||||
}
|
||||
|
||||
export interface StoredModRecipe extends GeneratedModDraft {
|
||||
schemaVersion: typeof AI_MOD_SCHEMA_VERSION;
|
||||
id: string;
|
||||
enabled: boolean;
|
||||
route: string;
|
||||
rootSelector: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface DomElementSummary {
|
||||
selector: string;
|
||||
tag: string;
|
||||
classes: string[];
|
||||
directText?: string;
|
||||
parentSelector: string | null;
|
||||
siblingIndex: number;
|
||||
siblingCount: number;
|
||||
layout: Record<string, string>;
|
||||
rowCount?: number;
|
||||
columnCount?: number;
|
||||
itemCount?: number;
|
||||
}
|
||||
|
||||
export interface ParentChainSummary {
|
||||
tag: string;
|
||||
classes: string[];
|
||||
layout: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface StructuralHints {
|
||||
hasTable: boolean;
|
||||
hasList: boolean;
|
||||
rowCount?: number;
|
||||
columnCount?: number;
|
||||
itemCount?: number;
|
||||
primaryClasses: string[];
|
||||
}
|
||||
|
||||
export interface SelectedElementContext {
|
||||
route: string;
|
||||
rootSelector: string;
|
||||
request: string;
|
||||
userContext: string;
|
||||
selectedHtml: string;
|
||||
domCatalog: DomElementSummary[];
|
||||
ancestorHtml?: string;
|
||||
parentChain?: ParentChainSummary[];
|
||||
structuralHints?: StructuralHints;
|
||||
tagName: string;
|
||||
dimensions: {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
computedStyle: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface KeyStatus {
|
||||
configured: boolean;
|
||||
}
|
||||
|
||||
export interface ModelSettings {
|
||||
modelId: string;
|
||||
}
|
||||
|
||||
export interface AdvancedScriptSupport {
|
||||
supported: boolean;
|
||||
reason?: string;
|
||||
instructions?: string;
|
||||
}
|
||||
|
||||
export interface GenerationProgress {
|
||||
type: "status" | "content" | "usage";
|
||||
text?: string;
|
||||
promptTokens?: number;
|
||||
completionTokens?: number;
|
||||
}
|
||||
|
||||
export interface CreatorServices {
|
||||
getKeyStatus: () => Promise<KeyStatus>;
|
||||
getModelSettings: () => Promise<ModelSettings>;
|
||||
saveModel: (modelId: string) => Promise<void>;
|
||||
getAdvancedScriptSupport: () => Promise<AdvancedScriptSupport>;
|
||||
openExtensionSettings: () => Promise<void>;
|
||||
saveKey: (apiKey: string) => Promise<void>;
|
||||
clearKey: () => Promise<void>;
|
||||
generate: (
|
||||
context: SelectedElementContext,
|
||||
onProgress?: (progress: GenerationProgress) => void,
|
||||
) => Promise<GeneratedModDraft>;
|
||||
loadMods: () => Promise<StoredModRecipe[]>;
|
||||
saveMod: (recipe: StoredModRecipe) => Promise<StoredModRecipe[]>;
|
||||
setModEnabled: (
|
||||
id: string,
|
||||
enabled: boolean,
|
||||
) => Promise<StoredModRecipe[]>;
|
||||
deleteMod: (id: string) => Promise<StoredModRecipe[]>;
|
||||
importMods: (json: string) => Promise<StoredModRecipe[]>;
|
||||
exportMods: () => Promise<string>;
|
||||
executeAdvancedScript: (recipe: StoredModRecipe) => Promise<void>;
|
||||
stopAdvancedScript: (id: string) => Promise<void>;
|
||||
}
|
||||
@@ -52,7 +52,8 @@ function showEditModal(
|
||||
const modal = document.createElement("div");
|
||||
modal.className = "timetable-edit-modal";
|
||||
|
||||
const override = overrides?.[String(item.ci)] ?? overridesBySubject?.[item.description];
|
||||
const override =
|
||||
overrides?.[String(item.ci)] ?? overridesBySubject?.[item.description];
|
||||
|
||||
const roomValue = override?.room ?? item.room ?? "";
|
||||
const staffValue = override?.staff ?? item.staff ?? "";
|
||||
@@ -97,21 +98,31 @@ function showEditModal(
|
||||
modal.addEventListener("mousedown", (e) => e.stopPropagation());
|
||||
modal.addEventListener("mouseup", (e) => e.stopPropagation());
|
||||
|
||||
const roomInput = modal.querySelector("#timetable-edit-room") as HTMLInputElement;
|
||||
const staffInput = modal.querySelector("#timetable-edit-staff") as HTMLInputElement;
|
||||
const applyFutureCheckbox = modal.querySelector("#timetable-edit-apply-future") as HTMLInputElement;
|
||||
const roomInput = modal.querySelector(
|
||||
"#timetable-edit-room",
|
||||
) as HTMLInputElement;
|
||||
const staffInput = modal.querySelector(
|
||||
"#timetable-edit-staff",
|
||||
) as HTMLInputElement;
|
||||
const applyFutureCheckbox = modal.querySelector(
|
||||
"#timetable-edit-apply-future",
|
||||
) as HTMLInputElement;
|
||||
|
||||
modal.querySelector(".timetable-edit-btn-save")?.addEventListener("click", () => {
|
||||
onSave(
|
||||
item.ci,
|
||||
roomInput.value.trim(),
|
||||
staffInput.value.trim(),
|
||||
applyFutureCheckbox?.checked ?? false,
|
||||
);
|
||||
removeModal();
|
||||
});
|
||||
modal
|
||||
.querySelector(".timetable-edit-btn-save")
|
||||
?.addEventListener("click", () => {
|
||||
onSave(
|
||||
item.ci,
|
||||
roomInput.value.trim(),
|
||||
staffInput.value.trim(),
|
||||
applyFutureCheckbox?.checked ?? false,
|
||||
);
|
||||
removeModal();
|
||||
});
|
||||
|
||||
modal.querySelector(".timetable-edit-btn-cancel")?.addEventListener("click", removeModal);
|
||||
modal
|
||||
.querySelector(".timetable-edit-btn-cancel")
|
||||
?.addEventListener("click", removeModal);
|
||||
|
||||
const clearBtn = modal.querySelector(".timetable-edit-btn-clear");
|
||||
if (clearBtn) {
|
||||
@@ -163,7 +174,9 @@ const timetableEditPlugin = {
|
||||
if (byCalendar) return byCalendar as HTMLElement;
|
||||
}
|
||||
|
||||
for (const entry of document.querySelectorAll(".timetablepage .entry.class")) {
|
||||
for (const entry of document.querySelectorAll(
|
||||
".timetablepage .entry.class",
|
||||
)) {
|
||||
const entryTitle = entry.querySelector(".title")?.textContent?.trim();
|
||||
if (entryTitle === title) return entry as HTMLElement;
|
||||
}
|
||||
@@ -174,7 +187,8 @@ const timetableEditPlugin = {
|
||||
const title = quickbar.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
if (!title) return;
|
||||
|
||||
const quickbarRoom = quickbar.querySelector(".meta .room")?.textContent?.trim() ?? "";
|
||||
const quickbarRoom =
|
||||
quickbar.querySelector(".meta .room")?.textContent?.trim() ?? "";
|
||||
const quickbarStaff =
|
||||
quickbar.querySelector(".meta .teacher")?.textContent?.trim() ?? "";
|
||||
|
||||
@@ -211,7 +225,10 @@ const timetableEditPlugin = {
|
||||
};
|
||||
|
||||
const processEntry = (entry: HTMLElement): void => {
|
||||
if (entry.classList.contains("assessment") || entry.hasAttribute("data-timetable-edit-processed")) return;
|
||||
// Mixed timetable entries can include both the `class` and `assessment`
|
||||
// classes, especially when an assessment is attached to a lesson. We still
|
||||
// need to apply the per-lesson override to that element.
|
||||
if (entry.hasAttribute("data-timetable-edit-processed")) return;
|
||||
|
||||
const ciStr = entry.getAttribute("data-instance");
|
||||
if (!ciStr) return;
|
||||
@@ -233,8 +250,10 @@ const timetableEditPlugin = {
|
||||
|
||||
const override = getEffectiveOverride(ci, description);
|
||||
if (override) {
|
||||
if (override.room !== undefined && roomEl) roomEl.textContent = override.room;
|
||||
if (override.staff !== undefined && teacherEl) teacherEl.textContent = override.staff;
|
||||
if (override.room !== undefined && roomEl)
|
||||
roomEl.textContent = override.room;
|
||||
if (override.staff !== undefined && teacherEl)
|
||||
teacherEl.textContent = override.staff;
|
||||
}
|
||||
|
||||
entry.addEventListener(
|
||||
@@ -250,14 +269,19 @@ const timetableEditPlugin = {
|
||||
};
|
||||
|
||||
const processAllEntries = () => {
|
||||
document.querySelectorAll(".timetablepage .entry.class").forEach((entry) => {
|
||||
processEntry(entry as HTMLElement);
|
||||
});
|
||||
document
|
||||
.querySelectorAll(".timetablepage .entry.class")
|
||||
.forEach((entry) => {
|
||||
processEntry(entry as HTMLElement);
|
||||
});
|
||||
};
|
||||
|
||||
const getVisibleClassQuickbar = (): HTMLElement | null => {
|
||||
const quickbar = document.querySelector(".timetablepage .quickbar.visible");
|
||||
if (!quickbar || quickbar.getAttribute("data-type") !== "class") return null;
|
||||
const quickbar = document.querySelector(
|
||||
".timetablepage .quickbar.visible",
|
||||
);
|
||||
if (!quickbar || quickbar.getAttribute("data-type") !== "class")
|
||||
return null;
|
||||
return quickbar as HTMLElement;
|
||||
};
|
||||
|
||||
@@ -284,10 +308,18 @@ const timetableEditPlugin = {
|
||||
if (override.room !== undefined && !roomEl) return;
|
||||
if (override.staff !== undefined && !teacherEl) return;
|
||||
|
||||
if (override.room !== undefined && roomEl && roomEl.textContent !== override.room) {
|
||||
if (
|
||||
override.room !== undefined &&
|
||||
roomEl &&
|
||||
roomEl.textContent !== override.room
|
||||
) {
|
||||
roomEl.textContent = override.room;
|
||||
}
|
||||
if (override.staff !== undefined && teacherEl && teacherEl.textContent !== override.staff) {
|
||||
if (
|
||||
override.staff !== undefined &&
|
||||
teacherEl &&
|
||||
teacherEl.textContent !== override.staff
|
||||
) {
|
||||
teacherEl.textContent = override.staff;
|
||||
}
|
||||
|
||||
@@ -300,7 +332,8 @@ const timetableEditPlugin = {
|
||||
const roomEl = quickbar.querySelector(".meta .room");
|
||||
const teacherEl = quickbar.querySelector(".meta .teacher");
|
||||
if (roomEl && roomEl.textContent !== room) roomEl.textContent = room;
|
||||
if (teacherEl && teacherEl.textContent !== staff) teacherEl.textContent = staff;
|
||||
if (teacherEl && teacherEl.textContent !== staff)
|
||||
teacherEl.textContent = staff;
|
||||
if (lastClickedCi !== null) lastSyncedQuickbarCi = lastClickedCi;
|
||||
};
|
||||
|
||||
@@ -325,7 +358,9 @@ const timetableEditPlugin = {
|
||||
|
||||
syncClassQuickbar(quickbar);
|
||||
|
||||
const hasButton = quickbar.querySelector(".timetable-edit-quickbar-btn");
|
||||
const hasButton = quickbar.querySelector(
|
||||
".timetable-edit-quickbar-btn",
|
||||
);
|
||||
const hasActions = quickbar.querySelector(".actions");
|
||||
if ((!hasButton || !hasActions) && ++attempts < maxAttempts) {
|
||||
quickbarSyncTimer = setTimeout(trySync, 50);
|
||||
@@ -364,9 +399,12 @@ const timetableEditPlugin = {
|
||||
const entryData = lastClickedEntry;
|
||||
if (!entryData) return;
|
||||
|
||||
const quickbarRoom = qb.querySelector(".meta .room")?.textContent?.trim() ?? "";
|
||||
const quickbarTeacher = qb.querySelector(".meta .teacher")?.textContent?.trim() ?? "";
|
||||
const quickbarTitle = qb.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const quickbarRoom =
|
||||
qb.querySelector(".meta .room")?.textContent?.trim() ?? "";
|
||||
const quickbarTeacher =
|
||||
qb.querySelector(".meta .teacher")?.textContent?.trim() ?? "";
|
||||
const quickbarTitle =
|
||||
qb.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const ci = lastClickedCi ?? entryData.item.ci;
|
||||
const item: TimetableEntryData = {
|
||||
ci,
|
||||
@@ -391,7 +429,10 @@ const timetableEditPlugin = {
|
||||
const current = getOverrides();
|
||||
api.storage.timetableOverrides = {
|
||||
...current,
|
||||
[String(saveCi)]: { room: room || undefined, staff: staff || undefined },
|
||||
[String(saveCi)]: {
|
||||
room: room || undefined,
|
||||
staff: staff || undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (entryData.roomEl) entryData.roomEl.textContent = room;
|
||||
@@ -409,17 +450,15 @@ const timetableEditPlugin = {
|
||||
delete bySubject[item.description];
|
||||
api.storage.timetableOverridesBySubject = bySubject;
|
||||
if (entryData.roomEl) entryData.roomEl.textContent = item.room;
|
||||
if (entryData.teacherEl) entryData.teacherEl.textContent = item.staff;
|
||||
if (entryData.teacherEl)
|
||||
entryData.teacherEl.textContent = item.staff;
|
||||
updateVisibleQuickbar(item.room, item.staff);
|
||||
processAllEntries();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
actions.insertBefore(
|
||||
btn,
|
||||
colourBtn ?? actions.firstChild,
|
||||
);
|
||||
actions.insertBefore(btn, colourBtn ?? actions.firstChild);
|
||||
};
|
||||
|
||||
const syncQuickbarFromDOM = () => {
|
||||
@@ -437,13 +476,19 @@ const timetableEditPlugin = {
|
||||
if (!quickbar) return;
|
||||
|
||||
const shouldSync = mutations.some((mutation) => {
|
||||
if (mutation.type === "attributes" && mutation.attributeName === "class") {
|
||||
if (
|
||||
mutation.type === "attributes" &&
|
||||
mutation.attributeName === "class"
|
||||
) {
|
||||
const target = mutation.target as HTMLElement;
|
||||
return target.classList.contains("quickbar");
|
||||
}
|
||||
if (mutation.type === "childList") {
|
||||
const target = mutation.target as HTMLElement;
|
||||
return target.classList?.contains("quickbar") || target.closest?.(".quickbar");
|
||||
return (
|
||||
target.classList?.contains("quickbar") ||
|
||||
target.closest?.(".quickbar")
|
||||
);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
@@ -483,11 +528,13 @@ const timetableEditPlugin = {
|
||||
const timetablePage = document.querySelector(".timetablepage");
|
||||
if (timetablePage && !observer) {
|
||||
observer = new MutationObserver(() => {
|
||||
document.querySelectorAll(".timetablepage .entry.class").forEach((entry) => {
|
||||
if (!entry.hasAttribute("data-timetable-edit-processed")) {
|
||||
processEntry(entry as HTMLElement);
|
||||
}
|
||||
});
|
||||
document
|
||||
.querySelectorAll(".timetablepage .entry.class")
|
||||
.forEach((entry) => {
|
||||
if (!entry.hasAttribute("data-timetable-edit-processed")) {
|
||||
processEntry(entry as HTMLElement);
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(timetablePage, { childList: true, subtree: true });
|
||||
}
|
||||
@@ -501,10 +548,14 @@ const timetableEditPlugin = {
|
||||
observer?.disconnect();
|
||||
quickbarObserver?.disconnect();
|
||||
if (quickbarSyncTimer !== null) clearTimeout(quickbarSyncTimer);
|
||||
document.querySelectorAll("[data-timetable-edit-processed]").forEach((el) => {
|
||||
el.removeAttribute("data-timetable-edit-processed");
|
||||
});
|
||||
document.querySelectorAll(".timetable-edit-quickbar-btn").forEach((el) => el.remove());
|
||||
document
|
||||
.querySelectorAll("[data-timetable-edit-processed]")
|
||||
.forEach((el) => {
|
||||
el.removeAttribute("data-timetable-edit-processed");
|
||||
});
|
||||
document
|
||||
.querySelectorAll(".timetable-edit-quickbar-btn")
|
||||
.forEach((el) => el.remove());
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,7 +17,6 @@ import enhancedNavigationPluginLazy from "./built-in/enhancedNavigation/lazy";
|
||||
import globalSearchPluginLazy from "./built-in/globalSearch/lazy";
|
||||
import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy";
|
||||
import errorPageKittenPlugin from "./built-in/errorPageKitten";
|
||||
import aiModCreatorPlugin from "./built-in/aiModCreator";
|
||||
|
||||
// Initialize plugin manager
|
||||
const pluginManager = PluginManager.getInstance();
|
||||
@@ -39,7 +38,6 @@ pluginManager.registerPlugin(enhancedNavigationPluginLazy);
|
||||
pluginManager.registerPlugin(globalSearchPluginLazy);
|
||||
pluginManager.registerPlugin(gradeAnalyticsPluginLazy);
|
||||
pluginManager.registerPlugin(errorPageKittenPlugin);
|
||||
pluginManager.registerPlugin(aiModCreatorPlugin);
|
||||
|
||||
export async function initializePlugins(): Promise<void> {
|
||||
await pluginManager.startAllPlugins();
|
||||
|
||||
@@ -16,6 +16,7 @@ import { updateAllColors } from "./colors/Manager";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
import { LUCIDE_MOON_ICON_SVG } from "@/lib/icons/lucideMoon";
|
||||
import { LUCIDE_SUN_ICON_SVG } from "@/lib/icons/lucideSun";
|
||||
import { ensureTitlebarFounderBadgeMounted, refreshTitlebarFounderBadge } from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge";
|
||||
|
||||
let cachedUserInfo: any = null;
|
||||
let userInfoFetchPromise: Promise<any> | null = null;
|
||||
@@ -181,6 +182,7 @@ async function handleUserInfoAndStudentData() {
|
||||
]);
|
||||
|
||||
updateUserInfo(userInfo);
|
||||
ensureTitlebarFounderBadgeMounted();
|
||||
await updateStudentInfo((await studentResponse.json()).payload, userInfo);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
@@ -227,11 +229,16 @@ function updateUserInfo(info: {
|
||||
stringToHTML(/* html */ `
|
||||
<div class="userInfo">
|
||||
<div class="userInfoText">
|
||||
<div style="display: flex; align-items: center;">
|
||||
<p class="userInfohouse userInfoCode" style="display: none;"></p>
|
||||
${displayName ? `<p class="userInfoName">${displayName}</p>` : ""}
|
||||
<div class="userInfoNameRow">
|
||||
<div class="userInfoHouseWrap">
|
||||
<p class="userInfohouse userInfoCode" style="display: none;"></p>
|
||||
<span class="bsplus-founder-badge-slot" hidden></span>
|
||||
</div>
|
||||
<div class="userInfoDetails">
|
||||
${displayName ? `<p class="userInfoName">${displayName}</p>` : ""}
|
||||
${metadata ? `<p class="userInfoCode">${metadata}</p>` : ""}
|
||||
</div>
|
||||
</div>
|
||||
${metadata ? `<p class="userInfoCode">${metadata}</p>` : ""}
|
||||
</div>
|
||||
</div>
|
||||
`).firstChild!,
|
||||
@@ -277,6 +284,7 @@ async function updateStudentInfo(students: any, info: Awaited<ReturnType<typeof
|
||||
|
||||
houseelement.innerText = text;
|
||||
houseelement.style.display = text ? "block" : "none";
|
||||
refreshTitlebarFounderBadge();
|
||||
}
|
||||
|
||||
function createNewsButton(fragment: DocumentFragment, menu: HTMLElement) {
|
||||
@@ -413,13 +421,20 @@ async function addEngageUserInfo() {
|
||||
stringToHTML(/* html */ `
|
||||
<div class="userInfo">
|
||||
<div class="userInfoText">
|
||||
${displayName ? `<p class="userInfoName">${displayName}</p>` : ""}
|
||||
${subText ? `<p class="userInfoCode">${subText}</p>` : ""}
|
||||
<div class="userInfoNameRow">
|
||||
<span class="bsplus-founder-badge-slot" hidden></span>
|
||||
<div class="userInfoDetails">
|
||||
${displayName ? `<p class="userInfoName">${displayName}</p>` : ""}
|
||||
${subText ? `<p class="userInfoCode">${subText}</p>` : ""}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).firstChild!,
|
||||
);
|
||||
|
||||
ensureTitlebarFounderBadgeMounted();
|
||||
|
||||
const iconNode = stringToHTML(/* html */ `
|
||||
<div class="userInfosvgdiv tooltip" id="engage-logouttooltip-wrap">
|
||||
<svg class="userInfosvg" viewBox="0 0 24 24"><path fill="var(--text-primary)" d="M12,19.2C9.5,19.2 7.29,17.92 6,16C6.03,14 10,12.9 12,12.9C14,12.9 17.97,14 18,16C16.71,17.92 14.5,19.2 12,19.2M12,5A3,3 0 0,1 15,8A3,3 0 0,1 12,11A3,3 0 0,1 9,8A3,3 0 0,1 12,5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12C22,6.47 17.5,2 12,2Z"></path></svg>
|
||||
|
||||
@@ -76,7 +76,7 @@ const contentConfig: ContentConfig = {
|
||||
},
|
||||
},
|
||||
userCode: {
|
||||
selector: ".userInfoText > .userInfoCode",
|
||||
selector: ".userInfoText .userInfoCode",
|
||||
action: (element) => {
|
||||
element.textContent = generateMockUserCode();
|
||||
},
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { refreshCloudUserFromServer } from "@/seqta/utils/cloudPfpSync";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import {
|
||||
founderBadgeChipHtml,
|
||||
pickPrimaryFounderBadge,
|
||||
type FounderBadgeItem,
|
||||
} from "@/seqta/utils/founderBadges";
|
||||
import { openFounderBadgeModal } from "@/seqta/ui/founderBadge/openFounderBadgeModal";
|
||||
|
||||
let subscribed = false;
|
||||
let refreshPending = false;
|
||||
|
||||
function renderBadgeChip(
|
||||
slot: HTMLElement,
|
||||
badge: FounderBadgeItem,
|
||||
signupNumber?: number | null,
|
||||
): void {
|
||||
const house = slot
|
||||
.closest(".userInfoHouseWrap")
|
||||
?.querySelector<HTMLElement>(".userInfohouse");
|
||||
if (house?.style.display === "none") {
|
||||
slot.replaceChildren();
|
||||
slot.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
slot.hidden = false;
|
||||
slot.innerHTML = founderBadgeChipHtml(badge, { titlebar: true });
|
||||
|
||||
const chip = slot.querySelector<HTMLButtonElement>(".bsplus-founder-badge");
|
||||
if (!chip) return;
|
||||
|
||||
chip.setAttribute("aria-label", `${badge.label}, click for details`);
|
||||
chip.addEventListener("click", () => openFounderBadgeModal(badge, signupNumber));
|
||||
}
|
||||
|
||||
async function syncTitlebarFounderBadge(): Promise<void> {
|
||||
const slots = document.querySelectorAll<HTMLElement>(".titlebar .bsplus-founder-badge-slot");
|
||||
for (const slot of slots) {
|
||||
slot.replaceChildren();
|
||||
slot.hidden = true;
|
||||
}
|
||||
|
||||
if (settingsState.showTitlebarFounderBadge === false || !cloudAuth.state.isLoggedIn) return;
|
||||
|
||||
let user = cloudAuth.state.user;
|
||||
if (user && user.signup_number == null && !user.badges?.length) {
|
||||
if (!refreshPending) {
|
||||
refreshPending = true;
|
||||
try {
|
||||
await refreshCloudUserFromServer();
|
||||
user = cloudAuth.state.user;
|
||||
} finally {
|
||||
refreshPending = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const badge = pickPrimaryFounderBadge(user?.badges ?? [], user?.signup_number);
|
||||
if (!badge) return;
|
||||
|
||||
for (const slot of slots) {
|
||||
renderBadgeChip(slot, badge, user?.signup_number);
|
||||
}
|
||||
}
|
||||
|
||||
export function refreshTitlebarFounderBadge(): void {
|
||||
void syncTitlebarFounderBadge();
|
||||
}
|
||||
|
||||
export function ensureTitlebarFounderBadgeMounted(): void {
|
||||
if (!subscribed) {
|
||||
subscribed = true;
|
||||
cloudAuth.subscribe(() => void syncTitlebarFounderBadge());
|
||||
settingsState.register("showTitlebarFounderBadge", () => void syncTitlebarFounderBadge());
|
||||
}
|
||||
void syncTitlebarFounderBadge();
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { closePopup, openPopup } from "@/seqta/utils/Openers/PopupManager";
|
||||
import { openFounderBadgeSettings } from "@/seqta/ui/founderBadge/openFounderBadgeSettings";
|
||||
import {
|
||||
founderBadgeChipHtml,
|
||||
tierBlobStyle,
|
||||
tierForBadgeKey,
|
||||
type FounderBadgeItem,
|
||||
} from "@/seqta/utils/founderBadges";
|
||||
|
||||
const ACCOUNTS_URL = "https://accounts.betterseqta.org";
|
||||
|
||||
function esc(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
export function openFounderBadgeModal(
|
||||
badge: FounderBadgeItem,
|
||||
signupNumber?: number | null,
|
||||
): void {
|
||||
const tier = tierForBadgeKey(badge.key);
|
||||
if (!tier) return;
|
||||
|
||||
const header = stringToHTML(/* html */ `
|
||||
<div class="whatsnewHeader bsplus-founder-badge-header">
|
||||
<h1>${esc(badge.label)}</h1>
|
||||
<p>${esc(tier.rankLabel)}</p>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const signupLine =
|
||||
signupNumber != null
|
||||
? `<p class="bsplus-founder-badge-signup">Cloud user #${signupNumber.toLocaleString()}</p>`
|
||||
: "";
|
||||
|
||||
const hero = stringToHTML(/* html */ `
|
||||
<div class="whatsnewImgContainer">
|
||||
<div class="bsplus-founder-badge-hero whatsnewImg" data-tier="${badge.key}" style="${tierBlobStyle(tier)}">
|
||||
<div class="bsplus-founder-badge-hero__blobs" aria-hidden="true"></div>
|
||||
<div class="bsplus-founder-badge-hero__vignette" aria-hidden="true"></div>
|
||||
<div class="bsplus-founder-badge-hero__stage">
|
||||
${founderBadgeChipHtml(badge, { hero: true })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const text = stringToHTML(/* html */ `
|
||||
<div class="whatsnewTextContainer bsplus-founder-badge-body" style="overflow-y: auto;">
|
||||
<p>${esc(tier.description)}</p>
|
||||
<p>
|
||||
Linked to your BetterSEQTA Cloud account at
|
||||
<a href="${ACCOUNTS_URL}" target="_blank" rel="noopener noreferrer">accounts.betterseqta.org</a>.
|
||||
</p>
|
||||
${signupLine}
|
||||
<div class="bsplus-founder-badge-actions">
|
||||
<button type="button" id="bsplus-founder-badge-settings-link" class="bsplus-cal-btn bsplus-cal-btn--ghost">
|
||||
Hide in settings
|
||||
</button>
|
||||
<button type="button" id="bsplus-founder-badge-dismiss" class="bsplus-cal-btn bsplus-cal-btn--primary">
|
||||
Got it
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: [hero, text],
|
||||
animateSelector: ".whatsnewImgContainer, .whatsnewTextContainer *",
|
||||
actions: [
|
||||
{ id: "bsplus-founder-badge-dismiss", onClick: () => closePopup() },
|
||||
{
|
||||
id: "bsplus-founder-badge-settings-link",
|
||||
onClick: () => void closePopup().then(() => openFounderBadgeSettings()),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
|
||||
import { openSettingsPopup } from "@/seqta/utils/setupSettingsButton";
|
||||
|
||||
const FOUNDER_BADGE_SETTING_SEARCH = "Titlebar founder badge";
|
||||
|
||||
/** Open BetterSEQTA+ settings on the titlebar founder badge toggle. */
|
||||
export async function openFounderBadgeSettings(): Promise<void> {
|
||||
requestSettingsDestination({
|
||||
page: "settings",
|
||||
section: "account",
|
||||
search: FOUNDER_BADGE_SETTING_SEARCH,
|
||||
});
|
||||
await openSettingsPopup();
|
||||
}
|
||||
|
||||
export { FOUNDER_BADGE_SETTING_SEARCH };
|
||||
@@ -120,11 +120,10 @@ function onCustomSidebarCaptureClick(event: MouseEvent) {
|
||||
const li = target.closest("li.item[data-key]");
|
||||
if (!(li instanceof HTMLElement) || !root.contains(li)) return;
|
||||
|
||||
// Open folder header row only — leaf clicks inside `.sub` must still navigate.
|
||||
// Already-open folder chrome (renders its own `.sub`) — ignore; use Back.
|
||||
if (
|
||||
li.classList.contains("hasChildren") &&
|
||||
li.querySelector(":scope > .sub") &&
|
||||
!target.closest(".sub")
|
||||
li.querySelector(":scope > .sub")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -37,6 +37,12 @@ function filterVisible(items: SidebarItem[]): SidebarItem[] {
|
||||
return items.filter((item) => menuItems[item.key]?.toggle !== false);
|
||||
}
|
||||
|
||||
function ensureActive(el: Element | null | undefined) {
|
||||
if (el instanceof HTMLElement && !el.classList.contains("active")) {
|
||||
el.classList.add("active");
|
||||
}
|
||||
}
|
||||
|
||||
function resetSidebarScroll() {
|
||||
const root = document.getElementById("bsplus-sidebar-root");
|
||||
if (!(root instanceof HTMLElement)) return;
|
||||
@@ -46,6 +52,48 @@ function resetSidebarScroll() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* SEQTA strips `.active` from menu items after navigation. Restore the custom list
|
||||
* state so the active subject/folder still matches the route and theme chrome.
|
||||
*/
|
||||
export function restoreCustomMenuActive() {
|
||||
const root = document.getElementById("bsplus-sidebar-root");
|
||||
if (!root) return;
|
||||
|
||||
for (const li of root.querySelectorAll("li.hasChildren")) {
|
||||
if (!(li instanceof HTMLElement)) continue;
|
||||
if (!li.querySelector(":scope > .sub")) continue;
|
||||
ensureActive(li);
|
||||
}
|
||||
|
||||
const activeKey = sidebarState.activeKey;
|
||||
const drilling = sidebarState.isDrilling;
|
||||
|
||||
if (drilling) {
|
||||
if (activeKey) {
|
||||
ensureActive(
|
||||
root.querySelector(`.sub li.item[data-key="${CSS.escape(activeKey)}"]`),
|
||||
);
|
||||
}
|
||||
for (const li of root.querySelectorAll(
|
||||
'.sub li.item[aria-current="page"]',
|
||||
)) {
|
||||
ensureActive(li);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeKey) {
|
||||
ensureActive(
|
||||
root.querySelector(`li.item[data-key="${CSS.escape(activeKey)}"]`),
|
||||
);
|
||||
}
|
||||
|
||||
for (const li of root.querySelectorAll('li.item[aria-current="page"]')) {
|
||||
ensureActive(li);
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear native drill state so it cannot steal pointer-events from the custom list. */
|
||||
export function clearNativeDrillActive(menu: HTMLElement) {
|
||||
getNativeMenuList(menu)
|
||||
@@ -224,7 +272,9 @@ class SidebarState {
|
||||
label: item.label,
|
||||
items: filterVisible(item.children),
|
||||
};
|
||||
const isRoot = this.visibleRootItems.some((entry) => entry.key === item.key);
|
||||
const isRoot = this.visibleRootItems.some(
|
||||
(entry) => entry.key === item.key,
|
||||
);
|
||||
|
||||
this.enterFrameKey = item.key;
|
||||
// Root folders replace the stack; nested folders append.
|
||||
@@ -326,22 +376,12 @@ class SidebarState {
|
||||
// SEQTA rewrites `.active` on the route change.
|
||||
if (this.isDrilling) {
|
||||
this.enterFrameKey = null;
|
||||
clearNativeDrillActive(menu);
|
||||
restoreCustomMenuActive();
|
||||
}
|
||||
|
||||
const native = findNativeMenuEntry(menu, item);
|
||||
if (native) {
|
||||
native.click();
|
||||
// Inside a drill panel, SEQTA native rows may no-op if their folder is not
|
||||
// `.active` — fall back to hash routing for standard (non-BS+) pages only.
|
||||
if (
|
||||
this.isDrilling &&
|
||||
item.path &&
|
||||
!item.betterseqta &&
|
||||
getPagePathFromHash() !== item.path
|
||||
) {
|
||||
location.hash = `?page=${item.path}`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ const STORAGE_KEYS = {
|
||||
user: "bsplus_user",
|
||||
} as const;
|
||||
|
||||
export type CloudBadge = {
|
||||
key: string;
|
||||
label: string;
|
||||
awarded_at?: number;
|
||||
};
|
||||
|
||||
export type CloudUser = {
|
||||
id: string;
|
||||
email?: string;
|
||||
@@ -20,6 +26,9 @@ export type CloudUser = {
|
||||
pfpUrl?: string;
|
||||
pfpHash?: string | null;
|
||||
admin_level?: number;
|
||||
signup_number?: number | null;
|
||||
badges?: CloudBadge[];
|
||||
is_founding_2500?: boolean;
|
||||
};
|
||||
|
||||
export type CloudAuthState = {
|
||||
|
||||
@@ -3,8 +3,20 @@ import { animate as motionAnimate, stagger } from "motion";
|
||||
|
||||
type AnimationTarget = string | Element | Element[] | NodeList | null;
|
||||
|
||||
export interface PopupRoot {
|
||||
background: HTMLElement;
|
||||
container: HTMLElement;
|
||||
}
|
||||
|
||||
export interface PopupAction {
|
||||
/** Element id inside popup content (e.g. button#bsplus-founder-badge-settings-link). */
|
||||
id: string;
|
||||
onClick: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
let isClosing = false;
|
||||
let pendingAfterClose: (() => void) | undefined;
|
||||
let escapeListener: ((event: KeyboardEvent) => void) | null = null;
|
||||
|
||||
function invokeAfterClose() {
|
||||
const fn = pendingAfterClose;
|
||||
@@ -12,9 +24,24 @@ function invokeAfterClose() {
|
||||
fn?.();
|
||||
}
|
||||
|
||||
function detachEscapeListener() {
|
||||
if (!escapeListener) return;
|
||||
document.removeEventListener("keydown", escapeListener);
|
||||
escapeListener = null;
|
||||
}
|
||||
|
||||
function attachEscapeListener() {
|
||||
detachEscapeListener();
|
||||
escapeListener = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") void closePopup();
|
||||
};
|
||||
document.addEventListener("keydown", escapeListener);
|
||||
}
|
||||
|
||||
export async function closePopup() {
|
||||
if (isClosing) return;
|
||||
isClosing = true;
|
||||
detachEscapeListener();
|
||||
|
||||
const background = document.getElementById("whatsnewbk");
|
||||
const popup = document.getElementsByClassName("whatsnewContainer")[0] as
|
||||
@@ -47,6 +74,7 @@ export async function closePopup() {
|
||||
|
||||
interface OpenPopupOptions {
|
||||
header?: Node | null;
|
||||
hero?: Node | null;
|
||||
content?: (Node | null | undefined)[];
|
||||
animateSelector?: AnimationTarget;
|
||||
/** Called once after this popup is fully closed (including skip-animation path). */
|
||||
@@ -55,6 +83,12 @@ interface OpenPopupOptions {
|
||||
clearJustUpdated?: boolean;
|
||||
/** Extra classes on `.whatsnewContainer` (e.g. `whatsnewContainer--scrollBody`). */
|
||||
containerClass?: string;
|
||||
/** Extra classes on `.whatsnewBackground` (e.g. frosted backdrop). */
|
||||
backgroundClass?: string;
|
||||
/** Wire click handlers for buttons/links by element id (deep links, dismiss, etc.). */
|
||||
actions?: PopupAction[];
|
||||
/** Called after the popup DOM is mounted — use for one-off setup when actions are not enough. */
|
||||
onReady?: (root: PopupRoot) => void;
|
||||
}
|
||||
|
||||
function chainAfterClose(next?: () => void) {
|
||||
@@ -66,13 +100,35 @@ function chainAfterClose(next?: () => void) {
|
||||
};
|
||||
}
|
||||
|
||||
function applyClassList(element: HTMLElement, classNames?: string) {
|
||||
if (!classNames) return;
|
||||
for (const name of classNames.split(/\s+/)) {
|
||||
if (name) element.classList.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
function wirePopupActions(actions?: PopupAction[]) {
|
||||
if (!actions?.length) return;
|
||||
queueMicrotask(() => {
|
||||
for (const action of actions) {
|
||||
document.getElementById(action.id)?.addEventListener("click", () => {
|
||||
void Promise.resolve(action.onClick());
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function openPopup({
|
||||
header,
|
||||
hero,
|
||||
content = [],
|
||||
animateSelector = ".whatsnewTextContainer *",
|
||||
afterClose,
|
||||
clearJustUpdated = false,
|
||||
containerClass,
|
||||
backgroundClass,
|
||||
actions,
|
||||
onReady,
|
||||
}: OpenPopupOptions = {}) {
|
||||
if (document.getElementById("whatsnewbk")) {
|
||||
chainAfterClose(afterClose);
|
||||
@@ -84,15 +140,13 @@ export function openPopup({
|
||||
const background = document.createElement("div");
|
||||
background.id = "whatsnewbk";
|
||||
background.classList.add("whatsnewBackground");
|
||||
applyClassList(background, backgroundClass);
|
||||
|
||||
const container = document.createElement("div");
|
||||
container.classList.add("whatsnewContainer");
|
||||
if (containerClass) {
|
||||
for (const name of containerClass.split(/\s+/)) {
|
||||
if (name) container.classList.add(name);
|
||||
}
|
||||
}
|
||||
applyClassList(container, containerClass);
|
||||
|
||||
if (hero) container.append(hero);
|
||||
if (header) container.append(header);
|
||||
for (const node of content) if (node) container.append(node);
|
||||
|
||||
@@ -139,4 +193,7 @@ export function openPopup({
|
||||
});
|
||||
|
||||
closeButton.addEventListener("click", () => void closePopup());
|
||||
attachEscapeListener();
|
||||
wirePopupActions(actions);
|
||||
onReady?.({ background, container });
|
||||
}
|
||||
@@ -11,10 +11,13 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
"Added an option in the Timetable to sync to Google Calendar and Outlook Calendar",
|
||||
"Added a new sidebar customisation page in the settings menu to change the sidebar layout, icons, and more.",
|
||||
"Added extension feedback in settings.",
|
||||
"Added a new toggleable titlebar founder badge to the topbar for BetterSEQTA Cloud celebrations.",
|
||||
"Addded Editing a teacher's name in the timetable editor now affect Assements.",
|
||||
"Added a 'this year' & custom date range option to grade analyitics.",
|
||||
"Removed white background around SEQTA Learn mobile App icons in settings.",
|
||||
"Re-added the kitten back to the 404 Error pages.",
|
||||
"Improved the sidebar to be more stable and performant.",
|
||||
"Fixed some issues related to HTML Sanitisation.",
|
||||
"Fixed Analytics page not respecting no animations setting. (#474)",
|
||||
"Fixed dropdown contrast and readability in settings and across SEQTA pages.",
|
||||
"Fixed Analytics sidebar item not hiding when toggled off in Edit Sidebar.",
|
||||
|
||||
@@ -72,6 +72,9 @@ function mergeMeIntoUser(current: CloudUser, data: Record<string, unknown>): Clo
|
||||
username: (raw.username as string | undefined) ?? current.username,
|
||||
displayName: (raw.displayName as string | undefined) ?? current.displayName,
|
||||
admin_level: (raw.admin_level as number | undefined) ?? current.admin_level,
|
||||
signup_number: (raw.signup_number as number | null | undefined) ?? current.signup_number,
|
||||
badges: (raw.badges as CloudUser["badges"]) ?? current.badges,
|
||||
is_founding_2500: (raw.is_founding_2500 as boolean | undefined) ?? current.is_founding_2500,
|
||||
pfpUrl,
|
||||
pfpHash,
|
||||
};
|
||||
|
||||
@@ -74,6 +74,7 @@ export function getDefaultSettingsState(): SettingsState {
|
||||
adaptiveThemeColourTransition: true,
|
||||
themeOfTheMonthDisabled: false,
|
||||
autoCloudSettingsSync: true,
|
||||
showTitlebarFounderBadge: true,
|
||||
selectedFont: "rubik",
|
||||
timeFormat: "24",
|
||||
privacyStatementShown: false,
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
/** Founder badge tiers — keep in sync with betterseqta-accounts/utils/badges.ts */
|
||||
|
||||
export const BADGE_TIERS = [
|
||||
{
|
||||
key: "founder_10",
|
||||
label: "Pioneer",
|
||||
threshold: 10,
|
||||
rankLabel: "Top 10",
|
||||
description: "One of the first 10 people to create a BetterSEQTA Cloud account.",
|
||||
base: "#78350f",
|
||||
blobs: ["rgba(251,191,36,0.58)", "rgba(234,88,12,0.48)", "rgba(254,243,199,0.42)"],
|
||||
icon: "sparkles",
|
||||
},
|
||||
{
|
||||
key: "founder_25",
|
||||
label: "Early Adopter",
|
||||
threshold: 25,
|
||||
rankLabel: "Top 25",
|
||||
description: "One of the first 25 people to join BetterSEQTA Cloud.",
|
||||
base: "#1e3a8a",
|
||||
blobs: ["rgba(79,70,229,0.52)", "rgba(37,99,235,0.46)", "rgba(129,140,248,0.38)"],
|
||||
icon: "sparkles",
|
||||
},
|
||||
{
|
||||
key: "founder_50",
|
||||
label: "Founding Member",
|
||||
threshold: 50,
|
||||
rankLabel: "Top 50",
|
||||
description: "One of the first 50 Cloud members, early supporter of BetterSEQTA.",
|
||||
base: "#0c4a6e",
|
||||
blobs: ["rgba(2,132,199,0.5)", "rgba(13,148,136,0.44)", "rgba(56,189,248,0.36)"],
|
||||
icon: "star",
|
||||
},
|
||||
{
|
||||
key: "founder_100",
|
||||
label: "Centurion",
|
||||
threshold: 100,
|
||||
rankLabel: "Top 100",
|
||||
description: "Among the first 100 BetterSEQTA Cloud accounts ever created.",
|
||||
base: "#064e3b",
|
||||
blobs: ["rgba(5,150,105,0.5)", "rgba(22,163,74,0.44)", "rgba(52,211,153,0.36)"],
|
||||
icon: "star",
|
||||
},
|
||||
{
|
||||
key: "founder_250",
|
||||
label: "Quarter Thousand",
|
||||
threshold: 250,
|
||||
rankLabel: "Top 250",
|
||||
description: "One of the first 250 people to sign up for BetterSEQTA Cloud.",
|
||||
base: "#7c2d12",
|
||||
blobs: ["rgba(217,119,6,0.52)", "rgba(234,88,12,0.46)", "rgba(251,191,36,0.38)"],
|
||||
icon: "trophy",
|
||||
},
|
||||
{
|
||||
key: "founder_500",
|
||||
label: "Half Thousand",
|
||||
threshold: 500,
|
||||
rankLabel: "Top 500",
|
||||
description: "Among the first 500 BetterSEQTA Cloud members.",
|
||||
base: "#7c2d12",
|
||||
blobs: ["rgba(234,88,12,0.52)", "rgba(249,115,22,0.46)", "rgba(251,146,60,0.38)"],
|
||||
icon: "trophy",
|
||||
},
|
||||
{
|
||||
key: "founder_1000",
|
||||
label: "Thousand Club",
|
||||
threshold: 1000,
|
||||
rankLabel: "Top 1,000",
|
||||
description: "One of the first 1,000 BetterSEQTA Cloud accounts.",
|
||||
base: "#881337",
|
||||
blobs: ["rgba(225,29,72,0.5)", "rgba(219,39,119,0.44)", "rgba(251,113,133,0.36)"],
|
||||
icon: "fire",
|
||||
},
|
||||
{
|
||||
key: "founder_2500",
|
||||
label: "Founding Cloud",
|
||||
threshold: 2500,
|
||||
rankLabel: "Top 2,500",
|
||||
description: "One of the first 2,500 Cloud members.",
|
||||
base: "#713f12",
|
||||
blobs: ["rgba(245,158,11,0.52)", "rgba(234,179,8,0.46)", "rgba(252,211,77,0.4)"],
|
||||
icon: "fire",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type BadgeKey = (typeof BADGE_TIERS)[number]["key"];
|
||||
|
||||
export type FounderBadgeItem = {
|
||||
key: string;
|
||||
label: string;
|
||||
awarded_at?: number;
|
||||
};
|
||||
|
||||
const TIER_BY_KEY = new Map(BADGE_TIERS.map((t) => [t.key, t]));
|
||||
|
||||
export function tierForBadgeKey(key: string) {
|
||||
return TIER_BY_KEY.get(key as BadgeKey);
|
||||
}
|
||||
|
||||
export function primaryFounderBadgeKey(signupNumber: number): BadgeKey | null {
|
||||
const tier = BADGE_TIERS.find((t) => signupNumber <= t.threshold);
|
||||
return tier?.key ?? null;
|
||||
}
|
||||
|
||||
export function pickPrimaryFounderBadge(
|
||||
badges: FounderBadgeItem[],
|
||||
signupNumber?: number | null,
|
||||
): FounderBadgeItem | null {
|
||||
if (signupNumber != null) {
|
||||
const key = primaryFounderBadgeKey(signupNumber);
|
||||
if (!key) return null;
|
||||
return badges.find((b) => b.key === key) ?? { key, label: TIER_BY_KEY.get(key)?.label ?? key };
|
||||
}
|
||||
|
||||
if (badges.length === 0) return null;
|
||||
|
||||
let best: FounderBadgeItem | null = null;
|
||||
let bestThreshold = Infinity;
|
||||
for (const badge of badges) {
|
||||
const tier = TIER_BY_KEY.get(badge.key as BadgeKey);
|
||||
if (tier && tier.threshold < bestThreshold) {
|
||||
bestThreshold = tier.threshold;
|
||||
best = badge;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
const ICON_PATHS: Record<string, string> = {
|
||||
sparkles:
|
||||
"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z",
|
||||
star: "M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005z",
|
||||
trophy:
|
||||
"M16.5 18.75h-9m9 0a3 3 0 013 3h-15a3 3 0 013-3m9 0v-3.375c0-.621-.503-1.125-1.125-1.125h-.871M7.5 18.75v-3.375c0-.621.504-1.125 1.125-1.125h.872m5.007 0H9.497m5.007 0a7.454 7.454 0 01-.982-3.172M9.497 14.25a7.454 7.454 0 00.981-3.172M5.25 4.236c-.982.143-1.954.317-2.916.52A6.003 6.003 0 007.73 9.728M5.25 4.236V4.5c0 2.108.966 3.99 2.48 5.228M5.25 4.236V2.721C7.456 2.41 9.71 2.25 12 2.25c2.291 0 4.545.16 6.75.47v1.516M7.73 9.728a6.726 6.726 0 002.748 1.35m8.272-6.842V4.5c0 2.108-.966 3.99-2.48 5.228m2.48-5.492a46.32 46.32 0 012.916.52 6.003 6.003 0 01-5.395 4.972m0 0a6.726 6.726 0 01-2.749 1.35m0 0a6.726 6.726 0 01-3.128 0m3.128 0a6.726 6.726 0 01-3.128 0",
|
||||
fire: "M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48zM12 18a3.75 3.75 0 00.495-7.467 5.99 5.99 0 00-1.925 3.546 5.974 5.974 0 01-2.133-1A3.75 3.75 0 0012 18z",
|
||||
};
|
||||
|
||||
export function badgeIconSvg(icon: string, size = 15): string {
|
||||
const path = ICON_PATHS[icon] ?? ICON_PATHS.sparkles;
|
||||
return `<svg class="bsplus-founder-badge__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="${size}" height="${size}" aria-hidden="true"><path d="${path}"/></svg>`;
|
||||
}
|
||||
|
||||
export function tierBlobStyle(tier: (typeof BADGE_TIERS)[number]): string {
|
||||
return [
|
||||
`--badge-base:${tier.base}`,
|
||||
`--badge-blob-a:${tier.blobs[0]}`,
|
||||
`--badge-blob-b:${tier.blobs[1]}`,
|
||||
`--badge-blob-c:${tier.blobs[2]}`,
|
||||
].join(";");
|
||||
}
|
||||
|
||||
export function founderBadgeChipHtml(
|
||||
badge: FounderBadgeItem,
|
||||
options?: { hero?: boolean; titlebar?: boolean },
|
||||
): string {
|
||||
const tier = tierForBadgeKey(badge.key);
|
||||
if (!tier) return "";
|
||||
|
||||
const hero = options?.hero ?? false;
|
||||
const titlebar = options?.titlebar ?? false;
|
||||
const mods = `${hero ? " bsplus-founder-badge--hero" : ""}${titlebar ? " bsplus-founder-badge--titlebar" : ""}`;
|
||||
const icon = titlebar ? "" : badgeIconSvg(tier.icon, hero ? 20 : 15);
|
||||
|
||||
return `<button type="button" class="bsplus-founder-badge${mods}" data-tier="${badge.key}" style="${tierBlobStyle(tier)}"><span class="bsplus-founder-badge__glass"><span class="bsplus-founder-badge__blobs" aria-hidden="true"></span><span class="bsplus-founder-badge__content">${icon}<span class="bsplus-founder-badge__label">${badge.label}</span></span></span></button>`;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
export type SettingsDestination =
|
||||
| { page: "settings"; section?: string }
|
||||
| { page: "settings"; section?: string; search?: string }
|
||||
| { page: "themes" | "backgrounds"; view?: "settings" | "store" };
|
||||
|
||||
export const SETTINGS_NAVIGATION_EVENT = "bsplus:navigate-settings";
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import stringToHTML from "./stringToHTML";
|
||||
|
||||
describe("stringToHTML", () => {
|
||||
it("preserves inline onclick handlers used by lesson action buttons", () => {
|
||||
const body = stringToHTML(
|
||||
`<div class="day-button clickable" onclick="location.href='../#?page=/courses/123:456'">Go</div>`,
|
||||
);
|
||||
|
||||
const el = body.firstElementChild as HTMLElement | null;
|
||||
expect(el).not.toBeNull();
|
||||
expect(el?.getAttribute("onclick")).toContain("location.href");
|
||||
});
|
||||
});
|
||||
@@ -16,8 +16,9 @@ export default function stringToHTML(str: string, styles = false) {
|
||||
const parser = new DOMParser();
|
||||
|
||||
str = DOMPurify.sanitize(str, {
|
||||
ADD_ATTR: ["onclick"],
|
||||
ALLOWED_URI_REGEXP:
|
||||
/^(?:(?:https?|mailto|tel):|\/|#|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
|
||||
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chrome-extension):|\/|#|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
|
||||
});
|
||||
|
||||
const doc = parser.parseFromString(str, "text/html");
|
||||
|
||||
@@ -96,6 +96,8 @@ export interface SettingsState {
|
||||
// BetterSEQTA Cloud (accounts.betterseqta.org) — stored via CloudAuth, not settingsState
|
||||
/** When not `false`, automatic cloud settings sync is enabled (default-on). */
|
||||
autoCloudSettingsSync?: boolean;
|
||||
/** When not `false`, show the Cloud founder badge in the SEQTA titlebar (default-on). */
|
||||
showTitlebarFounderBadge?: boolean;
|
||||
}
|
||||
|
||||
interface ToggleItem {
|
||||
|
||||
Reference in new issue
Block a user