electron-incremental-update 2.1.2 → 2.2.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.
@@ -1,13 +1,15 @@
1
1
  import { readableSize } from './chunk-WYQ5DRO7.js';
2
- import { convertLiteral, bytecodeModuleLoader, convertArrowFunctionAndTemplate, compileToBytecode, useStrict, toRelativePath } from './chunk-AUY7A2FL.js';
3
- import './chunk-7M7DIMDN.js';
2
+ import { convertLiteral, bytecodeModuleLoaderCode, bytecodeModuleLoader, convertArrowFunctionAndTemplate, compileToBytecode, useStrict, toRelativePath } from './chunk-I2EHKJU4.js';
3
+ import './chunk-CTUEQCKL.js';
4
4
  import { bytecodeLog, bytecodeId } from './chunk-5NKEXGI3.js';
5
- import { bytecodeModuleLoaderCode } from './chunk-7IRGAAL2.js';
6
5
  import path from 'node:path';
7
6
  import fs from 'node:fs';
8
7
  import { createFilter, normalizePath } from 'vite';
9
8
  import MagicString from 'magic-string';
10
9
 
10
+ function getBytecodeLoaderBlock(chunkFileName) {
11
+ return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`;
12
+ }
11
13
  function bytecodePlugin(env, options) {
12
14
  const {
13
15
  enable,
@@ -77,9 +79,6 @@ function bytecodePlugin(env, options) {
77
79
  const nonEntryChunks = chunks.filter((chunk) => !chunk.isEntry).map((chunk) => path.basename(chunk.fileName));
78
80
  const pattern = nonEntryChunks.map((chunk) => `(${chunk})`).join("|");
79
81
  const bytecodeRE = pattern ? new RegExp(`require\\(\\S*(?=(${pattern})\\S*\\))`, "g") : null;
80
- const getBytecodeLoaderBlock = (chunkFileName) => {
81
- return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`;
82
- };
83
82
  await Promise.all(
84
83
  bundles.map(async (name) => {
85
84
  const chunk = output[name];
@@ -29,17 +29,17 @@ function parseVersion(version) {
29
29
  }
30
30
  return ret;
31
31
  }
32
+ function compareStrings(str1, str2) {
33
+ if (str1 === "") {
34
+ return str2 !== "";
35
+ } else if (str2 === "") {
36
+ return true;
37
+ }
38
+ return str1 < str2;
39
+ }
32
40
  function defaultIsLowerVersion(oldVer, newVer) {
33
41
  const oldV = parseVersion(oldVer);
34
42
  const newV = parseVersion(newVer);
35
- function compareStrings(str1, str2) {
36
- if (str1 === "") {
37
- return str2 !== "";
38
- } else if (str2 === "") {
39
- return true;
40
- }
41
- return str1 < str2;
42
- }
43
43
  for (let key of Object.keys(oldV)) {
44
44
  if (key === "stage" && compareStrings(oldV[key], newV[key])) {
45
45
  return true;
@@ -49,8 +49,8 @@ function defaultIsLowerVersion(oldVer, newVer) {
49
49
  }
50
50
  return false;
51
51
  }
52
+ var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
52
53
  function isUpdateJSON(json) {
53
- const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
54
54
  return is(json) && is(json?.beta);
55
55
  }
56
56
  function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
@@ -22,8 +22,8 @@ function parseVersion(version) {
22
22
  }
23
23
  return ret;
24
24
  }
25
+ var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
25
26
  function isUpdateJSON(json) {
26
- const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
27
27
  return is(json) && is(json?.beta);
28
28
  }
29
29
  function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
@@ -1,6 +1,5 @@
1
- import { parseVersion } from './chunk-7M7DIMDN.js';
1
+ import { parseVersion } from './chunk-CTUEQCKL.js';
2
2
  import { bytecodeLog } from './chunk-5NKEXGI3.js';
3
- import { bytecodeGeneratorScript } from './chunk-7IRGAAL2.js';
4
3
  import path from 'node:path';
5
4
  import fs from 'node:fs';
6
5
  import cp from 'node:child_process';
@@ -8,6 +7,9 @@ import * as babel from '@babel/core';
8
7
  import MagicString from 'magic-string';
9
8
  import { getPackageInfoSync } from 'local-pkg';
10
9
 
10
+ // src/vite/bytecode/code.ts
11
+ var bytecodeGeneratorScript = "const vm = require('vm')\nconst v8 = require('v8')\nconst wrap = require('module').wrap\nv8.setFlagsFromString('--no-lazy')\nv8.setFlagsFromString('--no-flush-bytecode')\nlet code = ''\nprocess.stdin.setEncoding('utf-8')\nprocess.stdin.on('readable', () => {\n const data = process.stdin.read()\n if (data !== null) {\n code += data\n }\n})\nprocess.stdin.on('end', () => {\n try {\n if (typeof code !== 'string') {\n throw new Error('javascript code must be string.')\n }\n const script = new vm.Script(wrap(code), { produceCachedData: true })\n const bytecodeBuffer = script.createCachedData()\n process.stdout.write(bytecodeBuffer)\n } catch (error) {\n console.error(error)\n }\n})\n";
12
+ var bytecodeModuleLoaderCode = '"use strict";\nconst fs = require("fs");\nconst path = require("path");\nconst vm = require("vm");\nconst v8 = require("v8");\nconst Module = require("module");\nv8.setFlagsFromString("--no-lazy");\nv8.setFlagsFromString("--no-flush-bytecode");\nconst FLAG_HASH_OFFSET = 12;\nconst SOURCE_HASH_OFFSET = 8;\nlet dummyBytecode;\nfunction setFlagHashHeader(bytecodeBuffer) {\n if (!dummyBytecode) {\n const script = new vm.Script("", {\n produceCachedData: true\n });\n dummyBytecode = script.createCachedData();\n }\n dummyBytecode.slice(FLAG_HASH_OFFSET, FLAG_HASH_OFFSET + 4).copy(bytecodeBuffer, FLAG_HASH_OFFSET);\n};\nfunction getSourceHashHeader(bytecodeBuffer) {\n return bytecodeBuffer.slice(SOURCE_HASH_OFFSET, SOURCE_HASH_OFFSET + 4);\n};\nfunction buffer2Number(buffer) {\n let ret = 0;\n ret |= buffer[3] << 24;\n ret |= buffer[2] << 16;\n ret |= buffer[1] << 8;\n ret |= buffer[0];\n return ret;\n};\nModule._extensions[".jsc"] = Module._extensions[".cjsc"] = function (module, filename) {\n const bytecodeBuffer = fs.readFileSync(filename);\n if (!Buffer.isBuffer(bytecodeBuffer)) {\n throw new Error("BytecodeBuffer must be a buffer object.");\n }\n setFlagHashHeader(bytecodeBuffer);\n const length = buffer2Number(getSourceHashHeader(bytecodeBuffer));\n let dummyCode = "";\n if (length > 1) {\n dummyCode = "\\"" + "\\u200b".repeat(length - 2) + "\\"";\n }\n const script = new vm.Script(dummyCode, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true,\n cachedData: bytecodeBuffer\n });\n if (script.cachedDataRejected) {\n throw new Error("Invalid or incompatible cached data (cachedDataRejected)");\n }\n const require = function (id) {\n return module.require(id);\n };\n require.resolve = function (request, options) {\n return Module._resolveFilename(request, module, false, options);\n };\n if (process.mainModule) {\n require.main = process.mainModule;\n }\n require.extensions = Module._extensions;\n require.cache = Module._cache;\n const compiledWrapper = script.runInThisContext({\n filename: filename,\n lineOffset: 0,\n columnOffset: 0,\n displayErrors: true\n });\n const dirname = path.dirname(filename);\n const args = [module.exports, require, module, filename, dirname, process, global];\n return compiledWrapper.apply(module.exports, args);\n};\n';
11
13
  var electronModule = getPackageInfoSync("electron");
12
14
  var electronMajorVersion = parseVersion(electronModule.version).major;
13
15
  var useStrict = "'use strict';";
@@ -44,9 +46,9 @@ function toRelativePath(filename, importer) {
44
46
  const relPath = path.posix.relative(path.dirname(importer), filename);
45
47
  return relPath.startsWith(".") ? relPath : `./${relPath}`;
46
48
  }
49
+ var logErr = (...args) => bytecodeLog.error(args.join(" "), { timestamp: true });
47
50
  function compileToBytecode(code, electronPath = getElectronPath()) {
48
51
  let data = Buffer.from([]);
49
- const logErr = (...args) => bytecodeLog.error(args.join(" "), { timestamp: true });
50
52
  const bytecodePath = getBytecodeCompilerPath();
51
53
  return new Promise((resolve, reject) => {
52
54
  const proc = cp.spawn(electronPath, [bytecodePath], {
@@ -144,4 +146,4 @@ function convertLiteral(code, sourcemap, offset) {
144
146
  };
145
147
  }
146
148
 
147
- export { bytecodeModuleLoader, compileToBytecode, convertArrowFunctionAndTemplate, convertLiteral, decodeFn, electronMajorVersion, electronModule, obfuscateString, toRelativePath, useStrict };
149
+ export { bytecodeModuleLoader, bytecodeModuleLoaderCode, compileToBytecode, convertArrowFunctionAndTemplate, convertLiteral, electronMajorVersion, toRelativePath, useStrict };
@@ -1,4 +1,4 @@
1
- import { __require } from './chunk-RCRKUKFX.js';
1
+ import { __require } from './chunk-AAAM44NW.js';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import electron from 'electron';
@@ -1,4 +1,6 @@
1
- import { electronMajorVersion } from './chunk-AUY7A2FL.js';
1
+ import { electronMajorVersion } from './chunk-I2EHKJU4.js';
2
+ import './chunk-CTUEQCKL.js';
3
+ import { esmId } from './chunk-5NKEXGI3.js';
2
4
  import MagicString from 'magic-string';
3
5
 
4
6
  // src/vite/esm/constant.ts
@@ -41,4 +43,23 @@ function insertCJSShim(code, sourcemap, insertPosition = 0) {
41
43
  };
42
44
  }
43
45
 
44
- export { findStaticImports, insertCJSShim };
46
+ // src/vite/esm/index.ts
47
+ function esm() {
48
+ let sourcemap;
49
+ return {
50
+ name: esmId,
51
+ enforce: "post",
52
+ configResolved(config) {
53
+ sourcemap = config.build.sourcemap;
54
+ },
55
+ renderChunk(code, _chunk, options) {
56
+ if (options.format === "es") {
57
+ const lastESMImport = findStaticImports(code).pop();
58
+ const pos = lastESMImport ? lastESMImport.end : 0;
59
+ return insertCJSShim(code, sourcemap, pos);
60
+ }
61
+ }
62
+ };
63
+ }
64
+
65
+ export { esm };
package/dist/index.cjs CHANGED
@@ -19,8 +19,8 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
19
19
  });
20
20
 
21
21
  // src/utils/version.ts
22
+ var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
22
23
  function isUpdateJSON(json) {
23
- const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
24
24
  return is(json) && is(json?.beta);
25
25
  }
26
26
  var isDev = __EIU_IS_DEV__;
@@ -40,6 +40,9 @@ function restartApp() {
40
40
  electron__default.default.app.relaunch();
41
41
  electron__default.default.app.quit();
42
42
  }
43
+ function getPathFromMain(...paths) {
44
+ return isDev ? path__default.default.join(electron__default.default.app.getAppPath(), __EIU_ELECTRON_DIST_PATH__, "main", ...paths) : getPathFromAppNameAsar("main", ...paths);
45
+ }
43
46
 
44
47
  // src/entry/types.ts
45
48
  var UpdaterError = class extends Error {
@@ -103,7 +106,7 @@ var Updater = class extends events.EventEmitter {
103
106
  }
104
107
  this.logger?.debug(`Download from \`${this.provider.name}\``);
105
108
  try {
106
- const result = format === "json" ? await this.provider.downloadJSON(electron.app.name, __EIU_VERSION_PATH__, this.controller.signal) : await this.provider.downloadAsar(this.info, this.controller.signal, (info) => this.emit("download-progress", info));
109
+ const result = format === "json" ? await this.provider.downloadJSON(electron__default.default.app.name, __EIU_VERSION_PATH__, this.controller.signal) : await this.provider.downloadAsar(this.info, this.controller.signal, (info) => this.emit("download-progress", info));
107
110
  this.logger?.debug(`Download ${format} success${format === "buffer" ? `, file size: ${result.length}` : ""}`);
108
111
  return result;
109
112
  } catch (e) {
@@ -232,11 +235,7 @@ var defaultOnInstall = (install, _, __, logger) => {
232
235
  async function createElectronApp(appOptions = {}) {
233
236
  const appNameAsarPath = getPathFromAppNameAsar();
234
237
  const {
235
- mainPath = path__default.default.join(
236
- isDev ? path__default.default.join(electron.app.getAppPath(), __EIU_MAIN_DEV_DIR__) : appNameAsarPath,
237
- "main",
238
- __EIU_MAIN_FILE__
239
- ),
238
+ mainPath = getPathFromMain(__EIU_MAIN_FILE__),
240
239
  updater,
241
240
  onInstall = defaultOnInstall,
242
241
  beforeStart,
@@ -259,7 +258,7 @@ async function createElectronApp(appOptions = {}) {
259
258
  } catch (error) {
260
259
  logger?.error("startup error", error);
261
260
  onStartError?.(error, logger);
262
- electron.app.quit();
261
+ electron__default.default.app.quit();
263
262
  }
264
263
  }
265
264
  var initApp = createElectronApp;
package/dist/index.js CHANGED
@@ -1,9 +1,8 @@
1
- import { isDev, getAppVersion, getEntryVersion, getPathFromAppNameAsar, restartApp } from './chunk-2XSFM3E5.js';
2
- import { isUpdateJSON, __require } from './chunk-RCRKUKFX.js';
1
+ import { isDev, getAppVersion, getEntryVersion, getPathFromAppNameAsar, restartApp, getPathFromMain } from './chunk-JI27JWJN.js';
2
+ import { isUpdateJSON, __require } from './chunk-AAAM44NW.js';
3
3
  import fs2 from 'node:fs';
4
4
  import { EventEmitter } from 'node:events';
5
- import { app } from 'electron';
6
- import path from 'node:path';
5
+ import electron from 'electron';
7
6
 
8
7
  // src/entry/types.ts
9
8
  var UpdaterError = class extends Error {
@@ -67,7 +66,7 @@ var Updater = class extends EventEmitter {
67
66
  }
68
67
  this.logger?.debug(`Download from \`${this.provider.name}\``);
69
68
  try {
70
- const result = format === "json" ? await this.provider.downloadJSON(app.name, __EIU_VERSION_PATH__, this.controller.signal) : await this.provider.downloadAsar(this.info, this.controller.signal, (info) => this.emit("download-progress", info));
69
+ const result = format === "json" ? await this.provider.downloadJSON(electron.app.name, __EIU_VERSION_PATH__, this.controller.signal) : await this.provider.downloadAsar(this.info, this.controller.signal, (info) => this.emit("download-progress", info));
71
70
  this.logger?.debug(`Download ${format} success${format === "buffer" ? `, file size: ${result.length}` : ""}`);
72
71
  return result;
73
72
  } catch (e) {
@@ -196,11 +195,7 @@ var defaultOnInstall = (install, _, __, logger) => {
196
195
  async function createElectronApp(appOptions = {}) {
197
196
  const appNameAsarPath = getPathFromAppNameAsar();
198
197
  const {
199
- mainPath = path.join(
200
- isDev ? path.join(app.getAppPath(), __EIU_MAIN_DEV_DIR__) : appNameAsarPath,
201
- "main",
202
- __EIU_MAIN_FILE__
203
- ),
198
+ mainPath = getPathFromMain(__EIU_MAIN_FILE__),
204
199
  updater,
205
200
  onInstall = defaultOnInstall,
206
201
  beforeStart,
@@ -223,7 +218,7 @@ async function createElectronApp(appOptions = {}) {
223
218
  } catch (error) {
224
219
  logger?.error("startup error", error);
225
220
  onStartError?.(error, logger);
226
- app.quit();
221
+ electron.app.quit();
227
222
  }
228
223
  }
229
224
  var initApp = createElectronApp;
package/dist/provider.cjs CHANGED
@@ -37,17 +37,17 @@ function parseVersion(version) {
37
37
  }
38
38
  return ret;
39
39
  }
40
+ function compareStrings(str1, str2) {
41
+ if (str1 === "") {
42
+ return str2 !== "";
43
+ } else if (str2 === "") {
44
+ return true;
45
+ }
46
+ return str1 < str2;
47
+ }
40
48
  function defaultIsLowerVersion(oldVer, newVer) {
41
49
  const oldV = parseVersion(oldVer);
42
50
  const newV = parseVersion(newVer);
43
- function compareStrings(str1, str2) {
44
- if (str1 === "") {
45
- return str2 !== "";
46
- } else if (str2 === "") {
47
- return true;
48
- }
49
- return str1 < str2;
50
- }
51
51
  for (let key of Object.keys(oldV)) {
52
52
  if (key === "stage" && compareStrings(oldV[key], newV[key])) {
53
53
  return true;
@@ -57,8 +57,8 @@ function defaultIsLowerVersion(oldVer, newVer) {
57
57
  }
58
58
  return false;
59
59
  }
60
+ var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
60
61
  function isUpdateJSON(json) {
61
- const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
62
62
  return is(json) && is(json?.beta);
63
63
  }
64
64
 
package/dist/provider.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { defaultVerifySignature, defaultUnzipFile } from './chunk-PUVBFHOK.js';
2
- import { isUpdateJSON, defaultIsLowerVersion } from './chunk-RCRKUKFX.js';
2
+ import { isUpdateJSON, defaultIsLowerVersion } from './chunk-AAAM44NW.js';
3
3
  import { URL } from 'node:url';
4
4
  import electron from 'electron';
5
5
 
package/dist/utils.cjs CHANGED
@@ -148,17 +148,17 @@ function parseVersion(version) {
148
148
  }
149
149
  return ret;
150
150
  }
151
+ function compareStrings(str1, str2) {
152
+ if (str1 === "") {
153
+ return str2 !== "";
154
+ } else if (str2 === "") {
155
+ return true;
156
+ }
157
+ return str1 < str2;
158
+ }
151
159
  function defaultIsLowerVersion(oldVer, newVer) {
152
160
  const oldV = parseVersion(oldVer);
153
161
  const newV = parseVersion(newVer);
154
- function compareStrings(str1, str2) {
155
- if (str1 === "") {
156
- return str2 !== "";
157
- } else if (str2 === "") {
158
- return true;
159
- }
160
- return str1 < str2;
161
- }
162
162
  for (let key of Object.keys(oldV)) {
163
163
  if (key === "stage" && compareStrings(oldV[key], newV[key])) {
164
164
  return true;
@@ -168,8 +168,8 @@ function defaultIsLowerVersion(oldVer, newVer) {
168
168
  }
169
169
  return false;
170
170
  }
171
+ var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
171
172
  function isUpdateJSON(json) {
172
- const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
173
173
  return is(json) && is(json?.beta);
174
174
  }
175
175
  function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
package/dist/utils.js CHANGED
@@ -1,3 +1,3 @@
1
- export { beautifyDevTools, disableHWAccForWin7, getAppVersion, getEntryVersion, getPathFromAppNameAsar, getPathFromEntryAsar, getPathFromMain, getPathFromPreload, getPathFromPublic, handleUnexpectedErrors, importNative, isDev, isLinux, isMac, isWin, loadPage, requireNative, restartApp, setAppUserModelId, setPortableAppDataPath, singleInstance } from './chunk-2XSFM3E5.js';
1
+ export { beautifyDevTools, disableHWAccForWin7, getAppVersion, getEntryVersion, getPathFromAppNameAsar, getPathFromEntryAsar, getPathFromMain, getPathFromPreload, getPathFromPublic, handleUnexpectedErrors, importNative, isDev, isLinux, isMac, isWin, loadPage, requireNative, restartApp, setAppUserModelId, setPortableAppDataPath, singleInstance } from './chunk-JI27JWJN.js';
2
2
  export { aesDecrypt, aesEncrypt, defaultSignature, defaultUnzipFile, defaultVerifySignature, defaultZipFile, hashBuffer } from './chunk-PUVBFHOK.js';
3
- export { defaultIsLowerVersion, defaultVersionJsonGenerator, isUpdateJSON, parseVersion } from './chunk-RCRKUKFX.js';
3
+ export { defaultIsLowerVersion, defaultVersionJsonGenerator, isUpdateJSON, parseVersion } from './chunk-AAAM44NW.js';
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { PluginOption } from 'vite';
1
+ import { InlineConfig, PluginOption } from 'vite';
2
2
  import { ElectronSimpleOptions } from 'vite-plugin-electron/simple';
3
3
  import { Promisable } from '@subframe7536/type-utils';
4
- import { BuildOptions } from 'esbuild';
5
4
  export { isCI } from 'ci-info';
6
5
 
7
6
  /**
@@ -67,30 +66,20 @@ interface BuildEntryOption {
67
66
  */
68
67
  nativeModuleEntryMap?: Record<string, string>;
69
68
  /**
70
- * Custom options for esbuild
71
- * ```ts
72
- * // default options
73
- * const options = {
74
- * entryPoints: {
75
- * entry: appEntryPath,
76
- * ...moduleEntryMap,
77
- * },
78
- * bundle: true,
79
- * platform: 'node',
80
- * outdir: entryOutputDirPath,
81
- * minify,
82
- * sourcemap,
83
- * entryNames: '[dir]/[name]',
84
- * assetNames: '[dir]/[name]',
85
- * external: ['electron', 'original-fs'],
86
- * loader: {
87
- * '.node': 'empty',
88
- * },
89
- * define,
90
- * }
91
- * ```
69
+ * Skip process dynamic require
70
+ *
71
+ * Useful for `better-sqlite3` and other old packages
72
+ */
73
+ ignoreDynamicRequires?: boolean;
74
+ /**
75
+ * `external` option in `build.rollupOptions`
76
+ * @default source => source.endsWith('.node')
77
+ */
78
+ external?: (source: string, importer: string | undefined, isResolved: boolean) => boolean | null | undefined | void;
79
+ /**
80
+ * Custom options for `vite` build
92
81
  */
93
- overrideEsbuildOptions?: BuildOptions;
82
+ overrideViteOptions?: InlineConfig;
94
83
  /**
95
84
  * Resolve extra files on startup, such as `.node`
96
85
  * @remark won't trigger will reload
package/dist/vite.js CHANGED
@@ -1,17 +1,16 @@
1
1
  import { readableSize } from './chunk-WYQ5DRO7.js';
2
- import { isUpdateJSON, defaultVersionJsonGenerator } from './chunk-7M7DIMDN.js';
3
- import { log, id, bytecodeLog } from './chunk-5NKEXGI3.js';
2
+ import { isUpdateJSON, defaultVersionJsonGenerator } from './chunk-CTUEQCKL.js';
3
+ import { log, id } from './chunk-5NKEXGI3.js';
4
4
  import path3 from 'node:path';
5
- import fs from 'node:fs';
5
+ import fs2 from 'node:fs';
6
6
  import { normalizePath, mergeConfig } from 'vite';
7
7
  import ElectronSimple from 'vite-plugin-electron/simple';
8
- import { startup } from 'vite-plugin-electron';
8
+ import { startup, build } from 'vite-plugin-electron';
9
9
  import { notBundle } from 'vite-plugin-electron/plugin';
10
10
  import { loadPackageJSON } from 'local-pkg';
11
11
  import { isCI } from 'ci-info';
12
12
  export { isCI } from 'ci-info';
13
13
  import Asar from '@electron/asar';
14
- import { build } from 'esbuild';
15
14
  import zlib from 'node:zlib';
16
15
  import crypto from 'node:crypto';
17
16
  import { generate } from 'selfsigned';
@@ -24,11 +23,11 @@ async function buildAsar({
24
23
  rendererDistPath,
25
24
  generateGzipFile
26
25
  }) {
27
- fs.renameSync(rendererDistPath, path3.join(electronDistPath, "renderer"));
28
- fs.writeFileSync(path3.join(electronDistPath, "version"), version);
26
+ fs2.renameSync(rendererDistPath, path3.join(electronDistPath, "renderer"));
27
+ fs2.writeFileSync(path3.join(electronDistPath, "version"), version);
29
28
  await Asar.createPackage(electronDistPath, asarOutputPath);
30
- const buf = await generateGzipFile(fs.readFileSync(asarOutputPath));
31
- fs.writeFileSync(gzipPath, buf);
29
+ const buf = await generateGzipFile(fs2.readFileSync(asarOutputPath));
30
+ fs2.writeFileSync(gzipPath, buf);
32
31
  log.info(`Build update asar to '${gzipPath}' [${readableSize(buf.length)}]`, { timestamp: true });
33
32
  return buf;
34
33
  }
@@ -51,9 +50,9 @@ async function buildVersion({
51
50
  signature: "",
52
51
  version
53
52
  };
54
- if (fs.existsSync(versionPath)) {
53
+ if (fs2.existsSync(versionPath)) {
55
54
  try {
56
- const oldVersionJson = JSON.parse(fs.readFileSync(versionPath, "utf-8"));
55
+ const oldVersionJson = JSON.parse(fs2.readFileSync(versionPath, "utf-8"));
57
56
  if (isUpdateJSON(oldVersionJson)) {
58
57
  _json = oldVersionJson;
59
58
  } else {
@@ -67,7 +66,7 @@ async function buildVersion({
67
66
  if (!isUpdateJSON(_json)) {
68
67
  throw new Error("Invalid version info");
69
68
  }
70
- fs.writeFileSync(versionPath, JSON.stringify(_json, null, 2));
69
+ fs2.writeFileSync(versionPath, JSON.stringify(_json, null, 2));
71
70
  log.info(`build version info to '${versionPath}'`, { timestamp: true });
72
71
  }
73
72
  async function buildEntry({
@@ -76,86 +75,34 @@ async function buildEntry({
76
75
  appEntryPath,
77
76
  entryOutputDirPath,
78
77
  nativeModuleEntryMap,
79
- overrideEsbuildOptions
78
+ ignoreDynamicRequires,
79
+ external,
80
+ overrideViteOptions
80
81
  }, isESM, define, bytecodeOptions) {
81
- const option = mergeConfig(
82
- {
83
- entryPoints: {
84
- entry: appEntryPath,
85
- ...nativeModuleEntryMap
86
- },
87
- bundle: true,
88
- metafile: true,
89
- platform: "node",
90
- outdir: entryOutputDirPath,
91
- minify,
92
- sourcemap,
93
- entryNames: "[dir]/[name]",
94
- assetNames: "[dir]/[name]",
95
- external: ["electron", "original-fs"],
96
- treeShaking: true,
97
- loader: {
98
- ".node": "empty"
99
- },
100
- define,
101
- format: isESM ? "esm" : "cjs",
102
- write: !isESM,
103
- plugins: isESM ? [
104
- {
105
- name: "entry-esm-shim",
106
- setup(build2) {
107
- build2.onEnd(async ({ outputFiles }) => {
108
- const parse = (await import('./utils-KPSYP7HQ.js')).insertCJSShim;
109
- fs.mkdirSync(entryOutputDirPath, { recursive: true });
110
- outputFiles?.filter((file) => file.path.endsWith(".js")).forEach((file) => {
111
- const output = parse(file.text, sourcemap);
112
- fs.writeFileSync(file.path, output?.code || file.text, "utf-8");
113
- if (sourcemap && output?.map) {
114
- fs.writeFileSync(`${file.path}.map`, output.map.toString(), "utf-8");
115
- }
116
- });
117
- });
118
- }
119
- }
120
- ] : void 0
82
+ await build({
83
+ entry: {
84
+ entry: appEntryPath,
85
+ ...nativeModuleEntryMap
121
86
  },
122
- overrideEsbuildOptions ?? {}
123
- );
124
- const { metafile } = await build(option);
125
- if (!bytecodeOptions?.enable) {
126
- return;
127
- }
128
- const filePaths = Object.keys(metafile?.outputs ?? []).filter((filePath) => filePath.endsWith("js"));
129
- const {
130
- compileToBytecode,
131
- convertArrowFunctionAndTemplate,
132
- convertLiteral,
133
- useStrict
134
- } = await import('./utils-JZ4CMTJG.js');
135
- const { bytecodeModuleLoaderCode } = await import('./code-P5OANH3Q.js');
136
- for (const filePath of filePaths) {
137
- let code = fs.readFileSync(filePath, "utf-8");
138
- const fileName = path3.basename(filePath);
139
- const isEntry = fileName.endsWith("entry.js");
140
- let transformedCode = convertLiteral(convertArrowFunctionAndTemplate(code).code).code;
141
- if (bytecodeOptions.beforeCompile) {
142
- const result = await bytecodeOptions.beforeCompile(transformedCode, filePath);
143
- if (result) {
144
- transformedCode = result;
145
- }
146
- }
147
- const buffer = await compileToBytecode(transformedCode, bytecodeOptions.electronPath);
148
- fs.writeFileSync(
149
- filePath,
150
- `${isEntry ? bytecodeModuleLoaderCode : useStrict}${isEntry ? "" : "module.exports = "}require("./${fileName}c")`
151
- );
152
- fs.writeFileSync(`${filePath}c`, buffer);
153
- bytecodeLog.info(
154
- `${filePath} [${(buffer.byteLength / 1e3).toFixed(2)} kB]`,
155
- { timestamp: true }
156
- );
157
- }
158
- bytecodeLog.info(`${filePaths.length} file${filePaths.length > 1 ? "s" : ""} compiled into bytecode`, { timestamp: true });
87
+ vite: mergeConfig({
88
+ plugins: [
89
+ isESM && await import('./esm-5YR6V7VN.js').then((m) => m.esm()),
90
+ bytecodeOptions && await import('./bytecode-Z5ZF4YGN.js').then((m) => m.bytecodePlugin("main", bytecodeOptions))
91
+ ],
92
+ build: {
93
+ sourcemap,
94
+ minify,
95
+ outDir: entryOutputDirPath,
96
+ commonjsOptions: {
97
+ ignoreDynamicRequires
98
+ },
99
+ rollupOptions: {
100
+ external
101
+ }
102
+ },
103
+ define
104
+ }, overrideViteOptions ?? {})
105
+ });
159
106
  }
160
107
  async function defaultZipFile(buffer) {
161
108
  return new Promise((resolve, reject) => {
@@ -176,20 +123,20 @@ function defaultSignature(buffer, privateKey, cert, version) {
176
123
  }
177
124
  function generateKeyPair(keyLength, subject, days, privateKeyPath, certPath) {
178
125
  const privateKeyDir = path3.dirname(privateKeyPath);
179
- if (!fs.existsSync(privateKeyDir)) {
180
- fs.mkdirSync(privateKeyDir, { recursive: true });
126
+ if (!fs2.existsSync(privateKeyDir)) {
127
+ fs2.mkdirSync(privateKeyDir, { recursive: true });
181
128
  }
182
129
  const certDir = path3.dirname(certPath);
183
- if (!fs.existsSync(certDir)) {
184
- fs.mkdirSync(certDir, { recursive: true });
130
+ if (!fs2.existsSync(certDir)) {
131
+ fs2.mkdirSync(certDir, { recursive: true });
185
132
  }
186
133
  const { cert, private: privateKey } = generate(subject, {
187
134
  keySize: keyLength,
188
135
  algorithm: "sha256",
189
136
  days
190
137
  });
191
- fs.writeFileSync(privateKeyPath, privateKey.replace(/\r\n?/g, "\n"));
192
- fs.writeFileSync(certPath, cert.replace(/\r\n?/g, "\n"));
138
+ fs2.writeFileSync(privateKeyPath, privateKey.replace(/\r\n?/g, "\n"));
139
+ fs2.writeFileSync(certPath, cert.replace(/\r\n?/g, "\n"));
193
140
  }
194
141
  function parseKeys({
195
142
  keyLength,
@@ -205,15 +152,15 @@ function parseKeys({
205
152
  log.info("Use `UPDATER_PK` and `UPDATER_CERT` from environment variables", { timestamp: true });
206
153
  return { privateKey, cert };
207
154
  }
208
- if (!fs.existsSync(keysDir)) {
209
- fs.mkdirSync(keysDir);
155
+ if (!fs2.existsSync(keysDir)) {
156
+ fs2.mkdirSync(keysDir);
210
157
  }
211
- if (!fs.existsSync(privateKeyPath) || !fs.existsSync(certPath)) {
158
+ if (!fs2.existsSync(privateKeyPath) || !fs2.existsSync(certPath)) {
212
159
  log.info("No key pair found, generate new key pair", { timestamp: true });
213
160
  generateKeyPair(keyLength, parseSubjects(subject), days, privateKeyPath, certPath);
214
161
  }
215
- privateKey = fs.readFileSync(privateKeyPath, "utf-8");
216
- cert = fs.readFileSync(certPath, "utf-8");
162
+ privateKey = fs2.readFileSync(privateKeyPath, "utf-8");
163
+ cert = fs2.readFileSync(certPath, "utf-8");
217
164
  return { privateKey, cert };
218
165
  }
219
166
  function parseSubjects(subject) {
@@ -231,7 +178,9 @@ function parseOptions(pkg, sourcemap = false, minify = false, options = {}) {
231
178
  appEntryPath = "electron/entry.ts",
232
179
  nativeModuleEntryMap = {},
233
180
  postBuild,
234
- overrideEsbuildOptions = {}
181
+ ignoreDynamicRequires = false,
182
+ external = (source) => source.endsWith(".node"),
183
+ overrideViteOptions = {}
235
184
  } = {},
236
185
  paths: {
237
186
  asarOutputPath = `release/${pkg.name}.asar`,
@@ -272,7 +221,9 @@ function parseOptions(pkg, sourcemap = false, minify = false, options = {}) {
272
221
  entryOutputDirPath,
273
222
  appEntryPath,
274
223
  nativeModuleEntryMap,
275
- overrideEsbuildOptions
224
+ overrideViteOptions,
225
+ ignoreDynamicRequires,
226
+ external
276
227
  };
277
228
  const { privateKey, cert } = parseKeys({
278
229
  keyLength,
@@ -358,8 +309,8 @@ async function electronWithUpdater(options) {
358
309
  } = parseOptions(pkg, sourcemap, minify, updater);
359
310
  const { entryOutputDirPath, nativeModuleEntryMap, appEntryPath } = buildEntryOption;
360
311
  try {
361
- fs.rmSync(buildAsarOption.electronDistPath, { recursive: true, force: true });
362
- fs.rmSync(entryOutputDirPath, { recursive: true, force: true });
312
+ fs2.rmSync(buildAsarOption.electronDistPath, { recursive: true, force: true });
313
+ fs2.rmSync(entryOutputDirPath, { recursive: true, force: true });
363
314
  } catch {
364
315
  }
365
316
  log.info(`Clear cache files`, { timestamp: true });
@@ -373,7 +324,6 @@ async function electronWithUpdater(options) {
373
324
  __EIU_ENTRY_DIST_PATH__: JSON.stringify(normalizePath(buildEntryOption.entryOutputDirPath)),
374
325
  __EIU_IS_DEV__: JSON.stringify(!isBuild),
375
326
  __EIU_IS_ESM__: JSON.stringify(isESM),
376
- __EIU_MAIN_DEV_DIR__: JSON.stringify(normalizePath(buildAsarOption.electronDistPath)),
377
327
  __EIU_MAIN_FILE__: JSON.stringify(getMainFileBaseName(_main.files)),
378
328
  __EIU_SIGNATURE_CERT__: JSON.stringify(cert),
379
329
  __EIU_VERSION_PATH__: JSON.stringify(parseVersionPath(normalizePath(buildVersionOption.versionPath)))
@@ -392,11 +342,11 @@ async function electronWithUpdater(options) {
392
342
  return path3.join(entryOutputDirPath, ...paths);
393
343
  },
394
344
  copyToEntryOutputDir({ from, to, skipIfExist = true }) {
395
- if (fs.existsSync(from)) {
345
+ if (fs2.existsSync(from)) {
396
346
  const target = path3.join(entryOutputDirPath, to ?? path3.basename(from));
397
- if (!skipIfExist || !fs.existsSync(target)) {
347
+ if (!skipIfExist || !fs2.existsSync(target)) {
398
348
  try {
399
- fs.cpSync(from, target);
349
+ fs2.cpSync(from, target);
400
350
  } catch (error) {
401
351
  log.warn(`Copy failed: ${error}`, { timestamp: true });
402
352
  }
@@ -410,7 +360,7 @@ async function electronWithUpdater(options) {
410
360
  external: (src) => src.startsWith("node:") || Object.keys("dependencies" in pkg ? pkg.dependencies : {}).includes(src) || src === "original-fs",
411
361
  treeshake: true
412
362
  };
413
- const esmShimPlugin = isESM ? (await import('./esm-ZFXJ56BN.js')).esm() : void 0;
363
+ const esmShimPlugin = isESM ? (await import('./esm-5YR6V7VN.js')).esm() : void 0;
414
364
  const electronPluginOptions = {
415
365
  main: {
416
366
  entry: _main.files,
@@ -430,7 +380,7 @@ async function electronWithUpdater(options) {
430
380
  {
431
381
  plugins: [
432
382
  !isBuild && useNotBundle ? notBundle() : void 0,
433
- bytecodeOptions && (await import('./bytecode-I4PMYUGT.js')).bytecodePlugin("main", bytecodeOptions),
383
+ bytecodeOptions && await import('./bytecode-Z5ZF4YGN.js').then((m) => m.bytecodePlugin("main", bytecodeOptions)),
434
384
  esmShimPlugin
435
385
  ],
436
386
  build: {
@@ -450,7 +400,7 @@ async function electronWithUpdater(options) {
450
400
  vite: mergeConfig(
451
401
  {
452
402
  plugins: [
453
- bytecodeOptions && (await import('./bytecode-I4PMYUGT.js')).bytecodePlugin("preload", bytecodeOptions),
403
+ bytecodeOptions && (await import('./bytecode-Z5ZF4YGN.js')).bytecodePlugin("preload", bytecodeOptions),
454
404
  esmShimPlugin,
455
405
  {
456
406
  name: `${id}-build`,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "electron-incremental-update",
3
3
  "type": "module",
4
- "version": "2.1.2",
4
+ "version": "2.2.0",
5
5
  "description": "Electron incremental update tools with Vite plugin, support bytecode protection",
6
6
  "author": "subframe7536",
7
7
  "license": "MIT",
@@ -71,16 +71,16 @@
71
71
  "vite-plugin-electron": "^0.28.7"
72
72
  },
73
73
  "devDependencies": {
74
- "@subframe7536/eslint-config": "^0.7.5",
74
+ "@subframe7536/eslint-config": "^0.8.0",
75
75
  "@types/babel__core": "^7.20.5",
76
- "@types/node": "^20.14.15",
77
- "bumpp": "^9.5.1",
76
+ "@types/node": "^20.16.3",
77
+ "bumpp": "^9.5.2",
78
78
  "electron": "28.2.10",
79
- "eslint": "^9.9.0",
79
+ "eslint": "^9.9.1",
80
80
  "esno": "^4.7.0",
81
81
  "tsup": "^8.2.4",
82
82
  "typescript": "^5.5.4",
83
- "vite": "^5.4.0",
83
+ "vite": "^5.4.2",
84
84
  "vite-plugin-electron": "^0.28.7",
85
85
  "vitest": "^2.0.5"
86
86
  }
@@ -1,5 +0,0 @@
1
- // src/vite/bytecode/code.ts
2
- var bytecodeGeneratorScript = "const vm = require('vm')\nconst v8 = require('v8')\nconst wrap = require('module').wrap\nv8.setFlagsFromString('--no-lazy')\nv8.setFlagsFromString('--no-flush-bytecode')\nlet code = ''\nprocess.stdin.setEncoding('utf-8')\nprocess.stdin.on('readable', () => {\n const data = process.stdin.read()\n if (data !== null) {\n code += data\n }\n})\nprocess.stdin.on('end', () => {\n try {\n if (typeof code !== 'string') {\n throw new Error('javascript code must be string.')\n }\n const script = new vm.Script(wrap(code), { produceCachedData: true })\n const bytecodeBuffer = script.createCachedData()\n process.stdout.write(bytecodeBuffer)\n } catch (error) {\n console.error(error)\n }\n})\n";
3
- var bytecodeModuleLoaderCode = '"use strict";\nconst fs = require("fs");\nconst path = require("path");\nconst vm = require("vm");\nconst v8 = require("v8");\nconst Module = require("module");\nv8.setFlagsFromString("--no-lazy");\nv8.setFlagsFromString("--no-flush-bytecode");\nconst FLAG_HASH_OFFSET = 12;\nconst SOURCE_HASH_OFFSET = 8;\nlet dummyBytecode;\nfunction setFlagHashHeader(bytecodeBuffer) {\n if (!dummyBytecode) {\n const script = new vm.Script("", {\n produceCachedData: true\n });\n dummyBytecode = script.createCachedData();\n }\n dummyBytecode.slice(FLAG_HASH_OFFSET, FLAG_HASH_OFFSET + 4).copy(bytecodeBuffer, FLAG_HASH_OFFSET);\n};\nfunction getSourceHashHeader(bytecodeBuffer) {\n return bytecodeBuffer.slice(SOURCE_HASH_OFFSET, SOURCE_HASH_OFFSET + 4);\n};\nfunction buffer2Number(buffer) {\n let ret = 0;\n ret |= buffer[3] << 24;\n ret |= buffer[2] << 16;\n ret |= buffer[1] << 8;\n ret |= buffer[0];\n return ret;\n};\nModule._extensions[".jsc"] = Module._extensions[".cjsc"] = function (module, filename) {\n const bytecodeBuffer = fs.readFileSync(filename);\n if (!Buffer.isBuffer(bytecodeBuffer)) {\n throw new Error("BytecodeBuffer must be a buffer object.");\n }\n setFlagHashHeader(bytecodeBuffer);\n const length = buffer2Number(getSourceHashHeader(bytecodeBuffer));\n let dummyCode = "";\n if (length > 1) {\n dummyCode = "\\"" + "\\u200b".repeat(length - 2) + "\\"";\n }\n const script = new vm.Script(dummyCode, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true,\n cachedData: bytecodeBuffer\n });\n if (script.cachedDataRejected) {\n throw new Error("Invalid or incompatible cached data (cachedDataRejected)");\n }\n const require = function (id) {\n return module.require(id);\n };\n require.resolve = function (request, options) {\n return Module._resolveFilename(request, module, false, options);\n };\n if (process.mainModule) {\n require.main = process.mainModule;\n }\n require.extensions = Module._extensions;\n require.cache = Module._cache;\n const compiledWrapper = script.runInThisContext({\n filename: filename,\n lineOffset: 0,\n columnOffset: 0,\n displayErrors: true\n });\n const dirname = path.dirname(filename);\n const args = [module.exports, require, module, filename, dirname, process, global];\n return compiledWrapper.apply(module.exports, args);\n};\n';
4
-
5
- export { bytecodeGeneratorScript, bytecodeModuleLoaderCode };
@@ -1 +0,0 @@
1
- export { bytecodeGeneratorScript, bytecodeModuleLoaderCode } from './chunk-7IRGAAL2.js';
@@ -1,26 +0,0 @@
1
- import { findStaticImports, insertCJSShim } from './chunk-5CE27A6G.js';
2
- import './chunk-AUY7A2FL.js';
3
- import './chunk-7M7DIMDN.js';
4
- import { esmId } from './chunk-5NKEXGI3.js';
5
- import './chunk-7IRGAAL2.js';
6
-
7
- // src/vite/esm/index.ts
8
- function esm() {
9
- let sourcemap;
10
- return {
11
- name: esmId,
12
- enforce: "post",
13
- configResolved(config) {
14
- sourcemap = config.build.sourcemap;
15
- },
16
- renderChunk(code, _chunk, options) {
17
- if (options.format === "es") {
18
- const lastESMImport = findStaticImports(code).pop();
19
- const pos = lastESMImport ? lastESMImport.end : 0;
20
- return insertCJSShim(code, sourcemap, pos);
21
- }
22
- }
23
- };
24
- }
25
-
26
- export { esm };
@@ -1,4 +0,0 @@
1
- export { bytecodeModuleLoader, compileToBytecode, convertArrowFunctionAndTemplate, convertLiteral, decodeFn, electronMajorVersion, electronModule, obfuscateString, toRelativePath, useStrict } from './chunk-AUY7A2FL.js';
2
- import './chunk-7M7DIMDN.js';
3
- import './chunk-5NKEXGI3.js';
4
- import './chunk-7IRGAAL2.js';
@@ -1,5 +0,0 @@
1
- export { findStaticImports, insertCJSShim } from './chunk-5CE27A6G.js';
2
- import './chunk-AUY7A2FL.js';
3
- import './chunk-7M7DIMDN.js';
4
- import './chunk-5NKEXGI3.js';
5
- import './chunk-7IRGAAL2.js';