vite-userscript-plugin 0.0.0 → 0.3.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.
package/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Vitalij Ryndin
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,98 @@
1
+ # vite-userscript-plugin
2
+
3
+ ![ci](https://img.shields.io/github/workflow/status/crashmax-dev/vite-userscript-plugin/npm-publish)
4
+ ![npm](https://img.shields.io/npm/v/vite-userscript-plugin)
5
+ ![license](https://img.shields.io/github/license/crashmax-dev/vite-userscript-plugin)
6
+
7
+ > Tampermonkey userscript developing and build plugin based on [Vite](https://vitejs.dev).
8
+
9
+ ## Features
10
+
11
+ - 🔥 Hot reloading after changing any files.
12
+ - 🔧 Configure Tampermonkey's Userscript header.
13
+ - 💨 Import all `grant` by default in development mode.
14
+ - 📝 Automatically add used `grant` when building for production.
15
+
16
+ ## Install
17
+
18
+ ```
19
+ npm install vite-userscript-plugin -D
20
+ ```
21
+
22
+ ```
23
+ yarn add vite-userscript-plugin -D
24
+ ```
25
+
26
+ ```
27
+ pnpm add vite-userscript-plugin -D
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ### `vite.config.ts`
33
+
34
+ ```js
35
+ import { resolve } from 'path'
36
+ import { defineConfig } from 'vite'
37
+ import { UserscriptPlugin } from 'vite-userscript-plugin'
38
+ import { name, version } from './package.json'
39
+
40
+ export default defineConfig({
41
+ plugins: [
42
+ UserscriptPlugin({
43
+ entry: resolve(__dirname, 'src/index.ts'),
44
+ metadata: {
45
+ name,
46
+ version,
47
+ match: [
48
+ 'https://example.com',
49
+ 'https://example.org',
50
+ 'https://example.edu'
51
+ ]
52
+ }
53
+ })
54
+ ]
55
+ })
56
+ ```
57
+
58
+ ### `package.json`
59
+
60
+ ```json
61
+ {
62
+ "scripts": {
63
+ "dev": "vite build --watch",
64
+ "build": "vite build"
65
+ }
66
+ }
67
+ ```
68
+
69
+ ## Plugin Configuration
70
+
71
+ ```ts
72
+ export interface UserscriptPluginConfig {
73
+ /**
74
+ * Path of userscript entry.
75
+ */
76
+ entry: string
77
+
78
+ /**
79
+ * Userscript header config.
80
+ */
81
+ metadata: MetadataConfig
82
+
83
+ /**
84
+ * Import all `@grant` in development mode.
85
+ * @default true
86
+ */
87
+ autoGrants?: boolean
88
+
89
+ /**
90
+ * Server config (used in development mode for hot reloading).
91
+ */
92
+ server?: ServerConfig
93
+ }
94
+ ```
95
+
96
+ ## Example
97
+
98
+ See the [example](https://github.com/crashmax-dev/vite-userscript-plugin/tree/master/packages/demo) folder.
@@ -1,3 +1,4 @@
1
1
  export declare const regexpScripts: RegExp;
2
2
  export declare const regexpStyles: RegExp;
3
3
  export declare const template = "console.warn(\"__TEMPLATE__\")";
4
+ export declare const grants: readonly ["unsafeWindow", "window.onurlchange", "window.focus", "window.close", "GM_setValue", "GM_getValue", "GM_deleteValue", "GM_listValues", "GM_setClipboard", "GM_addStyle", "GM_addElement", "GM_addValueChangeListener", "GM_removeValueChangeListener", "GM_registerMenuCommand", "GM_unregisterMenuCommand", "GM_download", "GM_getTab", "GM_getTabs", "GM_saveTab", "GM_openInTab", "GM_notification", "GM_getResourceURL", "GM_getResourceText", "GM_xmlhttpRequest", "GM_webRequest", "GM_log", "GM_info"];
package/dist/constants.js CHANGED
@@ -1,3 +1,32 @@
1
1
  export const regexpScripts = new RegExp(/\.js/);
2
2
  export const regexpStyles = new RegExp(/\.css|\.sass|\.scss|\.less/);
3
3
  export const template = `console.warn("__TEMPLATE__")`;
4
+ export const grants = [
5
+ 'unsafeWindow',
6
+ 'window.onurlchange',
7
+ 'window.focus',
8
+ 'window.close',
9
+ 'GM_setValue',
10
+ 'GM_getValue',
11
+ 'GM_deleteValue',
12
+ 'GM_listValues',
13
+ 'GM_setClipboard',
14
+ 'GM_addStyle',
15
+ 'GM_addElement',
16
+ 'GM_addValueChangeListener',
17
+ 'GM_removeValueChangeListener',
18
+ 'GM_registerMenuCommand',
19
+ 'GM_unregisterMenuCommand',
20
+ 'GM_download',
21
+ 'GM_getTab',
22
+ 'GM_getTabs',
23
+ 'GM_saveTab',
24
+ 'GM_openInTab',
25
+ 'GM_notification',
26
+ 'GM_getResourceURL',
27
+ 'GM_getResourceText',
28
+ 'GM_xmlhttpRequest',
29
+ 'GM_webRequest',
30
+ 'GM_log',
31
+ 'GM_info'
32
+ ];
package/dist/css.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import type { ESBuildTransformResult } from 'vite';
2
1
  declare class CSS {
3
- private styles;
2
+ private readonly styles;
4
3
  add(entry: string, code: string, path: string): {
5
4
  code: string;
6
5
  } | null;
7
- minify(css: string, path: string): Promise<ESBuildTransformResult>;
8
- inject(): string;
6
+ minify(file: string, name: string): Promise<string>;
7
+ inject(): string | void;
8
+ merge(modules: string[]): void;
9
9
  }
10
10
  declare const _default: CSS;
11
11
  export default _default;
package/dist/css.js CHANGED
@@ -1,17 +1,17 @@
1
- import { transformWithEsbuild } from 'vite';
2
1
  import { regexpStyles, template } from './constants.js';
2
+ import { transform } from './helpers.js';
3
3
  class CSS {
4
4
  constructor() {
5
5
  Object.defineProperty(this, "styles", {
6
6
  enumerable: true,
7
7
  configurable: true,
8
8
  writable: true,
9
- value: []
9
+ value: new Map()
10
10
  });
11
11
  }
12
12
  add(entry, code, path) {
13
13
  if (regexpStyles.test(path)) {
14
- this.styles.push(code);
14
+ this.styles.set(path, code);
15
15
  return {
16
16
  code: ''
17
17
  };
@@ -23,16 +23,29 @@ class CSS {
23
23
  }
24
24
  return null;
25
25
  }
26
- async minify(css, path) {
27
- return await transformWithEsbuild(css, path, {
28
- minify: true,
26
+ async minify(file, name) {
27
+ return await transform({
28
+ file,
29
+ name,
29
30
  loader: 'css'
30
31
  });
31
32
  }
32
33
  inject() {
33
- const css = `GM_addStyle(\`${this.styles.join('')}\`)`;
34
- this.styles.length = 0;
35
- return css;
34
+ const styles = [...this.styles.values()].join('');
35
+ if (!styles)
36
+ return;
37
+ return `GM_addStyle(\`${styles}\`)`;
38
+ }
39
+ merge(modules) {
40
+ const styleModules = [];
41
+ for (const module of modules) {
42
+ const style = this.styles.get(module);
43
+ if (!style)
44
+ continue;
45
+ styleModules.push([module, style]);
46
+ }
47
+ this.styles.clear();
48
+ styleModules.forEach((value) => this.styles.set(...value));
36
49
  }
37
50
  }
38
51
  export default new CSS();
package/dist/helpers.d.ts CHANGED
@@ -1 +1,4 @@
1
- export declare function removeDuplicates(arr: string | string[] | undefined): any[];
1
+ import { Grants, Transform } from './types.js';
2
+ export declare function removeDuplicates(arr: string | string[] | readonly string[] | undefined): any[];
3
+ export declare function transform({ file, name, loader }: Transform): Promise<string>;
4
+ export declare function defineGrants(code: string): Grants[];
package/dist/helpers.js CHANGED
@@ -1,3 +1,21 @@
1
+ import { transformWithEsbuild } from 'vite';
2
+ import { grants } from './constants.js';
1
3
  export function removeDuplicates(arr) {
2
4
  return [...new Set(Array.isArray(arr) ? arr : arr ? [arr] : [])];
3
5
  }
6
+ export async function transform({ file, name, loader }) {
7
+ const { code } = await transformWithEsbuild(file, name, {
8
+ loader,
9
+ minify: true
10
+ });
11
+ return code;
12
+ }
13
+ export function defineGrants(code) {
14
+ const definedGrants = [];
15
+ for (const grant of grants) {
16
+ if (code.indexOf(grant) !== -1) {
17
+ definedGrants.push(grant);
18
+ }
19
+ }
20
+ return definedGrants;
21
+ }
package/dist/hmr.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const port: number;
2
+ declare const ws: WebSocket;
package/dist/hmr.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ const ws = new WebSocket(`ws://localhost:${port}`);
3
+ ws.addEventListener('message', () => {
4
+ location.reload();
5
+ });
6
+ ws.addEventListener('open', () => {
7
+ const { script } = GM_info;
8
+ console.group(`${script.name} / ${script.version}`);
9
+ console.log(GM_info);
10
+ console.groupEnd();
11
+ });
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { PluginOption } from 'vite';
2
- import type { PluginConfig } from './types.js';
3
- declare function UserscriptPlugin(config: PluginConfig): PluginOption;
2
+ import type { UserscriptPluginConfig } from './types.js';
3
+ declare function UserscriptPlugin(config: UserscriptPluginConfig): PluginOption;
4
4
  export { UserscriptPlugin };
5
5
  export default UserscriptPlugin;
6
- export type { PluginConfig };
6
+ export type { UserscriptPluginConfig };
package/dist/index.js CHANGED
@@ -1,12 +1,24 @@
1
1
  import { readFileSync, writeFileSync } from 'node:fs';
2
- import { resolve } from 'node:path';
3
- import { transformWithEsbuild } from 'vite';
2
+ import { createServer } from 'node:http';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import websocket from 'websocket';
4
6
  import { banner } from './banner.js';
5
- import { regexpScripts, template } from './constants.js';
7
+ import { grants, regexpScripts, template } from './constants.js';
6
8
  import css from './css.js';
7
- import { removeDuplicates } from './helpers.js';
9
+ import { defineGrants, removeDuplicates, transform } from './helpers.js';
8
10
  function UserscriptPlugin(config) {
9
11
  let pluginConfig;
12
+ let isBuildWatch;
13
+ let socketConnection = null;
14
+ const port = config.server?.port || 8000;
15
+ const server = createServer();
16
+ server.listen(port);
17
+ const WebSocketServer = websocket.server;
18
+ const ws = new WebSocketServer({ httpServer: server });
19
+ ws.on('request', (request) => {
20
+ socketConnection = request.accept(null, request.origin);
21
+ });
10
22
  return {
11
23
  name: 'vite-userscript-plugin',
12
24
  apply: 'build',
@@ -28,51 +40,56 @@ function UserscriptPlugin(config) {
28
40
  };
29
41
  },
30
42
  configResolved(cfg) {
31
- const { match, require, include, exclude, resource, connect, grant } = config.metadata;
43
+ pluginConfig = cfg;
44
+ isBuildWatch = (cfg.build.watch ?? false);
45
+ const { match, require, include, exclude, resource, connect } = config.metadata;
32
46
  config.metadata.match = removeDuplicates(match);
33
47
  config.metadata.require = removeDuplicates(require);
34
48
  config.metadata.include = removeDuplicates(include);
35
49
  config.metadata.exclude = removeDuplicates(exclude);
36
50
  config.metadata.resource = removeDuplicates(resource);
37
51
  config.metadata.connect = removeDuplicates(connect);
38
- config.metadata.grant = removeDuplicates([
39
- ...(grant ?? []),
40
- 'GM_addStyle',
41
- 'GM_info'
42
- ]);
43
- pluginConfig = cfg;
44
52
  },
45
53
  async transform(code, path) {
46
- const transformed = await css.minify(code, path);
47
- return css.add(config.entry, transformed.code.replace('\n', ''), path);
54
+ const style = await css.minify(code, path);
55
+ return css.add(config.entry, style.replace('\n', ''), path);
56
+ },
57
+ generateBundle(_, bundle) {
58
+ for (const [_, file] of Object.entries(bundle)) {
59
+ const styleModules = Object.keys(file.modules);
60
+ css.merge(styleModules);
61
+ }
48
62
  },
49
- async writeBundle(options, bundle) {
63
+ async writeBundle(_, bundle) {
50
64
  for (const [fileName] of Object.entries(bundle)) {
51
65
  if (regexpScripts.test(fileName)) {
52
66
  const rootDir = pluginConfig.root;
53
67
  const outDir = pluginConfig.build.outDir;
54
68
  const filePath = resolve(rootDir, outDir, fileName);
55
69
  const proxyFilePath = resolve(rootDir, outDir, `${config.metadata.name}.proxy.user.js`);
56
- const userFileName = resolve(rootDir, outDir, `${config.metadata.name}.user.js`);
70
+ const userFilePath = resolve(rootDir, outDir, `${config.metadata.name}.user.js`);
57
71
  try {
58
72
  let file = readFileSync(filePath, {
59
73
  encoding: 'utf8'
60
74
  });
75
+ const hmrScript = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), 'hmr.js'), 'utf-8');
61
76
  file = file.replace(template, `
62
77
  ${css.inject()}
63
- const { script } = GM_info
64
- console.group(script.name + ' / ' + script.version)
65
- console.log(GM_info)
66
- console.groupEnd()
78
+ const port = ${port}
79
+ ${hmrScript}
67
80
  `);
68
- const { code } = await transformWithEsbuild(file, fileName, {
69
- loader: 'js',
70
- minify: true
71
- });
81
+ file = await transform({ file, name: fileName, loader: 'js' });
82
+ // prettier-ignore
83
+ config.metadata.grant = removeDuplicates(isBuildWatch
84
+ ? grants
85
+ : config.autoGrants ?? true
86
+ ? defineGrants(file)
87
+ : [...(config.metadata.grant ?? []), 'GM_addStyle', 'GM_info']);
88
+ // prettier-ignore-end
72
89
  // source
73
- writeFileSync(filePath, code);
90
+ writeFileSync(filePath, file);
74
91
  // production
75
- writeFileSync(userFileName, `${banner(config.metadata)}\n\n${code}`);
92
+ writeFileSync(userFilePath, `${banner(config.metadata)}\n\n${file}`);
76
93
  // development
77
94
  writeFileSync(proxyFilePath, banner({
78
95
  ...config.metadata,
@@ -84,6 +101,13 @@ function UserscriptPlugin(config) {
84
101
  }
85
102
  }
86
103
  }
104
+ },
105
+ buildEnd() {
106
+ if (socketConnection) {
107
+ socketConnection.sendUTF(JSON.stringify({
108
+ message: 'reload'
109
+ }));
110
+ }
87
111
  }
88
112
  };
89
113
  }
package/dist/types.d.ts CHANGED
@@ -1,5 +1,11 @@
1
+ import { grants } from './constants.js';
2
+ export interface Transform {
3
+ file: string;
4
+ name: string;
5
+ loader: 'js' | 'css';
6
+ }
1
7
  export declare type RunAt = 'document-start' | 'document-body' | 'document-end' | 'document-idle' | 'context-menu';
2
- export declare type Grants = 'unsafeWindow' | 'window.onurlchange' | 'window.focus' | 'window.close' | 'GM_setValue' | 'GM_getValue' | 'GM_deleteValue' | 'GM_listValues' | 'GM_setClipboard' | 'GM_addStyle' | 'GM_addElement' | 'GM_addValueChangeListener' | 'GM_removeValueChangeListener' | 'GM_registerMenuCommand' | 'GM_unregisterMenuCommand' | 'GM_download' | 'GM_getTab' | 'GM_getTabs' | 'GM_saveTab' | 'GM_openInTab' | 'GM_notification' | 'GM_getResourceURL' | 'GM_getResourceText' | 'GM_xmlhttpRequest' | 'GM_webRequest' | 'GM_log' | 'GM_info';
8
+ export declare type Grants = typeof grants[number];
3
9
  export declare type MetadataConfig = {
4
10
  [property: string]: string | boolean | number | string[] | undefined;
5
11
  /**
@@ -183,13 +189,29 @@ export declare type MetadataConfig = {
183
189
  */
184
190
  'run-at'?: RunAt;
185
191
  };
186
- export interface PluginConfig {
192
+ export interface ServerConfig {
193
+ /**
194
+ * Server port.
195
+ * @default 8000
196
+ */
197
+ port?: number;
198
+ }
199
+ export interface UserscriptPluginConfig {
187
200
  /**
188
201
  * Path of userscript entry.
189
202
  */
190
203
  entry: string;
191
204
  /**
192
- * Userscript Metadata config.
205
+ * Userscript header config.
193
206
  */
194
207
  metadata: MetadataConfig;
208
+ /**
209
+ * Import all `@grant` in development mode.
210
+ * @default true
211
+ */
212
+ autoGrants?: boolean;
213
+ /**
214
+ * Server config (used in development mode for hot reloading).
215
+ */
216
+ server?: ServerConfig;
195
217
  }
package/package.json CHANGED
@@ -1,14 +1,39 @@
1
1
  {
2
2
  "name": "vite-userscript-plugin",
3
- "version": "0.0.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "main": "./dist/index.js",
7
7
  "files": [
8
8
  "dist"
9
9
  ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/crashmax-dev/vite-userscript-plugin.git"
13
+ },
14
+ "keywords": [
15
+ "vite",
16
+ "vite-plugin",
17
+ "userscript",
18
+ "tampermonkey"
19
+ ],
20
+ "author": {
21
+ "name": "Vitalij Ryndin",
22
+ "email": "sys@crashmax.ru",
23
+ "url": "https://crashmax.ru"
24
+ },
25
+ "license": "MIT",
26
+ "bugs": {
27
+ "url": "https://github.com/crashmax-dev/vite-userscript-plugin/issues"
28
+ },
29
+ "dependencies": {
30
+ "websocket": "^1.0.34"
31
+ },
10
32
  "devDependencies": {
11
- "@types/tampermonkey": "^4.0.5"
33
+ "@types/websocket": "^1.0.5"
34
+ },
35
+ "peerDependencies": {
36
+ "@types/tampermonkey": "latest"
12
37
  },
13
38
  "scripts": {
14
39
  "dev": "tsc --build --watch",