-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathphp.ts
More file actions
460 lines (377 loc) · 14.2 KB
/
php.ts
File metadata and controls
460 lines (377 loc) · 14.2 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
import {mkdirSync, statSync, writeFileSync, existsSync} from 'fs'
import fs_extra from 'fs-extra';
const {copySync, mkdirpSync} = fs_extra;
import Store from 'electron-store'
import {promisify} from 'util'
import {join} from 'path'
import {app} from 'electron'
import {execFile, spawn, spawnSync} from 'child_process'
import {createServer} from 'net'
import state from "./state.js";
import getPort, {portNumbers} from 'get-port';
import {ProcessResult} from "./ProcessResult.js";
// TODO: maybe in dev, don't go to the userData folder and stay in the Laravel app folder
const storagePath = join(app.getPath('userData'), 'storage')
const databasePath = join(app.getPath('userData'), 'database')
const databaseFile = join(databasePath, 'database.sqlite')
const bootstrapCache = join(app.getPath('userData'), 'bootstrap', 'cache')
const argumentEnv = getArgumentEnv();
const appPath = getAppPath();
mkdirpSync(bootstrapCache);
mkdirpSync(join(storagePath, 'logs'));
mkdirpSync(join(storagePath, 'framework', 'cache'));
mkdirpSync(join(storagePath, 'framework', 'sessions'));
mkdirpSync(join(storagePath, 'framework', 'views'));
mkdirpSync(join(storagePath, 'framework', 'testing'));
function runningSecureBuild() {
return existsSync(join(appPath, 'build', '__nativephp_app_bundle'))
&& process.env.NODE_ENV !== 'development';
}
function shouldMigrateDatabase(store) {
return store.get('migrated_version') !== app.getVersion()
&& process.env.NODE_ENV !== 'development';
}
function shouldOptimize(store) {
/*
* For some weird reason,
* the cached config is not picked up on subsequent launches,
* so we'll just rebuilt it every time for now
*/
return process.env.NODE_ENV !== 'development';
// return runningSecureBuild();
// return runningSecureBuild() && store.get('optimized_version') !== app.getVersion();
}
async function getPhpPort() {
// Try get-port first (fast path)
const suggestedPort = await getPort({
host: '127.0.0.1',
port: portNumbers(8100, 9000)
});
// Validate that we can actually bind to this port
if (await canBindToPort(suggestedPort)) {
return suggestedPort;
}
// If get-port gave us a bad port, manually search starting from suggestedPort + 1
console.warn(`Port ${suggestedPort} is not bindable, manually searching...`);
for (let port = suggestedPort + 1; port < 9000; port++) {
if (await canBindToPort(port)) {
return port;
}
}
throw new Error('Could not find an available port in range 8100-9000');
}
function canBindToPort(port: number): Promise<boolean> {
return new Promise((resolve) => {
const server = createServer();
server.listen(port, '127.0.0.1', () => {
server.close(() => resolve(true));
});
server.on('error', () => {
resolve(false);
});
});
}
async function retrievePhpIniSettings() {
const env = getDefaultEnvironmentVariables() as any;
const phpOptions = {
cwd: appPath,
env
};
let command = ['artisan', 'native:php-ini'];
if (runningSecureBuild()) {
command.unshift(join(appPath, 'build', '__nativephp_app_bundle'));
}
return await promisify(execFile)(state.php, command, phpOptions);
}
async function retrieveNativePHPConfig() {
const env = getDefaultEnvironmentVariables() as any;
const phpOptions = {
cwd: appPath,
env
};
let command = ['artisan', 'native:config'];
if (runningSecureBuild()) {
command.unshift(join(appPath, 'build', '__nativephp_app_bundle'));
}
return await promisify(execFile)(state.php, command, phpOptions);
}
function callPhp(args, options, phpIniSettings = {}) {
if (args[0] === 'artisan' && runningSecureBuild()) {
args.unshift(join(appPath, 'build', '__nativephp_app_bundle'));
}
let iniSettings = Object.assign(getDefaultPhpIniSettings(), phpIniSettings);
Object.keys(iniSettings).forEach(key => {
args.unshift('-d', `${key}=${iniSettings[key]}`);
});
if (parseInt(process.env.SHELL_VERBOSITY) > 0) {
console.log('Calling PHP', state.php, args);
}
return spawn(
state.php,
args,
{
cwd: options.cwd,
env: {
...process.env,
...options.env
},
}
);
}
function callPhpSync(args, options, phpIniSettings = {}) {
if (args[0] === 'artisan' && runningSecureBuild()) {
args.unshift(join(appPath, 'build', '__nativephp_app_bundle'));
}
let iniSettings = Object.assign(getDefaultPhpIniSettings(), phpIniSettings);
Object.keys(iniSettings).forEach(key => {
args.unshift('-d', `${key}=${iniSettings[key]}`);
});
if (parseInt(process.env.SHELL_VERBOSITY) > 0) {
console.log('Calling PHP', state.php, args);
}
return spawnSync(
state.php,
args,
{
cwd: options.cwd,
env: {
...process.env,
...options.env
}
}
);
}
function getArgumentEnv() {
const envArgs = process.argv.filter(arg => arg.startsWith('--env.'));
const env: {
TESTING?: number,
APP_PATH?: string
} = {};
envArgs.forEach(arg => {
const [key, value] = arg.slice(6).split('=');
env[key] = value;
});
return env;
}
function getAppPath() {
let appPath = join(import.meta.dirname, '../../resources/app/').replace('app.asar', 'app.asar.unpacked')
if (process.env.NODE_ENV === 'development' || argumentEnv.TESTING == 1) {
appPath = process.env.APP_PATH || argumentEnv.APP_PATH;
}
return appPath;
}
function ensureAppFoldersAreAvailable() {
// if (!runningSecureBuild()) {
console.log('Copying storage folder...');
console.log('Storage path:', storagePath);
if (!existsSync(storagePath) || process.env.NODE_ENV === 'development') {
console.log("App path:", appPath);
copySync(join(appPath, 'storage'), storagePath)
}
// }
mkdirSync(databasePath, {recursive: true})
// Create a database file if it doesn't exist
try {
statSync(databaseFile)
} catch (error) {
writeFileSync(databaseFile, '')
}
}
function startScheduler(secret, apiPort, phpIniSettings = {}) {
const env = getDefaultEnvironmentVariables(secret, apiPort);
const phpOptions = {
cwd: appPath,
env
};
return callPhp(['artisan', 'schedule:run'], phpOptions, phpIniSettings);
}
function getPath(name: string) {
try {
// @ts-ignore
return app.getPath(name);
} catch (error) {
return '';
}
}
// Define an interface for the environment variables
interface EnvironmentVariables {
APP_ENV: string;
APP_DEBUG: string;
LARAVEL_STORAGE_PATH: string;
NATIVEPHP_STORAGE_PATH: string;
NATIVEPHP_DATABASE_PATH: string;
NATIVEPHP_API_URL?: string;
NATIVEPHP_RUNNING: string;
NATIVEPHP_SECRET?: string;
NATIVEPHP_USER_HOME_PATH: string;
NATIVEPHP_APP_DATA_PATH: string;
NATIVEPHP_USER_DATA_PATH: string;
NATIVEPHP_DESKTOP_PATH: string;
NATIVEPHP_DOCUMENTS_PATH: string;
NATIVEPHP_DOWNLOADS_PATH: string;
NATIVEPHP_MUSIC_PATH: string;
NATIVEPHP_PICTURES_PATH: string;
NATIVEPHP_VIDEOS_PATH: string;
NATIVEPHP_RECENT_PATH: string;
NATIVEPHP_EXTRAS_PATH: string;
// Cache variables
APP_SERVICES_CACHE?: string;
APP_PACKAGES_CACHE?: string;
APP_CONFIG_CACHE?: string;
APP_ROUTES_CACHE?: string;
APP_EVENTS_CACHE?: string;
VIEW_COMPILED_PATH?: string;
}
function getDefaultEnvironmentVariables(secret?: string, apiPort?: number): EnvironmentVariables {
// Base variables with string values (no null values)
let variables: EnvironmentVariables = {
APP_ENV: process.env.NODE_ENV === 'development' ? 'local' : 'production',
APP_DEBUG: process.env.NODE_ENV === 'development' ? 'true' : 'false',
LARAVEL_STORAGE_PATH: storagePath,
NATIVEPHP_RUNNING: 'true',
NATIVEPHP_STORAGE_PATH: storagePath,
NATIVEPHP_DATABASE_PATH: databaseFile,
NATIVEPHP_USER_HOME_PATH: getPath('home'),
NATIVEPHP_APP_DATA_PATH: getPath('appData'),
NATIVEPHP_USER_DATA_PATH: getPath('userData'),
NATIVEPHP_DESKTOP_PATH: getPath('desktop'),
NATIVEPHP_DOCUMENTS_PATH: getPath('documents'),
NATIVEPHP_DOWNLOADS_PATH: getPath('downloads'),
NATIVEPHP_MUSIC_PATH: getPath('music'),
NATIVEPHP_PICTURES_PATH: getPath('pictures'),
NATIVEPHP_VIDEOS_PATH: getPath('videos'),
NATIVEPHP_RECENT_PATH: getPath('recent'),
NATIVEPHP_EXTRAS_PATH: app.isPackaged
? join(process.resourcesPath, '..', 'extras')
: join(process.env.APP_PATH, 'extras'),
};
// Only if the server has already started
if (secret && apiPort) {
variables.NATIVEPHP_API_URL = `http://localhost:${apiPort}/api/`;
variables.NATIVEPHP_SECRET = secret;
}
// Only add cache paths if in production mode
if (runningSecureBuild()) {
variables.APP_SERVICES_CACHE = join(bootstrapCache, 'services.php'); // Should be present and writable
variables.APP_PACKAGES_CACHE = join(bootstrapCache, 'packages.php'); // Should be present and writable
variables.APP_CONFIG_CACHE = join(bootstrapCache, 'config.php');
variables.APP_ROUTES_CACHE = join(bootstrapCache, 'routes-v7.php');
variables.APP_EVENTS_CACHE = join(bootstrapCache, 'events.php');
// variables.VIEW_COMPILED_PATH; // TODO: keep those in the phar file if we can.
}
return variables;
}
function getDefaultPhpIniSettings() {
return {
'memory_limit': '512M',
'curl.cainfo': state.caCert,
'openssl.cafile': state.caCert
}
}
function serveApp(secret, apiPort, phpIniSettings): Promise<ProcessResult> {
return new Promise(async (resolve, reject) => {
const appPath = getAppPath();
console.log('Starting PHP server...', `${state.php} artisan serve`, appPath, phpIniSettings)
ensureAppFoldersAreAvailable();
console.log('Making sure app folders are available')
const env = getDefaultEnvironmentVariables(secret, apiPort);
const phpOptions = {
cwd: appPath,
env
};
const store = new Store({
name: 'nativephp', // So it doesn't conflict with settings of the app
});
// Cache the project
if (shouldOptimize(store)) {
console.log('Caching view and routes...');
let result = callPhpSync(['artisan', 'optimize'], phpOptions, phpIniSettings);
if (result.status !== 0) {
console.error('Failed to cache view and routes:', result.stderr.toString());
} else {
store.set('optimized_version', app.getVersion())
}
}
// Migrate the database
if (shouldMigrateDatabase(store)) {
console.log('Migrating database...');
if(parseInt(process.env.SHELL_VERBOSITY) > 0) {
console.log('Database path:', databaseFile);
}
let result = callPhpSync(['artisan', 'migrate', '--force'], phpOptions, phpIniSettings);
if (result.status !== 0) {
console.error('Failed to migrate database:', result.stderr.toString());
} else {
store.set('migrated_version', app.getVersion())
}
}
if (process.env.NODE_ENV === 'development') {
console.log('Skipping Database migration while in development.')
console.log('You may migrate manually by running: php artisan native:migrate')
}
let serverPath: string;
let cwd: string;
if (runningSecureBuild()) {
serverPath = join(appPath, 'build', '__nativephp_app_bundle');
} else {
console.log('* * * Running from source * * *');
serverPath = join(appPath, 'vendor', 'laravel', 'framework', 'src', 'Illuminate', 'Foundation', 'resources', 'server.php');
cwd = join(appPath, 'public');
}
console.log('Starting PHP server...');
const phpPort = await getPhpPort();
const phpServer = callPhp(['-S', `127.0.0.1:${phpPort}`, serverPath], {
cwd: cwd,
env
}, phpIniSettings)
const portRegex = /Development Server \(.*:([0-9]+)\) started/gm
// Show urls called
phpServer.stdout.on('data', (data) => {
// [Tue Jan 14 19:51:00 2025] 127.0.0.1:52779 [POST] URI: /_native/api/events
if (parseInt(process.env.SHELL_VERBOSITY) > 0) {
console.log(data.toString().trim());
}
})
// Show PHP errors and indicate which port the server is running on
phpServer.stderr.on('data', (data) => {
const error = data.toString();
const match = portRegex.exec(data.toString());
if (match) {
const port = parseInt(match[1]);
console.log("PHP Server started on port: ", port);
resolve({
port,
process: phpServer,
});
} else {
if (error.includes('[NATIVE_EXCEPTION]:')) {
let logFile = join(storagePath, 'logs');
console.log();
console.error('Error in PHP:');
console.error(' ' + error.split('[NATIVE_EXCEPTION]:')[1].trim());
console.log('Please check your log files:');
console.log(' ' + logFile);
console.log();
}
}
});
// Log when any error occurs (not started, not killed, couldn't send message, etc)
phpServer.on('error', (error) => {
reject(error)
});
// Log when the PHP server exits
phpServer.on('close', (code) => {
console.log(`PHP server exited with code ${code}`);
});
})
}
export {
startScheduler,
serveApp,
getAppPath,
retrieveNativePHPConfig,
retrievePhpIniSettings,
getDefaultEnvironmentVariables,
getDefaultPhpIniSettings,
runningSecureBuild
}