@tomjs/vite-plugin-electron 1.11.0 → 2.0.1

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.mjs CHANGED
@@ -1,491 +1,454 @@
1
- // src/index.ts
2
- import fs2 from "node:fs";
3
- import path2 from "node:path";
1
+ import { t as ELECTRON_EXIT } from "./electron-BUQU2XNS.mjs";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
4
  import cloneDeep from "lodash.clonedeep";
5
- import merge2 from "lodash.merge";
6
-
7
- // src/builder.ts
5
+ import merge from "lodash.merge";
8
6
  import os from "node:os";
9
- import path from "node:path";
10
7
  import { cwd } from "node:process";
11
- import merge from "lodash.merge";
12
8
  import shell from "shelljs";
13
-
14
- // src/logger.ts
15
9
  import dayjs from "dayjs";
16
10
  import { blue, gray, green, red, yellow } from "kolorist";
11
+ import cp, { spawn } from "node:child_process";
12
+ import electron from "electron";
13
+ import { execa } from "execa";
14
+ import { build } from "tsdown";
17
15
 
18
- // src/constants.ts
19
- var PLUGIN_NAME = "tomjs:electron";
16
+ //#region src/constants.ts
17
+ const PLUGIN_NAME = "tomjs:electron";
20
18
 
21
- // src/logger.ts
19
+ //#endregion
20
+ //#region src/logger.ts
21
+ /**
22
+ * 日志
23
+ */
22
24
  var Logger = class {
23
- constructor(tag, withTime) {
24
- this.tag = PLUGIN_NAME;
25
- this.withTime = true;
26
- this.tag = `[${tag}]`;
27
- this.withTime = withTime ?? true;
28
- }
29
- getTime() {
30
- return `${this.withTime ? dayjs().format("HH:mm:ss") : ""} `;
31
- }
32
- /**
33
- * 调试
34
- */
35
- debug(msg, ...rest) {
36
- console.log(`${this.getTime()}${gray(this.tag)}`, msg, ...rest);
37
- }
38
- /**
39
- * 调试日志 等同 debug
40
- */
41
- log(msg, ...rest) {
42
- this.debug(msg, ...rest);
43
- }
44
- info(msg, ...rest) {
45
- console.log(`${this.getTime()}${blue(this.tag)}`, msg, ...rest);
46
- }
47
- warn(msg, ...rest) {
48
- console.log(`${this.getTime()}${yellow(this.tag)}`, msg, ...rest);
49
- }
50
- error(msg, ...rest) {
51
- console.log(`${this.getTime()}${red(this.tag)}`, msg, ...rest);
52
- }
53
- success(msg, ...rest) {
54
- console.log(`${this.getTime()}${green(this.tag)}`, msg, ...rest);
55
- }
25
+ constructor(tag, withTime) {
26
+ this.tag = PLUGIN_NAME;
27
+ this.withTime = true;
28
+ this.tag = `[${tag}]`;
29
+ this.withTime = withTime ?? true;
30
+ }
31
+ getTime() {
32
+ return `${this.withTime ? dayjs().format("HH:mm:ss") : ""} `;
33
+ }
34
+ /**
35
+ * 调试
36
+ */
37
+ debug(msg, ...rest) {
38
+ console.log(`${this.getTime()}${gray(this.tag)}`, msg, ...rest);
39
+ }
40
+ /**
41
+ * 调试日志 等同 debug
42
+ */
43
+ log(msg, ...rest) {
44
+ this.debug(msg, ...rest);
45
+ }
46
+ info(msg, ...rest) {
47
+ console.log(`${this.getTime()}${blue(this.tag)}`, msg, ...rest);
48
+ }
49
+ warn(msg, ...rest) {
50
+ console.log(`${this.getTime()}${yellow(this.tag)}`, msg, ...rest);
51
+ }
52
+ error(msg, ...rest) {
53
+ console.log(`${this.getTime()}${red(this.tag)}`, msg, ...rest);
54
+ }
55
+ success(msg, ...rest) {
56
+ console.log(`${this.getTime()}${green(this.tag)}`, msg, ...rest);
57
+ }
56
58
  };
57
59
  function createLogger(tag) {
58
- return new Logger(tag || PLUGIN_NAME, true);
60
+ return new Logger(tag || PLUGIN_NAME, true);
59
61
  }
60
62
 
