@php-wasm/web 0.9.18 → 0.9.20

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
@@ -1,1160 +1 @@
1
- // Generated by dts-bundle-generator v7.2.0
2
-
3
- import * as Comlink from 'comlink';
4
- import { Remote } from 'comlink';
5
-
6
- export type WithAPIState = {
7
- /**
8
- * Resolves to true when the remote API is ready for
9
- * Comlink communication, but not necessarily fully initialized yet.
10
- */
11
- isConnected: () => Promise<void>;
12
- /**
13
- * Resolves to true when the remote API is declares it's
14
- * fully loaded and ready to be used.
15
- */
16
- isReady: () => Promise<void>;
17
- };
18
- export type RemoteAPI<T> = Comlink.Remote<T> & WithAPIState;
19
- export declare function consumeAPI<APIType>(remote: Worker | Window, context?: undefined | EventTarget): RemoteAPI<APIType>;
20
- export type PublicAPI<Methods, PipedAPI = unknown> = RemoteAPI<Methods & PipedAPI>;
21
- export declare function exposeAPI<Methods, PipedAPI>(apiMethods?: Methods, pipedApi?: PipedAPI): [
22
- () => void,
23
- (e: Error) => void,
24
- PublicAPI<Methods, PipedAPI>
25
- ];
26
- declare class EmscriptenDownloadMonitor extends EventTarget {
27
- #private;
28
- expectAssets(assets: Record<string, number>): void;
29
- monitorFetch(fetchPromise: Promise<Response>): Promise<Response>;
30
- }
31
- export interface PHPResponseData {
32
- /**
33
- * Response headers.
34
- */
35
- readonly headers: Record<string, string[]>;
36
- /**
37
- * Response body. Contains the output from `echo`,
38
- * `print`, inline HTML etc.
39
- */
40
- readonly bytes: ArrayBuffer;
41
- /**
42
- * Stderr contents, if any.
43
- */
44
- readonly errors: string;
45
- /**
46
- * The exit code of the script. `0` is a success, while
47
- * `1` and `2` indicate an error.
48
- */
49
- readonly exitCode: number;
50
- /**
51
- * Response HTTP status code, e.g. 200.
52
- */
53
- readonly httpStatusCode: number;
54
- }
55
- declare class PHPResponse implements PHPResponseData {
56
- /** @inheritDoc */
57
- readonly headers: Record<string, string[]>;
58
- /** @inheritDoc */
59
- readonly bytes: ArrayBuffer;
60
- /** @inheritDoc */
61
- readonly errors: string;
62
- /** @inheritDoc */
63
- readonly exitCode: number;
64
- /** @inheritDoc */
65
- readonly httpStatusCode: number;
66
- constructor(httpStatusCode: number, headers: Record<string, string[]>, body: ArrayBuffer, errors?: string, exitCode?: number);
67
- static forHttpCode(httpStatusCode: number, text?: string): PHPResponse;
68
- static fromRawData(data: PHPResponseData): PHPResponse;
69
- toRawData(): PHPResponseData;
70
- /**
71
- * Response body as JSON.
72
- */
73
- get json(): any;
74
- /**
75
- * Response body as text.
76
- */
77
- get text(): string;
78
- }
79
- export type PHPRuntimeId = number;
80
- export type PHPRuntime = any;
81
- export type PHPLoaderModule = {
82
- dependencyFilename: string;
83
- dependenciesTotalSize: number;
84
- init: (jsRuntime: string, options: EmscriptenOptions) => PHPRuntime;
85
- };
86
- export type EmscriptenOptions = {
87
- onAbort?: (message: string) => void;
88
- /**
89
- * Set to true for debugging tricky WebAssembly errors.
90
- */
91
- debug?: boolean;
92
- ENV?: Record<string, string>;
93
- locateFile?: (path: string) => string;
94
- noInitialRun?: boolean;
95
- print?: (message: string) => void;
96
- printErr?: (message: string) => void;
97
- quit?: (status: number, toThrow: any) => void;
98
- onRuntimeInitialized?: () => void;
99
- monitorRunDependencies?: (left: number) => void;
100
- onMessage?: (listener: EmscriptenMessageListener) => void;
101
- instantiateWasm?: (info: WebAssembly.Imports, receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void) => void;
102
- } & Record<string, any>;
103
- export type EmscriptenMessageListener = (type: string, data: string) => void;
104
- /** Other WebAssembly declarations, for compatibility with older versions of Typescript */
105
- export declare namespace Emscripten {
106
- export interface RootFS extends Emscripten.FileSystemInstance {
107
- filesystems: Record<string, Emscripten.FileSystemType>;
108
- }
109
- export interface FileSystemType {
110
- mount(mount: FS.Mount): FS.FSNode;
111
- syncfs(mount: FS.Mount, populate: () => unknown, done: (err?: number | null) => unknown): void;
112
- }
113
- export type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER";
114
- export type JSType = "number" | "string" | "array" | "boolean";
115
- export type TypeCompatibleWithC = number | string | any[] | boolean;
116
- export type CIntType = "i8" | "i16" | "i32" | "i64";
117
- export type CFloatType = "float" | "double";
118
- export type CPointerType = "i8*" | "i16*" | "i32*" | "i64*" | "float*" | "double*" | "*";
119
- export type CType = CIntType | CFloatType | CPointerType;
120
- export interface CCallOpts {
121
- async?: boolean | undefined;
122
- }
123
- type NamespaceToInstance<T> = {
124
- [K in keyof T]: T[K] extends (...args: any[]) => any ? T[K] : never;
125
- };
126
- export type FileSystemInstance = NamespaceToInstance<typeof FS> & {
127
- mkdirTree(path: string): void;
128
- lookupPath(path: string, opts?: any): FS.Lookup;
129
- };
130
- export interface EmscriptenModule {
131
- print(str: string): void;
132
- printErr(str: string): void;
133
- arguments: string[];
134
- environment: Emscripten.EnvironmentType;
135
- preInit: Array<{
136
- (): void;
137
- }>;
138
- preRun: Array<{
139
- (): void;
140
- }>;
141
- postRun: Array<{
142
- (): void;
143
- }>;
144
- onAbort: {
145
- (what: any): void;
146
- };
147
- onRuntimeInitialized: {
148
- (): void;
149
- };
150
- preinitializedWebGLContext: WebGLRenderingContext;
151
- noInitialRun: boolean;
152
- noExitRuntime: boolean;
153
- logReadFiles: boolean;
154
- filePackagePrefixURL: string;
155
- wasmBinary: ArrayBuffer;
156
- destroy(object: object): void;
157
- getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;
158
- instantiateWasm(imports: WebAssembly.Imports, successCallback: (module: WebAssembly.Instance) => void): WebAssembly.Exports | undefined;
159
- locateFile(url: string, scriptDirectory: string): string;
160
- onCustomMessage(event: MessageEvent): void;
161
- HEAP: Int32Array;
162
- IHEAP: Int32Array;
163
- FHEAP: Float64Array;
164
- HEAP8: Int8Array;
165
- HEAP16: Int16Array;
166
- HEAP32: Int32Array;
167
- HEAPU8: Uint8Array;
168
- HEAPU16: Uint16Array;
169
- HEAPU32: Uint32Array;
170
- HEAPF32: Float32Array;
171
- HEAPF64: Float64Array;
172
- HEAP64: BigInt64Array;
173
- HEAPU64: BigUint64Array;
174
- TOTAL_STACK: number;
175
- TOTAL_MEMORY: number;
176
- FAST_MEMORY: number;
177
- addOnPreRun(cb: () => any): void;
178
- addOnInit(cb: () => any): void;
179
- addOnPreMain(cb: () => any): void;
180
- addOnExit(cb: () => any): void;
181
- addOnPostRun(cb: () => any): void;
182
- preloadedImages: any;
183
- preloadedAudios: any;
184
- _malloc(size: number): number;
185
- _free(ptr: number): void;
186
- }
187
- /**
188
- * A factory function is generated when setting the `MODULARIZE` build option
189
- * to `1` in your Emscripten build. It return a Promise that resolves to an
190
- * initialized, ready-to-call `EmscriptenModule` instance.
191
- *
192
- * By default, the factory function will be named `Module`. It's recommended to
193
- * use the `EXPORT_ES6` option, in which the factory function will be the
194
- * default export. If used without `EXPORT_ES6`, the factory function will be a
195
- * global variable. You can rename the variable using the `EXPORT_NAME` build
196
- * option. It's left to you to export any global variables as needed in your
197
- * application's types.
198
- * @param moduleOverrides Default properties for the initialized module.
199
- */
200
- export type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (moduleOverrides?: Partial<T>) => Promise<T>;
201
- export namespace FS {
202
- interface Lookup {
203
- path: string;
204
- node: FSNode;
205
- }
206
- interface Analyze {
207
- isRoot: boolean;
208
- exists: boolean;
209
- error: Error;
210
- name: string;
211
- path: Lookup["path"];
212
- object: Lookup["node"];
213
- parentExists: boolean;
214
- parentPath: Lookup["path"];
215
- parentObject: Lookup["node"];
216
- }
217
- interface Mount {
218
- type: Emscripten.FileSystemType;
219
- opts: object;
220
- mountpoint: string;
221
- mounts: Mount[];
222
- root: FSNode;
223
- }
224
- class FSStream {
225
- constructor();
226
- object: FSNode;
227
- readonly isRead: boolean;
228
- readonly isWrite: boolean;
229
- readonly isAppend: boolean;
230
- flags: number;
231
- position: number;
232
- }
233
- class FSNode {
234
- parent: FSNode;
235
- mount: Mount;
236
- mounted?: Mount;
237
- id: number;
238
- name: string;
239
- mode: number;
240
- rdev: number;
241
- readMode: number;
242
- writeMode: number;
243
- constructor(parent: FSNode, name: string, mode: number, rdev: number);
244
- read: boolean;
245
- write: boolean;
246
- readonly isFolder: boolean;
247
- readonly isDevice: boolean;
248
- }
249
- interface ErrnoError extends Error {
250
- name: "ErronoError";
251
- errno: number;
252
- code: string;
253
- }
254
- function lookupPath(path: string, opts: any): Lookup;
255
- function getPath(node: FSNode): string;
256
- function analyzePath(path: string, dontResolveLastLink?: boolean): Analyze;
257
- function isFile(mode: number): boolean;
258
- function isDir(mode: number): boolean;
259
- function isLink(mode: number): boolean;
260
- function isChrdev(mode: number): boolean;
261
- function isBlkdev(mode: number): boolean;
262
- function isFIFO(mode: number): boolean;
263
- function isSocket(mode: number): boolean;
264
- function major(dev: number): number;
265
- function minor(dev: number): number;
266
- function makedev(ma: number, mi: number): number;
267
- function registerDevice(dev: number, ops: any): void;
268
- function syncfs(populate: boolean, callback: (e: any) => any): void;
269
- function syncfs(callback: (e: any) => any, populate?: boolean): void;
270
- function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any;
271
- function unmount(mountpoint: string): void;
272
- function mkdir(path: string, mode?: number): any;
273
- function mkdev(path: string, mode?: number, dev?: number): any;
274
- function symlink(oldpath: string, newpath: string): any;
275
- function rename(old_path: string, new_path: string): void;
276
- function rmdir(path: string): void;
277
- function readdir(path: string): any;
278
- function unlink(path: string): void;
279
- function readlink(path: string): string;
280
- function stat(path: string, dontFollow?: boolean): any;
281
- function lstat(path: string): any;
282
- function chmod(path: string, mode: number, dontFollow?: boolean): void;
283
- function lchmod(path: string, mode: number): void;
284
- function fchmod(fd: number, mode: number): void;
285
- function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void;
286
- function lchown(path: string, uid: number, gid: number): void;
287
- function fchown(fd: number, uid: number, gid: number): void;
288
- function truncate(path: string, len: number): void;
289
- function ftruncate(fd: number, len: number): void;
290
- function utime(path: string, atime: number, mtime: number): void;
291
- function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream;
292
- function close(stream: FSStream): void;
293
- function llseek(stream: FSStream, offset: number, whence: number): any;
294
- function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number;
295
- function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number;
296
- function allocate(stream: FSStream, offset: number, length: number): void;
297
- function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any;
298
- function ioctl(stream: FSStream, cmd: any, arg: any): any;
299
- function readFile(path: string, opts: {
300
- encoding: "binary";
301
- flags?: string | undefined;
302
- }): Uint8Array;
303
- function readFile(path: string, opts: {
304
- encoding: "utf8";
305
- flags?: string | undefined;
306
- }): string;
307
- function readFile(path: string, opts?: {
308
- flags?: string | undefined;
309
- }): Uint8Array;
310
- function writeFile(path: string, data: string | ArrayBufferView, opts?: {
311
- flags?: string | undefined;
312
- }): void;
313
- function cwd(): string;
314
- function chdir(path: string): void;
315
- function init(input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any)): void;
316
- function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode;
317
- function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void;
318
- function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode;
319
- }
320
- export const MEMFS: Emscripten.FileSystemType;
321
- export const NODEFS: Emscripten.FileSystemType;
322
- export const IDBFS: Emscripten.FileSystemType;
323
- type StringToType<R> = R extends Emscripten.JSType ? {
324
- number: number;
325
- string: string;
326
- array: number[] | string[] | boolean[] | Uint8Array | Int8Array;
327
- boolean: boolean;
328
- null: null;
329
- }[R] : never;
330
- type ArgsToType<T extends Array<Emscripten.JSType | null>> = Extract<{
331
- [P in keyof T]: StringToType<T[P]>;
332
- }, any[]>;
333
- type ReturnToType<R extends Emscripten.JSType | null> = R extends null ? null : StringToType<Exclude<R, null>>;
334
- export function cwrap<I extends Array<Emscripten.JSType | null> | [
335
- ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, opts?: Emscripten.CCallOpts): (...arg: ArgsToType<I>) => ReturnToType<R>;
336
- export function ccall<I extends Array<Emscripten.JSType | null> | [
337
- ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, args: ArgsToType<I>, opts?: Emscripten.CCallOpts): ReturnToType<R>;
338
- export function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void;
339
- export function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number;
340
- export function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number;
341
- export function stackAlloc(size: number): number;
342
- export function stackSave(): number;
343
- export function stackRestore(ptr: number): void;
344
- export function UTF8ToString(ptr: number, maxBytesToRead?: number): string;
345
- export function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void;
346
- export function lengthBytesUTF8(str: string): number;
347
- export function allocateUTF8(str: string): number;
348
- export function allocateUTF8OnStack(str: string): number;
349
- export function UTF16ToString(ptr: number): string;
350
- export function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void;
351
- export function lengthBytesUTF16(str: string): number;
352
- export function UTF32ToString(ptr: number): string;
353
- export function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void;
354
- export function lengthBytesUTF32(str: string): number;
355
- export function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[];
356
- export function intArrayToString(array: number[]): string;
357
- export function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void;
358
- export function writeArrayToMemory(array: number[], buffer: number): void;
359
- export function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void;
360
- export function addRunDependency(id: any): void;
361
- export function removeRunDependency(id: any): void;
362
- export function addFunction(func: (...args: any[]) => any, signature?: string): number;
363
- export function removeFunction(funcPtr: number): void;
364
- export const ALLOC_NORMAL: number;
365
- export const ALLOC_STACK: number;
366
- export const ALLOC_STATIC: number;
367
- export const ALLOC_DYNAMIC: number;
368
- export const ALLOC_NONE: number;
369
- export {};
370
- }
371
- export interface RmDirOptions {
372
- /**
373
- * If true, recursively removes the directory and all its contents.
374
- * Default: true.
375
- */
376
- recursive?: boolean;
377
- }
378
- export interface ListFilesOptions {
379
- /**
380
- * If true, prepend given folder path to all file names.
381
- * Default: false.
382
- */
383
- prependPath: boolean;
384
- }
385
- export interface SemaphoreOptions {
386
- /**
387
- * The maximum number of concurrent locks.
388
- */
389
- concurrency: number;
390
- /**
391
- * The maximum time to wait for a lock to become available.
392
- */
393
- timeout?: number;
394
- }
395
- declare class Semaphore {
396
- private _running;
397
- private concurrency;
398
- private timeout?;
399
- private queue;
400
- constructor({ concurrency, timeout }: SemaphoreOptions);
401
- get remaining(): number;
402
- get running(): number;
403
- acquire(): Promise<() => void>;
404
- run<T>(fn: () => T | Promise<T>): Promise<T>;
405
- }
406
- export type PHPFactoryOptions = {
407
- isPrimary: boolean;
408
- };
409
- export type PHPFactory = (options: PHPFactoryOptions) => Promise<PHP>;
410
- export interface ProcessManagerOptions {
411
- /**
412
- * The maximum number of PHP instances that can exist at
413
- * the same time.
414
- */
415
- maxPhpInstances?: number;
416
- /**
417
- * The number of milliseconds to wait for a PHP instance when
418
- * we have reached the maximum number of PHP instances and
419
- * cannot spawn a new one. If the timeout is reached, we assume
420
- * all the PHP instances are deadlocked and a throw MaxPhpInstancesError.
421
- *
422
- * Default: 5000
423
- */
424
- timeout?: number;
425
- /**
426
- * The primary PHP instance that's never killed. This instance
427
- * contains the reference filesystem used by all other PHP instances.
428
- */
429
- primaryPhp?: PHP;
430
- /**
431
- * A factory function used for spawning new PHP instances.
432
- */
433
- phpFactory?: PHPFactory;
434
- }
435
- export interface SpawnedPHP {
436
- php: PHP;
437
- reap: () => void;
438
- }
439
- declare class PHPProcessManager implements AsyncDisposable {
440
- private primaryPhp?;
441
- private primaryIdle;
442
- private nextInstance;
443
- /**
444
- * All spawned PHP instances, including the primary PHP instance.
445
- * Used for bookkeeping and reaping all instances on dispose.
446
- */
447
- private allInstances;
448
- private phpFactory?;
449
- private maxPhpInstances;
450
- private semaphore;
451
- constructor(options?: ProcessManagerOptions);
452
- /**
453
- * Get the primary PHP instance.
454
- *
455
- * If the primary PHP instance is not set, it will be spawned
456
- * using the provided phpFactory.
457
- *
458
- * @throws {Error} when called twice before the first call is resolved.
459
- */
460
- getPrimaryPhp(): Promise<PHP>;
461
- /**
462
- * Get a PHP instance.
463
- *
464
- * It could be either the primary PHP instance, an idle disposable PHP instance,
465
- * or a newly spawned PHP instance – depending on the resource availability.
466
- *
467
- * @throws {MaxPhpInstancesError} when the maximum number of PHP instances is reached
468
- * and the waiting timeout is exceeded.
469
- */
470
- acquirePHPInstance(): Promise<SpawnedPHP>;
471
- /**
472
- * Initiated spawning of a new PHP instance.
473
- * This function is synchronous on purpose – it needs to synchronously
474
- * add the spawn promise to the allInstances array without waiting
475
- * for PHP to spawn.
476
- */
477
- private spawn;
478
- /**
479
- * Actually acquires the lock and spawns a new PHP instance.
480
- */
481
- private doSpawn;
482
- [Symbol.asyncDispose](): Promise<void>;
483
- }
484
- export type RewriteRule = {
485
- match: RegExp;
486
- replacement: string;
487
- };
488
- export interface BaseConfiguration {
489
- /**
490
- * The directory in the PHP filesystem where the server will look
491
- * for the files to serve. Default: `/var/www`.
492
- */
493
- documentRoot?: string;
494
- /**
495
- * Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
496
- */
497
- absoluteUrl?: string;
498
- /**
499
- * Rewrite rules
500
- */
501
- rewriteRules?: RewriteRule[];
502
- }
503
- export type PHPRequestHandlerFactoryArgs = PHPFactoryOptions & {
504
- requestHandler: PHPRequestHandler;
505
- };
506
- export type PHPRequestHandlerConfiguration = BaseConfiguration & ({
507
- /**
508
- * PHPProcessManager is required because the request handler needs
509
- * to make a decision for each request.
510
- *
511
- * Static assets are served using the primary PHP's filesystem, even
512
- * when serving 100 static files concurrently. No new PHP interpreter
513
- * is ever created as there's no need for it.
514
- *
515
- * Dynamic PHP requests, however, require grabbing an available PHP
516
- * interpreter, and that's where the PHPProcessManager comes in.
517
- */
518
- processManager: PHPProcessManager;
519
- } | {
520
- phpFactory: (requestHandler: PHPRequestHandlerFactoryArgs) => Promise<PHP>;
521
- /**
522
- * The maximum number of PHP instances that can exist at
523
- * the same time.
524
- */
525
- maxPhpInstances?: number;
526
- });
527
- declare class PHPRequestHandler {
528
- #private;
529
- rewriteRules: RewriteRule[];
530
- processManager: PHPProcessManager;
531
- /**
532
- * The request handler needs to decide whether to serve a static asset or
533
- * run the PHP interpreter. For static assets it should just reuse the primary
534
- * PHP even if there's 50 concurrent requests to serve. However, for
535
- * dynamic PHP requests, it needs to grab an available interpreter.
536
- * Therefore, it cannot just accept PHP as an argument as serving requests
537
- * requires access to ProcessManager.
538
- *
539
- * @param php - The PHP instance.
540
- * @param config - Request Handler configuration.
541
- */
542
- constructor(config: PHPRequestHandlerConfiguration);
543
- getPrimaryPhp(): Promise<PHP>;
544
- /**
545
- * Converts a path to an absolute URL based at the PHPRequestHandler
546
- * root.
547
- *
548
- * @param path The server path to convert to an absolute URL.
549
- * @returns The absolute URL.
550
- */
551
- pathToInternalUrl(path: string): string;
552
- /**
553
- * Converts an absolute URL based at the PHPRequestHandler to a relative path
554
- * without the server pathname and scope.
555
- *
556
- * @param internalUrl An absolute URL based at the PHPRequestHandler root.
557
- * @returns The relative path.
558
- */
559
- internalUrlToPath(internalUrl: string): string;
560
- /**
561
- * The absolute URL of this PHPRequestHandler instance.
562
- */
563
- get absoluteUrl(): string;
564
- /**
565
- * The directory in the PHP filesystem where the server will look
566
- * for the files to serve. Default: `/var/www`.
567
- */
568
- get documentRoot(): string;
569
- /**
570
- * Serves the request – either by serving a static file, or by
571
- * dispatching it to the PHP runtime.
572
- *
573
- * The request() method mode behaves like a web server and only works if
574
- * the PHP was initialized with a `requestHandler` option (which the online version
575
- * of WordPress Playground does by default).
576
- *
577
- * In the request mode, you pass an object containing the request information
578
- * (method, headers, body, etc.) and the path to the PHP file to run:
579
- *
580
- * ```ts
581
- * const php = PHP.load('7.4', {
582
- * requestHandler: {
583
- * documentRoot: "/www"
584
- * }
585
- * })
586
- * php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
587
- * const result = await php.request({
588
- * method: "GET",
589
- * headers: {
590
- * "Content-Type": "text/plain"
591
- * },
592
- * body: "Hello world!",
593
- * path: "/www/index.php"
594
- * });
595
- * // result.text === "Hello world!"
596
- * ```
597
- *
598
- * The `request()` method cannot be used in conjunction with `cli()`.
599
- *
600
- * @example
601
- * ```js
602
- * const output = await php.request({
603
- * method: 'GET',
604
- * url: '/index.php',
605
- * headers: {
606
- * 'X-foo': 'bar',
607
- * },
608
- * body: {
609
- * foo: 'bar',
610
- * },
611
- * });
612
- * console.log(output.stdout); // "Hello world!"
613
- * ```
614
- *
615
- * @param request - PHP Request data.
616
- */
617
- request(request: PHPRequest): Promise<PHPResponse>;
618
- }
619
- declare const __private__dont__use: unique symbol;
620
- export type UnmountFunction = (() => Promise<any>) | (() => any);
621
- export type MountHandler = (php: PHP, FS: Emscripten.RootFS, vfsMountPoint: string) => UnmountFunction | Promise<UnmountFunction>;
622
- declare class PHP implements Disposable {
623
- #private;
624
- protected [__private__dont__use]: any;
625
- requestHandler?: PHPRequestHandler;
626
- /**
627
- * An exclusive lock that prevent multiple requests from running at
628
- * the same time.
629
- */
630
- semaphore: Semaphore;
631
- /**
632
- * Initializes a PHP runtime.
633
- *
634
- * @internal
635
- * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
636
- * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
637
- */
638
- constructor(PHPRuntimeId?: PHPRuntimeId);
639
- /**
640
- * Adds an event listener for a PHP event.
641
- * @param eventType - The type of event to listen for.
642
- * @param listener - The listener function to be called when the event is triggered.
643
- */
644
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
645
- /**
646
- * Removes an event listener for a PHP event.
647
- * @param eventType - The type of event to remove the listener from.
648
- * @param listener - The listener function to be removed.
649
- */
650
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
651
- dispatchEvent<Event extends PHPEvent>(event: Event): void;
652
- /**
653
- * Listens to message sent by the PHP code.
654
- *
655
- * To dispatch messages, call:
656
- *
657
- * post_message_to_js(string $data)
658
- *
659
- * Arguments:
660
- * $data (string) – Data to pass to JavaScript.
661
- *
662
- * @example
663
- *
664
- * ```ts
665
- * const php = await PHP.load('8.0');
666
- *
667
- * php.onMessage(
668
- * // The data is always passed as a string
669
- * function (data: string) {
670
- * // Let's decode and log the data:
671
- * console.log(JSON.parse(data));
672
- * }
673
- * );
674
- *
675
- * // Now that we have a listener in place, let's
676
- * // dispatch a message:
677
- * await php.run({
678
- * code: `<?php
679
- * post_message_to_js(
680
- * json_encode([
681
- * 'post_id' => '15',
682
- * 'post_title' => 'This is a blog post!'
683
- * ])
684
- * ));
685
- * `,
686
- * });
687
- * ```
688
- *
689
- * @param listener Callback function to handle the message.
690
- */
691
- onMessage(listener: MessageListener): void;
692
- setSpawnHandler(handler: SpawnHandler | string): Promise<void>;
693
- /** @deprecated Use PHPRequestHandler instead. */
694
- get absoluteUrl(): string;
695
- /** @deprecated Use PHPRequestHandler instead. */
696
- get documentRoot(): string;
697
- /** @deprecated Use PHPRequestHandler instead. */
698
- pathToInternalUrl(path: string): string;
699
- /** @deprecated Use PHPRequestHandler instead. */
700
- internalUrlToPath(internalUrl: string): string;
701
- initializeRuntime(runtimeId: PHPRuntimeId): void;
702
- /** @inheritDoc */
703
- setSapiName(newName: string): Promise<void>;
704
- /**
705
- * Changes the current working directory in the PHP filesystem.
706
- * This is the directory that will be used as the base for relative paths.
707
- * For example, if the current working directory is `/root/php`, and the
708
- * path is `data`, the absolute path will be `/root/php/data`.
709
- *
710
- * @param path - The new working directory.
711
- */
712
- chdir(path: string): void;
713
- /**
714
- * Do not use. Use new PHPRequestHandler() instead.
715
- * @deprecated
716
- */
717
- request(request: PHPRequest): Promise<PHPResponse>;
718
- /**
719
- * Runs PHP code.
720
- *
721
- * This low-level method directly interacts with the WebAssembly
722
- * PHP interpreter.
723
- *
724
- * Every time you call run(), it prepares the PHP
725
- * environment and:
726
- *
727
- * * Resets the internal PHP state
728
- * * Populates superglobals ($_SERVER, $_GET, etc.)
729
- * * Handles file uploads
730
- * * Populates input streams (stdin, argv, etc.)
731
- * * Sets the current working directory
732
- *
733
- * You can use run() in two primary modes:
734
- *
735
- * ### Code snippet mode
736
- *
737
- * In this mode, you pass a string containing PHP code to run.
738
- *
739
- * ```ts
740
- * const result = await php.run({
741
- * code: `<?php echo "Hello world!";`
742
- * });
743
- * // result.text === "Hello world!"
744
- * ```
745
- *
746
- * In this mode, information like __DIR__ or __FILE__ isn't very
747
- * useful because the code is not associated with any file.
748
- *
749
- * Under the hood, the PHP snippet is passed to the `zend_eval_string`
750
- * C function.
751
- *
752
- * ### File mode
753
- *
754
- * In the file mode, you pass a scriptPath and PHP executes a file
755
- * found at a that path:
756
- *
757
- * ```ts
758
- * php.writeFile(
759
- * "/www/index.php",
760
- * `<?php echo "Hello world!";"`
761
- * );
762
- * const result = await php.run({
763
- * scriptPath: "/www/index.php"
764
- * });
765
- * // result.text === "Hello world!"
766
- * ```
767
- *
768
- * In this mode, you can rely on path-related information like __DIR__
769
- * or __FILE__.
770
- *
771
- * Under the hood, the PHP file is executed with the `php_execute_script`
772
- * C function.
773
- *
774
- * The `run()` method cannot be used in conjunction with `cli()`.
775
- *
776
- * @example
777
- * ```js
778
- * const result = await php.run(`<?php
779
- * $fp = fopen('php://stderr', 'w');
780
- * fwrite($fp, "Hello, world!");
781
- * `);
782
- * // result.errors === "Hello, world!"
783
- * ```
784
- *
785
- * @param options - PHP runtime options.
786
- */
787
- run(request: PHPRunOptions): Promise<PHPResponse>;
788
- /**
789
- * Defines a constant in the PHP runtime.
790
- * @param key - The name of the constant.
791
- * @param value - The value of the constant.
792
- */
793
- defineConstant(key: string, value: string | boolean | number | null): void;
794
- /**
795
- * Recursively creates a directory with the given path in the PHP filesystem.
796
- * For example, if the path is `/root/php/data`, and `/root` already exists,
797
- * it will create the directories `/root/php` and `/root/php/data`.
798
- *
799
- * @param path - The directory path to create.
800
- */
801
- mkdir(path: string): void;
802
- /**
803
- * @deprecated Use mkdir instead.
804
- */
805
- mkdirTree(path: string): void;
806
- /**
807
- * Reads a file from the PHP filesystem and returns it as a string.
808
- *
809
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
810
- * @param path - The file path to read.
811
- * @returns The file contents.
812
- */
813
- readFileAsText(path: string): string;
814
- /**
815
- * Reads a file from the PHP filesystem and returns it as an array buffer.
816
- *
817
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
818
- * @param path - The file path to read.
819
- * @returns The file contents.
820
- */
821
- readFileAsBuffer(path: string): Uint8Array;
822
- /**
823
- * Overwrites data in a file in the PHP filesystem.
824
- * Creates a new file if one doesn't exist yet.
825
- *
826
- * @param path - The file path to write to.
827
- * @param data - The data to write to the file.
828
- */
829
- writeFile(path: string, data: string | Uint8Array): void;
830
- /**
831
- * Removes a file from the PHP filesystem.
832
- *
833
- * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
834
- * @param path - The file path to remove.
835
- */
836
- unlink(path: string): void;
837
- /**
838
- * Moves a file or directory in the PHP filesystem to a
839
- * new location.
840
- *
841
- * @param oldPath The path to rename.
842
- * @param newPath The new path.
843
- */
844
- mv(fromPath: string, toPath: string): void;
845
- /**
846
- * Removes a directory from the PHP filesystem.
847
- *
848
- * @param path The directory path to remove.
849
- * @param options Options for the removal.
850
- */
851
- rmdir(path: string, options?: RmDirOptions): void;
852
- /**
853
- * Lists the files and directories in the given directory.
854
- *
855
- * @param path - The directory path to list.
856
- * @param options - Options for the listing.
857
- * @returns The list of files and directories in the given directory.
858
- */
859
- listFiles(path: string, options?: ListFilesOptions): string[];
860
- /**
861
- * Checks if a directory exists in the PHP filesystem.
862
- *
863
- * @param path – The path to check.
864
- * @returns True if the path is a directory, false otherwise.
865
- */
866
- isDir(path: string): boolean;
867
- /**
868
- * Checks if a file (or a directory) exists in the PHP filesystem.
869
- *
870
- * @param path - The file path to check.
871
- * @returns True if the file exists, false otherwise.
872
- */
873
- fileExists(path: string): boolean;
874
- /**
875
- * Hot-swaps the PHP runtime for a new one without
876
- * interrupting the operations of this PHP instance.
877
- *
878
- * @param runtime
879
- * @param cwd. Internal, the VFS path to recreate in the new runtime.
880
- * This arg is temporary and will be removed once BasePHP
881
- * is fully decoupled from the request handler and
882
- * accepts a constructor-level cwd argument.
883
- */
884
- hotSwapPHPRuntime(runtime: number, cwd?: string): void;
885
- /**
886
- * Mounts a filesystem to a given path in the PHP filesystem.
887
- *
888
- * @param virtualFSPath - Where to mount it in the PHP virtual filesystem.
889
- * @param mountHandler - The mount handler to use.
890
- * @return Unmount function to unmount the filesystem.
891
- */
892
- mount(virtualFSPath: string, mountHandler: MountHandler): Promise<UnmountFunction>;
893
- /**
894
- * Starts a PHP CLI session with given arguments.
895
- *
896
- * This method can only be used when PHP was compiled with the CLI SAPI
897
- * and it cannot be used in conjunction with `run()`.
898
- *
899
- * Once this method finishes running, the PHP instance is no
900
- * longer usable and should be discarded. This is because PHP
901
- * internally cleans up all the resources and calls exit().
902
- *
903
- * @param argv - The arguments to pass to the CLI.
904
- * @returns The exit code of the CLI session.
905
- */
906
- cli(argv: string[]): Promise<number>;
907
- setSkipShebang(shouldSkip: boolean): void;
908
- exit(code?: number): void;
909
- [Symbol.dispose](): void;
910
- }
911
- export type LimitedPHPApi = Pick<PHP, "request" | "defineConstant" | "addEventListener" | "removeEventListener" | "mkdir" | "mkdirTree" | "readFileAsText" | "readFileAsBuffer" | "writeFile" | "unlink" | "mv" | "rmdir" | "listFiles" | "isDir" | "fileExists" | "chdir" | "run" | "onMessage"> & {
912
- documentRoot: PHP["documentRoot"];
913
- absoluteUrl: PHP["absoluteUrl"];
914
- };
915
- declare class PHPWorker implements LimitedPHPApi {
916
- /** @inheritDoc @php-wasm/universal!RequestHandler.absoluteUrl */
917
- absoluteUrl: string;
918
- /** @inheritDoc @php-wasm/universal!RequestHandler.documentRoot */
919
- documentRoot: string;
920
- /** @inheritDoc */
921
- constructor(requestHandler?: PHPRequestHandler, monitor?: EmscriptenDownloadMonitor);
922
- __internal_setRequestHandler(requestHandler: PHPRequestHandler): void;
923
- /**
924
- * @internal
925
- * @deprecated
926
- * Do not use this method directly in the code consuming
927
- * the web API. It will change or even be removed without
928
- * a warning.
929
- */
930
- protected __internal_getPHP(): PHP | undefined;
931
- setPrimaryPHP(php: PHP): Promise<void>;
932
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.pathToInternalUrl */
933
- pathToInternalUrl(path: string): string;
934
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.internalUrlToPath */
935
- internalUrlToPath(internalUrl: string): string;
936
- /**
937
- * The onDownloadProgress event listener.
938
- */
939
- onDownloadProgress(callback: (progress: CustomEvent<ProgressEvent>) => void): Promise<void>;
940
- /** @inheritDoc @php-wasm/universal!PHP.mv */
941
- mv(fromPath: string, toPath: string): Promise<void>;
942
- /** @inheritDoc @php-wasm/universal!PHP.rmdir */
943
- rmdir(path: string, options?: RmDirOptions): Promise<void>;
944
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.request */
945
- request(request: PHPRequest): Promise<PHPResponse>;
946
- /** @inheritDoc @php-wasm/universal!/PHP.run */
947
- run(request: PHPRunOptions): Promise<PHPResponse>;
948
- /** @inheritDoc @php-wasm/universal!/PHP.chdir */
949
- chdir(path: string): void;
950
- /** @inheritDoc @php-wasm/universal!/PHP.setSapiName */
951
- setSapiName(newName: string): void;
952
- /** @inheritDoc @php-wasm/universal!/PHP.mkdir */
953
- mkdir(path: string): void;
954
- /** @inheritDoc @php-wasm/universal!/PHP.mkdirTree */
955
- mkdirTree(path: string): void;
956
- /** @inheritDoc @php-wasm/universal!/PHP.readFileAsText */
957
- readFileAsText(path: string): string;
958
- /** @inheritDoc @php-wasm/universal!/PHP.readFileAsBuffer */
959
- readFileAsBuffer(path: string): Uint8Array;
960
- /** @inheritDoc @php-wasm/universal!/PHP.writeFile */
961
- writeFile(path: string, data: string | Uint8Array): void;
962
- /** @inheritDoc @php-wasm/universal!/PHP.unlink */
963
- unlink(path: string): void;
964
- /** @inheritDoc @php-wasm/universal!/PHP.listFiles */
965
- listFiles(path: string, options?: ListFilesOptions): string[];
966
- /** @inheritDoc @php-wasm/universal!/PHP.isDir */
967
- isDir(path: string): boolean;
968
- /** @inheritDoc @php-wasm/universal!/PHP.fileExists */
969
- fileExists(path: string): boolean;
970
- /** @inheritDoc @php-wasm/universal!/PHP.onMessage */
971
- onMessage(listener: MessageListener): void;
972
- /** @inheritDoc @php-wasm/universal!/PHP.defineConstant */
973
- defineConstant(key: string, value: string | boolean | number | null): void;
974
- /** @inheritDoc @php-wasm/universal!/PHP.addEventListener */
975
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
976
- /** @inheritDoc @php-wasm/universal!/PHP.removeEventListener */
977
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
978
- }
979
- /**
980
- * Represents an event related to the PHP request.
981
- */
982
- export interface PHPRequestEndEvent {
983
- type: "request.end";
984
- }
985
- /**
986
- * Represents an error event related to the PHP request.
987
- */
988
- export interface PHPRequestErrorEvent {
989
- type: "request.error";
990
- error: Error;
991
- source?: "request" | "php-wasm";
992
- }
993
- /**
994
- * Represents a PHP runtime initialization event.
995
- */
996
- export interface PHPRuntimeInitializedEvent {
997
- type: "runtime.initialized";
998
- }
999
- /**
1000
- * Represents a PHP runtime destruction event.
1001
- */
1002
- export interface PHPRuntimeBeforeDestroyEvent {
1003
- type: "runtime.beforedestroy";
1004
- }
1005
- /**
1006
- * Represents an event related to the PHP instance.
1007
- * This is intentionally not an extension of CustomEvent
1008
- * to make it isomorphic between different JavaScript runtimes.
1009
- */
1010
- export type PHPEvent = PHPRequestEndEvent | PHPRequestErrorEvent | PHPRuntimeInitializedEvent | PHPRuntimeBeforeDestroyEvent;
1011
- /**
1012
- * A callback function that handles PHP events.
1013
- */
1014
- export type PHPEventListener = (event: PHPEvent) => void;
1015
- export type MessageListener = (data: string) => Promise<string | Uint8Array | void> | string | void;
1016
- export interface EventEmitter {
1017
- on(event: string, listener: (...args: any[]) => void): this;
1018
- emit(event: string, ...args: any[]): boolean;
1019
- }
1020
- export type ChildProcess = EventEmitter & {
1021
- stdout: EventEmitter;
1022
- stderr: EventEmitter;
1023
- };
1024
- export type SpawnHandler = (command: string, args: string[]) => ChildProcess;
1025
- export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
1026
- export type PHPRequestHeaders = Record<string, string>;
1027
- export interface PHPRequest {
1028
- /**
1029
- * Request method. Default: `GET`.
1030
- */
1031
- method?: HTTPMethod;
1032
- /**
1033
- * Request path or absolute URL.
1034
- */
1035
- url: string;
1036
- /**
1037
- * Request headers.
1038
- */
1039
- headers?: PHPRequestHeaders;
1040
- /**
1041
- * Request body.
1042
- * If an object is given, the request will be encoded as multipart
1043
- * and sent with a `multipart/form-data` header.
1044
- */
1045
- body?: string | Uint8Array | Record<string, string | Uint8Array | File>;
1046
- }
1047
- export interface PHPRunOptions {
1048
- /**
1049
- * Request path following the domain:port part.
1050
- */
1051
- relativeUri?: string;
1052
- /**
1053
- * Path of the .php file to execute.
1054
- */
1055
- scriptPath?: string;
1056
- /**
1057
- * Request protocol.
1058
- */
1059
- protocol?: string;
1060
- /**
1061
- * Request method. Default: `GET`.
1062
- */
1063
- method?: HTTPMethod;
1064
- /**
1065
- * Request headers.
1066
- */
1067
- headers?: PHPRequestHeaders;
1068
- /**
1069
- * Request body.
1070
- */
1071
- body?: string | Uint8Array;
1072
- /**
1073
- * Environment variables to set for this run.
1074
- */
1075
- env?: Record<string, string>;
1076
- /**
1077
- * $_SERVER entries to set for this run.
1078
- */
1079
- $_SERVER?: Record<string, string>;
1080
- /**
1081
- * The code snippet to eval instead of a php file.
1082
- */
1083
- code?: string;
1084
- }
1085
- declare const SupportedPHPVersions: readonly [
1086
- "8.3",
1087
- "8.2",
1088
- "8.1",
1089
- "8.0",
1090
- "7.4",
1091
- "7.3",
1092
- "7.2",
1093
- "7.1",
1094
- "7.0"
1095
- ];
1096
- export type SupportedPHPVersion = (typeof SupportedPHPVersions)[number];
1097
- interface LoaderOptions {
1098
- emscriptenOptions?: EmscriptenOptions;
1099
- onPhpLoaderModuleLoaded?: (module: PHPLoaderModule) => void;
1100
- /** @deprecated To be replaced with `extensions` in the future */
1101
- loadAllExtensions?: boolean;
1102
- }
1103
- export declare function loadWebRuntime(phpVersion: SupportedPHPVersion, options?: LoaderOptions): Promise<number>;
1104
- /**
1105
- * Loads the PHP loader module for the given PHP version.
1106
- *
1107
- * @param version The PHP version to load.
1108
- * @param variant Internal. Do not use.
1109
- * @returns The PHP loader module.
1110
- */
1111
- export declare function getPHPLoaderModule(version?: SupportedPHPVersion, variant?: "light" | "kitchen-sink"): Promise<PHPLoaderModule>;
1112
- /**
1113
- * Run this in the main application to register the service worker or
1114
- * reload the registered worker if the app expects a different version
1115
- * than the currently registered one.
1116
- *
1117
- * @param {string} scriptUrl The URL of the service worker script.
1118
- * @param {string} expectedVersion The expected version of the service worker script. If
1119
- * mismatched with the actual version, the service worker
1120
- * will be re-registered.
1121
- */
1122
- export declare function registerServiceWorker<Client extends Remote<PHPWorker>>(phpApi: Client, scope: string, scriptUrl: string): Promise<void>;
1123
- /**
1124
- * Setup a postMessage relay between the parent window and a nested iframe.
1125
- *
1126
- * When we're running a Playground instance inside an iframe, sometimes that
1127
- * iframe will contain another iframe and so on. The parent application, however,
1128
- * needs to be able to communicate with the innermost iframe. This function relays
1129
- * the communication both ways. Call it in in every iframe layer between the topmost
1130
- * window and the innermost iframe.
1131
- *
1132
- * @param nestedFrame The nested iframe element
1133
- * @param expectedOrigin The origin that the nested iframe is expected to be on. If not
1134
- * provided, any origin is allowed.
1135
- */
1136
- export declare function setupPostMessageRelay(nestedFrame: HTMLIFrameElement, expectedOrigin?: string): void;
1137
- /**
1138
- * Spawns a new Worker Thread.
1139
- *
1140
- * @param workerUrl The absolute URL of the worker script.
1141
- * @param config
1142
- * @returns The spawned Worker Thread.
1143
- */
1144
- export declare function spawnPHPWorkerThread(workerUrl: string, startupOptions?: Record<string, string | string[]>): Promise<Worker>;
1145
- export interface MountOptions {
1146
- initialSync: {
1147
- direction?: "opfs-to-memfs" | "memfs-to-opfs";
1148
- onProgress?: SyncProgressCallback;
1149
- };
1150
- }
1151
- export type SyncProgress = {
1152
- /** The number of files that have been synced. */
1153
- files: number;
1154
- /** The number of all files that need to be synced. */
1155
- total: number;
1156
- };
1157
- export type SyncProgressCallback = (progress: SyncProgress) => void;
1158
- export declare function createDirectoryHandleMountHandler(handle: FileSystemDirectoryHandle, options?: MountOptions): MountHandler;
1159
-
1160
- export {};
1
+ export * from './lib';