-
Notifications
You must be signed in to change notification settings - Fork 272
/
universal-php.ts
586 lines (534 loc) · 14.3 KB
/
universal-php.ts
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
import { Remote } from 'comlink';
import { PHPResponse } from './php-response';
/**
* Represents an event related to the PHP filesystem.
*/
export interface PHPRequestEndEvent {
type: 'request.end';
}
/**
* Represents an event related to the PHP instance.
* This is intentionally not an extension of CustomEvent
* to make it isomorphic between different JavaScript runtimes.
*/
export type PHPEvent = PHPRequestEndEvent;
/**
* A callback function that handles PHP events.
*/
export type PHPEventListener = (event: PHPEvent) => void;
/**
* Handles HTTP requests using PHP runtime as a backend.
*
* @public
* @example Use PHPRequestHandler implicitly with a new PHP instance:
* ```js
* import { PHP } from '@php-wasm/web';
*
* const php = await PHP.load( '7.4', {
* requestHandler: {
* // PHP FS path to serve the files from:
* documentRoot: '/www',
*
* // Used to populate $_SERVER['SERVER_NAME'] etc.:
* absoluteUrl: 'http://127.0.0.1'
* }
* } );
*
* php.mkdirTree('/www');
* php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
*
* const response = await php.request({ path: '/index.php' });
* console.log(response.text);
* // "Hi from PHP!"
* ```
*
* @example Explicitly create a PHPRequestHandler instance and run a PHP script:
* ```js
* import {
* loadPHPRuntime,
* PHP,
* PHPRequestHandler,
* getPHPLoaderModule,
* } from '@php-wasm/web';
*
* const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
* const php = new PHP( runtime );
*
* php.mkdirTree('/www');
* php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
*
* const server = new PHPRequestHandler(php, {
* // PHP FS path to serve the files from:
* documentRoot: '/www',
*
* // Used to populate $_SERVER['SERVER_NAME'] etc.:
* absoluteUrl: 'http://127.0.0.1'
* });
*
* const response = server.request({ path: '/index.php' });
* console.log(response.text);
* // "Hi from PHP!"
* ```
*/
export interface RequestHandler {
/**
* Serves the request – either by serving a static file, or by
* dispatching it to the PHP runtime.
*
* The request() method mode behaves like a web server and only works if
* the PHP was initialized with a `requestHandler` option (which the online version
* of WordPress Playground does by default).
*
* In the request mode, you pass an object containing the request information
* (method, headers, body, etc.) and the path to the PHP file to run:
*
* ```ts
* const php = PHP.load('7.4', {
* requestHandler: {
* documentRoot: "/www"
* }
* })
* php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
* const result = await php.request({
* method: "GET",
* headers: {
* "Content-Type": "text/plain"
* },
* body: "Hello world!",
* path: "/www/index.php"
* });
* // result.text === "Hello world!"
* ```
*
* The `request()` method cannot be used in conjunction with `cli()`.
*
* @example
* ```js
* const output = await php.request({
* method: 'GET',
* url: '/index.php',
* headers: {
* 'X-foo': 'bar',
* },
* formData: {
* foo: 'bar',
* },
* });
* console.log(output.stdout); // "Hello world!"
* ```
*
* @param request - PHP Request data.
*/
request(request: PHPRequest, maxRedirects?: number): Promise<PHPResponse>;
/**
* Converts a path to an absolute URL based at the PHPRequestHandler
* root.
*
* @param path The server path to convert to an absolute URL.
* @returns The absolute URL.
*/
pathToInternalUrl(path: string): string;
/**
* Converts an absolute URL based at the PHPRequestHandler to a relative path
* without the server pathname and scope.
*
* @param internalUrl An absolute URL based at the PHPRequestHandler root.
* @returns The relative path.
*/
internalUrlToPath(internalUrl: string): string;
/**
* The absolute URL of this PHPRequestHandler instance.
*/
absoluteUrl: string;
/**
* The directory in the PHP filesystem where the server will look
* for the files to serve. Default: `/var/www`.
*/
documentRoot: string;
}
export interface IsomorphicLocalPHP extends RequestHandler {
/**
* Defines a constant in the PHP runtime.
* @param key - The name of the constant.
* @param value - The value of the constant.
*/
defineConstant(key: string, value: string | number | null): void;
/**
* Adds an event listener for a PHP event.
* @param eventType - The type of event to listen for.
* @param listener - The listener function to be called when the event is triggered.
*/
addEventListener(
eventType: PHPEvent['type'],
listener: PHPEventListener
): void;
/**
* Removes an event listener for a PHP event.
* @param eventType - The type of event to remove the listener from.
* @param listener - The listener function to be removed.
*/
removeEventListener(
eventType: PHPEvent['type'],
listener: PHPEventListener
): void;
/**
* Sets the path to the php.ini file to use for the PHP instance.
*
* @param path - The path to the php.ini file.
*/
setPhpIniPath(path: string): void;
/**
* Sets a value for a specific key in the php.ini file for the PHP instance.
*
* @param key - The key to set the value for.
* @param value - The value to set for the key.
*/
setPhpIniEntry(key: string, value: string): void;
/**
* Recursively creates a directory with the given path in the PHP filesystem.
* For example, if the path is `/root/php/data`, and `/root` already exists,
* it will create the directories `/root/php` and `/root/php/data`.
*
* @param path - The directory path to create.
*/
mkdir(path: string): void;
/**
* @deprecated Use mkdir instead.
*/
mkdirTree(path: string): void;
/**
* Reads a file from the PHP filesystem and returns it as a string.
*
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
* @param path - The file path to read.
* @returns The file contents.
*/
readFileAsText(path: string): string;
/**
* Reads a file from the PHP filesystem and returns it as an array buffer.
*
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
* @param path - The file path to read.
* @returns The file contents.
*/
readFileAsBuffer(path: string): Uint8Array;
/**
* Overwrites data in a file in the PHP filesystem.
* Creates a new file if one doesn't exist yet.
*
* @param path - The file path to write to.
* @param data - The data to write to the file.
*/
writeFile(path: string, data: string | Uint8Array): void;
/**
* Removes a file from the PHP filesystem.
*
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
* @param path - The file path to remove.
*/
unlink(path: string): void;
/**
* Moves a file or directory in the PHP filesystem to a
* new location.
*
* @param oldPath The path to rename.
* @param newPath The new path.
*/
mv(oldPath: string, newPath: string): void;
/**
* Copies a file or directory in the PHP filesystem to a
* new location. The target directory's parent must be a
* valid location in the filesystem prior to copying.
*
* If the target path is a file that already exists,
* it will be overwritten.
*
* If the target path is a directory that already exists,
* the file or directory will be copied into it.
*
* If the target path's parent directory does not exist,
* an error will be thrown.
*
* @param oldPath The file or directory to be copied.
* @param newPath The new, full path to copy the file or directory to.
*/
cp(oldPath: string, newPath: string, options?: CpOptions): void;
/**
* Removes a directory from the PHP filesystem.
*
* @param path The directory path to remove.
* @param options Options for the removal.
*/
rmdir(path: string, options?: RmDirOptions): void;
/**
* Lists the files and directories in the given directory.
*
* @param path - The directory path to list.
* @param options - Options for the listing.
* @returns The list of files and directories in the given directory.
*/
listFiles(path: string, options?: ListFilesOptions): string[];
/**
* Checks if a directory exists in the PHP filesystem.
*
* @param path – The path to check.
* @returns True if the path is a directory, false otherwise.
*/
isDir(path: string): boolean;
/**
* Checks if a file (or a directory) exists in the PHP filesystem.
*
* @param path - The file path to check.
* @returns True if the file exists, false otherwise.
*/
fileExists(path: string): boolean;
/**
* Changes the current working directory in the PHP filesystem.
* This is the directory that will be used as the base for relative paths.
* For example, if the current working directory is `/root/php`, and the
* path is `data`, the absolute path will be `/root/php/data`.
*
* @param path - The new working directory.
*/
chdir(path: string): void;
/**
* Runs PHP code.
*
* This low-level method directly interacts with the WebAssembly
* PHP interpreter.
*
* Every time you call run(), it prepares the PHP
* environment and:
*
* * Resets the internal PHP state
* * Populates superglobals ($_SERVER, $_GET, etc.)
* * Handles file uploads
* * Populates input streams (stdin, argv, etc.)
* * Sets the current working directory
*
* You can use run() in two primary modes:
*
* ### Code snippet mode
*
* In this mode, you pass a string containing PHP code to run.
*
* ```ts
* const result = await php.run({
* code: `<?php echo "Hello world!";`
* });
* // result.text === "Hello world!"
* ```
*
* In this mode, information like __DIR__ or __FILE__ isn't very
* useful because the code is not associated with any file.
*
* Under the hood, the PHP snippet is passed to the `zend_eval_string`
* C function.
*
* ### File mode
*
* In the file mode, you pass a scriptPath and PHP executes a file
* found at a that path:
*
* ```ts
* php.writeFile(
* "/www/index.php",
* `<?php echo "Hello world!";"`
* );
* const result = await php.run({
* scriptPath: "/www/index.php"
* });
* // result.text === "Hello world!"
* ```
*
* In this mode, you can rely on path-related information like __DIR__
* or __FILE__.
*
* Under the hood, the PHP file is executed with the `php_execute_script`
* C function.
*
* The `run()` method cannot be used in conjunction with `cli()`.
*
* @example
* ```js
* const result = await php.run(`<?php
* $fp = fopen('php://stderr', 'w');
* fwrite($fp, "Hello, world!");
* `);
* // result.errors === "Hello, world!"
* ```
*
* @param options - PHP runtime options.
*/
run(options: PHPRunOptions): Promise<PHPResponse>;
/**
* Listens to message sent by the PHP code.
*
* To dispatch messages, call:
*
* post_message_to_js(string $data)
*
* Arguments:
* $data (string) – Data to pass to JavaScript.
*
* @example
*
* ```ts
* const php = await PHP.load('8.0');
*
* php.onMessage(
* // The data is always passed as a string
* function (data: string) {
* // Let's decode and log the data:
* console.log(JSON.parse(data));
* }
* );
*
* // Now that we have a listener in place, let's
* // dispatch a message:
* await php.run({
* code: `<?php
* post_message_to_js(
* json_encode([
* 'post_id' => '15',
* 'post_title' => 'This is a blog post!'
* ])
* ));
* `,
* });
* ```
*
* @param listener Callback function to handle the message.
*/
onMessage(listener: MessageListener): void;
/**
* Registers a handler to spawns a child process when
* `proc_open()`, `popen()`, `exec()`, `system()`, or `passthru()`
* is called.
*
* @param handler Callback function to spawn a process.
*/
setSpawnHandler(handler: SpawnHandler): void;
}
export type MessageListener = (
data: string
) => Promise<string | Uint8Array | void> | string | void;
interface EventEmitter {
on(event: string, listener: (...args: any[]) => void): this;
emit(event: string, ...args: any[]): boolean;
}
type ChildProcess = EventEmitter & {
stdout: EventEmitter;
stderr: EventEmitter;
};
export type SpawnHandler = (command: string) => ChildProcess;
export type IsomorphicRemotePHP = Remote<IsomorphicLocalPHP>;
export type UniversalPHP = IsomorphicLocalPHP | IsomorphicRemotePHP;
export type HTTPMethod =
| 'GET'
| 'POST'
| 'HEAD'
| 'OPTIONS'
| 'PATCH'
| 'PUT'
| 'DELETE';
export type PHPRequestHeaders = Record<string, string>;
export interface PHPRequest {
/**
* Request method. Default: `GET`.
*/
method?: HTTPMethod;
/**
* Request path or absolute URL.
*/
url: string;
/**
* Request headers.
*/
headers?: PHPRequestHeaders;
/**
* Uploaded files
*/
files?: Record<string, File>;
/**
* Request body without the files.
*/
body?: string;
/**
* Form data. If set, the request body will be ignored and
* the content-type header will be set to `application/x-www-form-urlencoded`.
*/
formData?: Record<string, unknown>;
}
export interface PHPRunOptions {
/**
* Request path following the domain:port part.
*/
relativeUri?: string;
/**
* Path of the .php file to execute.
*/
scriptPath?: string;
/**
* Request protocol.
*/
protocol?: string;
/**
* Request method. Default: `GET`.
*/
method?: HTTPMethod;
/**
* Request headers.
*/
headers?: PHPRequestHeaders;
/**
* Request body without the files.
*/
body?: string;
/**
* Uploaded files.
*/
fileInfos?: FileInfo[];
/**
* The code snippet to eval instead of a php file.
*/
code?: string;
}
/**
* Output of the PHP.wasm runtime.
*/
export interface PHPOutput {
/** Exit code of the PHP process. 0 means success, 1 and 2 mean error. */
exitCode: number;
/** Stdout data */
stdout: ArrayBuffer;
/** Stderr lines */
stderr: string[];
}
export interface FileInfo {
key: string;
name: string;
type: string;
data: Uint8Array;
}
export interface CpOptions {
/**
* If true, recursively copies the directory and all its contents.
* Default: false.
*/
recursive?: boolean;
}
export interface RmDirOptions {
/**
* If true, recursively removes the directory and all its contents.
* Default: true.
*/
recursive?: boolean;
}
export interface ListFilesOptions {
/**
* If true, prepend given folder path to all file names.
* Default: false.
*/
prependPath: boolean;
}