@tomjs/vite-plugin-vscode 4.3.0 → 5.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.
package/dist/index.js CHANGED
@@ -1,162 +1,161 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/index.ts
2
- var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
3
- var _os = require('os'); var _os2 = _interopRequireDefault(_os);
4
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
5
- var _process = require('process');
6
- var _node = require('@tomjs/node');
7
- var _lodashmerge = require('lodash.merge'); var _lodashmerge2 = _interopRequireDefault(_lodashmerge);
8
- var _nodehtmlparser = require('node-html-parser');
9
- var _tsup = require('tsup');
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import { cwd } from "node:process";
6
+ import { emptyDirSync, readFileSync, readJsonSync } from "@tomjs/node";
7
+ import { execa } from "execa";
8
+ import merge from "lodash.merge";
9
+ import { parse } from "node-html-parser";
10
+ import { build } from "tsdown";
11
+ import Logger from "@tomjs/logger";
10
12
 
11
- // src/constants.ts
12
- var PLUGIN_NAME = "tomjs:vscode";
13
- var PACKAGE_NAME = "@tomjs/vite-plugin-vscode";
14
- var WEBVIEW_METHOD_NAME = "__getWebviewHtml__";
13
+ //#region node_modules/.pnpm/tsdown@0.12.9_publint@0.3.12_typescript@5.7.3_vue-tsc@2.2.12_typescript@5.7.3_/node_modules/tsdown/esm-shims.js
14
+ const getFilename = () => fileURLToPath(import.meta.url);
15
+ const getDirname = () => path.dirname(getFilename());
16
+ const __dirname = /* @__PURE__ */ getDirname();
15
17
 
16
- // src/logger.ts
17
- var _logger = require('@tomjs/logger'); var _logger2 = _interopRequireDefault(_logger);
18
+ //#endregion
19
+ //#region src/constants.ts
20
+ const PLUGIN_NAME = "tomjs:vscode";
21
+ const ORG_NAME = "@tomjs";
22
+ const PACKAGE_NAME = "@tomjs/vite-plugin-vscode";
23
+ const WEBVIEW_METHOD_NAME = "__getWebviewHtml__";
24
+
25
+ //#endregion
26
+ //#region src/logger.ts
18
27
  function createLogger() {
19
- return new (0, _logger2.default)({
20
- prefix: `[${PLUGIN_NAME}]`,
21
- time: true
22
- });
28
+ return new Logger({
29
+ prefix: `[${PLUGIN_NAME}]`,
30
+ time: true
31
+ });
23
32
  }
24
33
 
25
- // src/utils.ts
34
+ //#endregion
35
+ //#region src/utils.ts
36
+ /**
37
+ * @see https://github.com/vitejs/vite/blob/v4.0.1/packages/vite/src/node/constants.ts#L137-L147
38
+ */
26
39
  function resolveHostname(hostname) {
27
- const loopbackHosts = /* @__PURE__ */ new Set([
28
- "localhost",
29
- "127.0.0.1",
30
- "::1",
31
- "0000:0000:0000:0000:0000:0000:0000:0001"
32
- ]);
33
- const wildcardHosts = /* @__PURE__ */ new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);
34
- return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
40
+ const loopbackHosts = new Set([
41
+ "localhost",
42
+ "127.0.0.1",
43
+ "::1",
44
+ "0000:0000:0000:0000:0000:0000:0000:0001"
45
+ ]);
46
+ const wildcardHosts = new Set([
47
+ "0.0.0.0",
48
+ "::",
49
+ "0000:0000:0000:0000:0000:0000:0000:0000"
50
+ ]);
51
+ return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
35
52
  }
