Skip to content
This repository was archived by the owner on Oct 18, 2024. It is now read-only.

Commit 4d105bd

Browse files
authored
Cleanup the bootstrapping file to make it easier to interpret (#31)
* Commit changes after installing. * Update eslint and remove yarn. * Move processes and interval logic to be inside class. * Change null values back to undefined. * Consolidate event listeners. * Consolidate event listeners. * Add some utility functions. * Store the Electron API port inside of state, and extract booting of Electron API to separate method. * Extract configs and boot logic for scheduler to separate methods. * Extract methods for starting PHP app and websockets. * Move PHP app, queue worker, websockets, and scheduler to separate methods. * Move auto updater to before PHP logic. * Fix order of methods, and make killChildProcesses into a class method. * Commit dist file.
1 parent a0a1766 commit 4d105bd

File tree

11 files changed

+8105
-8778
lines changed

11 files changed

+8105
-8778
lines changed

dist/index.js

Lines changed: 135 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -11,137 +11,179 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
1111
var __importDefault = (this && this.__importDefault) || function (mod) {
1212
return (mod && mod.__esModule) ? mod : { "default": mod };
1313
};
14+
const electron_1 = require("electron");
1415
const electron_updater_1 = require("electron-updater");
1516
const state_1 = __importDefault(require("./server/state"));
1617
const utils_1 = require("@electron-toolkit/utils");
1718
const server_1 = require("./server");
1819
const utils_2 = require("./server/utils");
19-
const electron_1 = require("electron");
2020
const path_1 = require("path");
2121
const ps_node_1 = __importDefault(require("ps-node"));
22-
let phpProcesses = [];
23-
let websocketProcess;
24-
let schedulerInterval;
25-
const killChildProcesses = () => {
26-
let processes = [
27-
...phpProcesses,
28-
websocketProcess,
29-
].filter((p) => p !== undefined);
30-
processes.forEach((process) => {
31-
try {
32-
ps_node_1.default.kill(process.pid);
33-
}
34-
catch (err) {
35-
console.error(err);
36-
}
37-
});
38-
};
3922
class NativePHP {
23+
constructor() {
24+
this.processes = [];
25+
this.schedulerInterval = undefined;
26+
}
4027
bootstrap(app, icon, phpBinary, cert) {
41-
require('@electron/remote/main').initialize();
28+
require("@electron/remote/main").initialize();
4229
state_1.default.icon = icon;
4330
state_1.default.php = phpBinary;
4431
state_1.default.caCert = cert;
4532
this.bootstrapApp(app);
4633
this.addEventListeners(app);
47-
this.addTerminateListeners(app);
4834
}
4935
addEventListeners(app) {
50-
app.on('open-url', (event, url) => {
51-
(0, utils_2.notifyLaravel)('events', {
52-
event: '\\Native\\Laravel\\Events\\App\\OpenedFromURL',
53-
payload: [url]
36+
app.on("open-url", (event, url) => {
37+
(0, utils_2.notifyLaravel)("events", {
38+
event: "\\Native\\Laravel\\Events\\App\\OpenedFromURL",
39+
payload: [url],
5440
});
5541
});
56-
app.on('open-file', (event, path) => {
57-
(0, utils_2.notifyLaravel)('events', {
58-
event: '\\Native\\Laravel\\Events\\App\\OpenFile',
59-
payload: [path]
42+
app.on("open-file", (event, path) => {
43+
(0, utils_2.notifyLaravel)("events", {
44+
event: "\\Native\\Laravel\\Events\\App\\OpenFile",
45+
payload: [path],
6046
});
6147
});
62-
app.on('window-all-closed', () => {
63-
if (process.platform !== 'darwin') {
48+
app.on("window-all-closed", () => {
49+
if (process.platform !== "darwin") {
6450
app.quit();
6551
}
6652
});
67-
}
68-
addTerminateListeners(app) {
69-
app.on('before-quit', (e) => {
70-
if (schedulerInterval) {
71-
clearInterval(schedulerInterval);
53+
app.on("before-quit", () => {
54+
if (this.schedulerInterval) {
55+
clearInterval(this.schedulerInterval);
56+
}
57+
this.killChildProcesses();
58+
});
59+
app.on("browser-window-created", (_, window) => {
60+
utils_1.optimizer.watchWindowShortcuts(window);
61+
});
62+
app.on("activate", function (event, hasVisibleWindows) {
63+
if (!hasVisibleWindows) {
64+
(0, utils_2.notifyLaravel)("booted");
7265
}
73-
killChildProcesses();
66+
event.preventDefault();
7467
});
7568
}
7669
bootstrapApp(app) {
77-
let nativePHPConfig = {};
78-
(0, server_1.retrieveNativePHPConfig)().then((result) => {
70+
return __awaiter(this, void 0, void 0, function* () {
71+
yield app.whenReady();
72+
const config = yield this.loadConfig();
73+
this.setDockIcon();
74+
this.setAppUserModelId(config);
75+
this.setDeepLinkHandler(config);
76+
this.startAutoUpdater(config);
77+
yield this.startElectronApi();
78+
state_1.default.phpIni = yield this.loadPhpIni();
79+
yield this.startPhpApp();
80+
yield this.startQueueWorker();
81+
yield this.startWebsockets();
82+
this.startScheduler();
83+
yield (0, utils_2.notifyLaravel)("booted");
84+
});
85+
}
86+
loadConfig() {
87+
return __awaiter(this, void 0, void 0, function* () {
88+
let config = {};
7989
try {
80-
nativePHPConfig = JSON.parse(result.stdout);
90+
const result = yield (0, server_1.retrieveNativePHPConfig)();
91+
config = JSON.parse(result.stdout);
8192
}
82-
catch (e) {
83-
console.error(e);
93+
catch (error) {
94+
console.error(error);
8495
}
85-
}).catch((err) => {
86-
console.error(err);
87-
}).finally(() => {
88-
this.setupApp(nativePHPConfig);
96+
return config;
8997
});
9098
}
91-
setupApp(nativePHPConfig) {
92-
electron_1.app.whenReady().then(() => __awaiter(this, void 0, void 0, function* () {
93-
var _a;
94-
if (process.platform === 'darwin' && process.env.NODE_ENV === 'development') {
95-
electron_1.app.dock.setIcon(state_1.default.icon);
99+
setDockIcon() {
100+
if (process.platform === "darwin" &&
101+
process.env.NODE_ENV === "development") {
102+
electron_1.app.dock.setIcon(state_1.default.icon);
103+
}
104+
}
105+
setAppUserModelId(config) {
106+
utils_1.electronApp.setAppUserModelId(config === null || config === void 0 ? void 0 : config.app_id);
107+
}
108+
setDeepLinkHandler(config) {
109+
const deepLinkProtocol = config === null || config === void 0 ? void 0 : config.deeplink_scheme;
110+
if (deepLinkProtocol) {
111+
if (process.defaultApp) {
112+
if (process.argv.length >= 2) {
113+
electron_1.app.setAsDefaultProtocolClient(deepLinkProtocol, process.execPath, [
114+
(0, path_1.resolve)(process.argv[1]),
115+
]);
116+
}
96117
}
97-
electron_1.app.on('browser-window-created', (_, window) => {
98-
utils_1.optimizer.watchWindowShortcuts(window);
99-
});
100-
let phpIniSettings = {};
118+
else {
119+
electron_1.app.setAsDefaultProtocolClient(deepLinkProtocol);
120+
}
121+
}
122+
}
123+
startAutoUpdater(config) {
124+
var _a;
125+
if (((_a = config === null || config === void 0 ? void 0 : config.updater) === null || _a === void 0 ? void 0 : _a.enabled) === true) {
126+
electron_updater_1.autoUpdater.checkForUpdatesAndNotify();
127+
}
128+
}
129+
startElectronApi() {
130+
return __awaiter(this, void 0, void 0, function* () {
131+
const electronApi = yield (0, server_1.startAPI)();
132+
state_1.default.electronApiPort = electronApi.port;
133+
console.log("Electron API server started on port", electronApi.port);
134+
});
135+
}
136+
loadPhpIni() {
137+
return __awaiter(this, void 0, void 0, function* () {
138+
let config = {};
101139
try {
102-
let { stdout } = yield (0, server_1.retrievePhpIniSettings)();
103-
phpIniSettings = JSON.parse(stdout);
140+
const result = yield (0, server_1.retrievePhpIniSettings)();
141+
config = JSON.parse(result.stdout);
104142
}
105-
catch (e) {
106-
console.error(e);
143+
catch (error) {
144+
console.error(error);
107145
}
108-
utils_1.electronApp.setAppUserModelId(nativePHPConfig === null || nativePHPConfig === void 0 ? void 0 : nativePHPConfig.app_id);
109-
const deepLinkProtocol = nativePHPConfig === null || nativePHPConfig === void 0 ? void 0 : nativePHPConfig.deeplink_scheme;
110-
if (deepLinkProtocol) {
111-
if (process.defaultApp) {
112-
if (process.argv.length >= 2) {
113-
electron_1.app.setAsDefaultProtocolClient(deepLinkProtocol, process.execPath, [(0, path_1.resolve)(process.argv[1])]);
114-
}
115-
}
116-
else {
117-
electron_1.app.setAsDefaultProtocolClient(deepLinkProtocol);
118-
}
146+
return config;
147+
});
148+
}
149+
startPhpApp() {
150+
return __awaiter(this, void 0, void 0, function* () {
151+
this.processes.push(yield (0, server_1.startPhpApp)());
152+
});
153+
}
154+
startQueueWorker() {
155+
return __awaiter(this, void 0, void 0, function* () {
156+
this.processes.push(yield (0, server_1.startQueue)());
157+
});
158+
}
159+
startWebsockets() {
160+
return __awaiter(this, void 0, void 0, function* () {
161+
this.processes.push(yield (0, server_1.startWebsockets)());
162+
});
163+
}
164+
startScheduler() {
165+
const now = new Date();
166+
const delay = (60 - now.getSeconds()) * 1000 + (1000 - now.getMilliseconds());
167+
setTimeout(() => {
168+
console.log("Running scheduler...");
169+
(0, server_1.runScheduler)();
170+
this.schedulerInterval = setInterval(() => {
171+
console.log("Running scheduler...");
172+
(0, server_1.runScheduler)();
173+
}, 60 * 1000);
174+
}, delay);
175+
}
176+
killChildProcesses() {
177+
this.processes
178+
.filter((p) => p !== undefined)
179+
.forEach((process) => {
180+
try {
181+
ps_node_1.default.kill(process.pid);
119182
}
120-
const apiPort = yield (0, server_1.startAPI)();
121-
console.log('API server started on port', apiPort.port);
122-
phpProcesses = yield (0, server_1.servePhpApp)(apiPort.port, phpIniSettings);
123-
websocketProcess = (0, server_1.serveWebsockets)();
124-
yield (0, utils_2.notifyLaravel)('booted');
125-
if (((_a = nativePHPConfig === null || nativePHPConfig === void 0 ? void 0 : nativePHPConfig.updater) === null || _a === void 0 ? void 0 : _a.enabled) === true) {
126-
electron_updater_1.autoUpdater.checkForUpdatesAndNotify();
183+
catch (err) {
184+
console.error(err);
127185
}
128-
let now = new Date();
129-
let delay = (60 - now.getSeconds()) * 1000 + (1000 - now.getMilliseconds());
130-
setTimeout(() => {
131-
console.log("Running scheduler...");
132-
(0, server_1.runScheduler)(apiPort.port, phpIniSettings);
133-
schedulerInterval = setInterval(() => {
134-
console.log("Running scheduler...");
135-
(0, server_1.runScheduler)(apiPort.port, phpIniSettings);
136-
}, 60 * 1000);
137-
}, delay);
138-
electron_1.app.on('activate', function (event, hasVisibleWindows) {
139-
if (!hasVisibleWindows) {
140-
(0, utils_2.notifyLaravel)('booted');
141-
}
142-
event.preventDefault();
143-
});
144-
}));
186+
});
145187
}
146188
}
147189
module.exports = new NativePHP();

dist/server/index.js

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,37 +12,37 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
1212
return (mod && mod.__esModule) ? mod : { "default": mod };
1313
};
1414
Object.defineProperty(exports, "__esModule", { value: true });
15-
exports.retrievePhpIniSettings = exports.retrieveNativePHPConfig = exports.serveWebsockets = exports.startAPI = exports.startQueue = exports.runScheduler = exports.servePhpApp = void 0;
15+
exports.retrievePhpIniSettings = exports.retrieveNativePHPConfig = exports.startWebsockets = exports.startAPI = exports.runScheduler = exports.startQueue = exports.startPhpApp = void 0;
1616
const websockets_1 = __importDefault(require("./websockets"));
17-
exports.serveWebsockets = websockets_1.default;
17+
exports.startWebsockets = websockets_1.default;
1818
const api_1 = __importDefault(require("./api"));
1919
const php_1 = require("./php");
2020
Object.defineProperty(exports, "retrieveNativePHPConfig", { enumerable: true, get: function () { return php_1.retrieveNativePHPConfig; } });
2121
Object.defineProperty(exports, "retrievePhpIniSettings", { enumerable: true, get: function () { return php_1.retrievePhpIniSettings; } });
2222
const utils_1 = require("./utils");
2323
const state_1 = __importDefault(require("./state"));
24-
function servePhpApp(apiPort, phpIniSettings) {
24+
function startPhpApp() {
2525
return __awaiter(this, void 0, void 0, function* () {
26-
const processes = [];
27-
const result = yield (0, php_1.serveApp)(state_1.default.randomSecret, apiPort, phpIniSettings);
28-
processes.push(result.process);
29-
processes.push((0, php_1.startQueueWorker)(state_1.default.randomSecret, apiPort, phpIniSettings));
26+
const result = yield (0, php_1.serveApp)(state_1.default.randomSecret, state_1.default.electronApiPort, state_1.default.phpIni);
3027
state_1.default.phpPort = result.port;
3128
yield (0, utils_1.appendCookie)();
32-
return processes;
29+
return result.process;
3330
});
3431
}
35-
exports.servePhpApp = servePhpApp;
36-
function runScheduler(apiPort, phpIniSettings) {
37-
(0, php_1.startScheduler)(state_1.default.randomSecret, apiPort, phpIniSettings);
38-
}
39-
exports.runScheduler = runScheduler;
40-
function startQueue(apiPort, phpIniSettings) {
32+
exports.startPhpApp = startPhpApp;
33+
function startQueue() {
4134
if (!process.env.NATIVE_PHP_SKIP_QUEUE) {
42-
return (0, php_1.startQueueWorker)(state_1.default.randomSecret, apiPort, phpIniSettings);
35+
return (0, php_1.startQueueWorker)(state_1.default.randomSecret, state_1.default.electronApiPort, state_1.default.phpIni);
36+
}
37+
else {
38+
return undefined;
4339
}
4440
}
4541
exports.startQueue = startQueue;
42+
function runScheduler() {
43+
(0, php_1.startScheduler)(state_1.default.randomSecret, state_1.default.electronApiPort, state_1.default.phpIni);
44+
}
45+
exports.runScheduler = runScheduler;
4646
function startAPI() {
4747
return (0, api_1.default)(state_1.default.randomSecret);
4848
}

dist/server/state.js

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,37 +7,38 @@ const electron_store_1 = __importDefault(require("electron-store"));
77
const utils_1 = require("./utils");
88
const settingsStore = new electron_store_1.default();
99
settingsStore.onDidAnyChange((newValue, oldValue) => {
10-
const changedKey = Object.keys(newValue).find(key => newValue[key] !== oldValue[key]);
10+
const changedKey = Object.keys(newValue).find((key) => newValue[key] !== oldValue[key]);
1111
if (changedKey) {
12-
(0, utils_1.notifyLaravel)('events', {
13-
event: 'Native\\Laravel\\Events\\Settings\\SettingChanged',
12+
(0, utils_1.notifyLaravel)("events", {
13+
event: "Native\\Laravel\\Events\\Settings\\SettingChanged",
1414
payload: {
1515
key: changedKey,
16-
value: newValue[changedKey] || null
17-
}
16+
value: newValue[changedKey] || null,
17+
},
1818
});
1919
}
2020
});
2121
function generateRandomString(length) {
22-
let result = '';
23-
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
22+
let result = "";
23+
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
2424
const charactersLength = characters.length;
2525
for (let i = 0; i < length; i += 1) {
26-
result += characters.charAt(Math.floor(Math.random() *
27-
charactersLength));
26+
result += characters.charAt(Math.floor(Math.random() * charactersLength));
2827
}
2928
return result;
3029
}
3130
exports.default = {
31+
electronApiPort: null,
3232
activeMenuBar: null,
3333
php: null,
3434
phpPort: null,
35+
phpIni: null,
3536
caCert: null,
3637
icon: null,
3738
store: settingsStore,
3839
randomSecret: generateRandomString(32),
3940
windows: {},
4041
findWindow(id) {
4142
return this.windows[id] || null;
42-
}
43+
},
4344
};

dist/server/websockets.js

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,15 @@ const path_1 = require("path");
88
const child_process_1 = require("child_process");
99
const php_1 = require("./php");
1010
const state_1 = __importDefault(require("./state"));
11-
function serveWebsockets() {
12-
if (!(0, fs_1.existsSync)((0, path_1.join)((0, php_1.getAppPath)(), 'vendor', 'beyondcode', 'laravel-websockets'))) {
11+
function startWebsockets() {
12+
if (!(0, fs_1.existsSync)((0, path_1.join)((0, php_1.getAppPath)(), "vendor", "beyondcode", "laravel-websockets"))) {
1313
return;
1414
}
1515
const phpServer = (0, child_process_1.spawn)(state_1.default.php, ["artisan", "websockets:serve"], {
16-
cwd: (0, php_1.getAppPath)()
17-
});
18-
phpServer.stdout.on("data", (data) => {
19-
});
20-
phpServer.stderr.on("data", (data) => {
16+
cwd: (0, php_1.getAppPath)(),
2117
});
18+
phpServer.stdout.on("data", (data) => { });
19+
phpServer.stderr.on("data", (data) => { });
2220
return phpServer;
2321
}
24-
exports.default = serveWebsockets;
22+
exports.default = startWebsockets;

0 commit comments

Comments
 (0)