Repository navigation
Expand file tree
/
Copy pathforge.config.js
More file actions
472 lines (417 loc) · 13.6 KB
/
Copy pathforge.config.js
File metadata and controls
472 lines (417 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
const net = require("node:net");
const fs = require("node:fs/promises");
const path = require("node:path");
const { FusesPlugin } = require("@electron-forge/plugin-fuses");
const { WebpackPlugin } = require("@electron-forge/plugin-webpack");
const { FuseV1Options, FuseVersion } = require("@electron/fuses");
const {
installWindowsWebpackMoveFallback,
} = require("./scripts/lib/windows-webpack-move");
const webpack = require("webpack");
const MIN_PORT = 1024;
const MAX_PORT = 65535;
const DEFAULT_DEV_SERVER_PORT = 3001;
const DEFAULT_LOGGER_PORT = 19001;
const PRODUCT_NAME = "SimpleShell";
const PACKAGE_NAME = "simpleshell";
const APP_BUNDLE_ID = "com.funkpopo.simpleshell";
const APP_CATEGORY_TYPE = "public.app-category.developer-tools";
const APP_HOMEPAGE = "https://github.com/funkpopo/simpleshell";
const APP_DESCRIPTION = "A Simple Cross-Platform Electron SSH Terminal";
const AUTHOR = "funkpopo <funkpopoisme@gmail.com>";
const LOCALE_PAKS_TO_KEEP = new Set(["en-US.pak", "zh-CN.pak"]);
const DEBIAN_CJK_FONT_DEPENDENCIES = ["fonts-noto-cjk"];
const RPM_CJK_FONT_DEPENDENCIES = ["google-noto-sans-cjk-fonts"];
const NATIVE_SERVICES_BASENAME =
process.platform === "win32" ? "simpleshell-core.exe" : "simpleshell-core";
const WINDOWS_ICON_PATH = path.join(__dirname, "src/renderer/assets/logo.ico");
const LICENSE_FILE_PATH = path.join(__dirname, "LICENSE");
const WINDOWS_INSTALLER_OUTPUT_DIR = path.join(__dirname, "installer");
const LINUX_ICON_PATH = path.join(
__dirname,
"src/renderer/assets/SimpleShell.png",
);
const WEBPACK_DIR = path.resolve(__dirname, ".webpack");
installWindowsWebpackMoveFallback(WEBPACK_DIR);
const closeWebpackCompiler = (compiler) =>
new Promise((resolve, reject) => {
if (typeof compiler.close !== "function") {
resolve();
return;
}
compiler.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
class WindowsSafeWebpackPlugin extends WebpackPlugin {
constructor(config) {
super(config);
const compileMain = this.compileMain;
this.compileMain = async (watch = false, logger) => {
if (watch) {
return compileMain.call(this, watch, logger);
}
let tab;
if (logger) {
tab = logger.createTab("Main Process");
}
const mainConfig = await this.configGenerator.getMainConfig();
await new Promise((resolve, reject) => {
const compiler = webpack(mainConfig);
compiler.run(async (err, stats) => {
let primaryError = err || null;
try {
if (tab && stats) {
tab.log(stats.toString({ colors: true }));
}
if (this.config.jsonStats) {
await this.writeJSONStats(
"main",
stats,
mainConfig.stats,
"main",
);
}
if (!primaryError && stats?.hasErrors()) {
primaryError = new Error(
`Compilation errors in the main process: ${stats.toString()}`,
);
}
await closeWebpackCompiler(compiler);
} catch (error) {
primaryError = primaryError || error;
}
if (primaryError) {
reject(primaryError);
return;
}
resolve();
});
});
};
this.runWebpack = async (options, rendererOptions) =>
new Promise((resolve, reject) => {
const compiler = webpack(options);
compiler.run(async (err, stats) => {
let primaryError = err || null;
try {
if (rendererOptions?.jsonStats) {
for (const [index, entryStats] of (
stats?.stats || []
).entries()) {
const name = rendererOptions.entryPoints[index].name;
const statsOptions = Array.isArray(options)
? options[index].stats
: options.stats;
await this.writeJSONStats(
"renderer",
entryStats,
statsOptions,
name,
);
}
}
await closeWebpackCompiler(compiler);
} catch (error) {
primaryError = primaryError || error;
}
if (primaryError) {
reject(primaryError);
return;
}
resolve(stats);
});
});
}
}
const parsePort = (rawValue, fallback) => {
const parsed = Number.parseInt(rawValue, 10);
return Number.isInteger(parsed) && parsed >= MIN_PORT && parsed <= MAX_PORT
? parsed
: fallback;
};
const isPortAvailable = (port) =>
new Promise((resolve) => {
const tester = net.createServer();
tester.unref();
tester.once("error", () => resolve(false));
tester.once("listening", () => tester.close(() => resolve(true)));
// Don't bind only to 127.0.0.1: Forge's logger binds to all interfaces (often `:::PORT`),
// and a port can be "free" on 127.0.0.1 but already taken on ::/0.0.0.0.
tester.listen({ port, exclusive: true });
});
// Forge uses fixed ports; take the first free one so a second dev instance or
// an integration run does not fail with EADDRINUSE.
const findAvailablePort = async (preferred, excluded) => {
for (let port = preferred; port <= MAX_PORT; port += 1) {
if (port !== excluded && (await isPortAvailable(port))) return port;
}
throw new Error(`Unable to locate a free TCP port from ${preferred}`);
};
const keepOnlyRequiredLocalePaks = async (buildPath) => {
const localesDir = path.join(buildPath, "locales");
let localeEntries = [];
try {
localeEntries = await fs.readdir(localesDir, { withFileTypes: true });
} catch (error) {
if (error && error.code === "ENOENT") {
return;
}
throw error;
}
const filesToRemove = localeEntries
.filter(
(entry) =>
entry.isFile() &&
entry.name.endsWith(".pak") &&
!LOCALE_PAKS_TO_KEEP.has(entry.name),
)
.map((entry) => fs.unlink(path.join(localesDir, entry.name)));
await Promise.all(filesToRemove);
};
const cleanupLocalesHook = ({ buildPath }) =>
keepOnlyRequiredLocalePaks(buildPath);
// The webpack plugin packages only `.webpack/` and package.json, so the only
// development leftover is the scripts block in the packaged manifest.
const stripPackagedScripts = async (buildPath) => {
const packageJsonPath = path.join(buildPath, "package.json");
let packageJson;
try {
packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
} catch (error) {
if (error && error.code === "ENOENT") {
return;
}
throw error;
}
delete packageJson.scripts;
await fs.writeFile(
packageJsonPath,
`${JSON.stringify(packageJson, null, 2)}\n`,
"utf8",
);
};
const removePackagedSourceMaps = async (rootPath) => {
let entries;
try {
entries = await fs.readdir(rootPath, { withFileTypes: true });
} catch (error) {
if (error && error.code === "ENOENT") {
return;
}
throw error;
}
await Promise.all(
entries.map(async (entry) => {
const entryPath = path.join(rootPath, entry.name);
if (entry.isDirectory()) {
await removePackagedSourceMaps(entryPath);
return;
}
if (entry.isFile() && entry.name.toLowerCase().endsWith(".map")) {
await fs.unlink(entryPath);
}
}),
);
};
const cleanupPackagedDevelopmentFilesHook = async ({ buildPath }) => {
await Promise.all([
stripPackagedScripts(buildPath),
removePackagedSourceMaps(buildPath),
]);
};
const buildMacSignConfig = () => {
if (!process.env.MAC_CODESIGN_IDENTITY) {
return undefined;
}
return {
identity: process.env.MAC_CODESIGN_IDENTITY,
hardenedRuntime: true,
optionsForFile: () => ({
hardenedRuntime: true,
}),
};
};
const buildMacNotarizeConfig = (macSignConfig) => {
if (!macSignConfig) {
return undefined;
}
if (process.env.MAC_NOTARIZE_KEYCHAIN_PROFILE) {
return {
keychainProfile: process.env.MAC_NOTARIZE_KEYCHAIN_PROFILE,
...(process.env.MAC_NOTARIZE_KEYCHAIN
? { keychain: process.env.MAC_NOTARIZE_KEYCHAIN }
: {}),
};
}
if (
process.env.APPLE_ID &&
process.env.APPLE_ID_PASSWORD &&
process.env.APPLE_TEAM_ID
) {
return {
appleId: process.env.APPLE_ID,
appleIdPassword: process.env.APPLE_ID_PASSWORD,
teamId: process.env.APPLE_TEAM_ID,
};
}
if (
process.env.APPLE_API_KEY &&
process.env.APPLE_API_KEY_ID &&
process.env.APPLE_API_ISSUER
) {
return {
appleApiKey: process.env.APPLE_API_KEY,
appleApiKeyId: process.env.APPLE_API_KEY_ID,
appleApiIssuer: process.env.APPLE_API_ISSUER,
};
}
return undefined;
};
module.exports = async () => {
const devServerPort = await findAvailablePort(
parsePort(process.env.WEBPACK_DEV_PORT, DEFAULT_DEV_SERVER_PORT),
);
const loggerPort = await findAvailablePort(
parsePort(process.env.WEBPACK_LOGGER_PORT, DEFAULT_LOGGER_PORT),
devServerPort,
);
const macSignConfig = buildMacSignConfig();
const macNotarizeConfig = buildMacNotarizeConfig(macSignConfig);
return {
packagerConfig: {
name: PRODUCT_NAME,
executableName: PRODUCT_NAME,
appBundleId: APP_BUNDLE_ID,
appCategoryType: APP_CATEGORY_TYPE,
appCopyright: `Copyright © ${new Date().getFullYear()} funkpopo`,
win32metadata: {
CompanyName: "funkpopo",
// Windows Task Manager uses FileDescription as the process display name.
FileDescription: PRODUCT_NAME,
OriginalFilename: `${PRODUCT_NAME}.exe`,
ProductName: PRODUCT_NAME,
InternalName: PRODUCT_NAME,
},
asar: true,
icon: "./src/renderer/assets/logo",
...(macSignConfig ? { osxSign: macSignConfig } : {}),
...(macNotarizeConfig ? { osxNotarize: macNotarizeConfig } : {}),
extraResource: [
path.join(
__dirname,
"native-services",
"bin",
`${process.platform}-${process.arch}`,
NATIVE_SERVICES_BASENAME,
),
],
afterPrune: [cleanupPackagedDevelopmentFilesHook],
afterComplete: [cleanupLocalesHook],
download: {
unsafelyDisableChecksums: false,
},
},
// No Node native modules to rebuild: native code lives in simpleshell-core.
rebuildConfig: {
onlyModules: [],
},
makers: [
{
name: "./scripts/makers/maker-nsis.js",
platforms: ["win32"],
config: {
projectRoot: __dirname,
appId: APP_BUNDLE_ID,
appName: PRODUCT_NAME,
executableName: PRODUCT_NAME,
outputDir: WINDOWS_INSTALLER_OUTPUT_DIR,
appIcon: WINDOWS_ICON_PATH,
licenseFile: LICENSE_FILE_PATH,
appCopyright: `Copyright (C) ${new Date().getFullYear()} funkpopo`,
},
},
{
name: "@electron-forge/maker-zip",
platforms: ["darwin"],
},
{
name: "@electron-forge/maker-deb",
config: {
options: {
name: PACKAGE_NAME,
productName: PRODUCT_NAME,
genericName: "SSH Terminal",
description: APP_DESCRIPTION,
productDescription: APP_DESCRIPTION,
section: "net",
priority: "optional",
maintainer: AUTHOR,
homepage: APP_HOMEPAGE,
depends: DEBIAN_CJK_FONT_DEPENDENCIES,
bin: PRODUCT_NAME,
icon: LINUX_ICON_PATH,
categories: ["Development", "Network", "Utility"],
},
},
},
{
name: "@electron-forge/maker-rpm",
config: {
options: {
name: PACKAGE_NAME,
productName: PRODUCT_NAME,
genericName: "SSH Terminal",
description: APP_DESCRIPTION,
productDescription: APP_DESCRIPTION,
license: "Apache-2.0",
group: "Applications/Internet",
homepage: APP_HOMEPAGE,
requires: RPM_CJK_FONT_DEPENDENCIES,
bin: PRODUCT_NAME,
icon: LINUX_ICON_PATH,
categories: ["Development", "Network", "Utility"],
},
},
},
],
plugins: [
new WindowsSafeWebpackPlugin({
mainConfig: "./webpack.main.config.js",
renderer: {
config: "./webpack.renderer.config.js",
entryPoints: [
{
html: "./src/renderer/index.html",
js: "./src/renderer/main.jsx",
name: "main_window",
preload: {
js: "./src/preload/index.js",
config: "./webpack.preload.config.js",
},
},
],
},
devContentSecurityPolicy:
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws://localhost:* ws://127.0.0.1:*; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; form-action 'none';",
port: devServerPort,
loggerPort,
}),
// Fuses are used to enable/disable various Electron functionality
// at package time, before code signing the application
new FusesPlugin({
version: FuseVersion.V1,
[FuseV1Options.RunAsNode]: false,
[FuseV1Options.EnableCookieEncryption]: true,
[FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,
[FuseV1Options.EnableNodeCliInspectArguments]: false,
[FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,
[FuseV1Options.OnlyLoadAppFromAsar]: true,
}),
],
};
};