electron-incremental-update 1.3.0 → 2.0.0-beta.10

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.cjs CHANGED
@@ -1,403 +1,202 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ 'use strict';
19
2
 
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- ErrorInfo: () => ErrorInfo,
24
- Updater: () => Updater,
25
- UpdaterError: () => UpdaterError,
26
- createUpdater: () => createUpdater,
27
- downloadBufferDefault: () => downloadBufferDefault,
28
- downloadJSONDefault: () => downloadJSONDefault,
29
- initApp: () => initApp,
30
- isLowerVersionDefault: () => isLowerVersionDefault,
31
- startupWithUpdater: () => startupWithUpdater
32
- });
33
- module.exports = __toCommonJS(src_exports);
34
- var import_node_path2 = require("path");
35
- var import_node_fs4 = require("fs");
36
- var import_electron4 = require("electron");
3
+ var fs3 = require('fs');
4
+ var events = require('events');
5
+ var electron = require('electron');
6
+ var path = require('path');
37
7
 
38
- // src/updater/core.ts
39
- var import_node_fs3 = require("fs");
40
- var import_electron3 = require("electron");
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
41
9
 
42
- // src/utils/electron.ts
43
- var import_node_fs = require("fs");
44
- var import_node_path = require("path");
45
- var import_node_os = require("os");
46
- var import_electron = require("electron");
47
- var is = {
48
- dev: !import_electron.app.isPackaged,
49
- win: process.platform === "win32",
50
- mac: process.platform === "darwin",
51
- linux: process.platform === "linux"
52
- };
53
- function getPathFromAppNameAsar(...path) {
54
- return is.dev ? "DEV.asar" : (0, import_node_path.join)((0, import_node_path.dirname)(import_electron.app.getAppPath()), `${import_electron.app.name}.asar`, ...path);
55
- }
56
- function getVersions() {
57
- const platform = is.win ? "Windows" : is.mac ? "MacOS" : process.platform.toUpperCase();
58
- return {
59
- appVersion: is.dev ? import_electron.app.getVersion() : (0, import_node_fs.readFileSync)(getPathFromAppNameAsar("version"), "utf-8"),
60
- entryVersion: import_electron.app.getVersion(),
61
- electronVersion: process.versions.electron,
62
- nodeVersion: process.versions.node,
63
- systemVersion: `${platform} ${(0, import_node_os.release)()}`
64
- };
65
- }
66
- function restartApp() {
67
- import_electron.app.relaunch();
68
- import_electron.app.quit();
69
- }
70
- function waitAppReady(timeout = 1e3) {
71
- return import_electron.app.isReady() ? Promise.resolve() : new Promise((resolve2, reject) => {
72
- const _ = setTimeout(() => {
73
- reject(new Error("app is not ready"));
74
- }, timeout);
75
- import_electron.app.whenReady().then(() => {
76
- clearTimeout(_);
77
- resolve2();
78
- });
79
- });
80
- }
10
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
11
+ var path__default = /*#__PURE__*/_interopDefault(path);
81
12
 
82
- // src/utils/zip.ts
83
- var import_node_fs2 = require("fs");
84
- var import_node_zlib = require("zlib");
85
- async function unzipFile(gzipPath, targetFilePath = gzipPath.slice(0, -3)) {
86
- if (!(0, import_node_fs2.existsSync)(gzipPath)) {
87
- throw new Error(`path to zipped file not exist: ${gzipPath}`);
88
- }
89
- const compressedBuffer = (0, import_node_fs2.readFileSync)(gzipPath);
90
- return new Promise((resolve2, reject) => {
91
- (0, import_node_zlib.brotliDecompress)(compressedBuffer, (err, buffer) => {
92
- (0, import_node_fs2.rmSync)(gzipPath);
93
- if (err) {
94
- reject(err);
95
- }
96
- (0, import_node_fs2.writeFileSync)(targetFilePath, buffer);
97
- resolve2(null);
98
- });
99
- });
100
- }
13
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
14
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
15
+ }) : x)(function(x) {
16
+ if (typeof require !== "undefined") return require.apply(this, arguments);
17
+ throw Error('Dynamic require of "' + x + '" is not supported');
18
+ });
101
19
 
