forked from quoid/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
255 lines (234 loc) · 7.77 KB
/
Copy pathutils.js
File metadata and controls
255 lines (234 loc) · 7.77 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
/**
* @param {number} ms millisecond timestamp
* @returns {string}
*/
export function formatDate(ms) {
const d = new Date(ms);
const yr = new Intl.DateTimeFormat("en", { year: "numeric" }).format(d);
const mo = new Intl.DateTimeFormat("en", { month: "short" }).format(d);
const dd = new Intl.DateTimeFormat("en", { day: "2-digit" }).format(d);
const hr = d.getHours();
const mn = d.getMinutes();
return `${mo} ${dd}, ${yr} at ${hr}:${mn}`;
}
export function uniqueId() {
return Math.random().toString(36).substring(2, 10);
}
/**
* awaitable function for waiting an arbitrary amount of time
* @param {number} ms the amount of time to wait in milliseconds
* @returns {Promise<void>}
*/
export function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// TODO: describe the items array that should get passed to this function
/**
* @param {Array} array
* @param {("lastModifiedAsc"|"lastModifiedDesc"|"nameAsc"|"nameDesc")} order
* @returns
*/
export function sortBy(array, order) {
if (order === "nameAsc") {
array.sort((a, b) => a.name.localeCompare(b.name));
} else if (order === "nameDesc") {
array.sort((a, b) => b.name.localeCompare(a.name));
} else if (order === "lastModifiedAsc") {
array.sort((a, b) => (a.lastModified < b.lastModified ? -1 : 1));
} else if (order === "lastModifiedDesc") {
array.sort((a, b) => (a.lastModified > b.lastModified ? -1 : 1));
}
// always keep temp file pinned to the top, should only ever have one temp script
// if (array.find(f => f.temp)) array.sort((a, b) => a.temp ? -1 : b.temp ? 1 : 0);
return array;
}
/**
*
* @param {string} description
* @param {string} name
* @param {("css"|"js")} type
* @returns {string}
*/
export function newScriptDefault(description, name, type) {
if (type === "css") {
return `/* ==UserStyle==\n@name ${name}\n@description ${description}\n@match <all_urls>\n==/UserStyle== */`;
}
return `// ==UserScript==\n// @name ${name}\n// @description ${description}\n// @match *://*/*\n// ==/UserScript==`;
}
/**
* @param {string} str
* @returns {?{code: string, content: str, metablock: string, metadata: object}}
*/
export function parse(str) {
if (typeof str != "string") return null;
const blocksReg =
/(?:(\/\/ ==UserScript==[ \t]*?\r?\n([\S\s]*?)\r?\n\/\/ ==\/UserScript==)([\S\s]*)|(\/\* ==UserStyle==[ \t]*?\r?\n([\S\s]*?)\r?\n==\/UserStyle== \*\/)([\S\s]*))/;
const blocks = str.match(blocksReg);
if (!blocks) return null;
const metablock = blocks[1] != null ? blocks[1] : blocks[4];
const metas = blocks[2] != null ? blocks[2] : blocks[5];
const code = blocks[3] != null ? blocks[3].trim() : blocks[6].trim();
const metadata = {};
const metaArray = metas.split("\n");
metaArray.forEach((m) => {
const parts = m
.trim()
.match(/^(?:[ \t]*(?:\/\/)?[ \t]*@)([\w-]+)[ \t]+([^\s]+[^\r\n\t\v\f]*)/);
const parts2 = m
.trim()
.match(/^(?:[ \t]*(?:\/\/)?[ \t]*@)(noframes)[ \t]*$/);
if (parts) {
metadata[parts[1]] = metadata[parts[1]] || [];
metadata[parts[1]].push(parts[2]);
} else if (parts2) {
metadata[parts2[1]] = metadata[parts2[1]] || [];
metadata[parts2[1]].push(true);
}
});
// fail if @name is missing or name is empty
if (!metadata.name || metadata.name[0].length < 2) return;
return {
code,
content: str,
metablock,
metadata,
};
}
/**
* @param {string} text editor code
* @returns {{match: boolean, meta: boolean} | {key: string, value: string, text: string}[]}
*/
export function parseMetadata(text) {
const groupsRe =
/(\/\/ ==UserScript==[ \t]*?\r?\n([\S\s]*?)\r?\n\/\/ ==\/UserScript==)([\S\s]*)/;
const groups = text.match(groupsRe);
// userscript code doesn't match the regex expression
// could be missing opening/closing tags, malformed
// or missing metadata between opening/closing tags (group 2 in regex exp)
if (!groups) {
return { match: false, meta: false };
}
// userscript code matches but content between opening/closing tag missing
// ex. opening/closing tags present, but newline characters between the tags
const metas = groups[2];
if (!metas) return { match: true, meta: false };
const metadata = [];
const metaArray = metas.split("\n");
for (let i = 0; i < metaArray.length; i++) {
const metaRegex =
/^(?:[ \t]*(?:\/\/)?[ \t]*@)([\w-]+)[ \t]*([^\s]+[^\r\n\t\v\f]*)?/;
const meta = metaArray[i];
const parts = meta.match(metaRegex);
if (parts)
metadata.push({ key: parts[1], value: parts[2], text: parts[0] });
}
// if there is content between the opening/closing tags, match will be found
// this additionally checks that there's at least one properly formed key
// if not keys found, assume metadata is missing
// checking that required keys are present will happen elsewhere
if (!Object.keys(metadata).length) return { match: true, meta: false };
return metadata;
}
export const validGrants = new Set([
"GM.info",
"GM_info",
"GM.addStyle",
"GM.openInTab",
"GM.closeTab",
"GM.setValue",
"GM.getValue",
"GM.deleteValue",
"GM.listValues",
"GM.setClipboard",
"GM.getTab",
"GM.saveTab",
"GM_xmlhttpRequest",
"GM.xmlHttpRequest",
"none",
]);
export const validMetaKeys = new Set([
"author",
"description",
"downloadURL",
"exclude",
"exclude-match",
"grant",
"icon",
"include",
"inject-into",
"match",
"name",
"noframes",
"require",
"run-at",
"updateURL",
"version",
"weight",
]);
export const extensionPaths = {
popup: "/dist/s/entry-ext-action-popup.html",
page: "/dist/s/entry-ext-extension-page.html",
};
export async function openExtensionPage() {
const url = browser.runtime.getURL(extensionPaths.page);
const tabs = await browser.tabs.query({ url });
const tab = tabs.find((e) => e.url.startsWith(url));
if (!tab) return browser.tabs.create({ url });
browser.tabs.update(tab.id, { active: true });
browser.windows.update(tab.windowId, { focused: true });
}
// Safari currently does not honor the target attribute of <a> elements in extension contexts
export async function openInBlank(url) {
browser.tabs.create({ url });
}
// Safari currently does not honor the download attribute of <a> elements in extension contexts
// Also not support https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/download
export async function downloadToFile(filename, content, type = "text/plain") {
const url = "https://quoid.github.io/userscripts/serve/download.html";
const tab = await browser.tabs.create({ url });
const exchange = { filename, content, type };
const exscript = (o) => {
// make sure executed only once
// @ts-ignore
if (window.US_DOWNLOAD === 1) return;
// @ts-ignore
window.US_DOWNLOAD = 1;
window.stop();
document.body.textContent = "Download is starting...";
const a = document.createElement("a");
a.download = o.filename;
a.href = URL.createObjectURL(new Blob([o.content], { type: o.type }));
a.click();
document.body.innerHTML += "<br>The download should have started.<br>";
a.textContent = o.filename;
document.body.append(a);
};
// Safari currently unable to stably executeScript on tab loading status
try {
await browser.tabs.executeScript(tab.id, {
code: `(${exscript})(${JSON.stringify(exchange)});`,
});
} catch {
const handleUpdated = async (tabId) => {
if (tabId !== tab.id) return;
try {
await browser.tabs.executeScript(tabId, {
code: `(${exscript})(${JSON.stringify(exchange)});`,
});
console.info(`[${filename}] Download is starting...`);
} catch {
console.info(`[${filename}] Start download failed, retrying...`);
}
};
browser.tabs.onUpdated.addListener(handleUpdated);
// Remove the listener when tab closing
const handleRemoved = (tabId) => {
if (tabId !== tab.id) return;
browser.tabs.onUpdated.removeListener(handleUpdated);
browser.tabs.onRemoved.removeListener(handleRemoved);
};
browser.tabs.onRemoved.addListener(handleRemoved);
}
}