userscript-extend-webpage 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of userscript-extend-webpage might be problematic. Click here for more details.

package/.prettierrc ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "singleQuote": true,
3
+ "tabWidth": 2,
4
+ "useTabs": false,
5
+ "semi": true,
6
+ "bracketSpacing": true,
7
+ "arrowParens": "avoid",
8
+ "endOfLine": "lf"
9
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 k34869
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # userscript-extend-webpage
2
+
3
+ ## install
4
+
5
+ ```shell
6
+ npm install userscript-extend-webpage
7
+ # pnpm add userscript-extend-webpage
8
+ # nub install userscript-extend-webpage
9
+ # ...
10
+ ```
11
+
12
+ ## usage
13
+
14
+ ```
15
+ Usage: uewp [options] [command]
16
+
17
+ Web extension development tool based on UserScript.
18
+
19
+ Options:
20
+ -V, --version output the version number
21
+ -h, --help display help for command
22
+
23
+ Commands:
24
+ init [name] Initialize uewp project.
25
+ dev [options] Build for development mode.
26
+ build Build for production mode.
27
+ docs Open tampermonkey documentation in default browser.
28
+ ```
package/lib/core.js ADDED
@@ -0,0 +1,165 @@
1
+ import path from 'path';
2
+ import { pathToFileURL } from 'url';
3
+ import fs from 'fs-extra';
4
+ import { execAsync } from './execAsync.js';
5
+ import { rollup } from 'rollup';
6
+ import postcss from 'rollup-plugin-postcss';
7
+ import postcssUrl from 'postcss-url';
8
+ import importRaw from 'rollup-plugin-import-raw';
9
+ import image from '@rollup/plugin-image';
10
+ import { isArray, isObject } from './utils.js';
11
+
12
+ /**
13
+ * 创建 uewp 项目
14
+ * @param {string} [name=''] 项目名称
15
+ * @return {Promise} 创建成功或失败的 Promise
16
+ */
17
+ async function createProject(name) {
18
+ const projectDirectory = name ?? '.';
19
+ return execAsync(
20
+ `git clone -b template --single-branch --depth 1 https://github.com/k34869/userscript-extend-webpage.git ${projectDirectory}`,
21
+ ).then(async () => {
22
+ return Promise.all([
23
+ fs.readFile(path.resolve(projectDirectory, 'package.json'), 'utf8'),
24
+ fs.writeFile(
25
+ path.resolve(projectDirectory, 'README.md'),
26
+ `# ${name ?? path.basename(process.cwd())}`,
27
+ ),
28
+ execAsync(`git -C ${projectDirectory} branch -M main`),
29
+ ]).then(([packageJson]) => {
30
+ const packages = JSON.parse(packageJson);
31
+ packages.name = name ?? path.basename(process.cwd());
32
+ return fs.writeFile(
33
+ path.resolve(projectDirectory, 'package.json'),
34
+ JSON.stringify(packages, null, 2),
35
+ 'utf8',
36
+ );
37
+ });
38
+ });
39
+ }
40
+
41
+ /**
42
+ * 获取 用户脚本 配置对象
43
+ * @return {Promise} resolve(配置对象)
44
+ */
45
+ async function getConfiguration() {
46
+ return Promise.all([
47
+ import(pathToFileURL(path.resolve(process.cwd(), 'userscript.config.js'))),
48
+ fs.readFile('./package.json', 'utf8'),
49
+ ]).then(values => {
50
+ const [{ default: comfigs }, packageJson] = values;
51
+ const userscriptConfig = structuredClone(comfigs);
52
+ const packages = JSON.parse(packageJson);
53
+
54
+ // userscript.config.js 与 package.json 配置合并
55
+ userscriptConfig.name = userscriptConfig.name ?? packages.name;
56
+ userscriptConfig.version = userscriptConfig.version ?? packages.version;
57
+ userscriptConfig.description =
58
+ userscriptConfig.description ?? packages.description;
59
+ userscriptConfig.author = userscriptConfig.author ?? packages.author;
60
+ userscriptConfig.license = userscriptConfig.license ?? packages.license;
61
+
62
+ return userscriptConfig;
63
+ });
64
+ }
65
+
66
+ /**
67
+ * 生成用户脚本头
68
+ * @param {object} configuration 配置对象
69
+ * @return {string} header 用户脚本元数据
70
+ */
71
+ function generateUserScriptHeader(configuration) {
72
+ let header = '';
73
+ for (const key in configuration) {
74
+ if (isArray(configuration[key])) {
75
+ for (const item of configuration[key]) {
76
+ header += `// @${key}\t${item}\n`;
77
+ }
78
+ } else if (isObject(configuration[key])) {
79
+ for (const subKey in configuration[key]) {
80
+ header += `// @${key} ${subKey} ${configuration[key][subKey]}\n`;
81
+ }
82
+ } else if (typeof configuration[key] === 'string') {
83
+ header += `// @${key}\t${configuration[key]}\n`;
84
+ } else {
85
+ throw new Error(`'userscript.json' configuration '${key}' type error.`);
86
+ }
87
+ }
88
+ return `// ==UserScript==\n${header}// ==/UserScript==\n`;
89
+ }
90
+
91
+ /**
92
+ * 模块打包
93
+ * @return {Promise} resolve(生成结果)
94
+ */
95
+ async function moduleBundler() {
96
+ return rollup({
97
+ input: './src/main.js',
98
+ plugins: [
99
+ postcss({
100
+ extract: false,
101
+ plugins: [
102
+ postcssUrl({
103
+ url: 'inline',
104
+ maxSize: 1024 * 10,
105
+ }),
106
+ ],
107
+ }),
108
+ image(),
109
+ importRaw(),
110
+ ],
111
+ }).then(bundle => {
112
+ return bundle.generate({
113
+ format: 'iife',
114
+ inlineDynamicImports: true,
115
+ });
116
+ });
117
+ }
118
+
119
+ /**
120
+ * 构建生成 UserScript
121
+ * @param {string} [mode='production'] 构建模式(production = 生产模式, development = 开发模式)
122
+ * @return {Promise} 构建成功或失败的 Promise
123
+ */
124
+ async function build(mode = 'production') {
125
+ return Promise.all([getConfiguration(), moduleBundler(), fs.mkdirs('./dist')])
126
+ .then(values => {
127
+ const [
128
+ userscriptConfig,
129
+ {
130
+ output: [{ code }],
131
+ },
132
+ ] = values;
133
+
134
+ if (mode === 'production') {
135
+ const header = generateUserScriptHeader(userscriptConfig);
136
+ return {
137
+ userscriptConfig,
138
+ code: `${header}\n${code}`,
139
+ };
140
+ } else if (mode === 'development') {
141
+ return fs
142
+ .writeFile(`./dist/${userscriptConfig.name}.dev.js`, code, 'utf8')
143
+ .then(() => {
144
+ const require = [
145
+ `file:///${path.resolve('./dist/', userscriptConfig.name + '.dev.js')}`,
146
+ ];
147
+ userscriptConfig.require = userscriptConfig.require
148
+ ? require.concat(userscriptConfig.require)
149
+ : require;
150
+ const header = generateUserScriptHeader(userscriptConfig);
151
+ return {
152
+ userscriptConfig,
153
+ code: header,
154
+ };
155
+ });
156
+ }
157
+ })
158
+ .then(async ({ userscriptConfig, code }) => {
159
+ return fs
160
+ .writeFile(`./dist/${userscriptConfig.name}.user.js`, code, 'utf8')
161
+ .then(() => userscriptConfig);
162
+ });
163
+ }
164
+
165
+ export { createProject, build };
@@ -0,0 +1,16 @@
1
+ import { exec } from 'child_process';
2
+
3
+ export function execAsync(command, options = {}) {
4
+ return new Promise((resolve, reject) => {
5
+ exec(command, options, (error, stdout, stderr) => {
6
+ if (error) {
7
+ // 将错误信息附加到 stdout/stderr 以便调试
8
+ error.stdout = stdout;
9
+ error.stderr = stderr;
10
+ reject(error);
11
+ } else {
12
+ resolve({ stdout, stderr });
13
+ }
14
+ });
15
+ });
16
+ }
package/lib/uewp.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * URL 模式匹配
3
+ * @param {string} pattern 模式
4
+ * @param {string} [url=location.href] 要匹配的 URL
5
+ * @return {boolean} 匹配是否成功
6
+ */
7
+ export function urlMatch(pattern, url = location.href) {
8
+ pattern = pattern.replace(/\*/g, '.*?');
9
+ pattern = '^' + pattern + '$';
10
+ const regex = new RegExp(pattern);
11
+ return regex.test(url);
12
+ }
13
+
14
+ /**
15
+ * 应用路由
16
+ * @param {object} routes 路由对象
17
+ * @return {void}
18
+ */
19
+ export function applyRoutes(routes) {
20
+ for (const route of routes) {
21
+ if (urlMatch(route.path)) {
22
+ if (typeof route.exectors === 'function') {
23
+ route.exectors();
24
+ } else if (typeof Array.isArray(route.exectors)) {
25
+ for (const handler of routes.exectors) {
26
+ if (typeof handler === 'function') {
27
+ handler();
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
33
+ }
package/lib/utils.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 判断字符串是否符合 URL 规范
3
+ * @param {String} string 输入字符串
4
+ * @return {Boolean}
5
+ */
6
+ export function isUrlFriendly(string) {
7
+ return /^[^\s~`!#$%\^&*+=\[\]\{|};:"'<>,/?]+$/.test(string);
8
+ }
9
+
10
+ /**
11
+ * 判断值是否是数组
12
+ * @param {any} value 输入值
13
+ * @return {Boolean}
14
+ */
15
+ export function isArray(value) {
16
+ return Object.prototype.toString.call(value) === '[object Array]';
17
+ }
18
+
19
+ /**
20
+ * 判断值是否是对象
21
+ * @param {any} value 输入值
22
+ * @return {Boolean}
23
+ */
24
+ export function isObject(value) {
25
+ return Object.prototype.toString.call(value) === '[object Object]';
26
+ }
package/main.js ADDED
@@ -0,0 +1,168 @@
1
+ import packages from './package.json' with { type: 'json' };
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import { program } from 'commander';
5
+ import { execAsync } from './lib/execAsync.js';
6
+ import { build, createProject } from './lib/core.js';
7
+ import { isUrlFriendly } from './lib/utils.js';
8
+ import chokidar from 'chokidar';
9
+ import ora from 'ora';
10
+ import chalk from 'chalk';
11
+ import ignore from 'ignore';
12
+
13
+ let prevName;
14
+
15
+ const initConsole = name => {
16
+ const spinner = ora('initialize').start();
17
+ spinner.start();
18
+ const projectName = name ?? path.basename(process.cwd());
19
+ if (isUrlFriendly(projectName)) {
20
+ createProject(name)
21
+ .then(() => {
22
+ spinner.stop();
23
+ console.log(
24
+ '\n',
25
+ chalk.green.bold(
26
+ 'initialization successful.',
27
+ '\n',
28
+ name
29
+ ? `project for '${projectName}' directory.`
30
+ : 'project for current directory.',
31
+ ),
32
+ );
33
+ })
34
+ .catch(error => {
35
+ console.log(error.stderr);
36
+ throw error;
37
+ });
38
+ } else {
39
+ throw new Error(
40
+ `Sorry, name can only contain URL-friendly characters and name can no longer contain special characters ("~'!()*").`,
41
+ );
42
+ }
43
+ };
44
+
45
+ const buildConsole = async mode => {
46
+ const start = process.hrtime();
47
+ const spinner = ora('building').start();
48
+ spinner.start();
49
+ return build(mode)
50
+ .then(({ name }) => {
51
+ const [sec, nanosec] = process.hrtime(start);
52
+ const ms = sec * 1000 + nanosec / 1e6;
53
+ spinner.stop();
54
+ if (mode === 'development') {
55
+ console.log(
56
+ '\n',
57
+ chalk.blue.bold(
58
+ `src/main.js -> dist/${name}.user.js @require dist/${name}.dev.js`,
59
+ '\n',
60
+ chalk.green.bold(`Took ${parseInt(ms)}ms`),
61
+ ),
62
+ );
63
+ } else {
64
+ console.log(
65
+ '\n',
66
+ chalk.blue.bold(
67
+ `src/main.js -> dist/${name}.user.js`,
68
+ '\n',
69
+ chalk.green.bold(`Took ${parseInt(ms)}ms`),
70
+ ),
71
+ );
72
+ }
73
+ return name;
74
+ })
75
+ .catch(error => {
76
+ throw error;
77
+ });
78
+ };
79
+
80
+ const watcherBuildConsole = (path, state) => {
81
+ const start = process.hrtime();
82
+ console.log(
83
+ chalk.yellow(
84
+ ` ${new Date()} '${path}' is ${state === undefined ? 'delete' : 'change'}, building...`,
85
+ ),
86
+ );
87
+ build('development').then(({ name }) => {
88
+ if (prevName !== name) {
89
+ console.log(
90
+ '',
91
+ chalk.blue.bold(
92
+ `src/main.js -> dist/${name}.user.js @require dist/${name}.dev.js`,
93
+ ),
94
+ );
95
+ }
96
+ prevName = name;
97
+ const [sec, nanosec] = process.hrtime(start);
98
+ const ms = sec * 1000 + nanosec / 1e6;
99
+ console.log(chalk.green.bold(` Took ${parseInt(ms)}ms`));
100
+ });
101
+ };
102
+
103
+ const openDocs = () => {
104
+ execAsync(
105
+ (process.platform === 'win32'
106
+ ? 'start'
107
+ : process.platform === 'darwin'
108
+ ? 'open'
109
+ : 'xdg-open') +
110
+ ' https://www.tampermonkey.net/documentation.php?locale=zh',
111
+ ).catch(error => {
112
+ throw error;
113
+ });
114
+ };
115
+
116
+ program
117
+ .name(packages.binName)
118
+ .version(packages.version)
119
+ .description(packages.description)
120
+ .action(buildConsole);
121
+
122
+ program
123
+ .command('init [name]')
124
+ .description('Initialize uewp project.')
125
+ .action(initConsole);
126
+
127
+ program
128
+ .command('dev')
129
+ .description('Build for development mode.')
130
+ .option('-w, --watch', 'Rebuilds when modules have changed on disk.')
131
+ .action(opts => {
132
+ buildConsole('development').then(fristName => {
133
+ prevName = fristName;
134
+ if (opts.watch) {
135
+ const ig = ignore();
136
+ const gitignoreContent = fs.readFileSync(
137
+ path.resolve('.gitignore'),
138
+ 'utf8',
139
+ );
140
+ ig.add(gitignoreContent);
141
+
142
+ const isIgnored = filePath => {
143
+ const relativePath = path.relative(process.cwd(), filePath);
144
+ return relativePath === '' ? false : ig.ignores(relativePath);
145
+ };
146
+
147
+ const watcher = chokidar.watch('./', {
148
+ ignored: isIgnored,
149
+ ignoreInitial: true,
150
+ persistent: true,
151
+ });
152
+ watcher.on('change', watcherBuildConsole);
153
+ watcher.on('unlink', watcherBuildConsole);
154
+ }
155
+ });
156
+ });
157
+
158
+ program
159
+ .command('build')
160
+ .description('Build for production mode.')
161
+ .action(buildConsole);
162
+
163
+ program
164
+ .command('docs')
165
+ .description('Open tampermonkey documentation in default browser.')
166
+ .action(openDocs);
167
+
168
+ program.parse();