electron-incremental-update 1.3.0 → 2.0.0-beta.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/vite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/vite.ts
2
2
  import { basename as basename2, join as join2, resolve } from "node:path";
3
- import { cpSync, existsSync as existsSync4, rmSync as rmSync2 } from "node:fs";
3
+ import { cpSync, existsSync as existsSync4, rmSync } from "node:fs";
4
4
  import { mergeConfig as mergeConfig2, normalizePath as normalizePath2 } from "vite";
5
5
  import ElectronSimple from "vite-plugin-electron/simple";
6
6
  import { startup } from "vite-plugin-electron";
@@ -14,27 +14,7 @@ import Asar from "@electron/asar";
14
14
  import { build } from "esbuild";
15
15
  import { mergeConfig } from "vite";
16
16
 
17
- // src/crypto/utils.ts
18
- import { createHash } from "node:crypto";
19
- function hashString(data, length) {
20
- const hash = createHash("SHA256").update(data).digest("binary");
21
- return Buffer.from(hash).subarray(0, length);
22
- }
23
-
24
- // src/crypto/enc.ts
25
- import { createCipheriv, createPrivateKey, createSign } from "node:crypto";
26
- function encrypt(plainText, key, iv) {
27
- const cipher = createCipheriv("aes-256-cbc", key, iv);
28
- let encrypted = cipher.update(plainText, "utf8", "base64url");
29
- encrypted += cipher.final("base64url");
30
- return encrypted;
31
- }
32
- var signature = (buffer, privateKey, cert, version) => {
33
- const sig = createSign("RSA-SHA256").update(buffer).sign(createPrivateKey(privateKey), "base64");
34
- return encrypt(`${sig}%${version}`, hashString(cert, 32), hashString(buffer, 16));
35
- };
36
-
37
- // src/utils/pure.ts
17
+ // src/utils/version.ts
38
18
  function parseVersion(version) {
39
19
  const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i.exec(version);
40
20
  if (!match) {
@@ -64,8 +44,8 @@ function isUpdateJSON(json) {
64
44
  }
65
45
 
66
46
  // src/utils/zip.ts
67
- import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
68
- import { brotliCompress, brotliDecompress } from "node:zlib";
47
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
48
+ import { brotliCompress } from "node:zlib";
69
49
  async function zipFile(filePath, targetFilePath = `${filePath}.gz`) {
70
50
  if (!existsSync(filePath)) {
71
51
  throw new Error(`path to be zipped not exist: ${filePath}`);
@@ -82,94 +62,36 @@ async function zipFile(filePath, targetFilePath = `${filePath}.gz`) {
82
62
  });
83
63
  }
84
64
 
85
- // src/build-plugins/log.ts
86
- import { createLogger } from "vite";
65
+ // src/utils/crypto/utils.ts
66
+ import { createHash } from "node:crypto";
67
+ function hashString(data, length) {
68
+ const hash = createHash("SHA256").update(data).digest("binary");
69
+ return Buffer.from(hash).subarray(0, length);
70
+ }
71
+
72
+ // src/utils/crypto/encrypt.ts
73
+ import { createCipheriv, createPrivateKey, createSign } from "node:crypto";
74
+ function encrypt(plainText, key, iv) {
75
+ const cipher = createCipheriv("aes-256-cbc", key, iv);
76
+ let encrypted = cipher.update(plainText, "utf8", "base64url");
77
+ encrypted += cipher.final("base64url");
78
+ return encrypted;
79
+ }
80
+ function signature(buffer, privateKey, cert, version) {
81
+ const sig = createSign("RSA-SHA256").update(buffer).sign(createPrivateKey(privateKey), "base64");
82
+ return encrypt(`${sig}%${version}`, hashString(cert, 32), hashString(buffer, 16));
83
+ }
87
84
 
88
85
  // src/build-plugins/constant.ts
86
+ import { createLogger } from "vite";
89
87
  var id = "electron-incremental-updater";
90
88
  var bytecodeId = `${id}-bytecode`;
91
- var loaderId = `${id}-loader`;
92
-
93
- // src/build-plugins/log.ts
94
89
  var log = createLogger("info", { prefix: `[${id}]` });
95
90
  var bytecodeLog = createLogger("info", { prefix: `[${bytecodeId}]` });
96
91
 
97
92
  // src/build-plugins/bytecode/code.ts
98
93
  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";
99
- var bytecodeModuleLoaderCode = [
100
- `"use strict";`,
101
- `const fs = require("fs");`,
102
- `const path = require("path");`,
103
- `const vm = require("vm");`,
104
- `const v8 = require("v8");`,
105
- `const Module = require("module");`,
106
- `v8.setFlagsFromString("--no-lazy");`,
107
- `v8.setFlagsFromString("--no-flush-bytecode");`,
108
- `const FLAG_HASH_OFFSET = 12;`,
109
- `const SOURCE_HASH_OFFSET = 8;`,
110
- `let dummyBytecode;`,
111
- `function setFlagHashHeader(bytecodeBuffer) {`,
112
- ` if (!dummyBytecode) {`,
113
- ` const script = new vm.Script("", {`,
114
- ` produceCachedData: true`,
115
- ` });`,
116
- ` dummyBytecode = script.createCachedData();`,
117
- ` }`,
118
- ` dummyBytecode.slice(FLAG_HASH_OFFSET, FLAG_HASH_OFFSET + 4).copy(bytecodeBuffer, FLAG_HASH_OFFSET);`,
119
- `};`,
120
- `function getSourceHashHeader(bytecodeBuffer) {`,
121
- ` return bytecodeBuffer.slice(SOURCE_HASH_OFFSET, SOURCE_HASH_OFFSET + 4);`,
122
- `};`,
123
- `function buffer2Number(buffer) {`,
124
- ` let ret = 0;`,
125
- ` ret |= buffer[3] << 24;`,
126
- ` ret |= buffer[2] << 16;`,
127
- ` ret |= buffer[1] << 8;`,
128
- ` ret |= buffer[0];`,
129
- ` return ret;`,
130
- `};`,
131
- `Module._extensions[".jsc"] = Module._extensions[".cjsc"] = function (module, filename) {`,
132
- ` const bytecodeBuffer = fs.readFileSync(filename);`,
133
- ` if (!Buffer.isBuffer(bytecodeBuffer)) {`,
134
- ` throw new Error("BytecodeBuffer must be a buffer object.");`,
135
- ` }`,
136
- ` setFlagHashHeader(bytecodeBuffer);`,
137
- ` const length = buffer2Number(getSourceHashHeader(bytecodeBuffer));`,
138
- ` let dummyCode = "";`,
139
- ` if (length > 1) {`,
140
- ` dummyCode = "\\"" + "\\u200b".repeat(length - 2) + "\\"";`,
141
- ` }`,
142
- ` const script = new vm.Script(dummyCode, {`,
143
- ` filename: filename,`,
144
- ` lineOffset: 0,`,
145
- ` displayErrors: true,`,
146
- ` cachedData: bytecodeBuffer`,
147
- ` });`,
148
- ` if (script.cachedDataRejected) {`,
149
- ` throw new Error("Invalid or incompatible cached data (cachedDataRejected)");`,
150
- ` }`,
151
- ` const require = function (id) {`,
152
- ` return module.require(id);`,
153
- ` };`,
154
- ` require.resolve = function (request, options) {`,
155
- ` return Module._resolveFilename(request, module, false, options);`,
156
- ` };`,
157
- ` if (process.mainModule) {`,
158
- ` require.main = process.mainModule;`,
159
- ` }`,
160
- ` require.extensions = Module._extensions;`,
161
- ` require.cache = Module._cache;`,
162
- ` const compiledWrapper = script.runInThisContext({`,
163
- ` filename: filename,`,
164
- ` lineOffset: 0,`,
165
- ` columnOffset: 0,`,
166
- ` displayErrors: true`,
167
- ` });`,
168
- ` const dirname = path.dirname(filename);`,
169
- ` const args = [module.exports, require, module, filename, dirname, process, global];`,
170
- ` return compiledWrapper.apply(module.exports, args);`,
171
- `};`
172
- ].join("\n");
94
+ 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';
173
95
 
174
96
  // src/build-plugins/bytecode/utils.ts
175
97
  import path from "node:path";
@@ -346,7 +268,7 @@ async function buildEntry({
346
268
  entryOutputDirPath,
347
269
  nativeModuleEntryMap,
348
270
  overrideEsbuildOptions
349
- }, cert, protectedStrings) {
271
+ }, define, protectedStrings) {
350
272
  const option = mergeConfig(
351
273
  {
352
274
  entryPoints: {
@@ -365,9 +287,7 @@ async function buildEntry({
365
287
  loader: {
366
288
  ".node": "empty"
367
289
  },
368
- define: {
369
- __SIGNATURE_CERT__: JSON.stringify(cert)
370
- }
290
+ define
371
291
  },
372
292
  overrideEsbuildOptions ?? {}
373
293
  );
@@ -383,7 +303,7 @@ async function buildEntry({
383
303
  if (isEntry) {
384
304
  code = code.replace(
385
305
  /(`-----BEGIN CERTIFICATE-----[\s\S]*-----END CERTIFICATE-----\n`)/,
386
- (_, cert2) => `"${cert2.slice(1, -1).replace(/\n/g, "\\n")}"`
306
+ (_, cert) => `"${cert.slice(1, -1).replace(/\n/g, "\\n")}"`
387
307
  );
388
308
  }
389
309
  const transformedCode = convertString(
@@ -678,6 +598,28 @@ ${bytecodeLoaderBlock}`) : _code;
678
598
  function debugStartup(args) {
679
599
  process.env.VSCODE_DEBUG ? console.log("[startup] Electron App") : args.startup();
680
600
  }
601
+ function getMainFilePath(options) {
602
+ let mainFilePath;
603
+ if (typeof options === "string") {
604
+ mainFilePath = basename2(options);
605
+ } else if (Array.isArray(options)) {
606
+ mainFilePath = basename2(options[0]);
607
+ } else {
608
+ const name = options?.index ?? options?.main;
609
+ if (!name) {
610
+ throw new Error(`\`options.main.files\` (${options}) must have "index" or "main" key, like \`{ index: "..." }\``);
611
+ }
612
+ mainFilePath = options?.index ? "index.js" : "main.js";
613
+ }
614
+ return mainFilePath.replace(/\.[cm]?ts$/, ".js");
615
+ }
616
+ function parseVersionPath(versionPath) {
617
+ versionPath = normalizePath2(versionPath);
618
+ if (!versionPath.startsWith("./")) {
619
+ versionPath = "./" + versionPath;
620
+ }
621
+ return new URL(versionPath, "file://").pathname.slice(1);
622
+ }
681
623
  async function electronWithUpdater(options) {
682
624
  let {
683
625
  isBuild,
@@ -705,8 +647,8 @@ async function electronWithUpdater(options) {
705
647
  minify = false;
706
648
  }
707
649
  try {
708
- rmSync2(_options.buildAsarOption.electronDistPath, { recursive: true, force: true });
709
- rmSync2(_options.buildEntryOption.entryOutputDirPath, { recursive: true, force: true });
650
+ rmSync(_options.buildAsarOption.electronDistPath, { recursive: true, force: true });
651
+ rmSync(_options.buildEntryOption.entryOutputDirPath, { recursive: true, force: true });
710
652
  } catch (ignore) {
711
653
  }
712
654
  log.info(`remove old files`, { timestamp: true });
@@ -717,8 +659,21 @@ async function electronWithUpdater(options) {
717
659
  if (resolve(normalizePath2(pkg.main)) !== resolve(_appPath)) {
718
660
  throw new Error(`wrong "main" field in package.json: "${pkg.main}", it should be "${_appPath}"`);
719
661
  }
662
+ const define = {
663
+ __EIU_ELECTRON_DIST_PATH__: JSON.stringify(buildAsarOption.electronDistPath),
664
+ __EIU_ENTRY_DIST_PATH__: JSON.stringify(buildEntryOption.entryOutputDirPath),
665
+ __EIU_IS_DEV__: JSON.stringify(!isBuild),
666
+ __EIU_MAIN_DEV_DIR__: JSON.stringify(buildAsarOption.electronDistPath),
667
+ __EIU_MAIN_FILE__: JSON.stringify(getMainFilePath(_main.files)),
668
+ __EIU_SIGNATURE_CERT__: JSON.stringify(cert),
669
+ __EUI_VERSION_PATH__: JSON.stringify(parseVersionPath(buildVersionOption.versionPath))
670
+ };
720
671
  const _buildEntry = async () => {
721
- await buildEntry(buildEntryOption, cert, isBuild ? bytecodeOptions?.protectedStrings : void 0);
672
+ await buildEntry(
673
+ buildEntryOption,
674
+ define,
675
+ isBuild ? bytecodeOptions?.protectedStrings : void 0
676
+ );
722
677
  log.info(`vite build entry to '${entryOutputDirPath}'`, { timestamp: true });
723
678
  };
724
679
  const _postBuild = postBuild ? async () => await postBuild({
@@ -741,10 +696,6 @@ async function electronWithUpdater(options) {
741
696
  };
742
697
  let isInit = false;
743
698
  const rollupOptions = {
744
- // external: [
745
- // /^node:/,
746
- // ...Object.keys('dependencies' in pkg ? pkg.dependencies as object : {}),
747
- // ],
748
699
  external: (src) => src.startsWith("node:") || Object.keys("dependencies" in pkg ? pkg.dependencies : {}).includes(src)
749
700
  };
750
701
  const electronPluginOptions = {
@@ -769,7 +720,8 @@ async function electronWithUpdater(options) {
769
720
  minify,
770
721
  outDir: `${buildAsarOption.electronDistPath}/main`,
771
722
  rollupOptions
772
- }
723
+ },
724
+ define
773
725
  },
774
726
  _main.vite ?? {}
775
727
  )
@@ -802,7 +754,8 @@ async function electronWithUpdater(options) {
802
754
  minify,
803
755
  outDir: `${buildAsarOption.electronDistPath}/preload`,
804
756
  rollupOptions
805
- }
757
+ },
758
+ define
806
759
  },
807
760
  _preload.vite ?? {}
808
761
  )
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "electron-incremental-update",
3
3
  "type": "module",
4
- "version": "1.3.0",
4
+ "version": "2.0.0-beta.1",
5
5
  "description": "electron incremental update tools, powered by vite",
6
6
  "author": "subframe7536",
7
7
  "license": "MIT",
@@ -23,12 +23,18 @@
23
23
  "./utils": {
24
24
  "import": "./dist/utils.js",
25
25
  "require": "./dist/utils.cjs"
26
+ },
27
+ "./provider": {
28
+ "import": "./dist/provider.js",
29
+ "require": "./dist/provider.cjs"
26
30
  }
27
31
  },
28
32
  "main": "dist/index.cjs",
29
33
  "module": "dist/index.js",
30
34
  "files": [
31
35
  "dist",
36
+ "provider.d.ts",
37
+ "provider.js",
32
38
  "utils.d.ts",
33
39
  "utils.js",
34
40
  "vite.d.ts",
@@ -61,15 +67,15 @@
61
67
  "devDependencies": {
62
68
  "@subframe7536/eslint-config": "^0.6.6",
63
69
  "@types/babel__core": "^7.20.5",
64
- "@types/node": "^20.14.7",
70
+ "@types/node": "^20.14.10",
65
71
  "bumpp": "^9.4.1",
66
72
  "electron": "28.2.10",
67
- "eslint": "^9.5.0",
73
+ "eslint": "^9.7.0",
68
74
  "esno": "^4.7.0",
69
75
  "tsup": "^8.1.0",
70
- "typescript": "^5.5.2",
71
- "vite": "^5.3.1",
76
+ "typescript": "^5.5.3",
77
+ "vite": "^5.3.3",
72
78
  "vite-plugin-electron": "^0.28.7",
73
- "vitest": "^1.6.0"
79
+ "vitest": "^2.0.2"
74
80
  }
75
81
  }
package/provider.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/provider'
package/provider.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/provider.cjs')
@@ -1,236 +0,0 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/utils/electron.ts
9
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
10
- import { basename, dirname, join } from "node:path";
11
- import { release } from "node:os";
12
- import { app } from "electron";
13
- var is = {
14
- dev: !app.isPackaged,
15
- win: process.platform === "win32",
16
- mac: process.platform === "darwin",
17
- linux: process.platform === "linux"
18
- };
19
- function getPathFromAppNameAsar(...path) {
20
- return is.dev ? "DEV.asar" : join(dirname(app.getAppPath()), `${electron.app.name}.asar`, ...path);
21
- }
22
- function getVersions() {
23
- const platform = is.win ? "Windows" : is.mac ? "MacOS" : process.platform.toUpperCase();
24
- return {
25
- appVersion: is.dev ? app.getVersion() : readFileSync(getPathFromAppNameAsar("version"), "utf-8"),
26
- entryVersion: app.getVersion(),
27
- electronVersion: process.versions.electron,
28
- nodeVersion: process.versions.node,
29
- systemVersion: `${platform} ${release()}`
30
- };
31
- }
32
- function loadNativeModuleFromEntry(devEntryDirPath = "../../dist-entry", entryDirPath = join(app.getAppPath(), basename(devEntryDirPath))) {
33
- const path = is.dev ? devEntryDirPath : entryDirPath;
34
- return (moduleName) => {
35
- try {
36
- return __require(join(path, moduleName));
37
- } catch (error) {
38
- console.error("fail to load module", error);
39
- }
40
- };
41
- }
42
- function restartApp() {
43
- app.relaunch();
44
- app.quit();
45
- }
46
- function setAppUserModelId(id) {
47
- app.setAppUserModelId(is.dev ? process.execPath : id ?? `org.${electron.app.name}`);
48
- }
49
- function disableHWAccForWin7() {
50
- if (release().startsWith("6.1")) {
51
- app.disableHardwareAcceleration();
52
- }
53
- }
54
- function singleInstance(window) {
55
- const result = app.requestSingleInstanceLock();
56
- result ? app.on("second-instance", () => {
57
- if (window) {
58
- window.show();
59
- if (window.isMinimized()) {
60
- window.restore();
61
- }
62
- window.focus();
63
- }
64
- }) : app.quit();
65
- return result;
66
- }
67
- function setPortableAppDataPath(dirName = "data") {
68
- const portablePath = join(dirname(app.getPath("exe")), dirName);
69
- if (!existsSync(portablePath)) {
70
- mkdirSync(portablePath);
71
- }
72
- app.setPath("appData", portablePath);
73
- }
74
- function waitAppReady(timeout = 1e3) {
75
- return app.isReady() ? Promise.resolve() : new Promise((resolve, reject) => {
76
- const _ = setTimeout(() => {
77
- reject(new Error("app is not ready"));
78
- }, timeout);
79
- app.whenReady().then(() => {
80
- clearTimeout(_);
81
- resolve();
82
- });
83
- });
84
- }
85
- function getPaths(entryDirName = "dist-entry") {
86
- const root = join(__dirname, "..");
87
- const mainDirPath = join(root, "main");
88
- const preloadDirPath = join(root, "preload");
89
- const rendererDirPath = join(root, "renderer");
90
- const devServerURL = process.env.VITE_DEV_SERVER_URL;
91
- const indexHTMLPath = join(rendererDirPath, "index.html");
92
- const publicDirPath = devServerURL ? join(root, "../public") : rendererDirPath;
93
- return {
94
- /**
95
- * @example
96
- * ```ts
97
- * devServerURL && win.loadURL(devServerURL)
98
- * ```
99
- */
100
- devServerURL,
101
- /**
102
- * @example
103
- * ```ts
104
- * win.loadFile(indexHTMLPath)
105
- * ```
106
- */
107
- indexHTMLPath,
108
- /**
109
- * get path inside entry asar
110
- * @param paths joined path
111
- */
112
- getPathFromEntryAsar(...paths) {
113
- return join(app.getAppPath(), entryDirName, ...paths);
114
- },
115
- /**
116
- * get path inside `${electron.app.name}.asar/main`
117
- * @param paths joined path
118
- */
119
- getPathFromMain(...paths) {
120
- return join(mainDirPath, ...paths);
121
- },
122
- /**
123
- * get path inside `${electron.app.name}.asar/preload`
124
- * @param paths joined path
125
- */
126
- getPathFromPreload(...paths) {
127
- return join(preloadDirPath, ...paths);
128
- },
129
- /**
130
- * get path inside public dir
131
- * @param paths joined path
132
- */
133
- getPathFromPublic(...paths) {
134
- return join(publicDirPath, ...paths);
135
- }
136
- };
137
- }
138
-
139
- // src/utils/zip.ts
140
- import { existsSync as existsSync2, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
141
- import { brotliCompress, brotliDecompress } from "node:zlib";
142
- async function unzipFile(gzipPath, targetFilePath = gzipPath.slice(0, -3)) {
143
- if (!existsSync2(gzipPath)) {
144
- throw new Error(`path to zipped file not exist: ${gzipPath}`);
145
- }
146
- const compressedBuffer = readFileSync2(gzipPath);
147
- return new Promise((resolve, reject) => {
148
- brotliDecompress(compressedBuffer, (err, buffer) => {
149
- rmSync(gzipPath);
150
- if (err) {
151
- reject(err);
152
- }
153
- writeFileSync(targetFilePath, buffer);
154
- resolve(null);
155
- });
156
- });
157
- }
158
- async function zipFile(filePath, targetFilePath = `${filePath}.gz`) {
159
- if (!existsSync2(filePath)) {
160
- throw new Error(`path to be zipped not exist: ${filePath}`);
161
- }
162
- const buffer = readFileSync2(filePath);
163
- return new Promise((resolve, reject) => {
164
- brotliCompress(buffer, (err, buffer2) => {
165
- if (err) {
166
- reject(err);
167
- }
168
- writeFileSync(targetFilePath, buffer2);
169
- resolve(null);
170
- });
171
- });
172
- }
173
-
174
- // src/utils/pure.ts
175
- function parseGithubCdnURL(originRepoURL, cdnPrefix, relativeFilePath) {
176
- if (!originRepoURL.startsWith("https://github.com/")) {
177
- throw new Error("origin url must start with https://github.com/");
178
- }
179
- originRepoURL = originRepoURL.trim().replace(/\/?$/, "/").trim();
180
- relativeFilePath = relativeFilePath.trim().replace(/^\/|\/?$/g, "").trim();
181
- cdnPrefix = cdnPrefix.trim().replace(/^\/?|\/?$/g, "").trim();
182
- return originRepoURL.replace("github.com", cdnPrefix) + relativeFilePath;
183
- }
184
- function handleUnexpectedErrors(callback) {
185
- process.on("uncaughtException", callback);
186
- process.on("unhandledRejection", callback);
187
- }
188
- function parseVersion(version) {
189
- const semver = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i;
190
- const match = semver.exec(version);
191
- if (!match) {
192
- throw new TypeError(`invalid version: ${version}`);
193
- }
194
- const [major, minor, patch] = match.slice(1, 4).map(Number);
195
- const ret = {
196
- major,
197
- minor,
198
- patch,
199
- stage: "",
200
- stageVersion: -1
201
- };
202
- if (match[4]) {
203
- let [stage, _v] = match[4].split(".");
204
- ret.stage = stage;
205
- ret.stageVersion = Number(_v) || -1;
206
- }
207
- if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) {
208
- throw new TypeError(`invalid version: ${version}`);
209
- }
210
- return ret;
211
- }
212
- function isUpdateJSON(json) {
213
- const is2 = (j) => !!(j && j.minimumVersion && j.signature && j.size && j.version);
214
- return is2(json) && is2(json?.beta);
215
- }
216
-
217
- export {
218
- __require,
219
- is,
220
- getPathFromAppNameAsar,
221
- getVersions,
222
- loadNativeModuleFromEntry,
223
- restartApp,
224
- setAppUserModelId,
225
- disableHWAccForWin7,
226
- singleInstance,
227
- setPortableAppDataPath,
228
- waitAppReady,
229
- getPaths,
230
- unzipFile,
231
- zipFile,
232
- parseGithubCdnURL,
233
- handleUnexpectedErrors,
234
- parseVersion,
235
- isUpdateJSON
236
- };