match
Some checks failed
build / Build (push) Failing after 6s
test / Run tests (push) Failing after 8s

This commit is contained in:
2025-04-01 18:04:30 +08:00
parent db8c5ec7b5
commit 20124be0e4
10 changed files with 162 additions and 65 deletions

View File

@ -1,7 +1,7 @@
import LoggerCore from "@App/app/logger/core";
import Logger from "@App/app/logger/logger";
import { Script, ScriptDAO } from "@App/app/repo/scripts";
import { Group, MessageConnect, MessageSend, MessageSender } from "@Packages/message/server";
import { GetSender, Group, MessageConnect, MessageSend, MessageSender } from "@Packages/message/server";
import { ValueService } from "@App/app/service/service_worker/value";
import PermissionVerify from "./permission_verify";
import { connect } from "@Packages/message/client";
@ -40,7 +40,7 @@ export default class GMApi {
this.logger = LoggerCore.logger().with({ service: "runtime/gm_api" });
}
async handlerRequest(data: MessageRequest, con: MessageConnect | null) {
async handlerRequest(data: MessageRequest, con: GetSender) {
this.logger.trace("GM API request", { api: data.api, uuid: data.uuid, param: data.params });
const api = PermissionVerify.apis.get(data.api);
if (!api) {
@ -53,7 +53,7 @@ export default class GMApi {
this.logger.error("verify error", { api: data.api }, Logger.E(e));
return Promise.reject(e);
}
return api.api.call(this, req, con);
return api.api.call(this, req, con.getConnect());
}
// 解析请求

View File

@ -1,15 +1,16 @@
import { MessageQueue } from "@Packages/message/message_queue";
import { Group, MessageSend } from "@Packages/message/server";
import { GetSender, Group, MessageSend } from "@Packages/message/server";
import { Script, SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL, ScriptDAO, ScriptRunResouce } from "@App/app/repo/scripts";
import { ValueService } from "./value";
import GMApi from "./gm_api";
import { subscribeScriptDelete, subscribeScriptEnable, subscribeScriptInstall } from "../queue";
import { ScriptService } from "./script";
import { runScript, stopScript } from "../offscreen/client";
import { dealMatches, getRunAt } from "./utils";
import { getRunAt } from "./utils";
import { randomString } from "@App/pkg/utils/utils";
import { compileInjectScript, compileScriptCode } from "@App/runtime/content/utils";
import Cache from "@App/app/cache";
import { dealMatches } from "@App/pkg/utils/match";
export class RuntimeService {
scriptDAO: ScriptDAO = new ScriptDAO();
@ -99,7 +100,10 @@ export class RuntimeService {
this.group.on("pageLoad", this.pageLoad.bind(this));
}
pageLoad() {
pageLoad(_, sender: GetSender) {
const chromeSender = sender.getSender() as chrome.runtime.MessageSender;
// 匹配当前页面的脚本
return Promise.resolve({ flag: this.scriptFlag });
}
@ -119,25 +123,41 @@ export class RuntimeService {
}
registerInjectScript() {
fetch("inject.js")
.then((res) => res.text())
.then((injectJs) => {
// 替换ScriptFlag
const code = `(function (ScriptFlag) {\n${injectJs}\n})('${this.scriptFlag}')`;
chrome.userScripts.register([
chrome.userScripts.getScripts({ ids: ["scriptcat-inject"] }).then((res) => {
if (res.length == 0) {
fetch("inject.js")
.then((res) => res.text())
.then((injectJs) => {
// 替换ScriptFlag
const code = `(function (ScriptFlag) {\n${injectJs}\n})('${this.scriptFlag}')`;
chrome.userScripts.register([
{
id: "scriptcat-inject",
js: [{ code }],
matches: ["<all_urls>"],
allFrames: true,
world: "MAIN",
runAt: "document_start",
},
]);
});
chrome.scripting.registerContentScripts([
{
id: "scriptcat-inject",
js: [{ code }],
id: "scriptcat-content",
js: ["src/content.js"],
matches: ["<all_urls>"],
allFrames: true,
world: "MAIN",
runAt: "document_start",
},
]);
});
}
});
}
async registryPageScript(script: Script) {
if (await Cache.getInstance().has("registryScript:" + script.uuid)) {
return;
}
const matches = script.metadata["match"];
if (!matches) {
return;
@ -167,12 +187,21 @@ export class RuntimeService {
if (script.metadata["run-at"]) {
registerScript.runAt = getRunAt(script.metadata["run-at"]);
}
chrome.userScripts.register([registerScript]);
chrome.userScripts.register([registerScript], () => {
Cache.getInstance().set("registryScript:" + script.uuid, true);
});
// 标记为已注册
}
unregistryPageScript(script: Script) {
chrome.userScripts.unregister({
ids: [script.uuid],
});
chrome.userScripts.unregister(
{
ids: [script.uuid],
},
() => {
// 删除缓存
Cache.getInstance().del("registryScript:" + script.uuid);
}
);
}
}

View File

@ -5,11 +5,6 @@ export function isExtensionRequest(details: chrome.webRequest.ResourceRequest &
);
}
// 处理油猴的match和include为chrome的matches
export function dealMatches(matches: string[]) {
return matches;
}
export function getRunAt(runAts: string[]): chrome.userScripts.RunAt {
if (runAts.length === 0) {
return "document_idle";

View File

@ -17,18 +17,6 @@
"128": "assets/logo.png"
}
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"src/content.js"
],
"run_at": "document_start",
"all_frames": true
}
],
"icons": {
"128": "assets/logo.png"
},

View File

@ -0,0 +1,11 @@
import { describe, it } from "vitest";
import { dealMatches, parseURL } from "./match";
// https://developer.chrome.com/docs/extensions/mv3/match_patterns/
describe("dealMatches", () => {
it("*://link.17173.com*", () => {
const url = parseURL("*://link.17173.com*");
const matches = dealMatches(["*://link.17173.com*"]);
console.log(url, matches);
});
});

52
src/pkg/utils/match.ts Normal file
View File

@ -0,0 +1,52 @@
export interface Url {
scheme: string;
host: string;
path: string;
search: string;
}
// 根据https://developer.chrome.com/docs/extensions/develop/concepts/match-patterns?hl=zh-cn进行匹配
export class Match {}
export function parseURL(url: string): Url | undefined {
const match = /^(.+?):\/\/(.*?)((\/.*?)(\?.*?|)|)$/.exec(url);
if (match) {
return {
scheme: match[1],
host: match[2],
path: match[4] || (url[url.length - 1] === "*" ? "*" : "/"),
search: match[5],
};
}
// 处理一些特殊情况
switch (url) {
case "*":
return {
scheme: "*",
host: "*",
path: "*",
search: "*",
};
default:
}
return undefined;
}
// 处理油猴的match和include为chrome的matches
export function dealMatches(matches: string[]) {
const result: string[] = [];
for (let i = 0; i < matches.length; i++) {
const url = parseURL(matches[i]);
if (url) {
// *开头但是不是*.的情况
if (url.host.startsWith("*")) {
if (!url.host.startsWith("*.")) {
// 删除开头的*号
url.host = url.host.slice(1);
}
}
result.push(`${url.scheme}://${url.host}${url.path}` + (url.search ? "?" + url.search : ""));
}
}
return result;
}

View File

@ -217,13 +217,3 @@ export function sleep(time: number) {
setTimeout(resolve, time);
});
}
// 使service_worker长时间存活
export async function waitUntil(promise: Promise<any>) {
const keepAlive = setInterval(chrome.runtime.getPlatformInfo, 25 * 1000);
try {
await promise;
} finally {
clearInterval(keepAlive);
}
}