102
- // src/utils/pure.ts
103
- function parseVersion(version) {
104
- const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i.exec(version);
105
- if (!match) {
106
- throw new TypeError(`invalid version: ${version}`);
107
- }
108
- const [major, minor, patch] = match.slice(1, 4).map(Number);
109
- const ret = {
110
- major,
111
- minor,
112
- patch,
113
- stage: "",
114
- stageVersion: -1
115
- };
116
- if (match[4]) {
117
- let [stage, _v] = match[4].split(".");
118
- ret.stage = stage;
119
- ret.stageVersion = Number(_v) || -1;
120
- }
121
- if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) {
122
- throw new TypeError(`invalid version: ${version}`);
123
- }
124
- return ret;
125
- }
20
+ // src/utils/version.ts
126
21
  function isUpdateJSON(json) {
127
- const is2 = (j) => !!(j && j.minimumVersion && j.signature && j.size && j.version);
128
- return is2(json) && is2(json?.beta);
22
+ const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
23
+ return is(json) && is(json?.beta);
129
24
  }
130
-
131
- // src/crypto/dec.ts
132
- var import_node_crypto2 = require("crypto");
133
-
134
- // src/crypto/utils.ts
135
- var import_node_crypto = require("crypto");
136
- function hashString(data, length) {
137
- const hash = (0, import_node_crypto.createHash)("SHA256").update(data).digest("binary");
138
- return Buffer.from(hash).subarray(0, length);
25
+ var isDev = __EIU_IS_DEV__;
26
+ process.platform === "win32";
27
+ process.platform === "darwin";
28
+ process.platform === "linux";
29
+ function getPathFromAppNameAsar(...paths) {
30
+ return isDev ? "DEV.asar" : path__default.default.join(path__default.default.dirname(electron.app.getAppPath()), `${electron.app.name}.asar`, ...paths);
139
31
  }
140
-
141
- // src/crypto/dec.ts
142
- function decrypt(encryptedText, key, iv) {
143
- const decipher = (0, import_node_crypto2.createDecipheriv)("aes-256-cbc", key, iv);
144
- let decrypted = decipher.update(encryptedText, "base64url", "utf8");
145
- decrypted += decipher.final("utf8");
146
- return decrypted;
32
+ function getAppVersion() {
33
+ return isDev ? getEntryVersion() : fs3__default.default.readFileSync(getPathFromAppNameAsar("version"), "utf-8");
34
+ }
35
+ function getEntryVersion() {
36
+ return electron.app.getVersion();
37
+ }
38
+ function restartApp() {
39
+ electron.app.relaunch();
40
+ electron.app.quit();
147
41
  }
148
- var verify = (buffer, signature, cert) => {
149
- try {
150
- const [sig, version] = decrypt(signature, hashString(cert, 32), hashString(buffer, 16)).split("%");
151
- const result = (0, import_node_crypto2.createVerify)("RSA-SHA256").update(buffer).verify(cert, sig, "base64");
152
- return result ? version : false;
153
- } catch (error) {
154
- return false;
155
- }
156
- };
157
-
158
- // src/crypto/enc.ts
159
- var import_node_crypto3 = require("crypto");
160
42
 
161
- // src/updater/types.ts
43
+ // src/entry/types.ts
162
44
  var ErrorInfo = {
163
- downlaod: "Download failed",
164
- validate: "Validate failed",
165
- param: "Missing params",
166
- version: "Unsatisfied version"
45
+ download: "Download Failed",
46
+ validate: "Validate Failed",
47
+ param: "Missing Params",
48
+ network: "Network Error"
167
49
  };
168
50
  var UpdaterError = class extends Error {
51
+ code;
169
52
  constructor(msg, info) {
170
- super(msg + ": " + info);
171
- }
172
- };
173
-
174
- // src/updater/defaultFunctions/download.ts
175
- var import_electron2 = require("electron");
176
- async function downlaodFn(url, headers, onResponse) {
177
- await waitAppReady();
178
- return new Promise((resolve2, reject) => {
179
- const request = import_electron2.net.request({ url, method: "GET", redirect: "follow" });
180
- Object.keys(headers).forEach((key) => request.setHeader(key, headers[key]));
181
- request.on("response", (res) => onResponse(res, resolve2, reject));
182
- request.on("error", reject);
183
- request.end();
184
- });
185
- }
186
- var downloadJSONDefault = async (url, headers) => {
187
- return await downlaodFn(url, headers, (resp, resolve2, reject) => {
188
- let data = "";
189
- resp.on("data", (chunk) => data += chunk);
190
- resp.on("end", () => {
191
- try {
192
- const json = JSON.parse(data);
193
- if (isUpdateJSON(json)) {
194
- resolve2(json);
195
- } else {
196
- throw Error;
197
- }
198
- } catch (ignore) {
199
- reject(new Error("invalid update json"));
200
- }
201
- });
202
- resp.on("aborted", () => reject(new Error("aborted")));
203
- resp.on("error", () => reject(new Error("download error")));
204
- });
205
- };
206
- var downloadBufferDefault = async (url, headers, total, onDownloading) => {
207
- let current = 0;
208
- return await downlaodFn(url, headers, (resp, resolve2, reject) => {
209
- let data = [];
210
- resp.on("data", (chunk) => {
211
- current += chunk.length;
212
- onDownloading?.({ percent: `${+(current / total).toFixed(2) * 100}%`, total, current });
213
- data.push(chunk);
214
- });
215
- resp.on("end", () => resolve2(Buffer.concat(data)));
216
- resp.on("aborted", () => reject(new Error("aborted")));
217
- resp.on("error", () => reject(new Error("download error")));
218
- });
219
- };
220
-
221
- // src/updater/defaultFunctions/compareVersion.ts
222
- var isLowerVersionDefault = (version1, version2) => {
223
- const oldV = parseVersion(version1);
224
- const newV = parseVersion(version2);
225
- function compareStrings(str1, str2) {
226
- if (str1 === "") {
227
- return str2 !== "";
228
- } else if (str2 === "") {
229
- return true;
230
- }
231
- return str1 < str2;
232
- }
233
- for (let key of Object.keys(oldV)) {
234
- if (key === "stage" && compareStrings(oldV[key], newV[key])) {
235
- return true;
236
- } else if (oldV[key] !== newV[key]) {
237
- return oldV[key] < newV[key];
238
- }
53
+ super("[" + ErrorInfo[msg] + "] " + info);
54
+ this.code = msg;
239
55
  }
240
- return false;
241
56
  };
242
57
 
243
- // src/updater/core.ts
244
- var Updater = class {
245
- CERT = __SIGNATURE_CERT__;
58
+ // src/entry/updater.ts
59
+ var Updater = class extends events.EventEmitter {
60
+ CERT = __EIU_SIGNATURE_CERT__;
246
61
  info;
247
- option;
248
- asarPath;
249
- gzipPath;
250
- tmpFilePath;
62
+ provider;
251
63
  /**
252
- * updater logger
64
+ * Updater logger
253
65
  */
254
66
  logger;
255
67
  /**
256
- * downloading progress hook
257
- * @param progress download progress
258
- * @example
259
- * updater.onDownloading = ({ percent, total, current }) => {
260
- * console.log(`download progress: ${percent}, total: ${total}, current: ${current}`)
261
- * }
68
+ * Whether to receive beta update
262
69
  */
263
- onDownloading;
70
+ receiveBeta;
264
71
  /**
265
- * whether receive beta version
72
+ * Whether force update in DEV
266
73
  */
267
- get receiveBeta() {
268
- return !!this.option.receiveBeta;
269
- }
270
- set receiveBeta(receiveBeta) {
271
- this.option.receiveBeta = receiveBeta;
272
- }
74
+ forceUpdate;
273
75
  /**
274
- * initialize incremental updater
275
- * @param option UpdaterOption
76
+ * Initialize incremental updater
77
+ * @param options UpdaterOption
276
78
  */
277
- constructor(option = {}) {
278
- this.option = option;
279
- if (option.SIGNATURE_CERT) {
280
- this.CERT = option.SIGNATURE_CERT;
79
+ constructor(options = {}) {
80
+ super();
81
+ this.provider = options.provider;
82
+ this.receiveBeta = options.receiveBeta;
83
+ this.CERT = options.SIGNATURE_CERT || __EIU_SIGNATURE_CERT__;
84
+ this.logger = options.logger;
85
+ if (isDev && !this.logger) {
86
+ this.logger = {
87
+ info: (...args) => console.log("[EIU-INFO ]", ...args),
88
+ debug: (...args) => console.log("[EIU-DEBUG]", ...args),
89
+ warn: (...args) => console.log("[EIU-WARN ]", ...args),
90
+ error: (...args) => console.error("[EIU-ERROR]", ...args)
91
+ };
92
+ this.logger.info("no logger set, enable dev-only logger");
281
93
  }
282
- this.asarPath = getPathFromAppNameAsar();
283
- this.gzipPath = `${this.asarPath}.gz`;
284
- this.tmpFilePath = `${this.asarPath}.tmp`;
285
- }
286
- async needUpdate(version, minVersion) {
287
- const isLowerVersion = this.option.overrideFunctions?.isLowerVersion ?? isLowerVersionDefault;
288
- const { appVersion, entryVersion } = getVersions();
289
- if (await isLowerVersion(entryVersion, minVersion)) {
290
- throw new UpdaterError(ErrorInfo.version, `entry version (${entryVersion}) < minimumVersion (${minVersion})`);
94
+ if (!this.provider) {
95
+ this.logger?.debug("No update provider, please setup provider before checking update");
291
96
  }
292
- this.logger?.info(`check update: current version is ${appVersion}, new version is ${version}`);
293
- return await isLowerVersion(appVersion, version);
294
97
  }
295
- async parseData(format, data) {
296
- if ((0, import_node_fs3.existsSync)(this.tmpFilePath)) {
297
- this.logger?.warn(`remove tmp file: ${this.tmpFilePath}`);
298
- (0, import_node_fs3.rmSync)(this.tmpFilePath);
299
- }
300
- if ((0, import_node_fs3.existsSync)(this.gzipPath)) {
301
- this.logger?.warn(`remove .gz file: ${this.gzipPath}`);
302
- (0, import_node_fs3.rmSync)(this.gzipPath);
98
+ checkProvider() {
99
+ if (!this.provider) {
100
+ throw new UpdaterError("param", "missing update provider");
303
101
  }
102
+ }
103
+ async fetch(format, data) {
304
104
  if (typeof data === "object") {
305
105
  if (format === "json" && isUpdateJSON(data) || format === "buffer" && Buffer.isBuffer(data)) {
306
106
  return data;
307
107
  } else {
308
- throw new UpdaterError(ErrorInfo.param, `invalid type at format '${format}': ${JSON.stringify(data)}`);
108
+ this.err("invalid type", "param", `invalid type at format '${format}': ${JSON.stringify(data)}`);
109
+ return;
309
110
  }
310
111
  }
311
- const ua = this.option.downloadConfig?.userAgent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36";
312
- const headers = {
313
- Accept: `application/${format === "json" ? "json" : "octet-stream"}`,
314
- UserAgent: ua,
315
- ...this.option.downloadConfig?.extraHeader
316
- };
317
- this.logger?.debug(`download headers: ${JSON.stringify(headers)}`);
318
- const config = format === "json" ? {
319
- name: "updateJsonURL",
320
- url: this.option.updateJsonURL,
321
- repoFallback: `${this.option.repository?.replace("github.com", "raw.githubusercontent.com")}/master/version.json`,
322
- fn: this.option.overrideFunctions?.downloadJSON ?? downloadJSONDefault
323
- } : {
324
- name: "releaseAsarURL",
325
- url: this.option.releaseAsarURL,
326
- repoFallback: `${this.option.repository}/releases/download/v${this.info?.version}/${import_electron3.app.name}-${this.info?.version}.asar.gz`,
327
- fn: this.option.overrideFunctions?.downloadBuffer ?? downloadBufferDefault
328
- };
329
- data ??= config.url;
330
- if (!data) {
331
- this.logger?.debug(`no ${config.name}, fallback to use repository`);
332
- if (!this.option.repository) {
333
- throw new UpdaterError(ErrorInfo.param, `${config.name} or repository is not set`);
334
- }
335
- if (format === "buffer" && !this.info?.version) {
336
- throw new UpdaterError(ErrorInfo.param, "version is not set");
337
- }
338
- data = config.repoFallback;
339
- }
340
- this.logger?.debug(`download ${format} from ${data}`);
112
+ this.logger?.debug(`download from ${this.provider.name}`);
341
113
  try {
342
- const ret = format === "json" ? await config.fn(data, headers) : await config.fn(data, headers, this.info.size, this.onDownloading);
343
- this.logger?.debug(`download ${format} success${format === "buffer" ? `, file size: ${ret.length}` : ""}`);
344
- return ret;
114
+ const result = format === "json" ? await this.provider.downloadJSON(data ?? __EIU_VERSION_PATH__) : await this.provider.downloadAsar(electron.app.name, this.info, (data2) => this.emit("download-progress", data2));
115
+ this.logger?.debug(`download ${format} success${format === "buffer" ? `, file size: ${result.length}` : ""}`);
116
+ return result;
345
117
  } catch (e) {
346
- throw new UpdaterError(ErrorInfo.downlaod, e.toString());
118
+ this.err(`fetch ${format} failed`, "network", `download ${format} failed: ${e}`);
347
119
  }
348
120
  }
121
+ /**
122
+ * Handle error message and emit error event
123
+ */
124
+ err(msg, code, errorInfo) {
125
+ const err = new UpdaterError(code, errorInfo);
126
+ this.logger?.error(msg, err);
127
+ this.emit("error", err);
128
+ }
349
129
  async checkUpdate(data) {
130
+ this.checkProvider();
131
+ const emitUnavailable = (msg) => {
132
+ this.logger?.info(msg);
133
+ this.emit("update-unavailable", msg);
134
+ return false;
135
+ };
136
+ const _data = await this.fetch("json", data);
137
+ if (!_data) {
138
+ return emitUnavailable("failed to get update info");
139
+ }
140
+ let { signature, version, minimumVersion, beta } = _data;
141
+ if (this.receiveBeta) {
142
+ version = beta.version;
143
+ signature = beta.signature;
144
+ minimumVersion = beta.minimumVersion;
145
+ }
146
+ this.logger?.debug(`checked update, version: ${version}, signature: ${signature}`);
147
+ if (isDev && !this.forceUpdate && !data) {
148
+ return emitUnavailable("skip check update in dev mode, to force update, set `updater.forceUpdate` to true or call checkUpdate with UpdateJSON");
149
+ }
150
+ const isLowerVersion = this.provider.isLowerVersion;
151
+ const entryVersion = getEntryVersion();
152
+ const appVersion = getAppVersion();
350
153
  try {
351
- let { signature, size, version, minimumVersion, beta } = await this.parseData("json", data);
352
- if (this.receiveBeta) {
353
- version = beta.version;
354
- signature = beta.signature;
355
- minimumVersion = beta.minimumVersion;
356
- size = beta.size;
154
+ if (isLowerVersion(entryVersion, minimumVersion)) {
155
+ return emitUnavailable(`entry version (${entryVersion}) < minimumVersion (${minimumVersion})`);
357
156
  }
358
- this.logger?.debug(`checked version: ${version}, size: ${size}, signature: ${signature}`);
359
- if (!await this.needUpdate(version, minimumVersion)) {
360
- this.logger?.info(`update unavailable: ${version} is the latest version`);
361
- return void 0;
362
- } else {
363
- this.logger?.info(`update available: ${version}`);
364
- this.info = {
365
- signature,
366
- minimumVersion,
367
- version,
368
- size
369
- };
370
- return this.info;
157
+ this.logger?.info(`check update: current version is ${appVersion}, new version is ${version}`);
158
+ if (!isLowerVersion(appVersion, version)) {
159
+ return emitUnavailable(`current version (${appVersion}) < new version (${version})`);
371
160
  }
372
- } catch (error) {
373
- this.logger?.error("check update failed", error);
374
- return error;
161
+ this.logger?.info(`update available: ${version}`);
162
+ this.info = { signature, minimumVersion, version };
163
+ this.emit("update-available", this.info);
164
+ return true;
165
+ } catch {
166
+ this.err("Fail to parse version", "validate", "fail to parse version string");
167
+ return false;
375
168
  }
376
169
  }
377
- async download(data, sig) {
170
+ async downloadUpdate(data, info) {
171
+ this.checkProvider();
172
+ const _sig = info?.signature ?? this.info?.signature;
173
+ const _version = info?.version ?? this.info?.version;
174
+ if (!_sig || !_version) {
175
+ this.err("download failed", "param", "no update signature, please call `checkUpdate` first or manually setup params");
176
+ return false;
177
+ }
178
+ const buffer = await this.fetch("buffer", data ? Buffer.from(data) : void 0);
179
+ if (!buffer) {
180
+ this.err("download failed", "param", "no update asar file buffer");
181
+ return false;
182
+ }
183
+ this.logger?.debug("verify start");
184
+ if (!await this.provider.verifySignaure(buffer, _version, _sig, this.CERT)) {
185
+ this.err("download failed", "validate", "invalid update asar file");
186
+ return false;
187
+ }
188
+ this.logger?.debug("verify success");
378
189
  try {
379
- const _sig = sig ?? this.info?.signature;
380
- if (!_sig) {
381
- throw new UpdaterError(ErrorInfo.param, "signature is empty");
382
- }
383
- const buffer = await this.parseData("buffer", data);
384
- this.logger?.debug("verify start");
385
- const _verify = this.option.overrideFunctions?.verifySignaure ?? verify;
386
- const _ver = await _verify(buffer, _sig, this.CERT);
387
- if (!_ver) {
388
- throw new UpdaterError(ErrorInfo.validate, "invalid signature or certificate");
389
- }
390
- this.logger?.debug("verify success");
391
- this.logger?.debug(`write to ${this.gzipPath}`);
392
- (0, import_node_fs3.writeFileSync)(this.gzipPath, buffer);
393
- this.logger?.debug(`extract to ${this.tmpFilePath}`);
394
- await unzipFile(this.gzipPath, this.tmpFilePath);
395
- this.logger?.info(`download success, version: ${_ver}`);
190
+ const tmpFilePath = getPathFromAppNameAsar() + ".tmp";
191
+ this.logger?.debug(`install to ${tmpFilePath}`);
192
+ fs3__default.default.writeFileSync(tmpFilePath, await this.provider.unzipFile(buffer));
193
+ this.logger?.info(`download success, version: ${_version}`);
396
194
  this.info = void 0;
195
+ this.emit("update-downloaded");
397
196
  return true;
398
197
  } catch (error) {
399
- this.logger?.error("download asar failed", error);
400
- return error;
198
+ this.err("download failed", "download", `fail to unwrap asar file, ${error}`);
199
+ return false;
401
200
  }
402
201
  }
403
202
  /**
@@ -408,13 +207,11 @@ var Updater = class {
408
207
  restartApp();
409
208
  }
410
209
  };
411
-
412
- // src/updater/index.ts
413
- function createUpdater(option) {
414
- return new Updater(option);
210
+ async function autoUpdate(updater) {
211
+ if (await updater.checkUpdate() && await updater.downloadUpdate()) {
212
+ updater.quitAndInstall();
213
+ }
415
214
  }
416
-
417
- // src/index.ts
418
215
  function startupWithUpdater(fn) {
419
216
  return fn;
420
217
  }
@@ -425,23 +222,13 @@ var defaultOnInstall = (install, _, __, logger) => {
425
222
  async function initApp(appOptions = {}) {
426
223
  const {
427
224
  updater,
428
- electronDevDistPath = "../dist-electron",
429
- mainPath = "main/index.js",
430
- hooks
431
- } = appOptions || {};
432
- const {
433
225
  onInstall = defaultOnInstall,
434
226
  beforeStart,
435
227
  onStartError
436
- } = hooks || {};
437
- function handleError(err, logger2) {
438
- console.error(err);
439
- onStartError?.(err, logger2);
440
- import_electron4.app.quit();
441
- }
228
+ } = appOptions;
442
229
  let updaterInstance;
443
230
  if (typeof updater === "object" || !updater) {
444
- updaterInstance = createUpdater(updater);
231
+ updaterInstance = new Updater(updater);
445
232
  } else {
446
233
  updaterInstance = await updater();
447
234
  }
@@ -449,27 +236,27 @@ async function initApp(appOptions = {}) {
449
236
  try {
450
237
  const appNameAsarPath = getPathFromAppNameAsar();
451
238
  const tempAsarPath = `${appNameAsarPath}.tmp`;
452
- if ((0, import_node_fs4.existsSync)(tempAsarPath)) {
239
+ if (fs3__default.default.existsSync(tempAsarPath)) {
453
240
  logger?.info(`installing new asar: ${tempAsarPath}`);
454
- await onInstall(() => (0, import_node_fs4.renameSync)(tempAsarPath, appNameAsarPath), tempAsarPath, appNameAsarPath, logger);
241
+ await onInstall(() => fs3__default.default.renameSync(tempAsarPath, appNameAsarPath), tempAsarPath, appNameAsarPath, logger);
455
242
  }
456
- const mainDir = is.dev ? electronDevDistPath : appNameAsarPath;
457
- const entry = (0, import_node_path2.resolve)(__dirname, mainDir, mainPath);
458
- await beforeStart?.(entry, logger);
459
- require(entry)(updaterInstance);
243
+ const mainFilePath = path__default.default.join(
244
+ isDev ? path__default.default.join(electron.app.getAppPath(), __EIU_MAIN_DEV_DIR__) : appNameAsarPath,
245
+ "main",
246
+ __EIU_MAIN_FILE__
247
+ );
248
+ await beforeStart?.(mainFilePath, logger);
249
+ __require(mainFilePath)(updaterInstance);
460
250
  } catch (error) {
461
- handleError(error, logger);
251
+ logger?.error("startup error", error);
252
+ onStartError?.(error, logger);
253
+ electron.app.quit();
462
254
  }
463
255
  }
464
- // Annotate the CommonJS export names for ESM import in node:
465
- 0 && (module.exports = {
466
- ErrorInfo,
467
- Updater,
468
- UpdaterError,
469
- createUpdater,
470
- downloadBufferDefault,
471
- downloadJSONDefault,
472
- initApp,
473
- isLowerVersionDefault,
474
- startupWithUpdater
475
- });
256
+
257
+ exports.ErrorInfo = ErrorInfo;
258
+ exports.Updater = Updater;
259
+ exports.UpdaterError = UpdaterError;
260
+ exports.autoUpdate = autoUpdate;
261
+ exports.initApp = initApp;
262
+ exports.startupWithUpdater = startupWithUpdater;