@tomjs/vite-plugin-vscode 4.3.0 → 5.1.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,164 +1,160 @@
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.15.12_publint@0.3.15_typescript@5.8.3_unrun@0.2.14_synckit@0.11.11__vue-tsc@3.1.5_typescript@5.8.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
+ return path$1.startsWith("http") ? path$1 : `${protocol}://${hostname}:${port}${path$1}`;
64
+ }
49
65
  }
50
66
 
51
- // src/index.ts
52
- var isDev = process.env.NODE_ENV === "development";
53
- var logger = createLogger();
67
+ //#endregion
68
+ //#region src/index.ts
69
+ const isDev = process.env.NODE_ENV === "development";
70
+ const logger = createLogger();
54
71
  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;
72
+ const pkgFile = path.resolve(process.cwd(), "package.json");
73
+ if (!fs.existsSync(pkgFile)) throw new Error("Main file is not specified, and no package.json found");
74
+ const pkg = readJsonSync(pkgFile);
75
+ if (!pkg.main) throw new Error("Main file is not specified, please check package.json");
76
+ return pkg;
64
77
  }
65
78
  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;
79
+ const pkg = getPkg();
80
+ const format = pkg.type === "module" ? "esm" : "cjs";
81
+ const opts = merge({
82
+ webview: true,
83
+ recommended: true,
84
+ extension: {
85
+ entry: "extension/index.ts",
86
+ outDir: "dist-extension",
87
+ target: format === "esm" ? ["node20"] : ["es2019", "node14"],
88
+ format,
89
+ shims: true,
90
+ clean: true,
91
+ dts: false,
92
+ treeshake: !isDev,
93
+ publint: false,
94
+ config: false,
95
+ outExtensions() {
96
+ return { js: ".js" };
97
+ },
98
+ external: ["vscode"]
99
+ }
100
+ }, options);
101
+ const opt = opts.extension || {};
102
+ if (isDev) opt.sourcemap = opt.sourcemap ?? true;
103
+ else {
104
+ opt.minify ??= true;
105
+ opt.clean ??= true;
106
+ }
107
+ if (typeof opt.external !== "function") {
108
+ opt.external = ["vscode"].concat(opt.external ?? []);
109
+ opt.external = [...new Set(opt.external)];
110
+ } else {
111
+ const fn = opt.external;
112
+ opt.external = function(id, parentId, isResolved) {
113
+ if (id === "vscode") return true;
114
+ return fn(id, parentId, isResolved);
115
+ };
116
+ }
117
+ if (!isDev && !opt.skipNodeModulesBundle && !opt.noExternal) opt.noExternal = Object.keys(pkg.dependencies || {}).concat(Object.keys(pkg.peerDependencies || {}));
118
+ opts.extension = opt;
119
+ if (opts.webview !== false) {
120
+ let name = WEBVIEW_METHOD_NAME;
121
+ if (typeof opts.webview === "string") name = opts.webview ?? WEBVIEW_METHOD_NAME;
122
+ opts.webview = Object.assign({ name }, opts.webview);
123
+ }
124
+ return opts;
118
125
  }
