@php-wasm/web 0.1.10 → 0.1.19

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/index.d.ts CHANGED
@@ -2,191 +2,288 @@
2
2
 
3
3
  import * as Comlink from 'comlink';
4
4
 
5
- export type JavascriptRuntime = "NODE" | "WEB" | "WORKER";
6
- export type PHPRequestHeaders = Record<string, string>;
7
- export interface FileInfo {
8
- key: string;
9
- name: string;
10
- type: string;
11
- data: Uint8Array;
12
- }
13
- export interface PHPRequest {
5
+ export interface PHPResponseData {
14
6
  /**
15
- * Request path following the domain:port part.
7
+ * Response headers.
16
8
  */
17
- relativeUri?: string;
9
+ readonly headers: Record<string, string[]>;
18
10
  /**
19
- * Path of the .php file to execute.
11
+ * Response body. Contains the output from `echo`,
12
+ * `print`, inline HTML etc.
20
13
  */
21
- scriptPath?: string;
14
+ readonly bytes: ArrayBuffer;
22
15
  /**
23
- * Request protocol.
16
+ * Stderr contents, if any.
24
17
  */
25
- protocol?: string;
18
+ readonly errors: string;
26
19
  /**
27
- * Request method. Default: `GET`.
20
+ * The exit code of the script. `0` is a success, while
21
+ * `1` and `2` indicate an error.
28
22
  */
29
- method?: "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
23
+ readonly exitCode: number;
30
24
  /**
31
- * Request headers.
25
+ * Response HTTP status code, e.g. 200.
32
26
  */
33
- headers?: PHPRequestHeaders;
27
+ readonly httpStatusCode: number;
28
+ }
29
+ /**
30
+ * PHP response. Body is an `ArrayBuffer` because it can
31
+ * contain binary data.
32
+ *
33
+ * This type is used in Comlink.transferHandlers.set('PHPResponse', { ... })
34
+ * so be sure to update that if you change this type.
35
+ */
36
+ export declare class PHPResponse implements PHPResponseData {
37
+ /** @inheritDoc */
38
+ readonly headers: Record<string, string[]>;
39
+ /** @inheritDoc */
40
+ readonly bytes: ArrayBuffer;
41
+ /** @inheritDoc */
42
+ readonly errors: string;
43
+ /** @inheritDoc */
44
+ readonly exitCode: number;
45
+ /** @inheritDoc */
46
+ readonly httpStatusCode: number;
47
+ constructor(httpStatusCode: number, headers: Record<string, string[]>, body: ArrayBuffer, errors?: string, exitCode?: number);
48
+ static fromRawData(data: PHPResponseData): PHPResponse;
49
+ toRawData(): PHPResponseData;
34
50
  /**
35
- * Request body without the files.
51
+ * Response body as JSON.
36
52
  */
37
- body?: string;
53
+ get json(): any;
38
54
  /**
39
- * Uploaded files.
55
+ * Response body as text.
40
56
  */
41
- fileInfos?: FileInfo[];
57
+ get text(): string;
58
+ }
59
+ export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
60
+ export type PHPRequestHeaders = Record<string, string>;
61
+ export interface PHPRequest {
42
62
  /**
43
- * The code snippet to eval instead of a php file.
63
+ * Request method. Default: `GET`.
44
64
  */
45
- code?: string;
46
- }
47
- export interface PHPResponse {
65
+ method?: HTTPMethod;
48
66
  /**
49
- * The exit code of the script. `0` is a success, while
50
- * `1` and `2` indicate an error.
67
+ * Request path or absolute URL.
51
68
  */
52
- exitCode: number;
69
+ url: string;
53
70
  /**
54
- * Response body. Contains the output from `echo`,
55
- * `print`, inline HTML etc.
71
+ * Request headers.
56
72
  */
57
- body: ArrayBuffer;
73
+ headers?: PHPRequestHeaders;
58
74
  /**
59
- * PHP errors.
75
+ * Uploaded files
60
76
  */
61
- errors: string;
77
+ files?: Record<string, File>;
62
78
  /**
63
- * Response headers.
79
+ * Request body without the files.
64
80
  */
65
- headers: Record<string, string[]>;
81
+ body?: string;
66
82
  /**
67
- * Response HTTP status code, e.g. 200.
83
+ * Form data. If set, the request body will be ignored and
84
+ * the content-type header will be set to `application/x-www-form-urlencoded`.
68
85
  */
69
- httpStatusCode: number;
86
+ formData?: Record<string, unknown>;
87
+ }
88
+ export interface PHPRequestHandlerConfiguration {
89
+ /**
90
+ * The directory in the PHP filesystem where the server will look
91
+ * for the files to serve. Default: `/var/www`.
92
+ */
93
+ documentRoot?: string;
94
+ /**
95
+ * Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
96
+ */
97
+ absoluteUrl?: string;
98
+ /**
99
+ * Callback used by the PHPRequestHandler to decide whether
100
+ * the requested path refers to a PHP file or a static file.
101
+ */
102
+ isStaticFilePath?: (path: string) => boolean;
70
103
  }
71
- export type PHPRuntimeId = number;
72
104
  /**
73
- * Loads the PHP runtime with the given arguments and data dependencies.
74
- *
75
- * This function handles the entire PHP initialization pipeline. In particular, it:
76
- *
77
- * * Instantiates the Emscripten PHP module
78
- * * Wires it together with the data dependencies and loads them
79
- * * Ensures is all happens in a correct order
80
- * * Waits until the entire loading sequence is finished
81
- *
82
- * Basic usage:
105
+ * A fake PHP server that handles HTTP requests but does not
106
+ * bind to any port.
83
107
  *
108
+ * @public
109
+ * @example Use PHPRequestHandler implicitly with a new PHP instance:
84
110
  * ```js
85
- * const phpLoaderModule = await getPHPLoaderModule("7.4");
86
- * const php = await loadPHPRuntime( phpLoaderModule );
87
- * console.log(php.run(`<?php echo "Hello, world!"; `));
88
- * // { stdout: ArrayBuffer containing the string "Hello, world!", stderr: [''], exitCode: 0 }
89
- * ```
90
- *
91
- * **The PHP loader module:**
111
+ * import { PHP } from '@php-wasm/web';
92
112
  *
93
- * In the basic usage example, `phpLoaderModule` is **not** a vanilla Emscripten module. Instead,
94
- * it's an ESM module that wraps the regular Emscripten output and adds some
95
- * extra functionality. It's generated by the Dockerfile shipped with this repo.
96
- * Here's the API it provides:
113
+ * const php = await PHP.load( '7.4', {
114
+ * requestHandler: {
115
+ * // PHP FS path to serve the files from:
116
+ * documentRoot: '/www',
97
117
  *
98
- * ```js
99
- * // php.wasm size in bytes:
100
- * export const dependenciesTotalSize = 5644199;
118
+ * // Used to populate $_SERVER['SERVER_NAME'] etc.:
119
+ * absoluteUrl: 'http://127.0.0.1'
120
+ * }
121
+ * } );
101
122
  *
102
- * // php.wasm filename:
103
- * export const dependencyFilename = 'php.wasm';
123
+ * php.mkdirTree('/www');
124
+ * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
104
125
  *
105
- * // Run Emscripten's generated module:
106
- * export default function(jsEnv, emscriptenModuleArgs) {}
126
+ * const response = await php.request({ path: '/index.php' });
127
+ * console.log(response.text);
128
+ * // "Hi from PHP!"
107
129
  * ```
108
130
  *
109
- * **PHP Filesystem:**
110
- *
111
- * Once initialized, the PHP has its own filesystem separate from the project
112
- * files. It's provided by [Emscripten and uses its FS library](https://emscripten.org/docs/api_reference/Filesystem-API.html).
113
- *
114
- * The API exposed to you via the PHP class is succinct and abstracts
115
- * await certain unintuitive parts of low-level FS interactions.
116
- *
117
- * Here's how to use it:
118
- *
131
+ * @example Explicitly create a PHPRequestHandler instance and run a PHP script:
119
132
  * ```js
120
- * // Recursively create a /var/www directory
121
- * php.mkdirTree('/var/www');
122
- *
123
- * console.log(php.fileExists('/var/www/file.txt'));
124
- * // false
125
- *
126
- * php.writeFile('/var/www/file.txt', 'Hello from the filesystem!');
127
- *
128
- * console.log(php.fileExists('/var/www/file.txt'));
129
- * // true
130
- *
131
- * console.log(php.readFile('/var/www/file.txt'));
132
- * // "Hello from the filesystem!
133
- *
134
- * // Delete the file:
135
- * php.unlink('/var/www/file.txt');
136
- * ```
137
- *
138
- * For more details consult the PHP class directly.
139
- *
140
- * **Data dependencies:**
141
- *
142
- * Using existing PHP packages by manually recreating them file-by-file would
143
- * be quite inconvenient. Fortunately, Emscripten provides a "data dependencies"
144
- * feature.
145
- *
146
- * Data dependencies consist of a `dependency.data` file and a `dependency.js` loader and
147
- * can be packaged with the [file_packager.py tool]( https://emscripten.org/docs/porting/files/packaging_files.html#packaging-using-the-file-packager-tool).
148
- * This project requires wrapping the Emscripten-generated `dependency.js` file in an ES
149
- * module as follows:
150
- *
151
- * 1. Prepend `export default function(emscriptenPHPModule) {'; `
152
- * 2. Prepend `export const dependencyFilename = '<DATA FILE NAME>'; `
153
- * 3. Prepend `export const dependenciesTotalSize = <DATA FILE SIZE>;`
154
- * 4. Append `}`
155
- *
156
- * Be sure to use the `--export-name="emscriptenPHPModule"` file_packager.py option.
133
+ * import {
134
+ * loadPHPRuntime,
135
+ * PHP,
136
+ * PHPRequestHandler,
137
+ * getPHPLoaderModule,
138
+ * } from '@php-wasm/web';
157
139
  *
158
- * You want the final output to look as follows:
140
+ * const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
141
+ * const php = new PHP( runtime );
159
142
  *
160
- * ```js
161
- * export const dependenciesTotalSize = 5644199;
162
- * export const dependencyFilename = 'dependency.data';
163
- * export default function(emscriptenPHPModule) {
164
- * // Emscripten-generated code:
165
- * var Module = typeof emscriptenPHPModule !== 'undefined' ? emscriptenPHPModule : {};
166
- * // ... the rest of it ...
167
- * }
168
- * ```
143
+ * php.mkdirTree('/www');
144
+ * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
169
145
  *
170
- * Such a constructions enables loading the `dependency.js` as an ES Module using
171
- * `import("/dependency.js")`.
146
+ * const server = new PHPRequestHandler(php, {
147
+ * // PHP FS path to serve the files from:
148
+ * documentRoot: '/www',
172
149
  *
173
- * Once it's ready, you can load PHP and your data dependencies as follows:
150
+ * // Used to populate $_SERVER['SERVER_NAME'] etc.:
151
+ * absoluteUrl: 'http://127.0.0.1'
152
+ * });
174
153
  *
175
- * ```js
176
- * const [phpLoaderModule, wordPressLoaderModule] = await Promise.all([
177
- * getPHPLoaderModule("7.4"),
178
- * import("/wp.js")
179
- * ]);
180
- * const php = await loadPHPRuntime(phpLoaderModule, {}, [wordPressLoaderModule]);
154
+ * const response = server.request({ path: '/index.php' });
155
+ * console.log(response.text);
156
+ * // "Hi from PHP!"
181
157
  * ```
158
+ */
159
+ export declare class PHPRequestHandler {
160
+ #private;
161
+ /**
162
+ * The PHP instance
163
+ */
164
+ php: BasePHP;
165
+ /**
166
+ * @param php - The PHP instance.
167
+ * @param config - Request Handler configuration.
168
+ */
169
+ constructor(php: BasePHP, config?: PHPRequestHandlerConfiguration);
170
+ /**
171
+ * Converts a path to an absolute URL based at the PHPRequestHandler
172
+ * root.
173
+ *
174
+ * @param path The server path to convert to an absolute URL.
175
+ * @returns The absolute URL.
176
+ */
177
+ pathToInternalUrl(path: string): string;
178
+ /**
179
+ * Converts an absolute URL based at the PHPRequestHandler to a relative path
180
+ * without the server pathname and scope.
181
+ *
182
+ * @param internalUrl An absolute URL based at the PHPRequestHandler root.
183
+ * @returns The relative path.
184
+ */
185
+ internalUrlToPath(internalUrl: string): string;
186
+ get isRequestRunning(): boolean;
187
+ /**
188
+ * The absolute URL of this PHPRequestHandler instance.
189
+ */
190
+ get absoluteUrl(): string;
191
+ /**
192
+ * The absolute URL of this PHPRequestHandler instance.
193
+ */
194
+ get documentRoot(): string;
195
+ /**
196
+ * Serves the request – either by serving a static file, or by
197
+ * dispatching it to the PHP runtime.
198
+ *
199
+ * @param request - The request.
200
+ * @returns The response.
201
+ */
202
+ request(request: PHPRequest): Promise<PHPResponse>;
203
+ }
204
+ export interface PHPBrowserConfiguration {
205
+ /**
206
+ * Should handle redirects internally?
207
+ */
208
+ handleRedirects?: boolean;
209
+ /**
210
+ * The maximum number of redirects to follow internally. Once
211
+ * exceeded, request() will return the redirecting response.
212
+ */
213
+ maxRedirects?: number;
214
+ }
215
+ /**
216
+ * A fake web browser that handles PHPRequestHandler's cookies and redirects
217
+ * internally without exposing them to the consumer.
182
218
  *
183
219
  * @public
184
- * @param phpLoaderModule - The ESM-wrapped Emscripten module. Consult the Dockerfile for the build process.
185
- * @param phpModuleArgs - The Emscripten module arguments, see https://emscripten.org/docs/api_reference/module.html#affecting-execution.
186
- * @param dataDependenciesModules - A list of the ESM-wrapped Emscripten data dependency modules.
187
- * @returns Loaded runtime id.
188
220
  */
189
- export declare function loadPHPRuntime(phpLoaderModule: PHPLoaderModule, phpModuleArgs?: EmscriptenOptions, dataDependenciesModules?: DataModule[]): Promise<number>;
221
+ export declare class PHPBrowser implements WithRequestHandler {
222
+ #private;
223
+ server: PHPRequestHandler;
224
+ /**
225
+ * @param server - The PHP server to browse.
226
+ * @param config - The browser configuration.
227
+ */
228
+ constructor(server: PHPRequestHandler, config?: PHPBrowserConfiguration);
229
+ /**
230
+ * Sends the request to the server.
231
+ *
232
+ * When cookies are present in the response, this method stores
233
+ * them and sends them with any subsequent requests.
234
+ *
235
+ * When a redirection is present in the response, this method
236
+ * follows it by discarding a response and sending a subsequent
237
+ * request.
238
+ *
239
+ * @param request - The request.
240
+ * @param redirects - Internal. The number of redirects handled so far.
241
+ * @returns PHPRequestHandler response.
242
+ */
243
+ request(request: PHPRequest, redirects?: number): Promise<PHPResponse>;
244
+ }
245
+ export type RuntimeType = "NODE" | "WEB" | "WORKER";
246
+ export interface FileInfo {
247
+ key: string;
248
+ name: string;
249
+ type: string;
250
+ data: Uint8Array;
251
+ }
252
+ export interface PHPRunOptions {
253
+ /**
254
+ * Request path following the domain:port part.
255
+ */
256
+ relativeUri?: string;
257
+ /**
258
+ * Path of the .php file to execute.
259
+ */
260
+ scriptPath?: string;
261
+ /**
262
+ * Request protocol.
263
+ */
264
+ protocol?: string;
265
+ /**
266
+ * Request method. Default: `GET`.
267
+ */
268
+ method?: HTTPMethod;
269
+ /**
270
+ * Request headers.
271
+ */
272
+ headers?: PHPRequestHeaders;
273
+ /**
274
+ * Request body without the files.
275
+ */
276
+ body?: string;
277
+ /**
278
+ * Uploaded files.
279
+ */
280
+ fileInfos?: FileInfo[];
281
+ /**
282
+ * The code snippet to eval instead of a php file.
283
+ */
284
+ code?: string;
285
+ }
286
+ export type PHPRuntimeId = number;
190
287
  export interface WithPHPIniBindings {
191
288
  setPhpIniPath(path: string): void;
192
289
  setPhpIniEntry(key: string, value: string): void;
@@ -274,21 +371,30 @@ export interface WithFilesystem {
274
371
  * @returns True if the file exists, false otherwise.
275
372
  */
276
373
  fileExists(path: string): boolean;
374
+ /**
375
+ * Changes the current working directory in the PHP filesystem.
376
+ * This is the directory that will be used as the base for relative paths.
377
+ * For example, if the current working directory is `/root/php`, and the
378
+ * path is `data`, the absolute path will be `/root/php/data`.
379
+ *
380
+ * @param path - The new working directory.
381
+ */
382
+ chdir(path: string): void;
277
383
  }
278
384
  export interface WithRun {
279
385
  /**
280
- * Dispatches a PHP request.
386
+ * Runs PHP code.
281
387
  * Cannot be used in conjunction with `cli()`.
282
388
  *
283
389
  * @example
284
390
  * ```js
285
- * const output = php.run('<?php echo "Hello world!";');
391
+ * const output = await php.run('<?php echo "Hello world!";');
286
392
  * console.log(output.stdout); // "Hello world!"
287
393
  * ```
288
394
  *
289
395
  * @example
290
396
  * ```js
291
- * console.log(php.run(`<?php
397
+ * console.log(await php.run(`<?php
292
398
  * $fp = fopen('php://stderr', 'w');
293
399
  * fwrite($fp, "Hello, world!");
294
400
  * `));
@@ -297,13 +403,37 @@ export interface WithRun {
297
403
  *
298
404
  * @param request - PHP Request data.
299
405
  */
300
- run(request?: PHPRequest): PHPResponse;
406
+ run(request?: PHPRunOptions): Promise<PHPResponse>;
407
+ }
408
+ export interface WithRequestHandler {
409
+ /**
410
+ * Dispatches a HTTP request using PHP as a backend.
411
+ * Cannot be used in conjunction with `cli()`.
412
+ *
413
+ * @example
414
+ * ```js
415
+ * const output = await php.request({
416
+ * method: 'GET',
417
+ * url: '/index.php',
418
+ * headers: {
419
+ * 'X-foo': 'bar',
420
+ * },
421
+ * formData: {
422
+ * foo: 'bar',
423
+ * },
424
+ * });
425
+ * console.log(output.stdout); // "Hello world!"
426
+ * ```
427
+ *
428
+ * @param request - PHP Request data.
429
+ */
430
+ request(request?: PHPRequest): Promise<PHPResponse>;
301
431
  }
302
432
  export type PHPRuntime = any;
303
433
  export type PHPLoaderModule = {
304
434
  dependencyFilename: string;
305
435
  dependenciesTotalSize: number;
306
- default: (jsRuntime: string, options: EmscriptenOptions) => PHPRuntime;
436
+ init: (jsRuntime: string, options: EmscriptenOptions) => PHPRuntime;
307
437
  };
308
438
  export type DataModule = {
309
439
  dependencyFilename: string;
@@ -321,40 +451,37 @@ export type EmscriptenOptions = {
321
451
  onRuntimeInitialized?: () => void;
322
452
  monitorRunDependencies?: (left: number) => void;
323
453
  } & Record<string, any>;
324
- export type MountSettings = {
325
- root: string;
326
- mountpoint: string;
327
- };
328
- /**
329
- * An environment-agnostic wrapper around the Emscripten PHP runtime
330
- * that abstracts the super low-level API and provides a more convenient
331
- * higher-level API.
332
- *
333
- * It exposes a minimal set of methods to run PHP scripts and to
334
- * interact with the PHP filesystem.
335
- *
336
- * @see {startPHP} This class is not meant to be used directly. Use `startPHP` instead.
337
- */
338
- export declare class PHP implements WithPHPIniBindings, WithFilesystem, WithNodeFilesystem, WithCLI, WithRun {
454
+ export type MountSettings = {
455
+ root: string;
456
+ };
457
+ declare abstract class BasePHP implements WithPHPIniBindings, WithFilesystem, WithNodeFilesystem, WithCLI, WithRequestHandler, WithRun {
339
458
  #private;
459
+ requestHandler?: PHPBrowser;
340
460
  /**
341
461
  * Initializes a PHP runtime.
342
462
  *
343
463
  * @internal
344
464
  * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
465
+ * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
345
466
  */
346
- constructor(PHPRuntimeId?: PHPRuntimeId);
467
+ constructor(PHPRuntimeId?: PHPRuntimeId, serverOptions?: PHPRequestHandlerConfiguration);
347
468
  initializeRuntime(runtimeId: PHPRuntimeId): void;
348
469
  /** @inheritDoc */
349
470
  setPhpIniPath(path: string): void;
350
471
  /** @inheritDoc */
351
472
  setPhpIniEntry(key: string, value: string): void;
352
473
  /** @inheritDoc */
353
- run(request?: PHPRequest): PHPResponse;
474
+ chdir(path: string): void;
475
+ /** @inheritDoc */
476
+ request(request: PHPRequest, maxRedirects?: number): Promise<PHPResponse>;
477
+ /** @inheritDoc */
478
+ run(request?: PHPRunOptions): Promise<PHPResponse>;
354
479
  cli(argv: string[]): Promise<number>;
355
480
  setSkipShebang(shouldSkip: boolean): void;
356
481
  addServerGlobalEntry(key: string, value: string): void;
482
+ /** @inheritDoc */
357
483
  mkdirTree(path: string): void;
484
+ /** @inheritDoc */
358
485
  readFileAsText(path: string): string;
359
486
  /** @inheritDoc */
360
487
  readFileAsBuffer(path: string): Uint8Array;
@@ -364,8 +491,11 @@ export declare class PHP implements WithPHPIniBindings, WithFilesystem, WithNode
364
491
  unlink(path: string): void;
365
492
  /** @inheritDoc */
366
493
  listFiles(path: string): string[];
494
+ /** @inheritDoc */
367
495
  isDir(path: string): boolean;
496
+ /** @inheritDoc */
368
497
  fileExists(path: string): boolean;
498
+ /** @inheritDoc */
369
499
  mount(settings: MountSettings, path: string): void;
370
500
  }
371
501
  /**
@@ -380,164 +510,149 @@ export interface PHPOutput {
380
510
  stderr: string[];
381
511
  }
382
512
  /**
383
- * Emscripten's filesystem-related Exception.
513
+ * Loads the PHP runtime with the given arguments and data dependencies.
384
514
  *
385
- * @see https://emscripten.org/docs/api_reference/Filesystem-API.html
386
- * @see https://github.com/emscripten-core/emscripten/blob/main/system/lib/libc/musl/arch/emscripten/bits/errno.h
387
- */
388
- export type ErrnoError = Error;
389
- export type PHPServerRequest = Pick<PHPRequest, "method" | "headers"> & {
390
- files?: Record<string, File>;
391
- } & ({
392
- absoluteUrl: string;
393
- relativeUrl?: never;
394
- } | {
395
- absoluteUrl?: never;
396
- relativeUrl: string;
397
- }) & ((Pick<PHPRequest, "body"> & {
398
- formData?: never;
399
- }) | {
400
- body?: never;
401
- formData: Record<string, unknown>;
402
- });
403
- /**
404
- * A fake PHP server that handles HTTP requests but does not
405
- * bind to any port.
515
+ * This function handles the entire PHP initialization pipeline. In particular, it:
516
+ *
517
+ * * Instantiates the Emscripten PHP module
518
+ * * Wires it together with the data dependencies and loads them
519
+ * * Ensures is all happens in a correct order
520
+ * * Waits until the entire loading sequence is finished
521
+ *
522
+ * Basic usage:
406
523
  *
407
- * @public
408
- * @example
409
524
  * ```js
410
- * import {
411
- * loadPHPRuntime,
412
- * PHP,
413
- * PHPServer,
414
- * PHPBrowser,
415
- * getPHPLoaderModule,
416
- * } from '@php-wasm/web';
525
+ * const phpLoaderModule = await getPHPLoaderModule("7.4");
526
+ * const php = await loadPHPRuntime( phpLoaderModule );
527
+ * console.log(php.run(`<?php echo "Hello, world!"; `));
528
+ * // { stdout: ArrayBuffer containing the string "Hello, world!", stderr: [''], exitCode: 0 }
529
+ * ```
417
530
  *
418
- * const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
419
- * const php = new PHP( runtime );
531
+ * **The PHP loader module:**
420
532
  *
421
- * php.mkdirTree('/www');
422
- * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
533
+ * In the basic usage example, `phpLoaderModule` is **not** a vanilla Emscripten module. Instead,
534
+ * it's an ESM module that wraps the regular Emscripten output and adds some
535
+ * extra functionality. It's generated by the Dockerfile shipped with this repo.
536
+ * Here's the API it provides:
423
537
  *
424
- * const server = new PHPServer(php, {
425
- * // PHP FS path to serve the files from:
426
- * documentRoot: '/www',
538
+ * ```js
539
+ * // php.wasm size in bytes:
540
+ * export const dependenciesTotalSize = 5644199;
427
541
  *
428
- * // Used to populate $_SERVER['SERVER_NAME'] etc.:
429
- * absoluteUrl: 'http://127.0.0.1'
430
- * });
542
+ * // php.wasm filename:
543
+ * export const dependencyFilename = 'php.wasm';
431
544
  *
432
- * const output = server.request({ path: '/index.php' }).body;
433
- * console.log(new TextDecoder().decode(output));
434
- * // "Hi from PHP!"
545
+ * // Run Emscripten's generated module:
546
+ * export default function(jsEnv, emscriptenModuleArgs) {}
547
+ * ```
548
+ *
549
+ * **PHP Filesystem:**
550
+ *
551
+ * Once initialized, the PHP has its own filesystem separate from the project
552
+ * files. It's provided by [Emscripten and uses its FS library](https://emscripten.org/docs/api_reference/Filesystem-API.html).
553
+ *
554
+ * The API exposed to you via the PHP class is succinct and abstracts
555
+ * await certain unintuitive parts of low-level FS interactions.
556
+ *
557
+ * Here's how to use it:
558
+ *
559
+ * ```js
560
+ * // Recursively create a /var/www directory
561
+ * php.mkdirTree('/var/www');
562
+ *
563
+ * console.log(php.fileExists('/var/www/file.txt'));
564
+ * // false
565
+ *
566
+ * php.writeFile('/var/www/file.txt', 'Hello from the filesystem!');
567
+ *
568
+ * console.log(php.fileExists('/var/www/file.txt'));
569
+ * // true
570
+ *
571
+ * console.log(php.readFile('/var/www/file.txt'));
572
+ * // "Hello from the filesystem!
573
+ *
574
+ * // Delete the file:
575
+ * php.unlink('/var/www/file.txt');
576
+ * ```
577
+ *
578
+ * For more details consult the PHP class directly.
579
+ *
580
+ * **Data dependencies:**
581
+ *
582
+ * Using existing PHP packages by manually recreating them file-by-file would
583
+ * be quite inconvenient. Fortunately, Emscripten provides a "data dependencies"
584
+ * feature.
585
+ *
586
+ * Data dependencies consist of a `dependency.data` file and a `dependency.js` loader and
587
+ * can be packaged with the [file_packager.py tool]( https://emscripten.org/docs/porting/files/packaging_files.html#packaging-using-the-file-packager-tool).
588
+ * This project requires wrapping the Emscripten-generated `dependency.js` file in an ES
589
+ * module as follows:
590
+ *
591
+ * 1. Prepend `export default function(emscriptenPHPModule) {'; `
592
+ * 2. Prepend `export const dependencyFilename = '<DATA FILE NAME>'; `
593
+ * 3. Prepend `export const dependenciesTotalSize = <DATA FILE SIZE>;`
594
+ * 4. Append `}`
595
+ *
596
+ * Be sure to use the `--export-name="emscriptenPHPModule"` file_packager.py option.
597
+ *
598
+ * You want the final output to look as follows:
599
+ *
600
+ * ```js
601
+ * export const dependenciesTotalSize = 5644199;
602
+ * export const dependencyFilename = 'dependency.data';
603
+ * export default function(emscriptenPHPModule) {
604
+ * // Emscripten-generated code:
605
+ * var Module = typeof emscriptenPHPModule !== 'undefined' ? emscriptenPHPModule : {};
606
+ * // ... the rest of it ...
607
+ * }
608
+ * ```
609
+ *
610
+ * Such a constructions enables loading the `dependency.js` as an ES Module using
611
+ * `import("/dependency.js")`.
612
+ *
613
+ * Once it's ready, you can load PHP and your data dependencies as follows:
614
+ *
615
+ * ```js
616
+ * const [phpLoaderModule, wordPressLoaderModule] = await Promise.all([
617
+ * getPHPLoaderModule("7.4"),
618
+ * import("/wp.js")
619
+ * ]);
620
+ * const php = await loadPHPRuntime(phpLoaderModule, {}, [wordPressLoaderModule]);
435
621
  * ```
622
+ *
623
+ * @public
624
+ * @param phpLoaderModule - The ESM-wrapped Emscripten module. Consult the Dockerfile for the build process.
625
+ * @param phpModuleArgs - The Emscripten module arguments, see https://emscripten.org/docs/api_reference/module.html#affecting-execution.
626
+ * @param dataDependenciesModules - A list of the ESM-wrapped Emscripten data dependency modules.
627
+ * @returns Loaded runtime id.
436
628
  */
437
- export declare class PHPServer {
438
- #private;
439
- /**
440
- * The PHP instance
441
- */
442
- php: PHP;
443
- /**
444
- * @param php - The PHP instance.
445
- * @param config - Server configuration.
446
- */
447
- constructor(php: PHP, config?: PHPServerConfigation);
448
- /**
449
- * Converts a path to an absolute URL based at the PHPServer
450
- * root.
451
- *
452
- * @param path The server path to convert to an absolute URL.
453
- * @returns The absolute URL.
454
- */
455
- pathToInternalUrl(path: string): string;
456
- /**
457
- * Converts an absolute URL based at the PHPServer to a relative path
458
- * without the server pathname and scope.
459
- *
460
- * @param internalUrl An absolute URL based at the PHPServer root.
461
- * @returns The relative path.
462
- */
463
- internalUrlToPath(internalUrl: string): string;
464
- /**
465
- * The absolute URL of this PHPServer instance.
466
- */
467
- get absoluteUrl(): string;
468
- /**
469
- * The absolute URL of this PHPServer instance.
470
- */
471
- get documentRoot(): string;
472
- /**
473
- * Serves the request – either by serving a static file, or by
474
- * dispatching it to the PHP runtime.
475
- *
476
- * @param request - The request.
477
- * @returns The response.
478
- */
479
- request(request: PHPServerRequest): Promise<PHPResponse>;
480
- }
481
- export interface PHPServerConfigation {
482
- /**
483
- * The directory in the PHP filesystem where the server will look
484
- * for the files to serve. Default: `/var/www`.
485
- */
486
- documentRoot?: string;
487
- /**
488
- * Server URL. Used to populate $_SERVER details like HTTP_HOST.
489
- */
490
- absoluteUrl?: string;
491
- /**
492
- * Callback used by the PHPServer to decide whether
493
- * the requested path refers to a PHP file or a static file.
494
- */
495
- isStaticFilePath?: (path: string) => boolean;
496
- }
497
- export interface WithRequest {
498
- /**
499
- * Sends the request to the server.
500
- *
501
- * When cookies are present in the response, this method stores
502
- * them and sends them with any subsequent requests.
503
- *
504
- * When a redirection is present in the response, this method
505
- * follows it by discarding a response and sending a subsequent
506
- * request.
507
- *
508
- * @param request - The request.
509
- * @param redirects - Internal. The number of redirects handled so far.
510
- * @returns PHPServer response.
511
- */
512
- request(request: PHPServerRequest, redirects?: number): Promise<PHPResponse>;
513
- }
629
+ export declare function loadPHPRuntime(phpLoaderModule: PHPLoaderModule, phpModuleArgs?: EmscriptenOptions, dataDependenciesModules?: DataModule[]): Promise<number>;
514
630
  /**
515
- * A fake web browser that handles PHPServer's cookies and redirects
516
- * internally without exposing them to the consumer.
631
+ * Emscripten's filesystem-related Exception.
517
632
  *
518
- * @public
633
+ * @see https://emscripten.org/docs/api_reference/Filesystem-API.html
634
+ * @see https://github.com/emscripten-core/emscripten/blob/main/system/lib/libc/musl/arch/emscripten/bits/errno.h
635
+ * @see https://github.com/emscripten-core/emscripten/blob/38eedc630f17094b3202fd48ac0c2c585dbea31e/system/include/wasi/api.h#L336
519
636
  */
520
- export declare class PHPBrowser implements WithRequest {
521
- #private;
522
- server: PHPServer;
523
- /**
524
- * @param server - The PHP server to browse.
525
- * @param config - The browser configuration.
526
- */
527
- constructor(server: PHPServer, config?: PHPBrowserConfiguration);
528
- request(request: PHPServerRequest, redirects?: number): Promise<PHPResponse>;
529
- }
530
- export interface PHPBrowserConfiguration {
531
- /**
532
- * Should handle redirects internally?
533
- */
534
- handleRedirects?: boolean;
535
- /**
536
- * The maximum number of redirects to follow internally. Once
537
- * exceeded, request() will return the redirecting response.
538
- */
539
- maxRedirects?: number;
637
+ export interface ErrnoError extends Error {
638
+ node?: any;
639
+ errno: number;
640
+ message: string;
540
641
  }
642
+ export declare const SupportedPHPVersions: readonly [
643
+ "8.2",
644
+ "8.1",
645
+ "8.0",
646
+ "7.4",
647
+ "7.3",
648
+ "7.2",
649
+ "7.1",
650
+ "7.0",
651
+ "5.6"
652
+ ];
653
+ export declare const LatestSupportedPHPVersion: "8.2";
654
+ export declare const SupportedPHPVersionsList: string[];
655
+ export type SupportedPHPVersion = (typeof SupportedPHPVersions)[number];
541
656
  export type WorkerStartupOptions<T extends Record<string, string> = Record<string, string>> = T;
542
657
  export declare function consumeAPI<APIType>(remote: Worker | Window): Comlink.Remote<APIType>;
543
658
  export type PublicAPI<Methods, PipedAPI = unknown> = Methods & PipedAPI & {
@@ -554,11 +669,44 @@ export interface MonitoredModule {
554
669
  declare class EmscriptenDownloadMonitor extends EventTarget {
555
670
  #private;
556
671
  constructor(modules?: MonitoredModule[]);
557
- getEmscriptenArgs(): {
672
+ getEmscriptenOptions(): {
558
673
  dataFileDownloads: Record<string, any>;
559
674
  };
560
675
  setModules(modules: MonitoredModule[]): void;
561
676
  }
677
+ export interface PHPWebLoaderOptions {
678
+ emscriptenOptions?: EmscriptenOptions;
679
+ downloadMonitor?: EmscriptenDownloadMonitor;
680
+ requestHandler?: PHPRequestHandlerConfiguration;
681
+ dataModules?: Array<DataModule | Promise<DataModule>>;
682
+ }
683
+ export declare class PHP extends BasePHP {
684
+ /**
685
+ * Creates a new PHP instance.
686
+ *
687
+ * Dynamically imports the PHP module, initializes the runtime,
688
+ * and sets up networking. It's a shorthand for the lower-level
689
+ * functions like `getPHPLoaderModule`, `loadPHPRuntime`, and
690
+ * `PHP.initializeRuntime`
691
+ *
692
+ * @param phpVersion The PHP Version to load
693
+ * @param options The options to use when loading PHP
694
+ * @returns A new PHP instance
695
+ */
696
+ static load(phpVersion: SupportedPHPVersion, options?: PHPWebLoaderOptions): Promise<PHP>;
697
+ /**
698
+ * Does what load() does, but synchronously returns
699
+ * an object with the PHP instance and a promise that
700
+ * resolves when the PHP instance is ready.
701
+ *
702
+ * @see load
703
+ */
704
+ static loadSync(phpVersion: SupportedPHPVersion, options?: PHPWebLoaderOptions): {
705
+ php: PHP;
706
+ phpReady: Promise<PHP>;
707
+ dataModules: Promise<DataModule[]>;
708
+ };
709
+ }
562
710
  /** @inheritdoc T */
563
711
  export type Promisify<T> = {
564
712
  [P in keyof T]: T[P] extends (...args: infer A) => infer R ? R extends void | Promise<any> ? T[P] : (...args: A) => Promise<ReturnType<T[P]>> : Promise<T[P]>;
@@ -573,22 +721,24 @@ export interface WithProgress {
573
721
  /**
574
722
  * A PHP client that can be used to run PHP code in the browser.
575
723
  */
576
- export declare class PHPClient implements Promisify<WithRequest & WithPHPIniBindings & WithFilesystem & WithRun & WithProgress & WithPathConversion> {
577
- /** @inheritDoc @php-wasm/web!PHPServer.absoluteUrl */
724
+ export declare class PHPClient implements Promisify<WithPHPIniBindings & WithFilesystem & WithRun & WithRequestHandler & WithProgress & WithPathConversion> {
725
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.absoluteUrl */
578
726
  absoluteUrl: Promise<string>;
579
- /** @inheritDoc @php-wasm/web!PHPServer.documentRoot */
727
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.documentRoot */
580
728
  documentRoot: Promise<string>;
581
729
  /** @inheritDoc */
582
- constructor(browser: PHPBrowser, monitor?: EmscriptenDownloadMonitor);
583
- /** @inheritDoc @php-wasm/web!PHPServer.pathToInternalUrl */
730
+ constructor(php: BasePHP, monitor?: EmscriptenDownloadMonitor);
731
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.pathToInternalUrl */
584
732
  pathToInternalUrl(path: string): Promise<string>;
585
- /** @inheritDoc @php-wasm/web!PHPServer.internalUrlToPath */
733
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.internalUrlToPath */
586
734
  internalUrlToPath(internalUrl: string): Promise<string>;
587
735
  onDownloadProgress(callback: (progress: CustomEvent<ProgressEvent>) => void): Promise<void>;
588
- /** @inheritDoc @php-wasm/web!PHPServer.request */
589
- request(request: PHPServerRequest, redirects?: number): Promise<PHPResponse>;
736
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.request */
737
+ request(request: PHPRequest, redirects?: number): Promise<PHPResponse>;
590
738
  /** @inheritDoc @php-wasm/web!PHP.run */
591
- run(request?: PHPRequest | undefined): Promise<PHPResponse>;
739
+ run(request?: PHPRunOptions): Promise<PHPResponse>;
740
+ /** @inheritDoc @php-wasm/web!PHP.chdir */
741
+ chdir(path: string): void;
592
742
  /** @inheritDoc @php-wasm/web!PHP.setPhpIniPath */
593
743
  setPhpIniPath(path: string): void;
594
744
  /** @inheritDoc @php-wasm/web!PHP.setPhpIniEntry */
@@ -610,8 +760,18 @@ export declare class PHPClient implements Promisify<WithRequest & WithPHPIniBind
610
760
  /** @inheritDoc @php-wasm/web!PHP.fileExists */
611
761
  fileExists(path: string): Promise<boolean>;
612
762
  }
613
- export declare const isAssignableToRemoteClient: PHPClient;
614
- export declare function getPHPLoaderModule(version?: string): Promise<PHPLoaderModule>;
763
+ export declare function getPHPLoaderModule(version?: SupportedPHPVersion): Promise<PHPLoaderModule>;
764
+ /**
765
+ * Run this in the main application to register the service worker or
766
+ * reload the registered worker if the app expects a different version
767
+ * than the currently registered one.
768
+ *
769
+ * @param {string} scriptUrl The URL of the service worker script.
770
+ * @param {string} expectedVersion The expected version of the service worker script. If
771
+ * mismatched with the actual version, the service worker
772
+ * will be re-registered.
773
+ */
774
+ export declare function registerServiceWorker<Client extends PHPClient>(phpApi: Client, scope: string, scriptUrl: string, expectedVersion: string): Promise<void>;
615
775
  export declare function parseWorkerStartupOptions<T extends Record<string, string>>(): WorkerStartupOptions<T>;
616
776
  /**
617
777
  * Recommended Worker Thread backend.
@@ -629,16 +789,5 @@ export declare const recommendedWorkerBackend: string;
629
789
  * @returns The spawned Worker Thread.
630
790
  */
631
791
  export declare function spawnPHPWorkerThread(workerUrl: string, workerBackend?: "webworker" | "iframe", startupOptions?: Record<string, string>): Promise<Window | Worker>;
632
- /**
633
- * Run this in the main application to register the service worker or
634
- * reload the registered worker if the app expects a different version
635
- * than the currently registered one.
636
- *
637
- * @param {string} scriptUrl The URL of the service worker script.
638
- * @param {string} expectedVersion The expected version of the service worker script. If
639
- * mismatched with the actual version, the service worker
640
- * will be re-registered.
641
- */
642
- export declare function registerServiceWorker<Client extends PHPClient>(phpApi: Client, scope: string, scriptUrl: string, expectedVersion: string): Promise<void>;
643
792
 
644
793
  export {};