electron-incremental-update 2.3.2 → 2.3.4

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "electron-incremental-update",
3
3
  "type": "module",
4
- "version": "2.3.2",
4
+ "version": "2.3.4",
5
5
  "description": "Electron incremental update tools with Vite plugin, support bytecode protection",
6
6
  "author": "subframe7536",
7
7
  "license": "MIT",
@@ -1,167 +0,0 @@
1
- import { readableSize } from './chunk-TPTWE33H.js';
2
- import { convertArrowFunctionAndTemplate, bytecodeModuleLoader, bytecodeModuleLoaderCode, convertLiteral, compileToBytecode, useStrict, toRelativePath } from './chunk-LR7LR5WG.js';
3
- import { bytecodeLog, bytecodeId } from './chunk-5NKEXGI3.js';
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import MagicString from 'magic-string';
7
- import { createFilter, normalizePath } from 'vite';
8
-
9
- function getBytecodeLoaderBlock(chunkFileName) {
10
- return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`;
11
- }
12
- function bytecodePlugin(env, options) {
13
- const {
14
- enable,
15
- preload = false,
16
- electronPath,
17
- beforeCompile
18
- } = options;
19
- if (!enable) {
20
- return null;
21
- }
22
- if (!preload && env === "preload") {
23
- bytecodeLog.warn('`bytecodePlugin` is skiped in preload. To enable in preload, please manually set the "enablePreload" option to true and set `sandbox: false` when creating the window', { timestamp: true });
24
- return null;
25
- }
26
- const filter = createFilter(/\.(m?[jt]s|[jt]sx)$/);
27
- let config;
28
- let bytecodeRequired = false;
29
- let bytecodeFiles = [];
30
- return {
31
- name: `${bytecodeId}-${env}`,
32
- apply: "build",
33
- enforce: "post",
34
- configResolved(resolvedConfig) {
35
- config = resolvedConfig;
36
- },
37
- transform(code, id) {
38
- if (!filter(id)) {
39
- return convertLiteral(code, !!config.build.sourcemap);
40
- }
41
- },
42
- generateBundle(options2) {
43
- if (options2.format !== "es" && bytecodeRequired) {
44
- this.emitFile({
45
- type: "asset",
46
- source: `${bytecodeModuleLoaderCode}
47
- `,
48
- name: "Bytecode Loader File",
49
- fileName: bytecodeModuleLoader
50
- });
51
- }
52
- },
53
- renderChunk(code, chunk, options2) {
54
- if (options2.format === "es") {
55
- bytecodeLog.warn(
56
- '`bytecodePlugin` does not support ES module, please set "build.rollupOptions.output.format" option to "cjs"',
57
- { timestamp: true }
58
- );
59
- return null;
60
- }
61
- if (chunk.type === "chunk") {
62
- bytecodeRequired = true;
63
- return convertArrowFunctionAndTemplate(code);
64
- }
65
- return null;
66
- },
67
- async writeBundle(options2, output) {
68
- if (options2.format === "es" || !bytecodeRequired) {
69
- return;
70
- }
71
- const outDir = options2.dir;
72
- bytecodeFiles = [];
73
- const bundles = Object.keys(output);
74
- const chunks = Object.values(output).filter(
75
- (chunk) => chunk.type === "chunk" && chunk.fileName !== bytecodeModuleLoader
76
- );
77
- const bytecodeChunks = chunks.map((chunk) => chunk.fileName);
78
- const nonEntryChunks = chunks.filter((chunk) => !chunk.isEntry).map((chunk) => path.basename(chunk.fileName));
79
- const pattern = nonEntryChunks.map((chunk) => `(${chunk})`).join("|");
80
- const bytecodeRE = pattern ? new RegExp(`require\\(\\S*(?=(${pattern})\\S*\\))`, "g") : null;
81
- await Promise.all(
82
- bundles.map(async (name) => {
83
- const chunk = output[name];
84
- if (chunk.type === "chunk") {
85
- let _code = chunk.code;
86
- const chunkFilePath = path.resolve(outDir, name);
87
- if (beforeCompile) {
88
- const cbResult = await beforeCompile(_code, chunkFilePath);
89
- if (cbResult) {
90
- _code = cbResult;
91
- }
92
- }
93
- if (bytecodeRE && _code.match(bytecodeRE)) {
94
- let match;
95
- const s = new MagicString(_code);
96
- while (match = bytecodeRE.exec(_code)) {
97
- const [prefix, chunkName] = match;
98
- const len = prefix.length + chunkName.length;
99
- s.overwrite(match.index, match.index + len, `${prefix + chunkName}c`, {
100
- contentOnly: true
101
- });
102
- }
103
- _code = s.toString();
104
- }
105
- if (bytecodeChunks.includes(name)) {
106
- const bytecodeBuffer = await compileToBytecode(_code, electronPath);
107
- fs.writeFileSync(`${chunkFilePath}c`, bytecodeBuffer);
108
- if (chunk.isEntry) {
109
- const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
110
- const bytecodeModuleBlock = `require("./${`${path.basename(name)}c`}");`;
111
- const code = `${useStrict}
112
- ${bytecodeLoaderBlock}
113
- module.exports=${bytecodeModuleBlock}
114
- `;
115
- fs.writeFileSync(chunkFilePath, code);
116
- } else {
117
- fs.unlinkSync(chunkFilePath);
118
- }
119
- bytecodeFiles.push({ name: `${name}c`, size: bytecodeBuffer.length });
120
- } else {
121
- if (chunk.isEntry) {
122
- let hasBytecodeMoudle = false;
123
- const idsToHandle = /* @__PURE__ */ new Set([...chunk.imports, ...chunk.dynamicImports]);
124
- for (const moduleId of idsToHandle) {
125
- if (bytecodeChunks.includes(moduleId)) {
126
- hasBytecodeMoudle = true;
127
- break;
128
- }
129
- const moduleInfo = this.getModuleInfo(moduleId);
130
- if (moduleInfo && !moduleInfo.isExternal) {
131
- const { importers, dynamicImporters } = moduleInfo;
132
- for (const importerId of importers) {
133
- idsToHandle.add(importerId);
134
- }
135
- for (const importerId of dynamicImporters) {
136
- idsToHandle.add(importerId);
137
- }
138
- }
139
- }
140
- const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
141
- _code = hasBytecodeMoudle ? _code.replace(
142
- new RegExp(`(${useStrict})|("use strict";)`),
143
- `${useStrict}
144
- ${bytecodeLoaderBlock}`
145
- ) : _code;
146
- }
147
- fs.writeFileSync(chunkFilePath, _code);
148
- }
149
- }
150
- })
151
- );
152
- },
153
- closeBundle() {
154
- const outDir = `${normalizePath(path.relative(config.root, path.resolve(config.root, config.build.outDir)))}/`;
155
- bytecodeFiles.forEach((file) => {
156
- bytecodeLog.info(
157
- `${outDir}${file.name} [${readableSize(file.size)}]`,
158
- { timestamp: true }
159
- );
160
- });
161
- bytecodeLog.info(`${bytecodeFiles.length} bundles compiled into bytecode.`, { timestamp: true });
162
- bytecodeFiles = [];
163
- }
164
- };
165
- }
166
-
167
- export { bytecodePlugin };
@@ -1,10 +0,0 @@
1
- import { createLogger } from 'vite';
2
-
3
- // src/vite/constant.ts
4
- var id = "electron-incremental-updater";
5
- var bytecodeId = `${id}-bytecode`;
6
- var esmId = `${id}-esm`;
7
- var log = createLogger("info", { prefix: `[${id}]` });
8
- var bytecodeLog = createLogger("info", { prefix: `[${bytecodeId}]` });
9
-
10
- export { bytecodeId, bytecodeLog, esmId, id, log };
@@ -1,192 +0,0 @@
1
- import { bytecodeLog } from './chunk-5NKEXGI3.js';
2
- import cp from 'node:child_process';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import * as babel from '@babel/core';
6
- import { getPackageInfoSync } from 'local-pkg';
7
- import MagicString from 'magic-string';
8
-
9
- // src/vite/bytecode/code.ts
10
- 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";
11
- 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';
12
-
13
- // src/utils/version.ts
14
- function parseVersion(version) {
15
- const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i.exec(version);
16
- if (!match) {
17
- throw new TypeError(`invalid version: ${version}`);
18
- }
19
- const [major, minor, patch] = match.slice(1, 4).map(Number);
20
- const ret = {
21
- major,
22
- minor,
23
- patch,
24
- stage: "",
25
- stageVersion: -1
26
- };
27
- if (match[4]) {
28
- let [stage, _v] = match[4].split(".");
29
- ret.stage = stage;
30
- ret.stageVersion = Number(_v) || -1;
31
- }
32
- if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) {
33
- throw new TypeError(`Invalid version: ${version}`);
34
- }
35
- return ret;
36
- }
37
- var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
38
- function isUpdateJSON(json) {
39
- return is(json) && is(json?.beta);
40
- }
41
- function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
42
- existingJson.beta = {
43
- version,
44
- minimumVersion,
45
- signature
46
- };
47
- if (!parseVersion(version).stage) {
48
- existingJson.version = version;
49
- existingJson.minimumVersion = minimumVersion;
50
- existingJson.signature = signature;
51
- }
52
- return existingJson;
53
- }
54
-
55
- // src/vite/bytecode/utils.ts
56
- var electronModule = getPackageInfoSync("electron");
57
- var electronMajorVersion = parseVersion(electronModule.version).major;
58
- var useStrict = "'use strict';";
59
- var bytecodeModuleLoader = "__loader__.js";
60
- function getElectronPath() {
61
- const electronModulePath = electronModule.rootPath;
62
- let electronExecPath = process.env.ELECTRON_EXEC_PATH || "";
63
- if (!electronExecPath) {
64
- if (!electronModulePath) {
65
- throw new Error("Electron is not installed");
66
- }
67
- const pathFile = path.join(electronModulePath, "path.txt");
68
- let executablePath;
69
- if (fs.existsSync(pathFile)) {
70
- executablePath = fs.readFileSync(pathFile, "utf-8");
71
- }
72
- if (executablePath) {
73
- electronExecPath = path.join(electronModulePath, "dist", executablePath);
74
- process.env.ELECTRON_EXEC_PATH = electronExecPath;
75
- } else {
76
- throw new Error("Electron executable file is not existed");
77
- }
78
- }
79
- return electronExecPath;
80
- }
81
- function getBytecodeCompilerPath() {
82
- const scriptPath = path.join(electronModule.rootPath, "EIU_bytenode.cjs");
83
- if (!fs.existsSync(scriptPath)) {
84
- fs.writeFileSync(scriptPath, bytecodeGeneratorScript);
85
- }
86
- return scriptPath;
87
- }
88
- function toRelativePath(filename, importer) {
89
- const relPath = path.posix.relative(path.dirname(importer), filename);
90
- return relPath.startsWith(".") ? relPath : `./${relPath}`;
91
- }
92
- var logErr = (...args) => bytecodeLog.error(args.join(" "), { timestamp: true });
93
- function compileToBytecode(code, electronPath = getElectronPath()) {
94
- let data = Buffer.from([]);
95
- const bytecodePath = getBytecodeCompilerPath();
96
- return new Promise((resolve, reject) => {
97
- const proc = cp.spawn(electronPath, [bytecodePath], {
98
- env: { ELECTRON_RUN_AS_NODE: "1" },
99
- stdio: ["pipe", "pipe", "pipe", "ipc"]
100
- });
101
- if (proc.stdin) {
102
- proc.stdin.write(code);
103
- proc.stdin.end();
104
- }
105
- if (proc.stdout) {
106
- proc.stdout.on("data", (chunk) => data = Buffer.concat([data, chunk]));
107
- proc.stdout.on("error", (err) => logErr(err));
108
- proc.stdout.on("end", () => resolve(data));
109
- }
110
- if (proc.stderr) {
111
- proc.stderr.on("data", (chunk) => logErr("Error: ", chunk.toString()));
112
- proc.stderr.on("error", (err) => logErr("Error: ", err));
113
- }
114
- proc.addListener("error", (err) => logErr(err));
115
- proc.on("error", (err) => reject(err));
116
- proc.on("exit", () => resolve(data));
117
- });
118
- }
119
- function convertArrowFunctionAndTemplate(code) {
120
- const result = babel.transform(code, {
121
- plugins: ["@babel/plugin-transform-arrow-functions", "@babel/plugin-transform-template-literals"]
122
- });
123
- return {
124
- code: result?.code || code,
125
- map: result?.map
126
- };
127
- }
128
- var decodeFn = ";function _0xstr_(a,b){return String.fromCharCode.apply(0,a.map(function(x){return x-b}))};";
129
- function obfuscateString(input, offset = ~~(Math.random() * 16) + 1) {
130
- const hexArray = input.split("").map((c) => `0x${(c.charCodeAt(0) + offset).toString(16)}`);
131
- return `_0xstr_([${hexArray.join(",")}],${offset})`;
132
- }
133
- function convertLiteral(code, sourcemap, offset) {
134
- const s = new MagicString(code);
135
- let hasTransformed = false;
136
- const ast = babel.parse(code, { ast: true });
137
- if (!ast) {
138
- throw new Error("Cannot parse code");
139
- }
140
- babel.traverse(ast, {
141
- StringLiteral(path2) {
142
- const parent = path2.parent;
143
- const node = path2.node;
144
- if (parent.type === "CallExpression") {
145
- if (parent.callee.type === "Identifier" && parent.callee.name === "require") {
146
- return;
147
- }
148
- if (parent.callee.type === "Import") {
149
- return;
150
- }
151
- }
152
- if (parent.type.startsWith("Export")) {
153
- return;
154
- }
155
- if (parent.type.startsWith("Import")) {
156
- return;
157
- }
158
- if (parent.type === "ObjectMethod" && parent.key === node) {
159
- return;
160
- }
161
- if (parent.type === "ObjectProperty" && parent.key === node) {
162
- const result2 = `[${obfuscateString(node.value, offset)}]`;
163
- const start2 = node.start;
164
- const end2 = node.end;
165
- if (start2 && end2) {
166
- s.overwrite(start2, end2, result2);
167
- hasTransformed = true;
168
- }
169
- return;
170
- }
171
- if (!node.value.trim()) {
172
- return;
173
- }
174
- const result = obfuscateString(node.value, offset);
175
- const start = node.start;
176
- const end = node.end;
177
- if (start && end) {
178
- s.overwrite(start, end, result);
179
- hasTransformed = true;
180
- }
181
- }
182
- });
183
- if (hasTransformed) {
184
- s.append("\n").append(decodeFn);
185
- }
186
- return {
187
- code: s.toString(),
188
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
189
- };
190
- }
191
-
192
- export { bytecodeModuleLoader, bytecodeModuleLoaderCode, compileToBytecode, convertArrowFunctionAndTemplate, convertLiteral, defaultVersionJsonGenerator, electronMajorVersion, isUpdateJSON, toRelativePath, useStrict };
@@ -1,23 +0,0 @@
1
- import { log } from './chunk-5NKEXGI3.js';
2
- import fs from 'node:fs';
3
-
4
- function readableSize(size) {
5
- const units = ["B", "KB", "MB", "GB"];
6
- let i = 0;
7
- while (size >= 1024 && i < units.length - 1) {
8
- size /= 1024;
9
- i++;
10
- }
11
- return `${size.toFixed(2)} ${units[i]}`;
12
- }
13
- function copyAndSkipIfExist(from, to, skipIfExist) {
14
- if (!skipIfExist || !fs.existsSync(to)) {
15
- try {
16
- fs.cpSync(from, to, { recursive: true });
17
- } catch (error) {
18
- log.warn(`Copy failed: ${error}`, { timestamp: true });
19
- }
20
- }
21
- }
22
-
23
- export { copyAndSkipIfExist, readableSize };
@@ -1 +0,0 @@
1
- export { bytecodeId, bytecodeLog, esmId, id, log } from './chunk-5NKEXGI3.js';
@@ -1,64 +0,0 @@
1
- import { electronMajorVersion } from './chunk-LR7LR5WG.js';
2
- import { esmId } from './chunk-5NKEXGI3.js';
3
- import MagicString from 'magic-string';
4
-
5
- // src/vite/esm/constant.ts
6
- var CJSShim = `
7
- // -- CommonJS Shims --
8
- import __cjs_url__ from 'node:url';
9
- import __cjs_path__ from 'node:path';
10
- import __cjs_mod__ from 'node:module';
11
- const __filename = __cjs_url__.fileURLToPath(import.meta.url);
12
- const __dirname = __cjs_path__.dirname(__filename);
13
- const require = __cjs_mod__.createRequire(import.meta.url);
14
- `;
15
- var CJSShim_electron_30 = `
16
- // -- CommonJS Shims --
17
- import __cjs_mod__ from 'node:module';
18
- const __filename = import.meta.filename;
19
- const __dirname = import.meta.dirname;
20
- const require = __cjs_mod__.createRequire(import.meta.url);
21
- `;
22
- var shim = electronMajorVersion >= 30 ? CJSShim_electron_30 : CJSShim;
23
-
24
- // src/vite/esm/utils.ts
25
- var ESMStaticImportRe = /(?<=\s|^|;)import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<=")[^"]*[^\s"](?=\s*")|(?<=')[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
26
- function findStaticImports(code) {
27
- const matches = [];
28
- for (const match of code.matchAll(ESMStaticImportRe)) {
29
- matches.push({ end: (match.index || 0) + match[0].length });
30
- }
31
- return matches;
32
- }
33
- function insertCJSShim(code, sourcemap, insertPosition = 0) {
34
- if (code.includes(shim) || !/__filename|__dirname|require\(|require\.resolve\(|require\.apply\(/.test(code)) {
35
- return null;
36
- }
37
- const s = new MagicString(code);
38
- s.appendRight(insertPosition, shim);
39
- return {
40
- code: s.toString(),
41
- map: sourcemap ? s.generateMap({ hires: "boundary" }) : null
42
- };
43
- }
44
-
45
- // src/vite/esm/index.ts
46
- function esm() {
47
- let sourcemap;
48
- return {
49
- name: esmId,
50
- enforce: "post",
51
- configResolved(config) {
52
- sourcemap = config.build.sourcemap;
53
- },
54
- renderChunk(code, _chunk, options) {
55
- if (options.format === "es") {
56
- const lastESMImport = findStaticImports(code).pop();
57
- const pos = lastESMImport ? lastESMImport.end : 0;
58
- return insertCJSShim(code, sourcemap, pos);
59
- }
60
- }
61
- };
62
- }
63
-
64
- export { esm };