36
53
  function resolveServerUrl(server) {
37
- const addressInfo = server.httpServer.address();
38
- const isAddressInfo = (x) => x == null ? void 0 : x.address;
39
- if (isAddressInfo(addressInfo)) {
40
- const { address, port } = addressInfo;
41
- const hostname = resolveHostname(address);
42
- const options = server.config.server;
43
- const protocol = options.https ? "https" : "http";
44
- const devBase = server.config.base;
45
- const path2 = typeof options.open === "string" ? options.open : devBase;
46
- const url = path2.startsWith("http") ? path2 : `${protocol}://${hostname}:${port}${path2}`;
47
- return url;
48
- }
54
+ const addressInfo = server.httpServer.address();
55
+ const isAddressInfo = (x) => x?.address;
56
+ if (isAddressInfo(addressInfo)) {
57
+ const { address, port } = addressInfo;
58
+ const hostname = resolveHostname(address);
59
+ const options = server.config.server;
60
+ const protocol = options.https ? "https" : "http";
61
+ const devBase = server.config.base;
62
+ const path$1 = typeof options.open === "string" ? options.open : devBase;
63
+ const url = path$1.startsWith("http") ? path$1 : `${protocol}://${hostname}:${port}${path$1}`;
64
+ return url;
65
+ }
49
66
  }
50
67
 
51
- // src/index.ts
52
- var isDev = process.env.NODE_ENV === "development";
53
- var logger = createLogger();
68
+ //#endregion
69
+ //#region src/index.ts
70
+ const isDev = process.env.NODE_ENV === "development";
71
+ const logger = createLogger();
54
72
  function getPkg() {
55
- const pkgFile = _path2.default.resolve(process.cwd(), "package.json");
56
- if (!_fs2.default.existsSync(pkgFile)) {
57
- throw new Error("Main file is not specified, and no package.json found");
58
- }
59
- const pkg = _node.readJsonSync.call(void 0, pkgFile);
60
- if (!pkg.main) {
61
- throw new Error("Main file is not specified, please check package.json");
62
- }
63
- return pkg;
73
+ const pkgFile = path.resolve(process.cwd(), "package.json");
74
+ if (!fs.existsSync(pkgFile)) throw new Error("Main file is not specified, and no package.json found");
75
+ const pkg = readJsonSync(pkgFile);
76
+ if (!pkg.main) throw new Error("Main file is not specified, please check package.json");
77
+ return pkg;
64
78
  }
65
79
  function preMergeOptions(options) {
66
- const pkg = getPkg();
67
- const format = pkg.type === "module" ? "esm" : "cjs";
68
- const opts = _lodashmerge2.default.call(void 0,
69
- {
70
- webview: true,
71
- recommended: true,
72
- debug: false,
73
- extension: {
74
- entry: "extension/index.ts",
75
- outDir: "dist-extension",
76
- target: format === "esm" ? ["node20"] : ["es2019", "node14"],
77
- format,
78
- shims: true,
79
- clean: true,
80
- dts: false,
81
- treeshake: isDev ? false : "smallest",
82
- outExtension() {
83
- return { js: ".js" };
84
- },
85
- external: ["vscode"],
86
- skipNodeModulesBundle: isDev
87
- }
88
- },
89
- options
90
- );
91
- const opt = opts.extension || {};
92
- ["entry", "format"].forEach((prop) => {
93
- const value = opt[prop];
94
- if (!Array.isArray(value) && value) {
95
- opt[prop] = [value];
96
- }
97
- });
98
- if (isDev) {
99
- opt.sourcemap = _nullishCoalesce(opt.sourcemap, () => ( true));
100
- } else {
101
- opt.minify ??= true;
102
- }
103
- opt.external = ["vscode"].concat(_nullishCoalesce(opt.external, () => ( [])));
104
- if (!opt.skipNodeModulesBundle) {
105
- opt.noExternal = Object.keys(pkg.dependencies || {}).concat(
106
- Object.keys(pkg.peerDependencies || {})
107
- );
108
- }
109
- opts.extension = opt;
110
- if (opts.webview !== false) {
111
- let name = WEBVIEW_METHOD_NAME;
112
- if (typeof opts.webview === "string") {
113
- name = _nullishCoalesce(opts.webview, () => ( WEBVIEW_METHOD_NAME));
114
- }
115
- opts.webview = Object.assign({ name }, opts.webview);
116
- }
117
- return opts;
80
+ const pkg = getPkg();
81
+ const format = pkg.type === "module" ? "esm" : "cjs";
82
+ const opts = merge({
83
+ webview: true,
84
+ recommended: true,
85
+ extension: {
86
+ entry: "extension/index.ts",
87
+ outDir: "dist-extension",
88
+ target: format === "esm" ? ["node20"] : ["es2019", "node14"],
89
+ format,
90
+ shims: true,
91
+ clean: true,
92
+ dts: false,
93
+ treeshake: !isDev,
94
+ publint: false,
95
+ config: false,
96
+ outExtensions() {
97
+ return { js: ".js" };
98
+ },
99
+ external: ["vscode"]
100
+ }
101
+ }, options);
102
+ const opt = opts.extension || {};
103
+ if (isDev) opt.sourcemap = opt.sourcemap ?? true;
104
+ else {
105
+ opt.minify ??= true;
106
+ opt.clean ??= true;
107
+ }
108
+ if (typeof opt.external !== "function") {
109
+ opt.external = ["vscode"].concat(opt.external ?? []);
110
+ opt.external = [...new Set(opt.external)];
111
+ } else {
112
+ const fn = opt.external;
113
+ opt.external = function(id, parentId, isResolved) {
114
+ if (id === "vscode") return true;
115
+ return fn(id, parentId, isResolved);
116
+ };
117
+ }
118
+ if (!isDev && !opt.skipNodeModulesBundle && !opt.noExternal) opt.noExternal = Object.keys(pkg.dependencies || {}).concat(Object.keys(pkg.peerDependencies || {}));
119
+ opts.extension = opt;
120
+ if (opts.webview !== false) {
121
+ let name = WEBVIEW_METHOD_NAME;
122
+ if (typeof opts.webview === "string") name = opts.webview ?? WEBVIEW_METHOD_NAME;
123
+ opts.webview = Object.assign({ name }, opts.webview);
124
+ }
125
+ return opts;
118
126
  }