119
- var prodCachePkgName = `${PACKAGE_NAME}-inject`;
126
+ const prodCachePkgName = `${PACKAGE_NAME}-inject`;
120
127
  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 = {
154
- ${Object.keys(cache).map((s) => `'${s}': \`${handleHtmlCode(cache[s])}\`,`).join("\n")}
155
- };`
156
- );
157
- const code = (
158
- /* js */
159
- `import { Uri } from 'vscode';
128
+ webview = Object.assign({}, webview);
129
+ const prodCacheFolder = path.join(cwd(), "node_modules", prodCachePkgName);
130
+ emptyDirSync(prodCacheFolder);
131
+ const destFile = path.join(prodCacheFolder, "index.js");
132
+ function handleHtmlCode(html) {
133
+ const root = parse(html);
134
+ const head = root.querySelector("head");
135
+ if (!head) root?.insertAdjacentHTML("beforeend", "<head></head>");
136
+ 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';">`;
137
+ head.insertAdjacentHTML("afterbegin", csp);
138
+ if (csp && csp.includes("{{nonce}}")) {
139
+ const tags = {
140
+ script: "src",
141
+ link: "href"
142
+ };
143
+ Object.keys(tags).forEach((tag) => {
144
+ root.querySelectorAll(tag).forEach((element) => {
145
+ const attr = element.getAttribute(tags[tag]);
146
+ if (attr) element.setAttribute(tags[tag], `{{baseUri}}${attr}`);
147
+ element.setAttribute("nonce", "{{nonce}}");
148
+ });
149
+ });
150
+ }
151
+ return root.removeWhitespace().toString();
152
+ }
153
+ const code = `import { Uri } from 'vscode';
160
154
 
161
- ${cacheCode}
155
+ ${`const htmlCode = {
156
+ ${Object.keys(cache).map((s) => `'${s}': \`${handleHtmlCode(cache[s])}\`,`).join("\n")}
157
+ };`}
162
158
 
163
159
  function uuid() {
164
160
  let text = '';
@@ -180,210 +176,157 @@ export default function getWebviewHtml(options){
180
176
 
181
177
  return html.replaceAll('{{cspSource}}', webview.cspSource).replaceAll('{{nonce}}', nonce).replaceAll('{{baseUri}}', baseUri);
182
178
  }
183
- `
184
- );
185
- _fs2.default.writeFileSync(destFile, code, { encoding: "utf8" });
186
- return fixWindowsPath(destFile);
179
+ `;
180
+ fs.writeFileSync(destFile, code, { encoding: "utf8" });
181
+ return fixWindowsPath(destFile);
187
182
  }
188
183
  function fixWindowsPath(webviewPath) {
189
- if (_os2.default.platform() === "win32") {
190
- webviewPath = webviewPath.replaceAll("\\", "/");
191
- }
192
- return webviewPath;
184
+ if (os.platform() === "win32") webviewPath = webviewPath.replaceAll("\\", "/");
185
+ return webviewPath;
193
186
  }
194
187
  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
- ];
188
+ const opts = preMergeOptions(options);
189
+ const handleConfig = (config) => {
190
+ let outDir = config?.build?.outDir || "dist";
191
+ opts.extension ??= {};
192
+ if (opts.recommended) {
193
+ opts.extension.outDir = path.resolve(outDir, "extension");
194
+ outDir = path.resolve(outDir, "webview");
195
+ }
196
+ const assetsDir = config?.build?.assetsDir || "assets";
197
+ const output = {
198
+ chunkFileNames: `${assetsDir}/[name].js`,
199
+ entryFileNames: `${assetsDir}/[name].js`,
200
+ assetFileNames: `${assetsDir}/[name].[ext]`
201
+ };
202
+ let rollupOutput = config?.build?.rollupOptions?.output ?? {};
203
+ if (Array.isArray(rollupOutput)) rollupOutput.map((s) => Object.assign(s, output));
204
+ else rollupOutput = Object.assign({}, rollupOutput, output);
205
+ return { build: {
206
+ outDir,
207
+ sourcemap: isDev ? true : config?.build?.sourcemap,
208
+ rollupOptions: { output: rollupOutput }
209
+ } };
210
+ };
211
+ let devWebviewClient;
212
+ if (opts.webview) devWebviewClient = readFileSync(path.join(__dirname, "client.iife.js"));
213
+ let resolvedConfig;
214
+ const prodHtmlCache = {};
215
+ let devtoolsFlag = false;
216
+ return [{
217
+ name: "@tomjs:vscode",
218
+ apply: "serve",
219
+ config(config) {
220
+ return handleConfig(config);
221
+ },
222
+ configResolved(config) {
223
+ resolvedConfig = config;
224
+ },
225
+ configureServer(server) {
226
+ if (!server || !server.httpServer) return;
227
+ server.httpServer?.once("listening", async () => {
228
+ const env = {
229
+ NODE_ENV: server.config.mode || "development",
230
+ VITE_DEV_SERVER_URL: resolveServerUrl(server)
231
+ };
232
+ logger.info("extension build start");
233
+ let buildCount = 0;
234
+ const webview = opts?.webview;
235
+ const { onSuccess: _onSuccess, ignoreWatch, silent, watchFiles,...tsdownOptions } = opts.extension || {};
236
+ await build(merge(tsdownOptions, {
237
+ watch: watchFiles ?? (opts.recommended ? ["extension"] : true),
238
+ ignoreWatch: [
239
+ ".history",
240
+ ".temp",
241
+ ".tmp",
242
+ ".cache",
243
+ "dist"
244
+ ].concat(Array.isArray(ignoreWatch) ? ignoreWatch : []),
245
+ env,
246
+ silent: silent ?? true,
247
+ plugins: !webview ? [] : [{
248
+ name: `${ORG_NAME}:vscode:inject`,
249
+ transform(code, id) {
250
+ if (id.includes("node_modules")) return;
251
+ if (code.includes(`${webview.name}(`)) return `import ${webview.name} from '${PACKAGE_NAME}/webview';\n${code}`;
252
+ return code;
253
+ }
254
+ }],
255
+ async onSuccess(config, signal) {
256
+ if (_onSuccess) {
257
+ if (typeof _onSuccess === "string") await execa(_onSuccess);
258
+ else if (typeof _onSuccess === "function") await _onSuccess(config, signal);
259
+ }
260
+ if (buildCount++ > 1) logger.info("extension rebuild success");
261
+ else logger.info("extension build success");
262
+ }
263
+ }));
264
+ });
265
+ },
266
+ transformIndexHtml(html) {
267
+ if (!opts.webview) return html;
268
+ if (opts.devtools ?? true) {
269
+ let port;
270
+ if (resolvedConfig.plugins.find((s) => ["vite:react-refresh", "vite:react-swc"].includes(s.name))) port = 8097;
271
+ else if (resolvedConfig.plugins.find((s) => ["vite:vue", "vite:vue2"].includes(s.name))) port = 8098;
272
+ if (port) html = html.replace(/<head>/i, `<head><script src="http://localhost:${port}"><\/script>`);
273
+ else if (!devtoolsFlag) {
274
+ devtoolsFlag = true;
275
+ logger.warn("Only support react-devtools and vue-devtools!");
276
+ }
277
+ }
278
+ return html.replace(/<head>/i, `<head><script>${devWebviewClient}<\/script>`);
279
+ }
280
+ }, {
281
+ name: "@tomjs:vscode",
282
+ apply: "build",
283
+ enforce: "post",
284
+ config(config) {
285
+ return handleConfig(config);
286
+ },
287
+ configResolved(config) {
288
+ resolvedConfig = config;
289
+ },
290
+ transformIndexHtml(html, ctx) {
291
+ if (!opts.webview) return html;
292
+ prodHtmlCache[ctx.chunk?.name] = html;
293
+ return html;
294
+ },
295
+ closeBundle() {
296
+ let webviewPath;
297
+ const webview = opts?.webview;
298
+ if (webview) webviewPath = genProdWebviewCode(prodHtmlCache, webview);
299
+ let outDir = resolvedConfig.build.outDir.replace(cwd(), "").replaceAll("\\", "/");
300
+ if (outDir.startsWith("/")) outDir = outDir.substring(1);
301
+ const env = {
302
+ NODE_ENV: resolvedConfig.mode || "production",
303
+ VITE_WEBVIEW_DIST: outDir
304
+ };
305
+ logger.info("extension build start");
306
+ const { onSuccess: _onSuccess, silent,...tsupOptions } = opts.extension || {};
307
+ build(merge(tsupOptions, {
308
+ env,
309
+ silent: silent ?? true,
310
+ plugins: !webview ? [] : [{
311
+ name: `${ORG_NAME}:vscode:inject`,
312
+ transform(code, id) {
313
+ if (id.includes("node_modules")) return;
314
+ if (code.includes(`${webview.name}(`)) return `import ${webview.name} from "${webviewPath}";\n${code}`;
315
+ return code;
316
+ }
317
+ }],
318
+ async onSuccess(config, signal) {
319
+ if (_onSuccess) {
320
+ if (typeof _onSuccess === "string") await execa(_onSuccess);
321
+ else if (typeof _onSuccess === "function") await _onSuccess(config, signal);
322
+ }
323
+ logger.info("extension build success");
324
+ }
325
+ }));
326
+ }
327
+ }];
384
328
  }
385
- var index_default = useVSCodePlugin;
386
-
387
-
329
+ var src_default = useVSCodePlugin;
388
330
 
389
- exports.default = index_default; exports.useVSCodePlugin = useVSCodePlugin;
331
+ //#endregion
332
+ export { src_default as default, useVSCodePlugin };