@unpackjs/plugin-react 0.27.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 dingff
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.
@@ -0,0 +1,93 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var click_to_component_exports = {};
29
+ __export(click_to_component_exports, {
30
+ addClickToComponentSupport: () => addClickToComponentSupport
31
+ });
32
+ module.exports = __toCommonJS(click_to_component_exports);
33
+ var import_node_fs = __toESM(require("node:fs"));
34
+ var import_node_http = __toESM(require("node:http"));
35
+ var import_node_path = __toESM(require("node:path"));
36
+ var import_shared = require("@unpackjs/shared");
37
+ var import_launch_editor = __toESM(require("launch-editor"));
38
+ function createServer() {
39
+ return new Promise((resolve) => {
40
+ const server = import_node_http.default.createServer((req, res) => {
41
+ const params = new URLSearchParams(req.url.slice(1));
42
+ const file = decodeURIComponent(params.get("file"));
43
+ const line = Number(params.get("line"));
44
+ const column = Number(params.get("column"));
45
+ res.writeHead(200, {
46
+ "Access-Control-Allow-Origin": "*",
47
+ "Access-Control-Allow-Methods": "*",
48
+ "Access-Control-Allow-Headers": "*",
49
+ "Access-Control-Allow-Private-Network": "true"
50
+ });
51
+ res.end("ok");
52
+ (0, import_launch_editor.default)(`${file}:${line}:${column}`);
53
+ });
54
+ (0, import_shared.getPort)(3100).then((port) => {
55
+ server.listen(port, () => {
56
+ resolve({
57
+ port
58
+ });
59
+ });
60
+ });
61
+ });
62
+ }
63
+ const addClickToComponentSupport = async ({
64
+ config,
65
+ unpackConfig,
66
+ webpack
67
+ }) => {
68
+ if (!(0, import_shared.isDev)() || unpackConfig.clickToComponent === false)
69
+ return config;
70
+ const { port } = await createServer();
71
+ const injectScript = import_node_fs.default.readFileSync(import_node_path.default.resolve(__dirname, "./injectScript.js"), "utf-8");
72
+ config.plugins.push(
73
+ // @ts-ignore
74
+ new webpack.BannerPlugin({
75
+ banner: `
76
+ if (!document.querySelector('#__click-to-component__')) {
77
+ const script = document.createElement('script')
78
+ window['CLICK_TO_COMPONENT'] = { port: ${port} }
79
+ script.setAttribute('type', 'text/javascript')
80
+ script.textContent = \`${injectScript}\`
81
+ document.body.appendChild(script)
82
+ }`,
83
+ entryOnly: true,
84
+ raw: true,
85
+ exclude: /\.css$/
86
+ })
87
+ );
88
+ return config;
89
+ };
90
+ // Annotate the CommonJS export names for ESM import in node:
91
+ 0 && (module.exports = {
92
+ addClickToComponentSupport
93
+ });
@@ -0,0 +1,7 @@
1
+ import { type BundlerConfiguration, type UnpackConfig } from '@unpackjs/shared';
2
+ export declare const addClickToComponentSupport: ({ config, unpackConfig, webpack, }: {
3
+ config: BundlerConfiguration;
4
+ unpackConfig: UnpackConfig;
5
+ webpack;
6
+ }) => Promise<BundlerConfiguration>;
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/click-to-component/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,oBAAoB,EAAE,KAAK,YAAY,EAAkB,MAAM,kBAAkB,CAAA;AA4B/F,eAAO,MAAM,0BAA0B,uCAIpC;IACD,MAAM,EAAE,oBAAoB,CAAA;IAC5B,YAAY,EAAE,YAAY,CAAA;IAC1B,OAAO,CAAA;CACR,KAAG,QAAQ,oBAAoB,CAqB/B,CAAA"}
@@ -0,0 +1,69 @@
1
+ import { createRequire } from 'node:module';
2
+ var require = createRequire(import.meta['url']);
3
+
4
+ import { fileURLToPath } from "url";
5
+ import path from "path";
6
+ var getFilename = () => fileURLToPath(import.meta.url);
7
+ var getDirname = () => path.dirname(getFilename());
8
+ var __dirname = /* @__PURE__ */ getDirname();
9
+ var __filename = /* @__PURE__ */ getFilename();
10
+ import fs from "node:fs";
11
+ import http from "node:http";
12
+ import path2 from "node:path";
13
+ import { getPort, isDev } from "@unpackjs/shared";
14
+ import launchEditor from "launch-editor";
15
+ function createServer() {
16
+ return new Promise((resolve) => {
17
+ const server = http.createServer((req, res) => {
18
+ const params = new URLSearchParams(req.url.slice(1));
19
+ const file = decodeURIComponent(params.get("file"));
20
+ const line = Number(params.get("line"));
21
+ const column = Number(params.get("column"));
22
+ res.writeHead(200, {
23
+ "Access-Control-Allow-Origin": "*",
24
+ "Access-Control-Allow-Methods": "*",
25
+ "Access-Control-Allow-Headers": "*",
26
+ "Access-Control-Allow-Private-Network": "true"
27
+ });
28
+ res.end("ok");
29
+ launchEditor(`${file}:${line}:${column}`);
30
+ });
31
+ getPort(3100).then((port) => {
32
+ server.listen(port, () => {
33
+ resolve({
34
+ port
35
+ });
36
+ });
37
+ });
38
+ });
39
+ }
40
+ const addClickToComponentSupport = async ({
41
+ config,
42
+ unpackConfig,
43
+ webpack
44
+ }) => {
45
+ if (!isDev() || unpackConfig.clickToComponent === false)
46
+ return config;
47
+ const { port } = await createServer();
48
+ const injectScript = fs.readFileSync(path2.resolve(__dirname, "./injectScript.js"), "utf-8");
49
+ config.plugins.push(
50
+ // @ts-ignore
51
+ new webpack.BannerPlugin({
52
+ banner: `
53
+ if (!document.querySelector('#__click-to-component__')) {
54
+ const script = document.createElement('script')
55
+ window['CLICK_TO_COMPONENT'] = { port: ${port} }
56
+ script.setAttribute('type', 'text/javascript')
57
+ script.textContent = \`${injectScript}\`
58
+ document.body.appendChild(script)
59
+ }`,
60
+ entryOnly: true,
61
+ raw: true,
62
+ exclude: /\.css$/
63
+ })
64
+ );
65
+ return config;
66
+ };
67
+ export {
68
+ addClickToComponentSupport
69
+ };
@@ -0,0 +1,137 @@
1
+ const COVER_ID = '__click-to-component__'
2
+ let cover = null
3
+ let currentDebugSource = null
4
+ let enabled = false
5
+ function debounce(fn, delay = 200) {
6
+ let timer = null
7
+ return (...args) => {
8
+ clearTimeout(timer)
9
+ timer = setTimeout(() => {
10
+ fn(...args)
11
+ }, delay)
12
+ }
13
+ }
14
+ function applyStyles(target, styles) {
15
+ Object.entries(styles).forEach(([key, value]) => {
16
+ target.style[key] = value
17
+ })
18
+ }
19
+ function createCover() {
20
+ cover = document.createElement('div')
21
+ cover.id = COVER_ID
22
+ applyStyles(cover, {
23
+ position: 'fixed',
24
+ zIndex: '999999',
25
+ background: 'rgba(120, 170, 210, 0.6)',
26
+ display: 'none',
27
+ pointerEvents: 'none',
28
+ })
29
+ document.body.appendChild(cover)
30
+ }
31
+ function updateCover(target) {
32
+ if (typeof target.getBoundingClientRect !== 'function') {
33
+ currentDebugSource = null
34
+ return
35
+ }
36
+ const { top, left, width, height } = target.getBoundingClientRect()
37
+ applyStyles(cover, {
38
+ top: top + 'px',
39
+ left: left + 'px',
40
+ width: width + 'px',
41
+ height: height + 'px',
42
+ display: 'block',
43
+ })
44
+ }
45
+ function hideCover() {
46
+ cover.style.display = 'none'
47
+ }
48
+ function getFiberWithDebugSourceByTarget(target) {
49
+ const fiberKey = Object.keys(target).find((key) => key.includes('__reactFiber'))
50
+ const maxDepth = 10
51
+ const doNext = (fiber, depth = 0) => {
52
+ if (!fiber) return
53
+ if (depth > maxDepth) {
54
+ console.warn('Recursion depth exceeded. Aborting to prevent stack overflow.')
55
+ return
56
+ }
57
+ if (fiber._debugSource) {
58
+ // console.log('_debugSource-depth', depth, fiber)
59
+ return fiber
60
+ }
61
+ if (fiber._debugOwner) {
62
+ return doNext(fiber._debugOwner, depth + 1)
63
+ }
64
+ console.warn('[WARN] click-to-component cannot work with the minified version of React.')
65
+ }
66
+ return doNext(target[fiberKey])
67
+ }
68
+ function getClosestNodeFromFiber(fiber) {
69
+ if (fiber.stateNode) {
70
+ return fiber.stateNode
71
+ }
72
+ return getClosestNodeFromFiber(fiber.return)
73
+ }
74
+ function openEditor() {
75
+ if (!currentDebugSource) return
76
+ const port = window.CLICK_TO_COMPONENT.port
77
+ const { fileName, lineNumber, columnNumber } = currentDebugSource
78
+ const url = [
79
+ 'http://localhost:',
80
+ port,
81
+ '/?file=',
82
+ fileName,
83
+ '&line=',
84
+ lineNumber,
85
+ '&column=',
86
+ columnNumber,
87
+ ].join('')
88
+ const sendXHR = () => {
89
+ const xhr = new XMLHttpRequest()
90
+ xhr.open('GET', url, true)
91
+ xhr.send()
92
+ xhr.addEventListener('error', () => {
93
+ // 通过img方式发送请求
94
+ const img = document.createElement('img')
95
+ img.src = url
96
+ })
97
+ }
98
+ sendXHR()
99
+ }
100
+ document.addEventListener(
101
+ 'mouseover',
102
+ debounce((e) => {
103
+ if (!enabled) return
104
+ const target = e.target
105
+ const fiber = getFiberWithDebugSourceByTarget(target)
106
+ if (!fiber) return
107
+ const closestNode = getClosestNodeFromFiber(fiber)
108
+ if (!closestNode) return
109
+ currentDebugSource = fiber._debugSource
110
+ updateCover(closestNode)
111
+ }, 30),
112
+ )
113
+ document.addEventListener(
114
+ 'click',
115
+ (e) => {
116
+ if (!enabled) return
117
+ e.stopPropagation()
118
+ e.preventDefault()
119
+ openEditor()
120
+ hideCover()
121
+ enabled = false
122
+ },
123
+ true,
124
+ )
125
+ document.addEventListener('keydown', (e) => {
126
+ if (e.key === 'Alt') {
127
+ enabled = true
128
+ }
129
+ })
130
+ document.addEventListener('keyup', (e) => {
131
+ if (e.key === 'Alt') {
132
+ enabled = false
133
+ hideCover()
134
+ }
135
+ })
136
+
137
+ createCover()
package/dist/index.cjs ADDED
@@ -0,0 +1,105 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var src_exports = {};
29
+ __export(src_exports, {
30
+ PLUGIN_NAME: () => PLUGIN_NAME,
31
+ pluginReact: () => pluginReact
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+ var import_node_path = __toESM(require("node:path"));
35
+ var import_react_refresh_webpack_plugin = __toESM(require("@pmmmwh/react-refresh-webpack-plugin"));
36
+ var import_plugin_react_refresh = __toESM(require("@rspack/plugin-react-refresh"));
37
+ var import_shared = require("@unpackjs/shared");
38
+ var import_click_to_component = require("./click-to-component/index.cjs");
39
+ const PLUGIN_NAME = "unpack:react";
40
+ const pluginReact = () => {
41
+ return {
42
+ name: PLUGIN_NAME,
43
+ bundlerConfig: async (config, { unpackConfig, mergeConfig, webpack }) => {
44
+ const next = await (0, import_click_to_component.addClickToComponentSupport)({ config, unpackConfig, webpack });
45
+ const jsExclude = [/node_modules[\\/](?!\.unpack)/];
46
+ const swcLoader = unpackConfig.bundler === "rspack" ? "builtin:swc-loader" : require.resolve("swc-loader");
47
+ const ReactRefreshPlugin = unpackConfig.bundler === "rspack" ? import_plugin_react_refresh.default : import_react_refresh_webpack_plugin.default;
48
+ const getSwcOptions = ({ tsx }) => {
49
+ return {
50
+ jsc: {
51
+ parser: {
52
+ tsx,
53
+ syntax: "typescript",
54
+ dynamicImport: true,
55
+ decorators: true
56
+ },
57
+ externalHelpers: true,
58
+ transform: {
59
+ react: {
60
+ runtime: "automatic",
61
+ refresh: (0, import_shared.isDevServer)()
62
+ }
63
+ }
64
+ },
65
+ env: {
66
+ targets: "Chrome >= 48"
67
+ }
68
+ };
69
+ };
70
+ return mergeConfig(next, {
71
+ module: {
72
+ rules: [
73
+ {
74
+ test: /\.(j|t)s$/,
75
+ exclude: jsExclude,
76
+ loader: swcLoader,
77
+ options: getSwcOptions({ tsx: false })
78
+ },
79
+ {
80
+ test: /\.(j|t)sx$/,
81
+ exclude: jsExclude,
82
+ loader: swcLoader,
83
+ options: getSwcOptions({ tsx: true })
84
+ }
85
+ ]
86
+ },
87
+ plugins: [
88
+ (0, import_shared.isDevServer)() && new ReactRefreshPlugin({
89
+ overlay: false
90
+ })
91
+ ],
92
+ resolve: {
93
+ alias: {
94
+ "@swc/helpers": import_node_path.default.dirname(require.resolve("@swc/helpers/package.json"))
95
+ }
96
+ }
97
+ });
98
+ }
99
+ };
100
+ };
101
+ // Annotate the CommonJS export names for ESM import in node:
102
+ 0 && (module.exports = {
103
+ PLUGIN_NAME,
104
+ pluginReact
105
+ });
@@ -0,0 +1,4 @@
1
+ import { type UnpackPlugin } from '@unpackjs/shared';
2
+ export declare const PLUGIN_NAME = "unpack:react";
3
+ export declare const pluginReact: () => UnpackPlugin;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,YAAY,EAAe,MAAM,kBAAkB,CAAA;AAGjE,eAAO,MAAM,WAAW,iBAAiB,CAAA;AACzC,eAAO,MAAM,WAAW,QAAO,YA+D9B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ import { createRequire } from 'node:module';
2
+ var require = createRequire(import.meta['url']);
3
+
4
+ import { fileURLToPath } from "url";
5
+ import path from "path";
6
+ var getFilename = () => fileURLToPath(import.meta.url);
7
+ var getDirname = () => path.dirname(getFilename());
8
+ var __dirname = /* @__PURE__ */ getDirname();
9
+ var __filename = /* @__PURE__ */ getFilename();
10
+ import path2 from "node:path";
11
+ import WebpackReactRefreshPlugin from "@pmmmwh/react-refresh-webpack-plugin";
12
+ import RspackReactRefreshPlugin from "@rspack/plugin-react-refresh";
13
+ import { isDevServer } from "@unpackjs/shared";
14
+ import { addClickToComponentSupport } from "./click-to-component/index.js";
15
+ const PLUGIN_NAME = "unpack:react";
16
+ const pluginReact = () => {
17
+ return {
18
+ name: PLUGIN_NAME,
19
+ bundlerConfig: async (config, { unpackConfig, mergeConfig, webpack }) => {
20
+ const next = await addClickToComponentSupport({ config, unpackConfig, webpack });
21
+ const jsExclude = [/node_modules[\\/](?!\.unpack)/];
22
+ const swcLoader = unpackConfig.bundler === "rspack" ? "builtin:swc-loader" : require.resolve("swc-loader");
23
+ const ReactRefreshPlugin = unpackConfig.bundler === "rspack" ? RspackReactRefreshPlugin : WebpackReactRefreshPlugin;
24
+ const getSwcOptions = ({ tsx }) => {
25
+ return {
26
+ jsc: {
27
+ parser: {
28
+ tsx,
29
+ syntax: "typescript",
30
+ dynamicImport: true,
31
+ decorators: true
32
+ },
33
+ externalHelpers: true,
34
+ transform: {
35
+ react: {
36
+ runtime: "automatic",
37
+ refresh: isDevServer()
38
+ }
39
+ }
40
+ },
41
+ env: {
42
+ targets: "Chrome >= 48"
43
+ }
44
+ };
45
+ };
46
+ return mergeConfig(next, {
47
+ module: {
48
+ rules: [
49
+ {
50
+ test: /\.(j|t)s$/,
51
+ exclude: jsExclude,
52
+ loader: swcLoader,
53
+ options: getSwcOptions({ tsx: false })
54
+ },
55
+ {
56
+ test: /\.(j|t)sx$/,
57
+ exclude: jsExclude,
58
+ loader: swcLoader,
59
+ options: getSwcOptions({ tsx: true })
60
+ }
61
+ ]
62
+ },
63
+ plugins: [
64
+ isDevServer() && new ReactRefreshPlugin({
65
+ overlay: false
66
+ })
67
+ ],
68
+ resolve: {
69
+ alias: {
70
+ "@swc/helpers": path2.dirname(require.resolve("@swc/helpers/package.json"))
71
+ }
72
+ }
73
+ });
74
+ }
75
+ };
76
+ };
77
+ export {
78
+ PLUGIN_NAME,
79
+ pluginReact
80
+ };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@unpackjs/plugin-react",
3
+ "version": "0.27.0",
4
+ "description": "",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "require": "./dist/index.cjs"
11
+ }
12
+ },
13
+ "main": "./dist/index.cjs",
14
+ "types": "./dist/index.d.ts",
15
+ "keywords": [],
16
+ "authors": [],
17
+ "license": "MIT",
18
+ "files": [
19
+ "dist",
20
+ "compiled"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@pmmmwh/react-refresh-webpack-plugin": "0.5.15",
27
+ "@rspack/plugin-react-refresh": "0.7.5",
28
+ "react-refresh": "0.14.2",
29
+ "swc-loader": "0.2.6",
30
+ "@swc/core": "1.7.0",
31
+ "@swc/helpers": "0.5.12",
32
+ "launch-editor": "2.8.0",
33
+ "@unpackjs/shared": "^0.27.0"
34
+ },
35
+ "scripts": {
36
+ "dev": "modern build --watch",
37
+ "build": "modern build"
38
+ }
39
+ }