119
- var prodCachePkgName = `${PACKAGE_NAME}-inject`;
127
+ const prodCachePkgName = `${PACKAGE_NAME}-inject`;
120
128
  function genProdWebviewCode(cache, webview) {
121
- webview = Object.assign({}, webview);
122
- const prodCacheFolder = _path2.default.join(_process.cwd.call(void 0, ), "node_modules", prodCachePkgName);
123
- _node.emptyDirSync.call(void 0, prodCacheFolder);
124
- const destFile = _path2.default.join(prodCacheFolder, "index.js");
125
- function handleHtmlCode(html) {
126
- const root = _nodehtmlparser.parse.call(void 0, html);
127
- const head = root.querySelector("head");
128
- if (!head) {
129
- root == null ? void 0 : root.insertAdjacentHTML("beforeend", "<head></head>");
130
- }
131
- const csp = (webview == null ? void 0 : webview.csp) || `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src {{cspSource}} 'unsafe-inline'; script-src 'nonce-{{nonce}}' 'unsafe-eval';">`;
132
- head.insertAdjacentHTML("afterbegin", csp);
133
- if (csp && csp.includes("{{nonce}}")) {
134
- const tags = {
135
- script: "src",
136
- link: "href"
137
- };
138
- Object.keys(tags).forEach((tag) => {
139
- const elements = root.querySelectorAll(tag);
140
- elements.forEach((element) => {
141
- const attr = element.getAttribute(tags[tag]);
142
- if (attr) {
143
- element.setAttribute(tags[tag], `{{baseUri}}${attr}`);
144
- }
145
- element.setAttribute("nonce", "{{nonce}}");
146
- });
147
- });
148
- }
149
- return root.removeWhitespace().toString();
150
- }
151
- const cacheCode = (
152
- /* js */
153
- `const htmlCode = {
129
+ webview = Object.assign({}, webview);
130
+ const prodCacheFolder = path.join(cwd(), "node_modules", prodCachePkgName);
131
+ emptyDirSync(prodCacheFolder);
132
+ const destFile = path.join(prodCacheFolder, "index.js");
133
+ function handleHtmlCode(html) {
134
+ const root = parse(html);
135
+ const head = root.querySelector("head");
136
+ if (!head) root?.insertAdjacentHTML("beforeend", "<head></head>");
137
+ const csp = webview?.csp || `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src {{cspSource}} 'unsafe-inline'; script-src 'nonce-{{nonce}}' 'unsafe-eval';">`;
138
+ head.insertAdjacentHTML("afterbegin", csp);
139
+ if (csp && csp.includes("{{nonce}}")) {
140
+ const tags = {
141
+ script: "src",
142
+ link: "href"
143
+ };
144
+ Object.keys(tags).forEach((tag) => {
145
+ const elements = root.querySelectorAll(tag);
146
+ elements.forEach((element) => {
147
+ const attr = element.getAttribute(tags[tag]);
148
+ if (attr) element.setAttribute(tags[tag], `{{baseUri}}${attr}`);
149
+ element.setAttribute("nonce", "{{nonce}}");
150
+ });
151
+ });
152
+ }
153
+ return root.removeWhitespace().toString();
154
+ }
155
+ const cacheCode = `const htmlCode = {
154
156
  ${Object.keys(cache).map((s) => `'${s}': \`${handleHtmlCode(cache[s])}\`,`).join("\n")}
