-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathscripts.ts
More file actions
425 lines (379 loc) · 14.8 KB
/
scripts.ts
File metadata and controls
425 lines (379 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import { Repo } from "./repo";
import type { Resource } from "./resource";
import type { SCMetadata } from "./metadata";
import type { GMInfoEnv } from "../service/content/types";
import type { URLRuleEntry } from "@App/pkg/utils/url_matcher";
// 脚本模型
export type SCRIPT_TYPE = 1 | 2 | 3;
export const SCRIPT_TYPE_NORMAL: SCRIPT_TYPE = 1;
export const SCRIPT_TYPE_CRONTAB: SCRIPT_TYPE = 2;
export const SCRIPT_TYPE_BACKGROUND: SCRIPT_TYPE = 3;
export type SCRIPT_STATUS = 1 | 2;
export const SCRIPT_STATUS_ENABLE: SCRIPT_STATUS = 1;
export const SCRIPT_STATUS_DISABLE: SCRIPT_STATUS = 2;
export type SCRIPT_RUN_STATUS = "running" | "complete" | "error";
export const SCRIPT_RUN_STATUS_RUNNING: SCRIPT_RUN_STATUS = "running";
export const SCRIPT_RUN_STATUS_COMPLETE: SCRIPT_RUN_STATUS = "complete";
export const SCRIPT_RUN_STATUS_ERROR: SCRIPT_RUN_STATUS = "error";
export { SCMetadata };
export type ConfigType = "text" | "checkbox" | "select" | "mult-select" | "number" | "textarea" | "switch";
export interface Config {
[key: string]: any;
title: string;
description: string;
default?: any;
type?: ConfigType;
bind?: string;
values?: any[];
password?: boolean;
// 文本类型时是字符串长度,数字类型时是最大值
max?: number;
min?: number;
rows?: number; // textarea行数
index: number; // 配置项排序位置
}
export interface ConfigGroup {
[key: string]: Config;
}
export type UserConfig = Partial<
Record<string, ConfigGroup> & {
"#options": { sort: string[] };
}
>;
// 排除掉 #options
export type UserConfigWithoutOptions = Omit<{ [key: string]: ConfigGroup }, "#options">;
export interface Script {
uuid: string; // 脚本uuid,通过脚本uuid识别唯一脚本
name: string; // 脚本名称
namespace: string; // 脚本命名空间
author?: string; // 脚本作者
originDomain?: string; // 脚本来源域名
origin?: string; // 脚本来源
checkUpdate?: boolean; // 是否检查更新
checkUpdateUrl?: string; // 检查更新URL
downloadUrl?: string; // 脚本下载URL
metadata: SCMetadata; // 脚本的元数据
selfMetadata?: SCMetadata; // 自定义脚本元数据
subscribeUrl?: string; // 如果是通过订阅脚本安装的话,会有订阅地址
config?: UserConfig; // 通过UserConfig定义的用户配置
type: SCRIPT_TYPE; // 脚本类型 1:普通脚本 2:定时脚本 3:后台脚本
status: SCRIPT_STATUS; // 脚本状态 1:启用 2:禁用 3:错误 4:初始化
sort: number; // 脚本顺序位置
runStatus: SCRIPT_RUN_STATUS; // 脚本运行状态,后台脚本才会有此状态 running:运行中 complete:完成 error:错误 retry:重试
error?: { error: string } | string; // 运行错误信息
createtime: number; // 脚本创建时间戳
updatetime?: number; // 脚本更新时间戳
checktime: number; // 脚本检查更新时间戳
lastruntime?: number; // 脚本最后一次运行时间戳
nextruntime?: number; // 脚本下一次运行时间戳
ignoreVersion?: string; // 忽略单一版本的更新检查
}
// 分开存储脚本代码
export interface ScriptCode {
uuid: string;
code: string; // 脚本执行代码
}
export interface ScriptSite {
[uuid: string]: string[] | undefined;
}
export type ScriptAndCode = Script & ScriptCode;
export type ValueStore = { [key: string]: any };
// 脚本运行时的资源,包含已经编译好的脚本与脚本需要的资源
export interface ScriptRunResource extends Script {
code: string; // 原始代码
value: ValueStore;
flag: string;
resource: { [key: string]: { base64?: string } & Omit<Resource, "base64"> }; // 资源列表,包含脚本需要的资源
metadata: SCMetadata; // 经自定义覆盖的 Metadata
originalMetadata: SCMetadata; // 原本的 Metadata (目前只需要 match, include, exclude)
}
/**
* 脚本加载信息。( service_worker / sandbox / popup 环境用 )
* 包含脚本元数据与用户配置。
*/
export interface ScriptLoadInfo extends ScriptRunResource {
/** 脚本元数据字符串 */
metadataStr: string;
/** 用户配置字符串 */
userConfigStr: string;
/** 用户配置对象(可选) */
userConfig?: UserConfig;
scriptUrlPatterns?: URLRuleEntry[];
}
/**
* 脚本加载信息。( Inject / Content 环境用,避免过多不必要资讯公开,减少页面加载资讯储存量 )
* 包含脚本元数据与用户配置。
*/
export type TScriptInfo = Override<
ScriptLoadInfo,
{
originalMetadata?: Partial<Record<string, string[]>>;
resource: Record<string, { base64?: string; content: string; contentType: string }>;
code: "" | string;
sort?: number;
flag: string;
runStatus?: SCRIPT_RUN_STATUS;
type?: SCRIPT_TYPE;
status?: SCRIPT_STATUS;
}
>;
export type TClientPageLoadInfo =
| {
ok: true;
injectScriptList: TScriptInfo[];
contentScriptList: TScriptInfo[];
envInfo: GMInfoEnv;
}
| { ok: false };
export class ScriptDAO extends Repo<Script> {
constructor() {
super("script");
}
enableCache(): void {
super.enableCache();
}
public save(val: Script) {
return super._save(val.uuid, val);
}
public findByName(name: string) {
return this.findOne((key, value) => {
return value.name === name;
});
}
public findByNameAndNamespace(name: string, namespace: string) {
return this.findOne((key, value) => {
return value.name === name && (!namespace || value.namespace === namespace);
});
}
public findByUUIDAndSubscribeUrl(uuid: string, suburl: string) {
return this.findOne((key, value) => {
return value.uuid === uuid && value.subscribeUrl === suburl;
});
}
public findByOriginAndSubscribeUrl(origin: string, suburl: string) {
return this.findOne((key, value) => {
return value.origin === origin && value.subscribeUrl === suburl;
});
}
public async searchExistingScript(targetScript: Script, toCheckScriptInfoEqual: boolean = true): Promise<Script[]> {
const removeScriptNameFromURL = (url: string) => {
// https://scriptcat.org/scripts/code/{id}/{scriptname}.user.js (单匹配)
if (url.startsWith("https://scriptcat.org/scripts/code/") && url.endsWith(".js")) {
const idx1 = url.indexOf("/", "https://scriptcat.org/scripts/code/".length);
const idx2 = url.indexOf("/", idx1 + 1);
if (idx1 > 0 && idx2 < 0) {
const idx3 = url.indexOf(".", idx1 + 1);
return url.substring(0, idx1 + 1) + "*" + url.substring(idx3);
}
}
// https://update.greasyfork.org/scripts/{id}/{scriptname}.user.js (单匹配)
if (url.startsWith("https://update.greasyfork.org/scripts/") && url.endsWith(".js")) {
const idx1 = url.indexOf("/", "https://update.greasyfork.org/scripts/".length);
const idx2 = url.indexOf("/", idx1 + 1);
if (idx1 > 0 && idx2 < 0) {
const idx3 = url.indexOf(".", idx1 + 1);
return url.substring(0, idx1 + 1) + "*" + url.substring(idx3);
}
}
// https://openuserjs.org/install/{username}/{scriptname}.user.js (复数匹配)
if (url.startsWith("https://openuserjs.org/install/") && url.endsWith(".js")) {
const idx1 = url.indexOf("/", "https://openuserjs.org/install/".length);
const idx2 = url.indexOf("/", idx1 + 1);
if (idx1 > 0 && idx2 < 0) {
const idx3 = url.indexOf(".", idx1 + 1);
return url.substring(0, idx1 + 1) + "*" + url.substring(idx3);
}
}
return url;
};
const valEqual = (val1: any, val2: any) => {
if (val1 && val2 && Array.isArray(val1) && Array.isArray(val2)) {
if (val1.length !== val2.length) return false;
if (val1.length < 2) {
return val1[0] === val2[0];
}
// 无视次序
const s = new Set([...val1, ...val2]);
if (s.size !== val1.length) return false;
return true;
}
return val1 === val2;
};
const isScriptInfoEqual = (script1: Script, script2: Script) => {
// @author, @copyright, @license 应该不会改
if (!valEqual(script1.metadata.author, script2.metadata.author)) return false;
if (!valEqual(script1.metadata.copyright, script2.metadata.copyright)) return false;
if (!valEqual(script1.metadata.license, script2.metadata.license)) return false;
// @grant, @connect 应该不会改
if (!valEqual(script1.metadata.grant, script2.metadata.grant)) return false;
if (!valEqual(script1.metadata.connect, script2.metadata.connect)) return false;
// @match @include 应该不会改
if (!valEqual(script1.metadata.match, script2.metadata.match)) return false;
if (!valEqual(script1.metadata.include, script2.metadata.include)) return false;
return true;
};
const { metadata, origin } = targetScript;
if (origin && !metadata?.updateurl?.[0] && !metadata?.downloadurl?.[0]) {
// scriptcat
const targetOrigin = removeScriptNameFromURL(origin);
return this.find((key, entry) => {
if (!entry.origin) return false;
const entryOrigin = removeScriptNameFromURL(entry.origin);
if (targetOrigin !== entryOrigin) return false;
if (toCheckScriptInfoEqual && !isScriptInfoEqual(targetScript, entry)) return false;
return true;
});
} else if (origin && (metadata?.updateurl?.[0] || metadata?.downloadurl?.[0])) {
// greasyfork
const targetOrigin = removeScriptNameFromURL(origin);
const targetUpdateURL = removeScriptNameFromURL(metadata?.updateurl?.[0] || "");
const targetDownloadURL = removeScriptNameFromURL(metadata?.downloadurl?.[0] || "");
return this.find((key, entry) => {
if (!entry.origin) return false;
const entryOrigin = removeScriptNameFromURL(entry.origin);
if (targetOrigin !== entryOrigin) return false;
const entryUpdateURL = removeScriptNameFromURL(entry.metadata?.updateurl?.[0] || "");
const entryDownloadURL = removeScriptNameFromURL(entry.metadata?.downloadurl?.[0] || "");
if (targetUpdateURL !== entryUpdateURL || targetDownloadURL !== entryDownloadURL) return false;
if (toCheckScriptInfoEqual && !isScriptInfoEqual(targetScript, entry)) return false;
return true;
});
} else {
return [];
}
}
}
// 为了防止脚本代码数据量过大,单独存储脚本代码
// 内部使用 OPFS 优先存储,fallback 到 chrome.storage.local(过渡期间)
export class ScriptCodeDAO {
private static readonly LEGACY_PREFIX = "scriptCode:";
private _dirHandlePromise: Promise<FileSystemDirectoryHandle> | null = null;
private getDirHandle(): Promise<FileSystemDirectoryHandle> {
if (!this._dirHandlePromise) {
this._dirHandlePromise = navigator.storage
.getDirectory()
.then((opfsRoot) => opfsRoot.getDirectoryHandle("script_codes", { create: true }));
}
return this._dirHandlePromise;
}
// 仅写入 OPFS,供迁移使用,避免写放大
public async saveToOPFS(val: ScriptCode): Promise<void> {
const folder = await this.getDirHandle();
const handle = await folder.getFileHandle(`${val.uuid}.user.js`, { create: true });
const writable = await handle.createWritable({ keepExistingData: false });
await writable.write(val.code);
await writable.close();
}
public async save(val: ScriptCode): Promise<ScriptCode> {
// 写入 OPFS(失败不影响 chrome.storage.local)
try {
await this.saveToOPFS(val);
} catch {
// OPFS 写入失败,忽略
}
// 过渡期间同步写入 chrome.storage.local
await this.legacySave(val);
return val;
}
public async get(key: string): Promise<ScriptCode | undefined> {
// 优先从 OPFS 读取
try {
const folder = await this.getDirHandle();
const handle = await folder.getFileHandle(`${key}.user.js`, { create: false });
const code = await handle.getFile().then((f) => f.text());
return { uuid: key, code };
} catch {
// OPFS 没有,fallback 到 chrome.storage.local
}
const result = await this.legacyGet(key);
if (result) {
// 懒迁移:写入 OPFS
this.saveToOPFS(result).catch(() => {});
}
return result;
}
public async gets(keys: string[]): Promise<(ScriptCode | undefined)[]> {
return Promise.all(keys.map((key) => this.get(key)));
}
public async delete(key: string): Promise<void> {
// 删除 OPFS
try {
const folder = await this.getDirHandle();
await folder.removeEntry(`${key}.user.js`);
} catch {
// 忽略删除失败
}
// 过渡期间同步删除 chrome.storage.local
await this.legacyDelete([key]);
}
public async deletes(keys: string[]): Promise<void> {
// 删除 OPFS
try {
const folder = await this.getDirHandle();
await Promise.all(
keys.map(async (key) => {
try {
await folder.removeEntry(`${key}.user.js`);
} catch {
// 忽略
}
})
);
} catch {
// 忽略
}
// 过渡期间同步删除 chrome.storage.local
await this.legacyDelete(keys);
}
// --- 过渡期间 chrome.storage.local 操作,过渡结束后删除 ---
// 从 chrome.storage.local 读取所有脚本代码(仅迁移使用)
public all(): Promise<ScriptCode[]> {
return new Promise((resolve) => {
chrome.storage.local.get(null, (items) => {
if (chrome.runtime.lastError) {
console.error("chrome.storage.local.get error:", chrome.runtime.lastError);
}
const result: ScriptCode[] = [];
for (const key in items) {
if (key.startsWith(ScriptCodeDAO.LEGACY_PREFIX)) {
result.push(items[key]);
}
}
resolve(result);
});
});
}
private legacySave(val: ScriptCode): Promise<void> {
const key = ScriptCodeDAO.LEGACY_PREFIX + val.uuid;
return new Promise((resolve) => {
chrome.storage.local.set({ [key]: val }, () => {
if (chrome.runtime.lastError) {
console.error("chrome.storage.local.set error:", chrome.runtime.lastError);
}
resolve();
});
});
}
private legacyGet(key: string): Promise<ScriptCode | undefined> {
const storageKey = ScriptCodeDAO.LEGACY_PREFIX + key;
return new Promise((resolve) => {
chrome.storage.local.get(storageKey, (items) => {
if (chrome.runtime.lastError) {
console.error("chrome.storage.local.get error:", chrome.runtime.lastError);
}
resolve(items[storageKey]);
});
});
}
private legacyDelete(keys: string[]): Promise<void> {
const storageKeys = keys.map((key) => ScriptCodeDAO.LEGACY_PREFIX + key);
return new Promise((resolve) => {
chrome.storage.local.remove(storageKeys, () => {
if (chrome.runtime.lastError) {
console.error("chrome.storage.local.remove error:", chrome.runtime.lastError);
}
resolve();
});
});
}
}