61
- // src/utils.ts
62
- import fs from "node:fs";
63
- function readJson(path3) {
64
- if (fs.existsSync(path3)) {
65
- return JSON.parse(fs.readFileSync(path3, "utf8"));
66
- }
63
+ //#endregion
64
+ //#region src/utils.ts
65
+ function readJson(path$1) {
66
+ if (fs.existsSync(path$1)) return JSON.parse(fs.readFileSync(path$1, "utf8"));
67
67
  }
68
- function writeJson(path3, data) {
69
- fs.writeFileSync(path3, JSON.stringify(data, null, 2), "utf8");
68
+ function writeJson(path$1, data) {
69
+ fs.writeFileSync(path$1, JSON.stringify(data, null, 2), "utf8");
70
70
  }
71
+ /**
72
+ * @see https://github.com/vitejs/vite/blob/v4.0.1/packages/vite/src/node/constants.ts#L137-L147
73
+ */
71
74
  function resolveHostname(hostname) {
72
- const loopbackHosts = /* @__PURE__ */ new Set([
73
- "localhost",
74
- "127.0.0.1",
75
- "::1",
76
- "0000:0000:0000:0000:0000:0000:0000:0001"
77
- ]);
78
- const wildcardHosts = /* @__PURE__ */ new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);
79
- return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
75
+ const loopbackHosts = new Set([
76
+ "localhost",
77
+ "127.0.0.1",
78
+ "::1",
79
+ "0000:0000:0000:0000:0000:0000:0000:0001"
80
+ ]);
81
+ const wildcardHosts = new Set([
82
+ "0.0.0.0",
83
+ "::",
84
+ "0000:0000:0000:0000:0000:0000:0000:0000"
85
+ ]);
86
+ return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
80
87
  }
81
88
  function resolveServerUrl(server) {
82
- const addressInfo = server.httpServer.address();
83
- const isAddressInfo = (x) => x == null ? void 0 : x.address;
84
- if (isAddressInfo(addressInfo)) {
85
- const { address, port } = addressInfo;
86
- const hostname = resolveHostname(address);
87
- const options = server.config.server;
88
- const protocol = options.https ? "https" : "http";
89
- const devBase = server.config.base;
90
- const path3 = typeof options.open === "string" ? options.open : devBase;
91
- const url = path3.startsWith("http") ? path3 : `${protocol}://${hostname}:${port}${path3}`;
92
- return url;
93
- }
89
+ const addressInfo = server.httpServer.address();
90
+ const isAddressInfo = (x) => x?.address;
91
+ if (isAddressInfo(addressInfo)) {
92
+ const { address, port } = addressInfo;
93
+ const hostname = resolveHostname(address);
94
+ const options = server.config.server;
95
+ const protocol = options.https ? "https" : "http";
96
+ const devBase = server.config.base;
97
+ const path$1 = typeof options.open === "string" ? options.open : devBase;
98
+ return path$1.startsWith("http") ? path$1 : `${protocol}://${hostname}:${port}${path$1}`;
99
+ }
100
+ }
101
+ /**
102
+ * Inspired `tree-kill`, implemented based on sync-api. #168
103
+ * @see https://github.com/pkrumins/node-tree-kill/blob/v1.2.2/index.js
104
+ */
105
+ function treeKillSync(pid) {
106
+ if (process.platform === "win32") cp.execSync(`taskkill /pid ${pid} /T /F`);
107
+ else killTree(pidTree({
108
+ pid,
109
+ ppid: process.pid
110
+ }));
111
+ }
112
+ function pidTree(tree) {
113
+ const command = process.platform === "darwin" ? `pgrep -P ${tree.pid}` : `ps -o pid --no-headers --ppid ${tree.ppid}`;
114
+ try {
115
+ const childs = cp.execSync(command, { encoding: "utf8" }).match(/\d+/g)?.map((id) => +id);
116
+ if (childs) tree.children = childs.map((cid) => pidTree({
117
+ pid: cid,
118
+ ppid: tree.pid
119
+ }));
120
+ } catch {}
121
+ return tree;
122
+ }
123
+ function killTree(tree) {
124
+ if (tree.children) for (const child of tree.children) killTree(child);
125
+ try {
126
+ process.kill(tree.pid);
127
+ } catch {}
94
128
  }
95
129
 
96
- // src/builder.ts
97
- var logger = createLogger();
130
+ //#endregion
131
+ //#region src/builder.ts
132
+ const logger$1 = createLogger();
98
133
  function getMirror() {
99
- let mirror = process.env.ELECTRON_MIRROR;
100
- if (mirror) {
101
- return mirror;
102
- }
103
- const res = shell.exec("npm config get registry", { silent: true });
104
- if (res.code === 0) {
105
- let registry = res.stdout;
106
- if (!registry) {
107
- return;
108
- }
109
- registry = registry.trim();
110
- if (registry && ["registry.npmmirror.com", "registry.npm.taobao.org"].find((s) => registry.includes(s))) {
111
- mirror = "https://npmmirror.com/mirrors/electron";
112
- }
113
- }
114
- return mirror;
134
+ let mirror = process.env.ELECTRON_MIRROR;
135
+ if (mirror) return mirror;
136
+ const res = shell.exec("npm config get registry", { silent: true });
137
+ if (res.code === 0) {
138
+ let registry = res.stdout;
139
+ if (!registry) return;
140
+ registry = registry.trim();
141
+ if (registry && ["registry.npmmirror.com", "registry.npm.taobao.org"].find((s) => registry.includes(s))) mirror = "https://npmmirror.com/mirrors/electron";
142
+ }
143
+ return mirror;
115
144
  }
116
145
  function getBuilderConfig(options, resolvedConfig) {
117
- var _a;
118
- const config = {
119
- directories: {
120
- buildResources: "electron/build",
121
- app: path.dirname(resolvedConfig.build.outDir),
122
- output: "release/${version}"
123
- },
124
- files: ["main", "preload", "renderer"],
125
- artifactName: "${productName}-${version}-${os}-${arch}.${ext}",
126
- electronDownload: {
127
- mirror: getMirror()
128
- },
129
- electronLanguages: ["zh-CN", "en-US"],
130
- win: {
131
- target: [
132
- {
133
- target: "nsis",
134
- arch: ["x64"]
135
- }
136
- ]
137
- },
138
- mac: {
139
- target: ["dmg"]
140
- },
141
- linux: {
142
- target: ["zip"]
143
- },
144
- nsis: {
145
- oneClick: false,
146
- perMachine: false,
147
- allowToChangeInstallationDirectory: true,
148
- deleteAppDataOnUninstall: false
149
- }
150
- };
151
- if (typeof options.builder == "boolean") {
152
- return config;
153
- }
154
- const { appId, productName } = options.builder || {};
155
- return merge(config, { appId, productName }, (_a = options.builder) == null ? void 0 : _a.builderConfig);
146
+ const config = {
147
+ directories: {
148
+ buildResources: "electron/build",
149
+ app: path.dirname(resolvedConfig.build.outDir),
150
+ output: "release/${version}"
151
+ },
152
+ files: [
153
+ "main",
154
+ "preload",
155
+ "renderer"
156
+ ],
157
+ artifactName: "${productName}-${version}-${os}-${arch}.${ext}",
158
+ electronDownload: { mirror: getMirror() },
159
+ electronLanguages: ["zh-CN", "en-US"],
160
+ win: { target: [{
161
+ target: "nsis",
162
+ arch: ["x64"]
163
+ }] },
164
+ mac: { target: ["dmg"] },
165
+ linux: { target: ["zip"] },
166
+ nsis: {
167
+ oneClick: false,
168
+ perMachine: false,
169
+ allowToChangeInstallationDirectory: true,
170
+ deleteAppDataOnUninstall: false
171
+ }
172
+ };
173
+ if (typeof options.builder == "boolean") return config;
174
+ const { appId, productName } = options.builder || {};
175
+ return merge(config, {
176
+ appId,
177
+ productName
178
+ }, options.builder?.builderConfig);
156
179
  }
157
180
  function createPkg(options, resolvedConfig) {
158
- var _a, _b;
159
- const externals = options.external || [];
160
- const viteExternals = (_a = resolvedConfig.build.rollupOptions) == null ? void 0 : _a.external;
161
- if (Array.isArray(viteExternals)) {
162
- externals.push(...viteExternals);
163
- } else if (typeof viteExternals === "string") {
164
- externals.push(viteExternals);
165
- }
166
- const pkg = readJson(path.join(process.cwd(), "package.json"));
167
- if (!pkg) {
168
- throw new Error(`package.json not found in ${process.cwd()}`);
169
- }
170
- const outDir = path.dirname(resolvedConfig.build.outDir);
171
- let main = pkg.main;
172
- if (main) {
173
- main = main.replace("./", "");
174
- main = main.substring(main.indexOf(outDir) + outDir.length);
175
- if (main.startsWith("/")) {
176
- main = main.substring(1);
177
- }
178
- } else {
179
- main = `main/index.${((_b = options == null ? void 0 : options.main) == null ? void 0 : _b.format) === "esm" ? "" : "m"}js`;
180
- }
181
- const newPkg = {
182
- name: pkg.name,
183
- version: pkg.version,
184
- description: pkg.description,
185
- type: pkg.type || "commonjs",
186
- author: getAuthor(pkg.author),
187
- main,
188
- dependencies: getDeps()
189
- };
190
- writeJson(path.join(outDir, "package.json"), newPkg);
191
- function getAuthor(author) {
192
- const uname = os.userInfo().username;
193
- if (!author) {
194
- return uname;
195
- } else if (typeof author === "string") {
196
- return author;
197
- } else if (typeof author === "object") {
198
- if (!author.name) {
199
- return uname;
200
- }
201
- const email = author.email ? ` <${author.email}>` : "";
202
- return `${author.name}${email}`;
203
- }
204
- return uname;
205
- }
206
- function checkDepName(rules, name) {
207
- return !!rules.find((s) => {
208
- if (typeof s === "string") {
209
- return s.includes(name);
210
- } else {
211
- return s.test(name);
212
- }
213
- });
214
- }
215
- function getDeps() {
216
- const deps = pkg.dependencies || {};
217
- const newDeps = {};
218
- Object.keys(deps).forEach((name) => {
219
- if (checkDepName(externals, name)) {
220
- newDeps[name] = deps[name];
221
- }
222
- });
223
- return newDeps;
224
- }
225
- return newPkg;
181
+ const externals = options.external || [];
182
+ const viteExternals = resolvedConfig.build.rollupOptions?.external;
183
+ if (Array.isArray(viteExternals)) externals.push(...viteExternals);
184
+ else if (typeof viteExternals === "string") externals.push(viteExternals);
185
+ const pkg = readJson(path.join(process.cwd(), "package.json"));
186
+ if (!pkg) throw new Error(`package.json not found in ${process.cwd()}`);
187
+ const outDir = path.dirname(resolvedConfig.build.outDir);
188
+ let main = pkg.main;
189
+ if (main) {
190
+ main = main.replace("./", "");
191
+ main = main.substring(main.indexOf(outDir) + outDir.length);
192
+ if (main.startsWith("/")) main = main.substring(1);
193
+ } else main = `main/index.${options?.main?.format === "esm" ? "" : "m"}js`;
194
+ const newPkg = {
195
+ name: pkg.name,
196
+ version: pkg.version,
197
+ description: pkg.description,
198
+ type: pkg.type || "commonjs",
199
+ author: getAuthor(pkg.author),
200
+ main,
201
+ dependencies: getDeps()
202
+ };
203
+ writeJson(path.join(outDir, "package.json"), newPkg);
204
+ function getAuthor(author) {
205
+ const uname = os.userInfo().username;
206
+ if (!author) return uname;
207
+ else if (typeof author === "string") return author;
208
+ else if (typeof author === "object") {
209
+ if (!author.name) return uname;
210
+ const email = author.email ? ` <${author.email}>` : "";
211
+ return `${author.name}${email}`;
212
+ }
213
+ return uname;
214
+ }
215
+ function checkDepName(rules, name) {
216
+ return !!rules.find((s) => {
217
+ if (typeof s === "string") return s.includes(name);
218
+ else return s.test(name);
219
+ });
220
+ }
221
+ function getDeps() {
222
+ const deps = pkg.dependencies || {};
223
+ const newDeps = {};
224
+ Object.keys(deps).forEach((name) => {
225
+ if (checkDepName(externals, name)) newDeps[name] = deps[name];
226
+ });
227
+ return newDeps;
228
+ }
229
+ return newPkg;
226
230
  }
227
231
  async function runElectronBuilder(options, resolvedConfig) {
228
- if (typeof options.builder == "boolean" && options.builder === false) {
229
- return;
230
- }
231
- logger.info("building electron app...");
232
- const DIST_PATH = path.join(cwd(), path.dirname(resolvedConfig.build.outDir));
233
- createPkg(options, resolvedConfig);
234
- logger.info(`create package.json and exec "npm install"`);
235
- shell.exec(`cd ${DIST_PATH} && npm install --emit=dev`);
236
- logger.info(`run electron-builder to package app`);
237
- const config = getBuilderConfig(options, resolvedConfig);
238
- const { build } = await import("electron-builder");
239
- await build({
240
- config
241
- });
232
+ if (typeof options.builder == "boolean" && options.builder === false) return;
233
+ logger$1.info("building electron app...");
234
+ const DIST_PATH = path.join(cwd(), path.dirname(resolvedConfig.build.outDir));
235
+ createPkg(options, resolvedConfig);
236
+ logger$1.info(`create package.json and exec "npm install"`);
237
+ shell.exec(`cd ${DIST_PATH} && npm install --emit=dev`);
238
+ logger$1.info(`run electron-builder to package app`);
239
+ const config = getBuilderConfig(options, resolvedConfig);
240
+ const { build: build$1 } = await import("electron-builder");
241
+ await build$1({ config });
242
242
  }
243
243
 
244
- // src/main.ts
245
- import { spawn } from "node:child_process";
246
- import electron from "electron";
247
- import treeKill from "tree-kill";
248
- import { build as tsupBuild } from "tsup";
249
- var logger2 = createLogger();
244
+ //#endregion
245
+ //#region src/main.ts
246
+ const logger = createLogger();
250
247
  function getBuildOptions(options) {
251
- return ["main", "preload"].filter((s) => options[s] && options[s].entry).map((s) => {
252
- options[s].__NAME__ = s;
253
- return options[s];
254
- }).map((cfg) => {
255
- return {
256
- ...cfg,
257
- splitting: false,
258
- silent: true
259
- };
260
- });
248
+ return ["main", "preload"].filter((s) => options[s] && options[s].entry).map((s) => {
249
+ options[s].__NAME__ = s;
250
+ return options[s];
251
+ }).map((cfg) => {
252
+ return {
253
+ ...cfg,
254
+ logLevel: "silent"
255
+ };
256
+ });
261
257
  }
258
+ /**
259
+ * startup electron app
260
+ */
262
261
  async function startup(options) {
263
- if (options.debug) {
264
- return;
265
- }
266
- await startup.exit();
267
- const args = ["."];
268
- if (options.inspect) {
269
- if (typeof options.inspect === "number") {
270
- args.push(`--inspect=${options.inspect}`);
271
- } else {
272
- args.push(`--inspect`);
273
- }
274
- }
275
- process.electronApp = spawn(electron, args, {
276
- stdio: "inherit"
277
- });
278
- process.electronApp.once("exit", process.exit);
279
- process.once("exit", () => {
280
- startup.exit();
281
- process.electronApp.kill();
282
- });
262
+ console.log("startup electron debug mode:", options.debug);
263
+ if (options.debug) return;
264
+ await startup.exit();
265
+ const args = [".", "--no-sandbox"];
266
+ if (options.inspect) if (typeof options.inspect === "number") args.push(`--inspect=${options.inspect}`);
267
+ else args.push(`--inspect`);
268
+ process.electronApp = spawn(electron, args, { stdio: [
269
+ "inherit",
270
+ "inherit",
271
+ "inherit",
272
+ "ipc"
273
+ ] });
274
+ process.electronApp.once("exit", process.exit);
275
+ if (!startup.hookedProcessExit) {
276
+ startup.hookedProcessExit = true;
277
+ process.once("exit", startup.exit);
278
+ }
283
279
  }
280
+ startup.send = (message) => {
281
+ if (process.electronApp) process.electronApp.send?.(message);
282
+ };
283
+ startup.hookedProcessExit = false;
284
284
  startup.exit = async () => {
285
- if (!process.electronApp) {
286
- return;
287
- }
288
- process.electronApp.removeAllListeners();
289
- return new Promise((resolve, reject) => {
290
- treeKill(process.electronApp.pid, (err) => {
291
- if (err) {
292
- reject(err);
293
- } else {
294
- resolve(true);
295
- }
296
- });
297
- });
285
+ if (!process.electronApp) return;
286
+ await new Promise((resolve) => {
287
+ startup.send(ELECTRON_EXIT);
288
+ process.electronApp.removeAllListeners();
289
+ process.electronApp.once("exit", resolve);
290
+ treeKillSync(process.electronApp.pid);
291
+ });
298
292
  };
299
293
  async function runServe(options, server) {
300
- options.debug && logger2.warn(`debug mode`);
301
- const buildOptions = getBuildOptions(options);
302
- const buildCounts = [0, buildOptions.length > 1 ? 0 : 1];
303
- for (let i = 0; i < buildOptions.length; i++) {
304
- const tsOpts = buildOptions[i];
305
- const { __NAME__: name, onSuccess: _onSuccess, watch, ...tsupOptions } = tsOpts;
306
- logger2.info(`${name} build`);
307
- const onSuccess = async () => {
308
- if (typeof _onSuccess === "function") {
309
- await _onSuccess();
310
- }
311
- if (buildCounts[i] <= 0) {
312
- buildCounts[i]++;
313
- logger2.info(`${name} build success`);
314
- if (buildCounts[0] === 1 && buildCounts[1] === 1) {
315
- logger2.info("startup electron");
316
- await startup(options);
317
- }
318
- return;
319
- }
320
- logger2.success(`${name} rebuild success`);
321
- if (name === "main") {
322
- logger2.info("restart electron");
323
- await startup(options);
324
- } else {
325
- logger2.info("reload page");
326
- server.ws.send({
327
- type: "full-reload"
328
- });
329
- }
330
- };
331
- await tsupBuild({ onSuccess, watch: true, ...tsupOptions });
332
- }
294
+ options.debug && logger.warn(`debug mode`);
295
+ const buildOptions = getBuildOptions(options);
296
+ const buildCounts = [0, buildOptions.length > 1 ? 0 : 1];
297
+ for (let i = 0; i < buildOptions.length; i++) {
298
+ const { __NAME__: name, ignoreWatch, onSuccess: _onSuccess, watchFiles, ...tsupOptions } = buildOptions[i];
299
+ logger.info(`${name} build`);
300
+ const onSuccess = async (config, signal) => {
301
+ if (_onSuccess) {
302
+ if (typeof _onSuccess === "string") await execa(_onSuccess);
303
+ else if (typeof _onSuccess === "function") await _onSuccess(config, signal);
304
+ }
305
+ if (buildCounts[i] <= 0) {
306
+ buildCounts[i]++;
307
+ logger.info(`${name} build success`);
308
+ if (buildCounts[0] === 1 && buildCounts[1] === 1) {
309
+ logger.info("startup electron");
310
+ await startup(options);
311
+ }
312
+ return;
313
+ }
314
+ logger.success(`${name} rebuild success`);
315
+ if (name === "main") {
316
+ logger.info("restart electron");
317
+ await startup(options);
318
+ } else {
319
+ logger.info("reload page");
320
+ server.ws.send({ type: "full-reload" });
321
+ }
322
+ };
323
+ await build({
324
+ onSuccess,
325
+ ...tsupOptions,
326
+ watch: watchFiles ?? (options.recommended ? [`electron/${name}`] : true),
327
+ ignoreWatch: (Array.isArray(ignoreWatch) ? ignoreWatch : []).concat([
328
+ ".history",
329
+ ".temp",
330
+ ".tmp",
331
+ ".cache",
332
+ "dist"
333
+ ])
334
+ });
335
+ }
333
336
  }
334
337
  async function runBuild(options) {
335
- const buildOptions = getBuildOptions(options);
336
- for (let i = 0; i < buildOptions.length; i++) {
337
- await tsupBuild(buildOptions[i]);
338
- }
338
+ const buildOptions = getBuildOptions(options);
339
+ for (let i = 0; i < buildOptions.length; i++) await build(buildOptions[i]);
339
340
  }
340
341
 
341
- // src/index.ts
342
- var isDev = process.env.NODE_ENV === "development";
342
+ //#endregion
343
+ //#region src/index.ts
344
+ const isDev = process.env.NODE_ENV === "development";
343
345
  function getPkg() {
344
- const pkgFile = path2.resolve(process.cwd(), "package.json");
345
- if (!fs2.existsSync(pkgFile)) {
346
- throw new Error("Main file is not specified, and no package.json found");
347
- }
348
- const pkg = readJson(pkgFile);
349
- if (!pkg.main) {
350
- throw new Error("Main file is not specified, please check package.json");
351
- }
352
- return pkg;
346
+ const pkgFile = path.resolve(process.cwd(), "package.json");
347
+ if (!fs.existsSync(pkgFile)) throw new Error("Main file is not specified, and no package.json found");
348
+ const pkg = readJson(pkgFile);
349
+ if (!pkg.main) throw new Error("Main file is not specified, please check package.json");
350
+ return pkg;
353
351
  }
354
352
  function preMergeOptions(options) {
355
- const pkg = getPkg();
356
- const format = pkg.type === "module" ? "esm" : "cjs";
357
- const electron2 = {
358
- target: format === "esm" ? "node18.18" : "node16",
359
- format,
360
- shims: true,
361
- clean: true,
362
- dts: false,
363
- treeshake: !!isDev,
364
- outExtension({ format: format2 }) {
365
- return {
366
- js: format2 === "esm" ? ".mjs" : `.js`
367
- };
368
- }
369
- };
370
- const opts = merge2(
371
- {
372
- recommended: true,
373
- debug: false,
374
- external: ["electron"],
375
- main: {
376
- ...electron2
377
- },
378
- preload: {
379
- ...electron2
380
- },
381
- builder: false
382
- },
383
- cloneDeep(options)
384
- );
385
- ["main", "preload"].forEach((prop) => {
386
- const opt = opts[prop];
387
- const fmt = opt.format;
388
- opt.format = ["cjs", "esm"].includes(fmt) ? [fmt] : [format];
389
- const entry = opt.entry;
390
- if (entry === void 0) {
391
- const filePath = `electron/${prop}/index.ts`;
392
- if (fs2.existsSync(path2.join(process.cwd(), filePath))) {
393
- opt.entry = [filePath];
394
- }
395
- } else if (typeof entry === "string") {
396
- opt.entry = [entry];
397
- }
398
- if (isDev) {
399
- opt.sourcemap ??= true;
400
- } else {
401
- opt.minify ??= true;
402
- }
403
- const external = opt.external || opts.external || ["electron"];
404
- opt.external = [...new Set(["electron"].concat(external))];
405
- });
406
- return opts;
353
+ const format = getPkg().type === "module" ? "esm" : "cjs";
354
+ const electron$1 = {
355
+ target: format === "esm" ? "node18.18" : "node16",
356
+ format,
357
+ shims: true,
358
+ clean: true,
359
+ dts: false,
360
+ treeshake: !!isDev,
361
+ outExtensions({ format: format$1 }) {
362
+ return { js: format$1 === "es" ? ".mjs" : ".js" };
363
+ }
364
+ };
365
+ const opts = merge({
366
+ recommended: true,
367
+ debug: false,
368
+ external: ["electron"],
369
+ main: { ...electron$1 },
370
+ preload: { ...electron$1 },
371
+ builder: false
372
+ }, cloneDeep(options));
373
+ ["main", "preload"].forEach((prop) => {
374
+ const opt = opts[prop];
375
+ const fmt = opt.format;
376
+ opt.format = ["cjs", "esm"].includes(fmt) ? [fmt] : [format];
377
+ const entry = opt.entry;
378
+ if (entry === void 0) {
379
+ const filePath = `electron/${prop}/index.ts`;
380
+ if (fs.existsSync(path.join(process.cwd(), filePath))) opt.entry = [filePath];
381
+ } else if (typeof entry === "string") opt.entry = [entry];
382
+ if (isDev) opt.sourcemap ??= true;
383
+ else opt.minify ??= true;
384
+ const external = opt.external || opts.external || ["electron"];
385
+ opt.external = [...new Set(["electron"].concat(external))];
386
+ });
387
+ return opts;
407
388
  }
408
389
  function geNumberBooleanValue(value) {
409
- if (typeof value !== "string" || value.trim() === "") {
410
- return;
411
- }
412
- if (["true", "false"].includes(value)) {
413
- return value === "true";
414
- }
415
- const v = Number(value);
416
- return Number.isNaN(v) ? void 0 : v;
390
+ if (typeof value !== "string" || value.trim() === "") return;
391
+ if (["true", "false"].includes(value)) return value === "true";
392
+ const v = Number(value);
393
+ return Number.isNaN(v) ? void 0 : v;
417
394
  }
418
395
  function getBooleanValue(value) {
419
- if (typeof value !== "string" || value.trim() === "") {
420
- return;
421
- }
422
- if (["true", "false"].includes(value)) {
423
- return value === "true";
424
- }
425
- if (["1", "0"].includes(value)) {
426
- return value === "1";
427
- }
396
+ if (typeof value !== "string" || value.trim() === "") return;
397
+ if (["true", "false"].includes(value)) return value === "true";
398
+ if (["1", "0"].includes(value)) return value === "1";
428
399
  }
400
+ /**
401
+ * A simple vite plugin for electron
402
+ * @param options
403
+ */
429
404
  function useElectronPlugin(options) {
430
- const opts = preMergeOptions(options);
431
- let isServer = false;
432
- let resolvedConfig;
433
- return {
434
- name: PLUGIN_NAME,
435
- config(config, env) {
436
- var _a;
437
- isServer = env.command === "serve";
438
- let outDir = ((_a = config == null ? void 0 : config.build) == null ? void 0 : _a.outDir) || "dist";
439
- opts.main ||= {};
440
- opts.preload ||= {};
441
- if (opts.recommended) {
442
- opts.main.outDir = path2.join(outDir, "main");
443
- opts.preload.outDir = path2.join(outDir, "preload");
444
- outDir = path2.join(outDir, "renderer");
445
- } else {
446
- opts.main.outDir ||= path2.join("dist-electron", "main");
447
- opts.preload.outDir ||= path2.join("dist-electron", "preload");
448
- }
449
- return {
450
- build: {
451
- outDir
452
- }
453
- };
454
- },
455
- configResolved(config) {
456
- opts.debug = getBooleanValue(config.env.VITE_ELECTRON_DEBUG) ?? opts.debug;
457
- opts.inspect = geNumberBooleanValue(config.env.VITE_ELECTRON_INSPECT) ?? opts.inspect;
458
- opts.builder = getBooleanValue(config.env.VITE_ELECTRON_BUILDER) ?? opts.builder;
459
- resolvedConfig = config;
460
- },
461
- configureServer(server) {
462
- if (!server || !server.httpServer) {
463
- return;
464
- }
465
- server.httpServer.on("listening", async () => {
466
- const env = {
467
- NODE_ENV: server.config.mode || "development",
468
- VITE_DEV_SERVER_URL: resolveServerUrl(server)
469
- };
470
- ["main", "preload"].forEach((prop) => {
471
- opts[prop].env = env;
472
- });
473
- await runServe(opts, server);
474
- });
475
- },
476
- async closeBundle() {
477
- if (isServer) {
478
- return;
479
- }
480
- await runBuild(opts);
481
- if (opts.recommended && opts.builder) {
482
- await runElectronBuilder(opts, resolvedConfig);
483
- }
484
- }
485
- };
405
+ const opts = preMergeOptions(options);
406
+ let isServer = false;
407
+ let resolvedConfig;
408
+ return {
409
+ name: PLUGIN_NAME,
410
+ config(config, env) {
411
+ isServer = env.command === "serve";
412
+ let outDir = config?.build?.outDir || "dist";
413
+ opts.main ||= {};
414
+ opts.preload ||= {};
415
+ if (opts.recommended) {
416
+ opts.main.outDir = path.join(outDir, "main");
417
+ opts.preload.outDir = path.join(outDir, "preload");
418
+ outDir = path.join(outDir, "renderer");
419
+ } else {
420
+ opts.main.outDir ||= path.join("dist-electron", "main");
421
+ opts.preload.outDir ||= path.join("dist-electron", "preload");
422
+ }
423
+ return { build: { outDir } };
424
+ },
425
+ configResolved(config) {
426
+ opts.debug = getBooleanValue(config.env.VITE_ELECTRON_DEBUG) ?? opts.debug;
427
+ opts.inspect = geNumberBooleanValue(config.env.VITE_ELECTRON_INSPECT) ?? opts.inspect;
428
+ opts.builder = getBooleanValue(config.env.VITE_ELECTRON_BUILDER) ?? opts.builder;
429
+ resolvedConfig = config;
430
+ },
431
+ configureServer(server) {
432
+ if (!server || !server.httpServer) return;
433
+ server.httpServer.on("listening", async () => {
434
+ const env = {
435
+ NODE_ENV: server.config.mode || "development",
436
+ VITE_DEV_SERVER_URL: resolveServerUrl(server)
437
+ };
438
+ ["main", "preload"].forEach((prop) => {
439
+ opts[prop].env = env;
440
+ });
441
+ await runServe(opts, server);
442
+ });
443
+ },
444
+ async closeBundle() {
445
+ if (isServer) return;
446
+ await runBuild(opts);
447
+ if (opts.recommended && opts.builder) await runElectronBuilder(opts, resolvedConfig);
448
+ }
449
+ };
486
450
  }
487
- var index_default = useElectronPlugin;
488
- export {
489
- index_default as default,
490
- useElectronPlugin
491
- };
451
+ var src_default = useElectronPlugin;
452
+
453
+ //#endregion
454
+ export { src_default as default, useElectronPlugin };