155
- };`
156
- );
157
- const code = (
158
- /* js */
159
- `import { Uri } from 'vscode';
157
+ };`;
158
+ const code = `import { Uri } from 'vscode';
160
159
 
161
160
  ${cacheCode}
162
161
 
@@ -180,210 +179,157 @@ export default function getWebviewHtml(options){
180
179
 
181
180
  return html.replaceAll('{{cspSource}}', webview.cspSource).replaceAll('{{nonce}}', nonce).replaceAll('{{baseUri}}', baseUri);
182
181
  }
183
- `
184
- );
185
- _fs2.default.writeFileSync(destFile, code, { encoding: "utf8" });
186
- return fixWindowsPath(destFile);
182
+ `;
183
+ fs.writeFileSync(destFile, code, { encoding: "utf8" });
184
+ return fixWindowsPath(destFile);
187
185
  }
188
186
  function fixWindowsPath(webviewPath) {
189
- if (_os2.default.platform() === "win32") {
190
- webviewPath = webviewPath.replaceAll("\\", "/");
191
- }
192
- return webviewPath;
187
+ if (os.platform() === "win32") webviewPath = webviewPath.replaceAll("\\", "/");
188
+ return webviewPath;
193
189
  }
194
190
  function useVSCodePlugin(options) {
195
- const opts = preMergeOptions(options);
196
- const handleConfig = (config) => {
197
- var _a, _b, _c, _d, _e;
198
- let outDir = ((_a = config == null ? void 0 : config.build) == null ? void 0 : _a.outDir) || "dist";
199
- opts.extension ??= {};
200
- if (opts.recommended) {
201
- opts.extension.outDir = _path2.default.resolve(outDir, "extension");
202
- outDir = _path2.default.resolve(outDir, "webview");
203
- }
204
- const assetsDir = ((_b = config == null ? void 0 : config.build) == null ? void 0 : _b.assetsDir) || "assets";
205
- const output = {
206
- chunkFileNames: `${assetsDir}/[name].js`,
207
- entryFileNames: `${assetsDir}/[name].js`,
208
- assetFileNames: `${assetsDir}/[name].[ext]`
209
- };
210
- let rollupOutput = _nullishCoalesce(((_d = (_c = config == null ? void 0 : config.build) == null ? void 0 : _c.rollupOptions) == null ? void 0 : _d.output), () => ( {}));
211
- if (Array.isArray(rollupOutput)) {
212
- rollupOutput.map((s) => Object.assign(s, output));
213
- } else {
214
- rollupOutput = Object.assign({}, rollupOutput, output);
215
- }
216
- return {
217
- build: {
218
- outDir,
219
- sourcemap: isDev ? true : (_e = config == null ? void 0 : config.build) == null ? void 0 : _e.sourcemap,
220
- rollupOptions: {
221
- output: rollupOutput
222
- }
223
- }
224
- };
225
- };
226
- let devWebviewClient;
227
- if (opts.webview) {
228
- devWebviewClient = _node.readFileSync.call(void 0, _path2.default.join(__dirname, "client.global.js"));
229
- }
230
- let resolvedConfig;
231
- const prodHtmlCache = {};
232
- let devtoolsFlag = false;
233
- return [
234
- {
235
- name: "@tomjs:vscode",
236
- apply: "serve",
237
- config(config) {
238
- return handleConfig(config);
239
- },
240
- configResolved(config) {
241
- resolvedConfig = config;
242
- },
243
- configureServer(server) {
244
- var _a;
245
- if (!server || !server.httpServer) {
246
- return;
247
- }
248
- (_a = server.httpServer) == null ? void 0 : _a.once("listening", async () => {
249
- const env = {
250
- NODE_ENV: server.config.mode || "development",
251
- VITE_DEV_SERVER_URL: resolveServerUrl(server)
252
- };
253
- logger.info("extension build start");
254
- let buildCount = 0;
255
- const webview = opts == null ? void 0 : opts.webview;
256
- const { onSuccess: _onSuccess, ...tsupOptions } = opts.extension || {};
257
- await _tsup.build.call(void 0,
258
- _lodashmerge2.default.call(void 0, tsupOptions, {
259
- watch: true,
260
- env,
261
- silent: true,
262
- esbuildPlugins: !webview ? [] : [
263
- {
264
- name: "@tomjs:vscode:inject",
265
- setup(build) {
266
- build.onLoad({ filter: /\.ts$/ }, async (args) => {
267
- const file = _fs2.default.readFileSync(args.path, "utf-8");
268
- if (file.includes(`${webview.name}(`)) {
269
- return {
270
- contents: `import ${webview.name} from '${PACKAGE_NAME}/webview';
271
- ${file}`,
272
- loader: "ts"
273
- };
274
- }
275
- return {};
276
- });
277
- }
278
- }
279
- ],
280
- async onSuccess() {
281
- if (typeof _onSuccess === "function") {
282
- await _onSuccess();
283
- }
284
- if (buildCount++ > 1) {
285
- logger.info("extension rebuild success");
286
- } else {
287
- logger.info("extension build success");
288
- }
289
- }
290
- })
291
- );
292
- });
293
- },
294
- transformIndexHtml(html) {
295
- if (!opts.webview) {
296
- return html;
297
- }
298
- if (_nullishCoalesce(opts.devtools, () => ( true))) {
299
- let port;
300
- if (resolvedConfig.plugins.find(
301
- (s) => ["vite:react-refresh", "vite:react-swc"].includes(s.name)
302
- )) {
303
- port = 8097;
304
- } else if (resolvedConfig.plugins.find((s) => ["vite:vue", "vite:vue2"].includes(s.name))) {
305
- port = 8098;
306
- }
307
- if (port) {
308
- html = html.replace(/<head>/i, `<head><script src="http://localhost:${port}"></script>`);
309
- } else if (!devtoolsFlag) {
310
- devtoolsFlag = true;
311
- logger.warn("Only support react-devtools and vue-devtools!");
312
- }
313
- }
314
- return html.replace(/<head>/i, `<head><script>${devWebviewClient}</script>`);
315
- }
316
- },
317
- {
318
- name: "@tomjs:vscode",
319
- apply: "build",
320
- enforce: "post",
321
- config(config) {
322
- return handleConfig(config);
323
- },
324
- configResolved(config) {
325
- resolvedConfig = config;
326
- },
327
- transformIndexHtml(html, ctx) {
328
- var _a;
329
- if (!opts.webview) {
330
- return html;
331
- }
332
- prodHtmlCache[(_a = ctx.chunk) == null ? void 0 : _a.name] = html;
333
- return html;
334
- },
335
- closeBundle() {
336
- let webviewPath;
337
- const webview = opts == null ? void 0 : opts.webview;
338
- if (webview) {
339
- webviewPath = genProdWebviewCode(prodHtmlCache, webview);
340
- }
341
- let outDir = resolvedConfig.build.outDir.replace(_process.cwd.call(void 0, ), "").replaceAll("\\", "/");
342
- if (outDir.startsWith("/")) {
343
- outDir = outDir.substring(1);
344
- }
345
- const env = {
346
- NODE_ENV: resolvedConfig.mode || "production",
347
- VITE_WEBVIEW_DIST: outDir
348
- };
349
- logger.info("extension build start");
350
- const { onSuccess: _onSuccess, ...tsupOptions } = opts.extension || {};
351
- _tsup.build.call(void 0,
352
- _lodashmerge2.default.call(void 0, tsupOptions, {
353
- env,
354
- silent: true,
355
- esbuildPlugins: !webview ? [] : [
356
- {
357
- name: "@tomjs:vscode:inject",
358
- setup(build) {
359
- build.onLoad({ filter: /\.ts$/ }, async (args) => {
360
- const file = _fs2.default.readFileSync(args.path, "utf-8");
361
- if (file.includes(`${webview.name}(`)) {
362
- return {
363
- contents: `import ${webview.name} from \`${webviewPath}\`;
364
- ${file}`,
365
- loader: "ts"
366
- };
367
- }
368
- return {};
369
- });
370
- }
371
- }
372
- ],
373
- async onSuccess() {
374
- if (typeof _onSuccess === "function") {
375
- await _onSuccess();
376
- }
377
- logger.info("extension build success");
378
- }
379
- })
380
- );
381
- }
382
- }
383
- ];
191
+ const opts = preMergeOptions(options);
192
+ const handleConfig = (config) => {
193
+ let outDir = config?.build?.outDir || "dist";
194
+ opts.extension ??= {};
195
+ if (opts.recommended) {
196
+ opts.extension.outDir = path.resolve(outDir, "extension");
197
+ outDir = path.resolve(outDir, "webview");
198
+ }
199
+ const assetsDir = config?.build?.assetsDir || "assets";
200
+ const output = {
201
+ chunkFileNames: `${assetsDir}/[name].js`,
202
+ entryFileNames: `${assetsDir}/[name].js`,
203
+ assetFileNames: `${assetsDir}/[name].[ext]`
204
+ };
205
+ let rollupOutput = config?.build?.rollupOptions?.output ?? {};
206
+ if (Array.isArray(rollupOutput)) rollupOutput.map((s) => Object.assign(s, output));
207
+ else rollupOutput = Object.assign({}, rollupOutput, output);
208
+ return { build: {
209
+ outDir,
210
+ sourcemap: isDev ? true : config?.build?.sourcemap,
211
+ rollupOptions: { output: rollupOutput }
212
+ } };
213
+ };
214
+ let devWebviewClient;
215
+ if (opts.webview) devWebviewClient = readFileSync(path.join(__dirname, "client.iife.js"));
216
+ let resolvedConfig;
217
+ const prodHtmlCache = {};
218
+ let devtoolsFlag = false;
219
+ return [{
220
+ name: "@tomjs:vscode",
221
+ apply: "serve",
222
+ config(config) {
223
+ return handleConfig(config);
224
+ },
225
+ configResolved(config) {
226
+ resolvedConfig = config;
227
+ },
228
+ configureServer(server) {
229
+ if (!server || !server.httpServer) return;
230
+ server.httpServer?.once("listening", async () => {
231
+ const env = {
232
+ NODE_ENV: server.config.mode || "development",
233
+ VITE_DEV_SERVER_URL: resolveServerUrl(server)
234
+ };
235
+ logger.info("extension build start");
236
+ let buildCount = 0;
237
+ const webview = opts?.webview;
238
+ const { onSuccess: _onSuccess, ignoreWatch, silent, watchFiles,...tsdownOptions } = opts.extension || {};
239
+ await build(merge(tsdownOptions, {
240
+ watch: watchFiles ?? (opts.recommended ? ["extension"] : true),
241
+ ignoreWatch: [
242
+ ".history",
243
+ ".temp",
244
+ ".tmp",
245
+ ".cache",
246
+ "dist"
247
+ ].concat(Array.isArray(ignoreWatch) ? ignoreWatch : []),
248
+ env,
249
+ silent: silent ?? true,
250
+ plugins: !webview ? [] : [{
251
+ name: `${ORG_NAME}:vscode:inject`,
252
+ transform(code, id) {
253
+ if (id.includes("node_modules")) return;
254
+ if (code.includes(`${webview.name}(`)) return `import ${webview.name} from '${PACKAGE_NAME}/webview';\n${code}`;
255
+ return code;
256
+ }
257
+ }],
258
+ async onSuccess(config, signal) {
259
+ if (_onSuccess) {
260
+ if (typeof _onSuccess === "string") await execa(_onSuccess);
261
+ else if (typeof _onSuccess === "function") await _onSuccess(config, signal);
262
+ }
263
+ if (buildCount++ > 1) logger.info("extension rebuild success");
264
+ else logger.info("extension build success");
265
+ }
266
+ }));
267
+ });
268
+ },
269
+ transformIndexHtml(html) {
270
+ if (!opts.webview) return html;
271
+ if (opts.devtools ?? true) {
272
+ let port;
273
+ if (resolvedConfig.plugins.find((s) => ["vite:react-refresh", "vite:react-swc"].includes(s.name))) port = 8097;
274
+ else if (resolvedConfig.plugins.find((s) => ["vite:vue", "vite:vue2"].includes(s.name))) port = 8098;
275
+ if (port) html = html.replace(/<head>/i, `<head><script src="http://localhost:${port}"><\/script>`);
276
+ else if (!devtoolsFlag) {
277
+ devtoolsFlag = true;
278
+ logger.warn("Only support react-devtools and vue-devtools!");
279
+ }
280
+ }
281
+ return html.replace(/<head>/i, `<head><script>${devWebviewClient}<\/script>`);
282
+ }
283
+ }, {
284
+ name: "@tomjs:vscode",
285
+ apply: "build",
286
+ enforce: "post",
287
+ config(config) {
288
+ return handleConfig(config);
289
+ },
290
+ configResolved(config) {
291
+ resolvedConfig = config;
292
+ },
293
+ transformIndexHtml(html, ctx) {
294
+ if (!opts.webview) return html;
295
+ prodHtmlCache[ctx.chunk?.name] = html;
296
+ return html;
297
+ },
298
+ closeBundle() {
299
+ let webviewPath;
300
+ const webview = opts?.webview;
301
+ if (webview) webviewPath = genProdWebviewCode(prodHtmlCache, webview);
302
+ let outDir = resolvedConfig.build.outDir.replace(cwd(), "").replaceAll("\\", "/");
303
+ if (outDir.startsWith("/")) outDir = outDir.substring(1);
304
+ const env = {
305
+ NODE_ENV: resolvedConfig.mode || "production",
306
+ VITE_WEBVIEW_DIST: outDir
307
+ };
308
+ logger.info("extension build start");
309
+ const { onSuccess: _onSuccess, silent,...tsupOptions } = opts.extension || {};
310
+ build(merge(tsupOptions, {
311
+ env,
312
+ silent: silent ?? true,
313
+ plugins: !webview ? [] : [{
314
+ name: `${ORG_NAME}:vscode:inject`,
315
+ transform(code, id) {
316
+ if (id.includes("node_modules")) return;
317
+ if (code.includes(`${webview.name}(`)) return `import ${webview.name} from "${webviewPath}";\n${code}`;
318
+ return code;
319
+ }
320
+ }],
321
+ async onSuccess(config, signal) {
322
+ if (_onSuccess) {
323
+ if (typeof _onSuccess === "string") await execa(_onSuccess);
324
+ else if (typeof _onSuccess === "function") await _onSuccess(config, signal);
325
+ }
326
+ logger.info("extension build success");
327
+ }
328
+ }));
329
+ }
330
+ }];
384
331
  }
385
- var index_default = useVSCodePlugin;
386
-
387
-
332
+ var src_default = useVSCodePlugin;
388
333
 
389
- exports.default = index_default; exports.useVSCodePlugin = useVSCodePlugin;
334
+ //#endregion
335
+ export { src_default as default, useVSCodePlugin };