@wp-playground/client 0.7.20 → 0.9.2

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.
Files changed (4) hide show
  1. package/index.cjs +70 -105
  2. package/index.d.ts +919 -677
  3. package/index.js +3250 -3904
  4. package/package.json +2 -2
package/index.d.ts CHANGED
@@ -195,156 +195,664 @@ export declare class PHPResponse implements PHPResponseData {
195
195
  */
196
196
  get text(): string;
197
197
  }
198
- /**
199
- * Represents an event related to the PHP request.
200
- */
201
- export interface PHPRequestEndEvent {
202
- type: "request.end";
198
+ export type RuntimeType = "NODE" | "WEB" | "WORKER";
199
+ export type PHPRuntimeId = number;
200
+ /** Other WebAssembly declarations, for compatibility with older versions of Typescript */
201
+ export declare namespace Emscripten {
202
+ export interface RootFS extends Emscripten.FileSystemInstance {
203
+ filesystems: Record<string, Emscripten.FileSystemType>;
204
+ }
205
+ export interface FileSystemType {
206
+ mount(mount: FS.Mount): FS.FSNode;
207
+ syncfs(mount: FS.Mount, populate: () => unknown, done: (err?: number | null) => unknown): void;
208
+ }
209
+ export type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER";
210
+ export type JSType = "number" | "string" | "array" | "boolean";
211
+ export type TypeCompatibleWithC = number | string | any[] | boolean;
212
+ export type CIntType = "i8" | "i16" | "i32" | "i64";
213
+ export type CFloatType = "float" | "double";
214
+ export type CPointerType = "i8*" | "i16*" | "i32*" | "i64*" | "float*" | "double*" | "*";
215
+ export type CType = CIntType | CFloatType | CPointerType;
216
+ export interface CCallOpts {
217
+ async?: boolean | undefined;
218
+ }
219
+ type NamespaceToInstance<T> = {
220
+ [K in keyof T]: T[K] extends (...args: any[]) => any ? T[K] : never;
221
+ };
222
+ export type FileSystemInstance = NamespaceToInstance<typeof FS> & {
223
+ mkdirTree(path: string): void;
224
+ lookupPath(path: string, opts?: any): FS.Lookup;
225
+ };
226
+ export interface EmscriptenModule {
227
+ print(str: string): void;
228
+ printErr(str: string): void;
229
+ arguments: string[];
230
+ environment: Emscripten.EnvironmentType;
231
+ preInit: Array<{
232
+ (): void;
233
+ }>;
234
+ preRun: Array<{
235
+ (): void;
236
+ }>;
237
+ postRun: Array<{
238
+ (): void;
239
+ }>;
240
+ onAbort: {
241
+ (what: any): void;
242
+ };
243
+ onRuntimeInitialized: {
244
+ (): void;
245
+ };
246
+ preinitializedWebGLContext: WebGLRenderingContext;
247
+ noInitialRun: boolean;
248
+ noExitRuntime: boolean;
249
+ logReadFiles: boolean;
250
+ filePackagePrefixURL: string;
251
+ wasmBinary: ArrayBuffer;
252
+ destroy(object: object): void;
253
+ getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;
254
+ instantiateWasm(imports: WebAssembly.Imports, successCallback: (module: WebAssembly.Instance) => void): WebAssembly.Exports | undefined;
255
+ locateFile(url: string, scriptDirectory: string): string;
256
+ onCustomMessage(event: MessageEvent): void;
257
+ HEAP: Int32Array;
258
+ IHEAP: Int32Array;
259
+ FHEAP: Float64Array;
260
+ HEAP8: Int8Array;
261
+ HEAP16: Int16Array;
262
+ HEAP32: Int32Array;
263
+ HEAPU8: Uint8Array;
264
+ HEAPU16: Uint16Array;
265
+ HEAPU32: Uint32Array;
266
+ HEAPF32: Float32Array;
267
+ HEAPF64: Float64Array;
268
+ HEAP64: BigInt64Array;
269
+ HEAPU64: BigUint64Array;
270
+ TOTAL_STACK: number;
271
+ TOTAL_MEMORY: number;
272
+ FAST_MEMORY: number;
273
+ addOnPreRun(cb: () => any): void;
274
+ addOnInit(cb: () => any): void;
275
+ addOnPreMain(cb: () => any): void;
276
+ addOnExit(cb: () => any): void;
277
+ addOnPostRun(cb: () => any): void;
278
+ preloadedImages: any;
279
+ preloadedAudios: any;
280
+ _malloc(size: number): number;
281
+ _free(ptr: number): void;
282
+ }
283
+ /**
284
+ * A factory function is generated when setting the `MODULARIZE` build option
285
+ * to `1` in your Emscripten build. It return a Promise that resolves to an
286
+ * initialized, ready-to-call `EmscriptenModule` instance.
287
+ *
288
+ * By default, the factory function will be named `Module`. It's recommended to
289
+ * use the `EXPORT_ES6` option, in which the factory function will be the
290
+ * default export. If used without `EXPORT_ES6`, the factory function will be a
291
+ * global variable. You can rename the variable using the `EXPORT_NAME` build
292
+ * option. It's left to you to export any global variables as needed in your
293
+ * application's types.
294
+ * @param moduleOverrides Default properties for the initialized module.
295
+ */
296
+ export type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (moduleOverrides?: Partial<T>) => Promise<T>;
297
+ export namespace FS {
298
+ interface Lookup {
299
+ path: string;
300
+ node: FSNode;
301
+ }
302
+ interface Analyze {
303
+ isRoot: boolean;
304
+ exists: boolean;
305
+ error: Error;
306
+ name: string;
307
+ path: Lookup["path"];
308
+ object: Lookup["node"];
309
+ parentExists: boolean;
310
+ parentPath: Lookup["path"];
311
+ parentObject: Lookup["node"];
312
+ }
313
+ interface Mount {
314
+ type: Emscripten.FileSystemType;
315
+ opts: object;
316
+ mountpoint: string;
317
+ mounts: Mount[];
318
+ root: FSNode;
319
+ }
320
+ class FSStream {
321
+ constructor();
322
+ object: FSNode;
323
+ readonly isRead: boolean;
324
+ readonly isWrite: boolean;
325
+ readonly isAppend: boolean;
326
+ flags: number;
327
+ position: number;
328
+ }
329
+ class FSNode {
330
+ parent: FSNode;
331
+ mount: Mount;
332
+ mounted?: Mount;
333
+ id: number;
334
+ name: string;
335
+ mode: number;
336
+ rdev: number;
337
+ readMode: number;
338
+ writeMode: number;
339
+ constructor(parent: FSNode, name: string, mode: number, rdev: number);
340
+ read: boolean;
341
+ write: boolean;
342
+ readonly isFolder: boolean;
343
+ readonly isDevice: boolean;
344
+ }
345
+ interface ErrnoError extends Error {
346
+ name: "ErronoError";
347
+ errno: number;
348
+ code: string;
349
+ }
350
+ function lookupPath(path: string, opts: any): Lookup;
351
+ function getPath(node: FSNode): string;
352
+ function analyzePath(path: string, dontResolveLastLink?: boolean): Analyze;
353
+ function isFile(mode: number): boolean;
354
+ function isDir(mode: number): boolean;
355
+ function isLink(mode: number): boolean;
356
+ function isChrdev(mode: number): boolean;
357
+ function isBlkdev(mode: number): boolean;
358
+ function isFIFO(mode: number): boolean;
359
+ function isSocket(mode: number): boolean;
360
+ function major(dev: number): number;
361
+ function minor(dev: number): number;
362
+ function makedev(ma: number, mi: number): number;
363
+ function registerDevice(dev: number, ops: any): void;
364
+ function syncfs(populate: boolean, callback: (e: any) => any): void;
365
+ function syncfs(callback: (e: any) => any, populate?: boolean): void;
366
+ function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any;
367
+ function unmount(mountpoint: string): void;
368
+ function mkdir(path: string, mode?: number): any;
369
+ function mkdev(path: string, mode?: number, dev?: number): any;
370
+ function symlink(oldpath: string, newpath: string): any;
371
+ function rename(old_path: string, new_path: string): void;
372
+ function rmdir(path: string): void;
373
+ function readdir(path: string): any;
374
+ function unlink(path: string): void;
375
+ function readlink(path: string): string;
376
+ function stat(path: string, dontFollow?: boolean): any;
377
+ function lstat(path: string): any;
378
+ function chmod(path: string, mode: number, dontFollow?: boolean): void;
379
+ function lchmod(path: string, mode: number): void;
380
+ function fchmod(fd: number, mode: number): void;
381
+ function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void;
382
+ function lchown(path: string, uid: number, gid: number): void;
383
+ function fchown(fd: number, uid: number, gid: number): void;
384
+ function truncate(path: string, len: number): void;
385
+ function ftruncate(fd: number, len: number): void;
386
+ function utime(path: string, atime: number, mtime: number): void;
387
+ function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream;
388
+ function close(stream: FSStream): void;
389
+ function llseek(stream: FSStream, offset: number, whence: number): any;
390
+ function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number;
391
+ function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number;
392
+ function allocate(stream: FSStream, offset: number, length: number): void;
393
+ function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any;
394
+ function ioctl(stream: FSStream, cmd: any, arg: any): any;
395
+ function readFile(path: string, opts: {
396
+ encoding: "binary";
397
+ flags?: string | undefined;
398
+ }): Uint8Array;
399
+ function readFile(path: string, opts: {
400
+ encoding: "utf8";
401
+ flags?: string | undefined;
402
+ }): string;
403
+ function readFile(path: string, opts?: {
404
+ flags?: string | undefined;
405
+ }): Uint8Array;
406
+ function writeFile(path: string, data: string | ArrayBufferView, opts?: {
407
+ flags?: string | undefined;
408
+ }): void;
409
+ function cwd(): string;
410
+ function chdir(path: string): void;
411
+ function init(input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any)): void;
412
+ function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode;
413
+ function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void;
414
+ function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode;
415
+ }
416
+ export const MEMFS: Emscripten.FileSystemType;
417
+ export const NODEFS: Emscripten.FileSystemType;
418
+ export const IDBFS: Emscripten.FileSystemType;
419
+ type StringToType<R> = R extends Emscripten.JSType ? {
420
+ number: number;
421
+ string: string;
422
+ array: number[] | string[] | boolean[] | Uint8Array | Int8Array;
423
+ boolean: boolean;
424
+ null: null;
425
+ }[R] : never;
426
+ type ArgsToType<T extends Array<Emscripten.JSType | null>> = Extract<{
427
+ [P in keyof T]: StringToType<T[P]>;
428
+ }, any[]>;
429
+ type ReturnToType<R extends Emscripten.JSType | null> = R extends null ? null : StringToType<Exclude<R, null>>;
430
+ export function cwrap<I extends Array<Emscripten.JSType | null> | [
431
+ ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, opts?: Emscripten.CCallOpts): (...arg: ArgsToType<I>) => ReturnToType<R>;
432
+ export function ccall<I extends Array<Emscripten.JSType | null> | [
433
+ ], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, args: ArgsToType<I>, opts?: Emscripten.CCallOpts): ReturnToType<R>;
434
+ export function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void;
435
+ export function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number;
436
+ export function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number;
437
+ export function stackAlloc(size: number): number;
438
+ export function stackSave(): number;
439
+ export function stackRestore(ptr: number): void;
440
+ export function UTF8ToString(ptr: number, maxBytesToRead?: number): string;
441
+ export function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void;
442
+ export function lengthBytesUTF8(str: string): number;
443
+ export function allocateUTF8(str: string): number;
444
+ export function allocateUTF8OnStack(str: string): number;
445
+ export function UTF16ToString(ptr: number): string;
446
+ export function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void;
447
+ export function lengthBytesUTF16(str: string): number;
448
+ export function UTF32ToString(ptr: number): string;
449
+ export function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void;
450
+ export function lengthBytesUTF32(str: string): number;
451
+ export function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[];
452
+ export function intArrayToString(array: number[]): string;
453
+ export function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void;
454
+ export function writeArrayToMemory(array: number[], buffer: number): void;
455
+ export function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void;
456
+ export function addRunDependency(id: any): void;
457
+ export function removeRunDependency(id: any): void;
458
+ export function addFunction(func: (...args: any[]) => any, signature?: string): number;
459
+ export function removeFunction(funcPtr: number): void;
460
+ export const ALLOC_NORMAL: number;
461
+ export const ALLOC_STACK: number;
462
+ export const ALLOC_STATIC: number;
463
+ export const ALLOC_DYNAMIC: number;
464
+ export const ALLOC_NONE: number;
465
+ export {};
203
466
  }
204
- /**
205
- * Represents an error event related to the PHP request.
206
- */
207
- export interface PHPRequestErrorEvent {
208
- type: "request.error";
209
- error: Error;
210
- source?: "request" | "php-wasm";
467
+ export interface RmDirOptions {
468
+ /**
469
+ * If true, recursively removes the directory and all its contents.
470
+ * Default: true.
471
+ */
472
+ recursive?: boolean;
211
473
  }
212
- /**
213
- * Represents a PHP runtime initialization event.
214
- */
215
- export interface PHPRuntimeInitializedEvent {
216
- type: "runtime.initialized";
474
+ export interface ListFilesOptions {
475
+ /**
476
+ * If true, prepend given folder path to all file names.
477
+ * Default: false.
478
+ */
479
+ prependPath: boolean;
217
480
  }
218
- /**
219
- * Represents a PHP runtime destruction event.
220
- */
221
- export interface PHPRuntimeBeforeDestroyEvent {
222
- type: "runtime.beforedestroy";
481
+ export interface SemaphoreOptions {
482
+ /**
483
+ * The maximum number of concurrent locks.
484
+ */
485
+ concurrency: number;
486
+ /**
487
+ * The maximum time to wait for a lock to become available.
488
+ */
489
+ timeout?: number;
223
490
  }
224
- /**
225
- * Represents an event related to the PHP instance.
226
- * This is intentionally not an extension of CustomEvent
227
- * to make it isomorphic between different JavaScript runtimes.
228
- */
229
- export type PHPEvent = PHPRequestEndEvent | PHPRequestErrorEvent | PHPRuntimeInitializedEvent | PHPRuntimeBeforeDestroyEvent;
230
- /**
231
- * A callback function that handles PHP events.
232
- */
233
- export type PHPEventListener = (event: PHPEvent) => void;
234
- export interface IsomorphicLocalPHP {
235
- /** @deprecated Use PHPRequestHandler instead. */
236
- request(request: PHPRequest): Promise<PHPResponse>;
237
- /** @deprecated Use PHPRequestHandler instead. */
238
- pathToInternalUrl(path: string): string;
239
- /** @deprecated Use PHPRequestHandler instead. */
240
- internalUrlToPath(internalUrl: string): string;
241
- /** @deprecated Use PHPRequestHandler instead. */
242
- absoluteUrl: string;
243
- /** @deprecated Use PHPRequestHandler instead. */
244
- documentRoot: string;
491
+ declare class Semaphore {
492
+ private _running;
493
+ private concurrency;
494
+ private timeout?;
495
+ private queue;
496
+ constructor({ concurrency, timeout }: SemaphoreOptions);
497
+ get remaining(): number;
498
+ get running(): number;
499
+ acquire(): Promise<() => void>;
500
+ run<T>(fn: () => T | Promise<T>): Promise<T>;
501
+ }
502
+ export declare function phpVar(value: unknown): string;
503
+ export declare function phpVars<T extends Record<string, unknown>>(vars: T): Record<keyof T, string>;
504
+ export type PHPFactoryOptions = {
505
+ isPrimary: boolean;
506
+ };
507
+ export type PHPFactory = (options: PHPFactoryOptions) => Promise<PHP>;
508
+ export interface ProcessManagerOptions {
245
509
  /**
246
- * Sets the SAPI name exposed by the PHP module.
247
- * @param newName - The new SAPI name.
510
+ * The maximum number of PHP instances that can exist at
511
+ * the same time.
248
512
  */
249
- setSapiName(newName: string): void;
513
+ maxPhpInstances?: number;
250
514
  /**
251
- * Defines a constant in the PHP runtime.
252
- * @param key - The name of the constant.
253
- * @param value - The value of the constant.
515
+ * The number of milliseconds to wait for a PHP instance when
516
+ * we have reached the maximum number of PHP instances and
517
+ * cannot spawn a new one. If the timeout is reached, we assume
518
+ * all the PHP instances are deadlocked and a throw MaxPhpInstancesError.
519
+ *
520
+ * Default: 5000
254
521
  */
255
- defineConstant(key: string, value: boolean | string | number | null): void;
522
+ timeout?: number;
256
523
  /**
257
- * Adds an event listener for a PHP event.
258
- * @param eventType - The type of event to listen for.
259
- * @param listener - The listener function to be called when the event is triggered.
524
+ * The primary PHP instance that's never killed. This instance
525
+ * contains the reference filesystem used by all other PHP instances.
260
526
  */
261
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
527
+ primaryPhp?: PHP;
262
528
  /**
263
- * Removes an event listener for a PHP event.
264
- * @param eventType - The type of event to remove the listener from.
265
- * @param listener - The listener function to be removed.
529
+ * A factory function used for spawning new PHP instances.
266
530
  */
267
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
531
+ phpFactory?: PHPFactory;
532
+ }
533
+ export interface SpawnedPHP {
534
+ php: PHP;
535
+ reap: () => void;
536
+ }
537
+ declare class PHPProcessManager implements AsyncDisposable {
538
+ private primaryPhp?;
539
+ private primaryIdle;
540
+ private nextInstance;
268
541
  /**
269
- * Recursively creates a directory with the given path in the PHP filesystem.
270
- * For example, if the path is `/root/php/data`, and `/root` already exists,
271
- * it will create the directories `/root/php` and `/root/php/data`.
272
- *
273
- * @param path - The directory path to create.
542
+ * All spawned PHP instances, including the primary PHP instance.
543
+ * Used for bookkeeping and reaping all instances on dispose.
274
544
  */
275
- mkdir(path: string): void;
545
+ private allInstances;
546
+ private phpFactory?;
547
+ private maxPhpInstances;
548
+ private semaphore;
549
+ constructor(options?: ProcessManagerOptions);
276
550
  /**
277
- * @deprecated Use mkdir instead.
551
+ * Get the primary PHP instance.
552
+ *
553
+ * If the primary PHP instance is not set, it will be spawned
554
+ * using the provided phpFactory.
555
+ *
556
+ * @throws {Error} when called twice before the first call is resolved.
278
557
  */
279
- mkdirTree(path: string): void;
558
+ getPrimaryPhp(): Promise<PHP>;
280
559
  /**
281
- * Reads a file from the PHP filesystem and returns it as a string.
560
+ * Get a PHP instance.
282
561
  *
283
- * @throws {@link @php-wasm/universal:ErrnoError} If the file doesn't exist.
284
- * @param path - The file path to read.
285
- * @returns The file contents.
562
+ * It could be either the primary PHP instance, an idle disposable PHP instance,
563
+ * or a newly spawned PHP instance – depending on the resource availability.
564
+ *
565
+ * @throws {MaxPhpInstancesError} when the maximum number of PHP instances is reached
566
+ * and the waiting timeout is exceeded.
286
567
  */
287
- readFileAsText(path: string): string;
568
+ acquirePHPInstance(): Promise<SpawnedPHP>;
288
569
  /**
289
- * Reads a file from the PHP filesystem and returns it as an array buffer.
570
+ * Initiated spawning of a new PHP instance.
571
+ * This function is synchronous on purpose – it needs to synchronously
572
+ * add the spawn promise to the allInstances array without waiting
573
+ * for PHP to spawn.
574
+ */
575
+ private spawn;
576
+ /**
577
+ * Actually acquires the lock and spawns a new PHP instance.
578
+ */
579
+ private doSpawn;
580
+ [Symbol.asyncDispose](): Promise<void>;
581
+ }
582
+ export type RewriteRule = {
583
+ match: RegExp;
584
+ replacement: string;
585
+ };
586
+ export interface BaseConfiguration {
587
+ /**
588
+ * The directory in the PHP filesystem where the server will look
589
+ * for the files to serve. Default: `/var/www`.
590
+ */
591
+ documentRoot?: string;
592
+ /**
593
+ * Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
594
+ */
595
+ absoluteUrl?: string;
596
+ /**
597
+ * Rewrite rules
598
+ */
599
+ rewriteRules?: RewriteRule[];
600
+ }
601
+ export type PHPRequestHandlerFactoryArgs = PHPFactoryOptions & {
602
+ requestHandler: PHPRequestHandler;
603
+ };
604
+ export type PHPRequestHandlerConfiguration = BaseConfiguration & ({
605
+ /**
606
+ * PHPProcessManager is required because the request handler needs
607
+ * to make a decision for each request.
290
608
  *
291
- * @throws {@link @php-wasm/universal:ErrnoError} If the file doesn't exist.
292
- * @param path - The file path to read.
293
- * @returns The file contents.
609
+ * Static assets are served using the primary PHP's filesystem, even
610
+ * when serving 100 static files concurrently. No new PHP interpreter
611
+ * is ever created as there's no need for it.
612
+ *
613
+ * Dynamic PHP requests, however, require grabbing an available PHP
614
+ * interpreter, and that's where the PHPProcessManager comes in.
294
615
  */
295
- readFileAsBuffer(path: string): Uint8Array;
616
+ processManager: PHPProcessManager;
617
+ } | {
618
+ phpFactory: (requestHandler: PHPRequestHandlerFactoryArgs) => Promise<PHP>;
296
619
  /**
297
- * Overwrites data in a file in the PHP filesystem.
298
- * Creates a new file if one doesn't exist yet.
620
+ * The maximum number of PHP instances that can exist at
621
+ * the same time.
622
+ */
623
+ maxPhpInstances?: number;
624
+ });
625
+ /**
626
+ * Handles HTTP requests using PHP runtime as a backend.
627
+ *
628
+ * @public
629
+ * @example Use PHPRequestHandler implicitly with a new PHP instance:
630
+ * ```js
631
+ * import { PHP } from '@php-wasm/web';
632
+ *
633
+ * const php = await PHP.load( '7.4', {
634
+ * requestHandler: {
635
+ * // PHP FS path to serve the files from:
636
+ * documentRoot: '/www',
637
+ *
638
+ * // Used to populate $_SERVER['SERVER_NAME'] etc.:
639
+ * absoluteUrl: 'http://127.0.0.1'
640
+ * }
641
+ * } );
642
+ *
643
+ * php.mkdirTree('/www');
644
+ * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
645
+ *
646
+ * const response = await php.request({ path: '/index.php' });
647
+ * console.log(response.text);
648
+ * // "Hi from PHP!"
649
+ * ```
650
+ *
651
+ * @example Explicitly create a PHPRequestHandler instance and run a PHP script:
652
+ * ```js
653
+ * import {
654
+ * loadPHPRuntime,
655
+ * PHP,
656
+ * PHPRequestHandler,
657
+ * getPHPLoaderModule,
658
+ * } from '@php-wasm/web';
659
+ *
660
+ * const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
661
+ * const php = new PHP( runtime );
662
+ *
663
+ * php.mkdirTree('/www');
664
+ * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
665
+ *
666
+ * const server = new PHPRequestHandler(php, {
667
+ * // PHP FS path to serve the files from:
668
+ * documentRoot: '/www',
669
+ *
670
+ * // Used to populate $_SERVER['SERVER_NAME'] etc.:
671
+ * absoluteUrl: 'http://127.0.0.1'
672
+ * });
673
+ *
674
+ * const response = server.request({ path: '/index.php' });
675
+ * console.log(response.text);
676
+ * // "Hi from PHP!"
677
+ * ```
678
+ */
679
+ export declare class PHPRequestHandler {
680
+ #private;
681
+ rewriteRules: RewriteRule[];
682
+ processManager: PHPProcessManager;
683
+ /**
684
+ * The request handler needs to decide whether to serve a static asset or
685
+ * run the PHP interpreter. For static assets it should just reuse the primary
686
+ * PHP even if there's 50 concurrent requests to serve. However, for
687
+ * dynamic PHP requests, it needs to grab an available interpreter.
688
+ * Therefore, it cannot just accept PHP as an argument as serving requests
689
+ * requires access to ProcessManager.
299
690
  *
300
- * @param path - The file path to write to.
301
- * @param data - The data to write to the file.
691
+ * @param php - The PHP instance.
692
+ * @param config - Request Handler configuration.
302
693
  */
303
- writeFile(path: string, data: string | Uint8Array): void;
694
+ constructor(config: PHPRequestHandlerConfiguration);
695
+ getPrimaryPhp(): Promise<PHP>;
304
696
  /**
305
- * Removes a file from the PHP filesystem.
697
+ * Converts a path to an absolute URL based at the PHPRequestHandler
698
+ * root.
306
699
  *
307
- * @throws {@link @php-wasm/universal:ErrnoError} If the file doesn't exist.
308
- * @param path - The file path to remove.
700
+ * @param path The server path to convert to an absolute URL.
701
+ * @returns The absolute URL.
309
702
  */
310
- unlink(path: string): void;
703
+ pathToInternalUrl(path: string): string;
311
704
  /**
312
- * Moves a file or directory in the PHP filesystem to a
313
- * new location.
705
+ * Converts an absolute URL based at the PHPRequestHandler to a relative path
706
+ * without the server pathname and scope.
314
707
  *
315
- * @param oldPath The path to rename.
316
- * @param newPath The new path.
708
+ * @param internalUrl An absolute URL based at the PHPRequestHandler root.
709
+ * @returns The relative path.
317
710
  */
318
- mv(oldPath: string, newPath: string): void;
711
+ internalUrlToPath(internalUrl: string): string;
319
712
  /**
320
- * Removes a directory from the PHP filesystem.
713
+ * The absolute URL of this PHPRequestHandler instance.
714
+ */
715
+ get absoluteUrl(): string;
716
+ /**
717
+ * The directory in the PHP filesystem where the server will look
718
+ * for the files to serve. Default: `/var/www`.
719
+ */
720
+ get documentRoot(): string;
721
+ /**
722
+ * Serves the request – either by serving a static file, or by
723
+ * dispatching it to the PHP runtime.
321
724
  *
322
- * @param path The directory path to remove.
323
- * @param options Options for the removal.
725
+ * The request() method mode behaves like a web server and only works if
726
+ * the PHP was initialized with a `requestHandler` option (which the online version
727
+ * of WordPress Playground does by default).
728
+ *
729
+ * In the request mode, you pass an object containing the request information
730
+ * (method, headers, body, etc.) and the path to the PHP file to run:
731
+ *
732
+ * ```ts
733
+ * const php = PHP.load('7.4', {
734
+ * requestHandler: {
735
+ * documentRoot: "/www"
736
+ * }
737
+ * })
738
+ * php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
739
+ * const result = await php.request({
740
+ * method: "GET",
741
+ * headers: {
742
+ * "Content-Type": "text/plain"
743
+ * },
744
+ * body: "Hello world!",
745
+ * path: "/www/index.php"
746
+ * });
747
+ * // result.text === "Hello world!"
748
+ * ```
749
+ *
750
+ * The `request()` method cannot be used in conjunction with `cli()`.
751
+ *
752
+ * @example
753
+ * ```js
754
+ * const output = await php.request({
755
+ * method: 'GET',
756
+ * url: '/index.php',
757
+ * headers: {
758
+ * 'X-foo': 'bar',
759
+ * },
760
+ * body: {
761
+ * foo: 'bar',
762
+ * },
763
+ * });
764
+ * console.log(output.stdout); // "Hello world!"
765
+ * ```
766
+ *
767
+ * @param request - PHP Request data.
324
768
  */
325
- rmdir(path: string, options?: RmDirOptions): void;
769
+ request(request: PHPRequest): Promise<PHPResponse>;
770
+ }
771
+ declare const __private__dont__use: unique symbol;
772
+ export type UnmountFunction = (() => Promise<any>) | (() => any);
773
+ export type MountHandler = (php: PHP, FS: Emscripten.RootFS, vfsMountPoint: string) => UnmountFunction | Promise<UnmountFunction>;
774
+ declare class PHP implements Disposable {
775
+ #private;
776
+ protected [__private__dont__use]: any;
777
+ requestHandler?: PHPRequestHandler;
326
778
  /**
327
- * Lists the files and directories in the given directory.
779
+ * An exclusive lock that prevent multiple requests from running at
780
+ * the same time.
781
+ */
782
+ semaphore: Semaphore;
783
+ /**
784
+ * Initializes a PHP runtime.
328
785
  *
329
- * @param path - The directory path to list.
330
- * @param options - Options for the listing.
331
- * @returns The list of files and directories in the given directory.
786
+ * @internal
787
+ * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
788
+ * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
789
+ */
790
+ constructor(PHPRuntimeId?: PHPRuntimeId);
791
+ /**
792
+ * Adds an event listener for a PHP event.
793
+ * @param eventType - The type of event to listen for.
794
+ * @param listener - The listener function to be called when the event is triggered.
332
795
  */
333
- listFiles(path: string, options?: ListFilesOptions): string[];
796
+ addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
334
797
  /**
335
- * Checks if a directory exists in the PHP filesystem.
336
- *
337
- * @param path The path to check.
338
- * @returns True if the path is a directory, false otherwise.
798
+ * Removes an event listener for a PHP event.
799
+ * @param eventType - The type of event to remove the listener from.
800
+ * @param listener - The listener function to be removed.
339
801
  */
340
- isDir(path: string): boolean;
802
+ removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
803
+ dispatchEvent<Event extends PHPEvent>(event: Event): void;
341
804
  /**
342
- * Checks if a file (or a directory) exists in the PHP filesystem.
805
+ * Listens to message sent by the PHP code.
343
806
  *
344
- * @param path - The file path to check.
345
- * @returns True if the file exists, false otherwise.
807
+ * To dispatch messages, call:
808
+ *
809
+ * post_message_to_js(string $data)
810
+ *
811
+ * Arguments:
812
+ * $data (string) – Data to pass to JavaScript.
813
+ *
814
+ * @example
815
+ *
816
+ * ```ts
817
+ * const php = await PHP.load('8.0');
818
+ *
819
+ * php.onMessage(
820
+ * // The data is always passed as a string
821
+ * function (data: string) {
822
+ * // Let's decode and log the data:
823
+ * console.log(JSON.parse(data));
824
+ * }
825
+ * );
826
+ *
827
+ * // Now that we have a listener in place, let's
828
+ * // dispatch a message:
829
+ * await php.run({
830
+ * code: `<?php
831
+ * post_message_to_js(
832
+ * json_encode([
833
+ * 'post_id' => '15',
834
+ * 'post_title' => 'This is a blog post!'
835
+ * ])
836
+ * ));
837
+ * `,
838
+ * });
839
+ * ```
840
+ *
841
+ * @param listener Callback function to handle the message.
346
842
  */
347
- fileExists(path: string): boolean;
843
+ onMessage(listener: MessageListener): void;
844
+ setSpawnHandler(handler: SpawnHandler | string): Promise<void>;
845
+ /** @deprecated Use PHPRequestHandler instead. */
846
+ get absoluteUrl(): string;
847
+ /** @deprecated Use PHPRequestHandler instead. */
848
+ get documentRoot(): string;
849
+ /** @deprecated Use PHPRequestHandler instead. */
850
+ pathToInternalUrl(path: string): string;
851
+ /** @deprecated Use PHPRequestHandler instead. */
852
+ internalUrlToPath(internalUrl: string): string;
853
+ initializeRuntime(runtimeId: PHPRuntimeId): void;
854
+ /** @inheritDoc */
855
+ setSapiName(newName: string): Promise<void>;
348
856
  /**
349
857
  * Changes the current working directory in the PHP filesystem.
350
858
  * This is the directory that will be used as the base for relative paths.
@@ -354,6 +862,11 @@ export interface IsomorphicLocalPHP {
354
862
  * @param path - The new working directory.
355
863
  */
356
864
  chdir(path: string): void;
865
+ /**
866
+ * Do not use. Use new PHPRequestHandler() instead.
867
+ * @deprecated
868
+ */
869
+ request(request: PHPRequest): Promise<PHPResponse>;
357
870
  /**
358
871
  * Runs PHP code.
359
872
  *
@@ -423,556 +936,323 @@ export interface IsomorphicLocalPHP {
423
936
  *
424
937
  * @param options - PHP runtime options.
425
938
  */
426
- run(options: PHPRunOptions): Promise<PHPResponse>;
427
- /**
428
- * Listens to message sent by the PHP code.
429
- *
430
- * To dispatch messages, call:
431
- *
432
- * post_message_to_js(string $data)
433
- *
434
- * Arguments:
435
- * $data (string) – Data to pass to JavaScript.
436
- *
437
- * @example
438
- *
439
- * ```ts
440
- * const php = await PHP.load('8.0');
441
- *
442
- * php.onMessage(
443
- * // The data is always passed as a string
444
- * function (data: string) {
445
- * // Let's decode and log the data:
446
- * console.log(JSON.parse(data));
447
- * }
448
- * );
449
- *
450
- * // Now that we have a listener in place, let's
451
- * // dispatch a message:
452
- * await php.run({
453
- * code: `<?php
454
- * post_message_to_js(
455
- * json_encode([
456
- * 'post_id' => '15',
457
- * 'post_title' => 'This is a blog post!'
458
- * ])
459
- * ));
460
- * `,
461
- * });
462
- * ```
463
- *
464
- * @param listener Callback function to handle the message.
465
- */
466
- onMessage(listener: MessageListener): void;
467
- }
468
- export type MessageListener = (data: string) => Promise<string | Uint8Array | void> | string | void;
469
- export interface EventEmitter {
470
- on(event: string, listener: (...args: any[]) => void): this;
471
- emit(event: string, ...args: any[]): boolean;
472
- }
473
- export type ChildProcess = EventEmitter & {
474
- stdout: EventEmitter;
475
- stderr: EventEmitter;
476
- };
477
- export type SpawnHandler = (command: string, args: string[]) => ChildProcess;
478
- /**
479
- * The omited methods must either be called synchronously before
480
- * the PHP internal state is initialized, or with a complex argument
481
- * that can't be serialized over a remote connection. Therefeore,
482
- * they don't make sense in a remote PHP instance.
483
- */
484
- export type IsomorphicRemotePHP = Remote<Omit<IsomorphicLocalPHP, "setSapiName">>;
485
- export type UniversalPHP = IsomorphicLocalPHP | IsomorphicRemotePHP;
486
- export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
487
- export type PHPRequestHeaders = Record<string, string>;
488
- export interface PHPRequest {
489
- /**
490
- * Request method. Default: `GET`.
491
- */
492
- method?: HTTPMethod;
493
- /**
494
- * Request path or absolute URL.
495
- */
496
- url: string;
497
- /**
498
- * Request headers.
499
- */
500
- headers?: PHPRequestHeaders;
501
- /**
502
- * Request body.
503
- * If an object is given, the request will be encoded as multipart
504
- * and sent with a `multipart/form-data` header.
505
- */
506
- body?: string | Uint8Array | Record<string, string | Uint8Array | File>;
507
- }
508
- export interface PHPRunOptions {
509
- /**
510
- * Request path following the domain:port part.
511
- */
512
- relativeUri?: string;
513
- /**
514
- * Path of the .php file to execute.
515
- */
516
- scriptPath?: string;
517
- /**
518
- * Request protocol.
519
- */
520
- protocol?: string;
521
- /**
522
- * Request method. Default: `GET`.
523
- */
524
- method?: HTTPMethod;
525
- /**
526
- * Request headers.
527
- */
528
- headers?: PHPRequestHeaders;
529
- /**
530
- * Request body.
531
- */
532
- body?: string | Uint8Array;
533
- /**
534
- * Environment variables to set for this run.
535
- */
536
- env?: Record<string, string>;
537
- /**
538
- * $_SERVER entries to set for this run.
539
- */
540
- $_SERVER?: Record<string, string>;
541
- /**
542
- * The code snippet to eval instead of a php file.
543
- */
544
- code?: string;
545
- }
546
- /**
547
- * Output of the PHP.wasm runtime.
548
- */
549
- export interface PHPOutput {
550
- /** Exit code of the PHP process. 0 means success, 1 and 2 mean error. */
551
- exitCode: number;
552
- /** Stdout data */
553
- stdout: ArrayBuffer;
554
- /** Stderr lines */
555
- stderr: string[];
556
- }
557
- export interface RmDirOptions {
558
- /**
559
- * If true, recursively removes the directory and all its contents.
560
- * Default: true.
561
- */
562
- recursive?: boolean;
563
- }
564
- export interface ListFilesOptions {
565
- /**
566
- * If true, prepend given folder path to all file names.
567
- * Default: false.
568
- */
569
- prependPath: boolean;
570
- }
571
- /**
572
- * Rewrites the php.ini file with the given entries.
573
- *
574
- * @param php The PHP instance.
575
- * @param entries The entries to write to the php.ini file.
576
- */
577
- export declare function setPhpIniEntries(php: UniversalPHP, entries: Record<string, unknown>): Promise<void>;
578
- export type RuntimeType = "NODE" | "WEB" | "WORKER";
579
- export type PHPRuntimeId = number;
580
- export type PHPRuntime = any;
581
- export type PHPLoaderModule = {
582
- dependencyFilename: string;
583
- dependenciesTotalSize: number;
584
- init: (jsRuntime: string, options: EmscriptenOptions) => PHPRuntime;
585
- };
586
- export type EmscriptenOptions = {
587
- onAbort?: (message: string) => void;
588
- /**
589
- * Set to true for debugging tricky WebAssembly errors.
590
- */
591
- debug?: boolean;
592
- ENV?: Record<string, string>;
593
- locateFile?: (path: string) => string;
594
- noInitialRun?: boolean;
595
- print?: (message: string) => void;
596
- printErr?: (message: string) => void;
597
- quit?: (status: number, toThrow: any) => void;
598
- onRuntimeInitialized?: () => void;
599
- monitorRunDependencies?: (left: number) => void;
600
- onMessage?: (listener: EmscriptenMessageListener) => void;
601
- instantiateWasm?: (info: WebAssembly.Imports, receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void) => void;
602
- } & Record<string, any>;
603
- export type EmscriptenMessageListener = (type: string, data: string) => void;
604
- export interface SemaphoreOptions {
605
- /**
606
- * The maximum number of concurrent locks.
607
- */
608
- concurrency: number;
939
+ run(request: PHPRunOptions): Promise<PHPResponse>;
609
940
  /**
610
- * The maximum time to wait for a lock to become available.
941
+ * Defines a constant in the PHP runtime.
942
+ * @param key - The name of the constant.
943
+ * @param value - The value of the constant.
611
944
  */
612
- timeout?: number;
613
- }
614
- declare class Semaphore {
615
- private _running;
616
- private concurrency;
617
- private timeout?;
618
- private queue;
619
- constructor({ concurrency, timeout }: SemaphoreOptions);
620
- get remaining(): number;
621
- get running(): number;
622
- acquire(): Promise<() => void>;
623
- run<T>(fn: () => T | Promise<T>): Promise<T>;
624
- }
625
- export declare function phpVar(value: unknown): string;
626
- export declare function phpVars<T extends Record<string, unknown>>(vars: T): Record<keyof T, string>;
627
- export type RewriteRule = {
628
- match: RegExp;
629
- replacement: string;
630
- };
631
- export interface BaseConfiguration {
945
+ defineConstant(key: string, value: string | boolean | number | null): void;
632
946
  /**
633
- * The directory in the PHP filesystem where the server will look
634
- * for the files to serve. Default: `/var/www`.
947
+ * Recursively creates a directory with the given path in the PHP filesystem.
948
+ * For example, if the path is `/root/php/data`, and `/root` already exists,
949
+ * it will create the directories `/root/php` and `/root/php/data`.
950
+ *
951
+ * @param path - The directory path to create.
635
952
  */
636
- documentRoot?: string;
953
+ mkdir(path: string): void;
637
954
  /**
638
- * Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
955
+ * @deprecated Use mkdir instead.
639
956
  */
640
- absoluteUrl?: string;
957
+ mkdirTree(path: string): void;
641
958
  /**
642
- * Rewrite rules
959
+ * Reads a file from the PHP filesystem and returns it as a string.
960
+ *
961
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
962
+ * @param path - The file path to read.
963
+ * @returns The file contents.
643
964
  */
644
- rewriteRules?: RewriteRule[];
645
- }
646
- export type PHPRequestHandlerFactoryArgs<PHP extends BasePHP> = PHPFactoryOptions & {
647
- requestHandler: PHPRequestHandler<PHP>;
648
- };
649
- export type PHPRequestHandlerConfiguration<PHP extends BasePHP> = BaseConfiguration & ({
965
+ readFileAsText(path: string): string;
650
966
  /**
651
- * PHPProcessManager is required because the request handler needs
652
- * to make a decision for each request.
653
- *
654
- * Static assets are served using the primary PHP's filesystem, even
655
- * when serving 100 static files concurrently. No new PHP interpreter
656
- * is ever created as there's no need for it.
967
+ * Reads a file from the PHP filesystem and returns it as an array buffer.
657
968
  *
658
- * Dynamic PHP requests, however, require grabbing an available PHP
659
- * interpreter, and that's where the PHPProcessManager comes in.
969
+ * @throws {@link @php-wasm/universal:ErrnoError} If the file doesn't exist.
970
+ * @param path - The file path to read.
971
+ * @returns The file contents.
660
972
  */
661
- processManager: PHPProcessManager<PHP>;
662
- } | {
663
- phpFactory: (requestHandler: PHPRequestHandlerFactoryArgs<PHP>) => Promise<PHP>;
973
+ readFileAsBuffer(path: string): Uint8Array;
664
974
  /**
665
- * The maximum number of PHP instances that can exist at
666
- * the same time.
975
+ * Overwrites data in a file in the PHP filesystem.
976
+ * Creates a new file if one doesn't exist yet.
977
+ *
978
+ * @param path - The file path to write to.
979
+ * @param data - The data to write to the file.
667
980
  */
668
- maxPhpInstances?: number;
669
- });
670
- /**
671
- * Handles HTTP requests using PHP runtime as a backend.
672
- *
673
- * @public
674
- * @example Use PHPRequestHandler implicitly with a new PHP instance:
675
- * ```js
676
- * import { PHP } from '@php-wasm/web';
677
- *
678
- * const php = await PHP.load( '7.4', {
679
- * requestHandler: {
680
- * // PHP FS path to serve the files from:
681
- * documentRoot: '/www',
682
- *
683
- * // Used to populate $_SERVER['SERVER_NAME'] etc.:
684
- * absoluteUrl: 'http://127.0.0.1'
685
- * }
686
- * } );
687
- *
688
- * php.mkdirTree('/www');
689
- * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
690
- *
691
- * const response = await php.request({ path: '/index.php' });
692
- * console.log(response.text);
693
- * // "Hi from PHP!"
694
- * ```
695
- *
696
- * @example Explicitly create a PHPRequestHandler instance and run a PHP script:
697
- * ```js
698
- * import {
699
- * loadPHPRuntime,
700
- * PHP,
701
- * PHPRequestHandler,
702
- * getPHPLoaderModule,
703
- * } from '@php-wasm/web';
704
- *
705
- * const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
706
- * const php = new PHP( runtime );
707
- *
708
- * php.mkdirTree('/www');
709
- * php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
710
- *
711
- * const server = new PHPRequestHandler(php, {
712
- * // PHP FS path to serve the files from:
713
- * documentRoot: '/www',
714
- *
715
- * // Used to populate $_SERVER['SERVER_NAME'] etc.:
716
- * absoluteUrl: 'http://127.0.0.1'
717
- * });
718
- *
719
- * const response = server.request({ path: '/index.php' });
720
- * console.log(response.text);
721
- * // "Hi from PHP!"
722
- * ```
723
- */
724
- export declare class PHPRequestHandler<PHP extends BasePHP> {
725
- #private;
726
- rewriteRules: RewriteRule[];
727
- processManager: PHPProcessManager<PHP>;
981
+ writeFile(path: string, data: string | Uint8Array): void;
728
982
  /**
729
- * The request handler needs to decide whether to serve a static asset or
730
- * run the PHP interpreter. For static assets it should just reuse the primary
731
- * PHP even if there's 50 concurrent requests to serve. However, for
732
- * dynamic PHP requests, it needs to grab an available interpreter.
733
- * Therefore, it cannot just accept PHP as an argument as serving requests
734
- * requires access to ProcessManager.
983
+ * Removes a file from the PHP filesystem.
735
984
  *
736
- * @param php - The PHP instance.
737
- * @param config - Request Handler configuration.
985
+ * @throws {@link @php-wasm/universal:ErrnoError} If the file doesn't exist.
986
+ * @param path - The file path to remove.
738
987
  */
739
- constructor(config: PHPRequestHandlerConfiguration<PHP>);
740
- getPrimaryPhp(): Promise<PHP>;
988
+ unlink(path: string): void;
741
989
  /**
742
- * Converts a path to an absolute URL based at the PHPRequestHandler
743
- * root.
990
+ * Moves a file or directory in the PHP filesystem to a
991
+ * new location.
744
992
  *
745
- * @param path The server path to convert to an absolute URL.
746
- * @returns The absolute URL.
993
+ * @param oldPath The path to rename.
994
+ * @param newPath The new path.
747
995
  */
748
- pathToInternalUrl(path: string): string;
996
+ mv(fromPath: string, toPath: string): void;
749
997
  /**
750
- * Converts an absolute URL based at the PHPRequestHandler to a relative path
751
- * without the server pathname and scope.
998
+ * Removes a directory from the PHP filesystem.
752
999
  *
753
- * @param internalUrl An absolute URL based at the PHPRequestHandler root.
754
- * @returns The relative path.
1000
+ * @param path The directory path to remove.
1001
+ * @param options Options for the removal.
755
1002
  */
756
- internalUrlToPath(internalUrl: string): string;
1003
+ rmdir(path: string, options?: RmDirOptions): void;
757
1004
  /**
758
- * The absolute URL of this PHPRequestHandler instance.
1005
+ * Lists the files and directories in the given directory.
1006
+ *
1007
+ * @param path - The directory path to list.
1008
+ * @param options - Options for the listing.
1009
+ * @returns The list of files and directories in the given directory.
759
1010
  */
760
- get absoluteUrl(): string;
1011
+ listFiles(path: string, options?: ListFilesOptions): string[];
761
1012
  /**
762
- * The directory in the PHP filesystem where the server will look
763
- * for the files to serve. Default: `/var/www`.
1013
+ * Checks if a directory exists in the PHP filesystem.
1014
+ *
1015
+ * @param path – The path to check.
1016
+ * @returns True if the path is a directory, false otherwise.
764
1017
  */
765
- get documentRoot(): string;
1018
+ isDir(path: string): boolean;
766
1019
  /**
767
- * Serves the request either by serving a static file, or by
768
- * dispatching it to the PHP runtime.
1020
+ * Checks if a file (or a directory) exists in the PHP filesystem.
769
1021
  *
770
- * The request() method mode behaves like a web server and only works if
771
- * the PHP was initialized with a `requestHandler` option (which the online version
772
- * of WordPress Playground does by default).
1022
+ * @param path - The file path to check.
1023
+ * @returns True if the file exists, false otherwise.
1024
+ */
1025
+ fileExists(path: string): boolean;
1026
+ /**
1027
+ * Hot-swaps the PHP runtime for a new one without
1028
+ * interrupting the operations of this PHP instance.
773
1029
  *
774
- * In the request mode, you pass an object containing the request information
775
- * (method, headers, body, etc.) and the path to the PHP file to run:
1030
+ * @param runtime
1031
+ * @param cwd. Internal, the VFS path to recreate in the new runtime.
1032
+ * This arg is temporary and will be removed once BasePHP
1033
+ * is fully decoupled from the request handler and
1034
+ * accepts a constructor-level cwd argument.
1035
+ */
1036
+ hotSwapPHPRuntime(runtime: number, cwd?: string): void;
1037
+ /**
1038
+ * Mounts a filesystem to a given path in the PHP filesystem.
776
1039
  *
777
- * ```ts
778
- * const php = PHP.load('7.4', {
779
- * requestHandler: {
780
- * documentRoot: "/www"
781
- * }
782
- * })
783
- * php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
784
- * const result = await php.request({
785
- * method: "GET",
786
- * headers: {
787
- * "Content-Type": "text/plain"
788
- * },
789
- * body: "Hello world!",
790
- * path: "/www/index.php"
791
- * });
792
- * // result.text === "Hello world!"
793
- * ```
1040
+ * @param virtualFSPath - Where to mount it in the PHP virtual filesystem.
1041
+ * @param mountHandler - The mount handler to use.
1042
+ * @return Unmount function to unmount the filesystem.
1043
+ */
1044
+ mount(virtualFSPath: string, mountHandler: MountHandler): Promise<UnmountFunction>;
1045
+ /**
1046
+ * Starts a PHP CLI session with given arguments.
794
1047
  *
795
- * The `request()` method cannot be used in conjunction with `cli()`.
1048
+ * This method can only be used when PHP was compiled with the CLI SAPI
1049
+ * and it cannot be used in conjunction with `run()`.
796
1050
  *
797
- * @example
798
- * ```js
799
- * const output = await php.request({
800
- * method: 'GET',
801
- * url: '/index.php',
802
- * headers: {
803
- * 'X-foo': 'bar',
804
- * },
805
- * body: {
806
- * foo: 'bar',
807
- * },
808
- * });
809
- * console.log(output.stdout); // "Hello world!"
810
- * ```
1051
+ * Once this method finishes running, the PHP instance is no
1052
+ * longer usable and should be discarded. This is because PHP
1053
+ * internally cleans up all the resources and calls exit().
811
1054
  *
812
- * @param request - PHP Request data.
1055
+ * @param argv - The arguments to pass to the CLI.
1056
+ * @returns The exit code of the CLI session.
813
1057
  */
814
- request(request: PHPRequest): Promise<PHPResponse>;
1058
+ cli(argv: string[]): Promise<number>;
1059
+ setSkipShebang(shouldSkip: boolean): void;
1060
+ exit(code?: number): void;
1061
+ [Symbol.dispose](): void;
815
1062
  }
816
- declare const __private__dont__use: unique symbol;
817
- declare abstract class BasePHP implements IsomorphicLocalPHP, Disposable {
818
- #private;
819
- protected [__private__dont__use]: any;
820
- requestHandler?: PHPRequestHandler<any>;
821
- /**
822
- * An exclusive lock that prevent multiple requests from running at
823
- * the same time.
824
- */
825
- semaphore: Semaphore;
1063
+ export type LimitedPHPApi = Pick<PHP, "request" | "defineConstant" | "addEventListener" | "removeEventListener" | "mkdir" | "mkdirTree" | "readFileAsText" | "readFileAsBuffer" | "writeFile" | "unlink" | "mv" | "rmdir" | "listFiles" | "isDir" | "fileExists" | "chdir" | "run" | "onMessage"> & {
1064
+ documentRoot: PHP["documentRoot"];
1065
+ absoluteUrl: PHP["absoluteUrl"];
1066
+ };
1067
+ declare class PHPWorker implements LimitedPHPApi {
1068
+ /** @inheritDoc @php-wasm/universal!RequestHandler.absoluteUrl */
1069
+ absoluteUrl: string;
1070
+ /** @inheritDoc @php-wasm/universal!RequestHandler.documentRoot */
1071
+ documentRoot: string;
1072
+ /** @inheritDoc */
1073
+ constructor(requestHandler?: PHPRequestHandler, monitor?: EmscriptenDownloadMonitor);
1074
+ __internal_setRequestHandler(requestHandler: PHPRequestHandler): void;
826
1075
  /**
827
- * Initializes a PHP runtime.
828
- *
829
1076
  * @internal
830
- * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
831
- * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
1077
+ * @deprecated
1078
+ * Do not use this method directly in the code consuming
1079
+ * the web API. It will change or even be removed without
1080
+ * a warning.
832
1081
  */
833
- constructor(PHPRuntimeId?: PHPRuntimeId);
834
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
835
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
836
- dispatchEvent<Event extends PHPEvent>(event: Event): void;
837
- /** @inheritDoc */
838
- onMessage(listener: MessageListener): Promise<void>;
839
- /** @inheritDoc */
840
- setSpawnHandler(handler: SpawnHandler | string): Promise<void>;
841
- /** @inheritDoc */
842
- get absoluteUrl(): string;
843
- /** @inheritDoc */
844
- get documentRoot(): string;
845
- /** @inheritDoc */
1082
+ protected __internal_getPHP(): PHP | undefined;
1083
+ setPrimaryPHP(php: PHP): Promise<void>;
1084
+ /** @inheritDoc @php-wasm/universal!PHPRequestHandler.pathToInternalUrl */
846
1085
  pathToInternalUrl(path: string): string;
847
- /** @inheritDoc */
1086
+ /** @inheritDoc @php-wasm/universal!PHPRequestHandler.internalUrlToPath */
848
1087
  internalUrlToPath(internalUrl: string): string;
849
- initializeRuntime(runtimeId: PHPRuntimeId): void;
850
- /** @inheritDoc */
851
- setSapiName(newName: string): Promise<void>;
852
- /** @inheritDoc */
853
- chdir(path: string): void;
854
1088
  /**
855
- * Do not use. Use new PHPRequestHandler() instead.
856
- * @deprecated
1089
+ * The onDownloadProgress event listener.
857
1090
  */
1091
+ onDownloadProgress(callback: (progress: CustomEvent<ProgressEvent>) => void): Promise<void>;
1092
+ /** @inheritDoc @php-wasm/universal!PHP.mv */
1093
+ mv(fromPath: string, toPath: string): Promise<void>;
1094
+ /** @inheritDoc @php-wasm/universal!PHP.rmdir */
1095
+ rmdir(path: string, options?: RmDirOptions): Promise<void>;
1096
+ /** @inheritDoc @php-wasm/universal!PHPRequestHandler.request */
858
1097
  request(request: PHPRequest): Promise<PHPResponse>;
859
- /** @inheritDoc */
1098
+ /** @inheritDoc @php-wasm/universal!/PHP.run */
860
1099
  run(request: PHPRunOptions): Promise<PHPResponse>;
861
- defineConstant(key: string, value: string | boolean | number | null): void;
862
- /** @inheritDoc */
1100
+ /** @inheritDoc @php-wasm/universal!/PHP.chdir */
1101
+ chdir(path: string): void;
1102
+ /** @inheritDoc @php-wasm/universal!/PHP.setSapiName */
1103
+ setSapiName(newName: string): void;
1104
+ /** @inheritDoc @php-wasm/universal!/PHP.mkdir */
863
1105
  mkdir(path: string): void;
864
- /** @inheritDoc */
1106
+ /** @inheritDoc @php-wasm/universal!/PHP.mkdirTree */
865
1107
  mkdirTree(path: string): void;
866
- /** @inheritDoc */
1108
+ /** @inheritDoc @php-wasm/universal!/PHP.readFileAsText */
867
1109
  readFileAsText(path: string): string;
868
- /** @inheritDoc */
1110
+ /** @inheritDoc @php-wasm/universal!/PHP.readFileAsBuffer */
869
1111
  readFileAsBuffer(path: string): Uint8Array;
870
- /** @inheritDoc */
1112
+ /** @inheritDoc @php-wasm/universal!/PHP.writeFile */
871
1113
  writeFile(path: string, data: string | Uint8Array): void;
872
- /** @inheritDoc */
1114
+ /** @inheritDoc @php-wasm/universal!/PHP.unlink */
873
1115
  unlink(path: string): void;
874
- /** @inheritDoc */
875
- mv(fromPath: string, toPath: string): void;
876
- /** @inheritDoc */
877
- rmdir(path: string, options?: RmDirOptions): void;
878
- /** @inheritDoc */
1116
+ /** @inheritDoc @php-wasm/universal!/PHP.listFiles */
879
1117
  listFiles(path: string, options?: ListFilesOptions): string[];
880
- /** @inheritDoc */
1118
+ /** @inheritDoc @php-wasm/universal!/PHP.isDir */
881
1119
  isDir(path: string): boolean;
882
- /** @inheritDoc */
1120
+ /** @inheritDoc @php-wasm/universal!/PHP.fileExists */
883
1121
  fileExists(path: string): boolean;
884
- /**
885
- * Hot-swaps the PHP runtime for a new one without
886
- * interrupting the operations of this PHP instance.
887
- *
888
- * @param runtime
889
- * @param cwd. Internal, the VFS path to recreate in the new runtime.
890
- * This arg is temporary and will be removed once BasePHP
891
- * is fully decoupled from the request handler and
892
- * accepts a constructor-level cwd argument.
893
- */
894
- hotSwapPHPRuntime(runtime: number, cwd?: string): void;
895
- exit(code?: number): void;
896
- [Symbol.dispose](): void;
1122
+ /** @inheritDoc @php-wasm/universal!/PHP.onMessage */
1123
+ onMessage(listener: MessageListener): void;
1124
+ /** @inheritDoc @php-wasm/universal!/PHP.defineConstant */
1125
+ defineConstant(key: string, value: string | boolean | number | null): void;
1126
+ /** @inheritDoc @php-wasm/universal!/PHP.addEventListener */
1127
+ addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
1128
+ /** @inheritDoc @php-wasm/universal!/PHP.removeEventListener */
1129
+ removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
897
1130
  }
898
- export type PHPFactoryOptions = {
899
- isPrimary: boolean;
1131
+ /**
1132
+ * Represents an event related to the PHP request.
1133
+ */
1134
+ export interface PHPRequestEndEvent {
1135
+ type: "request.end";
1136
+ }
1137
+ /**
1138
+ * Represents an error event related to the PHP request.
1139
+ */
1140
+ export interface PHPRequestErrorEvent {
1141
+ type: "request.error";
1142
+ error: Error;
1143
+ source?: "request" | "php-wasm";
1144
+ }
1145
+ /**
1146
+ * Represents a PHP runtime initialization event.
1147
+ */
1148
+ export interface PHPRuntimeInitializedEvent {
1149
+ type: "runtime.initialized";
1150
+ }
1151
+ /**
1152
+ * Represents a PHP runtime destruction event.
1153
+ */
1154
+ export interface PHPRuntimeBeforeDestroyEvent {
1155
+ type: "runtime.beforedestroy";
1156
+ }
1157
+ /**
1158
+ * Represents an event related to the PHP instance.
1159
+ * This is intentionally not an extension of CustomEvent
1160
+ * to make it isomorphic between different JavaScript runtimes.
1161
+ */
1162
+ export type PHPEvent = PHPRequestEndEvent | PHPRequestErrorEvent | PHPRuntimeInitializedEvent | PHPRuntimeBeforeDestroyEvent;
1163
+ /**
1164
+ * A callback function that handles PHP events.
1165
+ */
1166
+ export type PHPEventListener = (event: PHPEvent) => void;
1167
+ export type UniversalPHP = LimitedPHPApi | Remote<LimitedPHPApi>;
1168
+ export type MessageListener = (data: string) => Promise<string | Uint8Array | void> | string | void;
1169
+ export interface EventEmitter {
1170
+ on(event: string, listener: (...args: any[]) => void): this;
1171
+ emit(event: string, ...args: any[]): boolean;
1172
+ }
1173
+ export type ChildProcess = EventEmitter & {
1174
+ stdout: EventEmitter;
1175
+ stderr: EventEmitter;
900
1176
  };
901
- export type PHPFactory<PHP extends BasePHP> = (options: PHPFactoryOptions) => Promise<PHP>;
902
- export interface ProcessManagerOptions<PHP extends BasePHP> {
1177
+ export type SpawnHandler = (command: string, args: string[]) => ChildProcess;
1178
+ export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE";
1179
+ export type PHPRequestHeaders = Record<string, string>;
1180
+ export interface PHPRequest {
903
1181
  /**
904
- * The maximum number of PHP instances that can exist at
905
- * the same time.
1182
+ * Request method. Default: `GET`.
906
1183
  */
907
- maxPhpInstances?: number;
1184
+ method?: HTTPMethod;
908
1185
  /**
909
- * The number of milliseconds to wait for a PHP instance when
910
- * we have reached the maximum number of PHP instances and
911
- * cannot spawn a new one. If the timeout is reached, we assume
912
- * all the PHP instances are deadlocked and a throw MaxPhpInstancesError.
913
- *
914
- * Default: 5000
1186
+ * Request path or absolute URL.
915
1187
  */
916
- timeout?: number;
1188
+ url: string;
917
1189
  /**
918
- * The primary PHP instance that's never killed. This instance
919
- * contains the reference filesystem used by all other PHP instances.
1190
+ * Request headers.
920
1191
  */
921
- primaryPhp?: PHP;
1192
+ headers?: PHPRequestHeaders;
922
1193
  /**
923
- * A factory function used for spawning new PHP instances.
1194
+ * Request body.
1195
+ * If an object is given, the request will be encoded as multipart
1196
+ * and sent with a `multipart/form-data` header.
924
1197
  */
925
- phpFactory?: PHPFactory<PHP>;
926
- }
927
- export interface SpawnedPHP<PHP extends BasePHP> {
928
- php: PHP;
929
- reap: () => void;
1198
+ body?: string | Uint8Array | Record<string, string | Uint8Array | File>;
930
1199
  }
931
- declare class PHPProcessManager<PHP extends BasePHP> implements AsyncDisposable {
932
- private primaryPhp?;
933
- private primaryIdle;
934
- private nextInstance;
1200
+ export interface PHPRunOptions {
935
1201
  /**
936
- * All spawned PHP instances, including the primary PHP instance.
937
- * Used for bookkeeping and reaping all instances on dispose.
1202
+ * Request path following the domain:port part.
938
1203
  */
939
- private allInstances;
940
- private phpFactory?;
941
- private maxPhpInstances;
942
- private semaphore;
943
- constructor(options?: ProcessManagerOptions<PHP>);
1204
+ relativeUri?: string;
944
1205
  /**
945
- * Get the primary PHP instance.
946
- *
947
- * If the primary PHP instance is not set, it will be spawned
948
- * using the provided phpFactory.
949
- *
950
- * @throws {Error} when called twice before the first call is resolved.
1206
+ * Path of the .php file to execute.
951
1207
  */
952
- getPrimaryPhp(): Promise<PHP>;
1208
+ scriptPath?: string;
953
1209
  /**
954
- * Get a PHP instance.
955
- *
956
- * It could be either the primary PHP instance, an idle disposable PHP instance,
957
- * or a newly spawned PHP instance – depending on the resource availability.
958
- *
959
- * @throws {MaxPhpInstancesError} when the maximum number of PHP instances is reached
960
- * and the waiting timeout is exceeded.
1210
+ * Request protocol.
961
1211
  */
962
- acquirePHPInstance(): Promise<SpawnedPHP<PHP>>;
1212
+ protocol?: string;
963
1213
  /**
964
- * Initiated spawning of a new PHP instance.
965
- * This function is synchronous on purpose – it needs to synchronously
966
- * add the spawn promise to the allInstances array without waiting
967
- * for PHP to spawn.
1214
+ * Request method. Default: `GET`.
968
1215
  */
969
- private spawn;
1216
+ method?: HTTPMethod;
970
1217
  /**
971
- * Actually acquires the lock and spawns a new PHP instance.
1218
+ * Request headers.
972
1219
  */
973
- private doSpawn;
974
- [Symbol.asyncDispose](): Promise<void>;
1220
+ headers?: PHPRequestHeaders;
1221
+ /**
1222
+ * Request body.
1223
+ */
1224
+ body?: string | Uint8Array;
1225
+ /**
1226
+ * Environment variables to set for this run.
1227
+ */
1228
+ env?: Record<string, string>;
1229
+ /**
1230
+ * $_SERVER entries to set for this run.
1231
+ */
1232
+ $_SERVER?: Record<string, string>;
1233
+ /**
1234
+ * The code snippet to eval instead of a php file.
1235
+ */
1236
+ code?: string;
1237
+ }
1238
+ /**
1239
+ * Output of the PHP.wasm runtime.
1240
+ */
1241
+ export interface PHPOutput {
1242
+ /** Exit code of the PHP process. 0 means success, 1 and 2 mean error. */
1243
+ exitCode: number;
1244
+ /** Stdout data */
1245
+ stdout: ArrayBuffer;
1246
+ /** Stderr lines */
1247
+ stderr: string[];
975
1248
  }
1249
+ /**
1250
+ * Rewrites the php.ini file with the given entries.
1251
+ *
1252
+ * @param php The PHP instance.
1253
+ * @param entries The entries to write to the php.ini file.
1254
+ */
1255
+ export declare function setPhpIniEntries(php: UniversalPHP, entries: Record<string, unknown>): Promise<void>;
976
1256
  /**
977
1257
  * Emscripten's filesystem-related Exception.
978
1258
  *
@@ -1955,6 +2235,28 @@ export interface WPCLIStep {
1955
2235
  * Runs PHP code using [WP-CLI](https://developer.wordpress.org/cli/commands/).
1956
2236
  */
1957
2237
  export declare const wpCLI: StepHandler<WPCLIStep, Promise<PHPResponse>>;
2238
+ /**
2239
+ * Deletes WordPress posts and comments and sets the auto increment sequence for the
2240
+ * posts and comments tables to 0.
2241
+ *
2242
+ * @private
2243
+ * @internal
2244
+ * @inheritDoc resetData
2245
+ * @example
2246
+ *
2247
+ * <code>
2248
+ * {
2249
+ * "step": "resetData"
2250
+ * }
2251
+ * </code>
2252
+ */
2253
+ export interface ResetDataStep {
2254
+ step: "resetData";
2255
+ }
2256
+ /**
2257
+ * @param playground Playground client.
2258
+ */
2259
+ export declare const resetData: StepHandler<ResetDataStep>;
1958
2260
  /**
1959
2261
  * Used by the export step to exclude the Playground-specific files
1960
2262
  * from the zip file. Keep it in sync with the list of files created
@@ -1972,7 +2274,7 @@ export type StepDefinition = Step & {
1972
2274
  * If you add a step here, make sure to also
1973
2275
  * add it to the exports below.
1974
2276
  */
1975
- export type GenericStep<Resource> = ActivatePluginStep | ActivateThemeStep | CpStep | DefineWpConfigConstsStep | DefineSiteUrlStep | EnableMultisiteStep | ImportWxrStep<Resource> | ImportWordPressFilesStep<Resource> | InstallPluginStep<Resource> | InstallThemeStep<Resource> | LoginStep | MkdirStep | MvStep | RequestStep | RmStep | RmdirStep | RunPHPStep | RunPHPWithOptionsStep | RunWpInstallationWizardStep | RunSqlStep<Resource> | SetSiteOptionsStep | UnzipStep<Resource> | UpdateUserMetaStep | WriteFileStep<Resource> | WPCLIStep;
2277
+ export type GenericStep<Resource> = ActivatePluginStep | ActivateThemeStep | CpStep | DefineWpConfigConstsStep | DefineSiteUrlStep | EnableMultisiteStep | ImportWxrStep<Resource> | ImportWordPressFilesStep<Resource> | InstallPluginStep<Resource> | InstallThemeStep<Resource> | LoginStep | MkdirStep | MvStep | ResetDataStep | RequestStep | RmStep | RmdirStep | RunPHPStep | RunPHPWithOptionsStep | RunWpInstallationWizardStep | RunSqlStep<Resource> | SetSiteOptionsStep | UnzipStep<Resource> | UpdateUserMetaStep | WriteFileStep<Resource> | WPCLIStep;
1976
2278
  /**
1977
2279
  * Progress reporting details.
1978
2280
  */
@@ -2153,90 +2455,11 @@ export type WithAPIState = {
2153
2455
  isReady: () => Promise<void>;
2154
2456
  };
2155
2457
  export type RemoteAPI<T> = Comlink.Remote<T> & WithAPIState;
2156
- export interface PHPWebLoaderOptions {
2157
- emscriptenOptions?: EmscriptenOptions;
2158
- onPhpLoaderModuleLoaded?: (module: PHPLoaderModule) => void;
2159
- /** @deprecated To be replaced with `extensions` in the future */
2160
- loadAllExtensions?: boolean;
2161
- }
2162
- declare class WebPHP extends BasePHP {
2163
- /**
2164
- * Creates a new PHP instance.
2165
- *
2166
- * Dynamically imports the PHP module, initializes the runtime,
2167
- * and sets up networking. It's a shorthand for the lower-level
2168
- * functions like `getPHPLoaderModule`, `loadPHPRuntime`, and
2169
- * `PHP.initializeRuntime`
2170
- *
2171
- * @param phpVersion The PHP Version to load
2172
- * @param options The options to use when loading PHP
2173
- * @returns A new PHP instance
2174
- */
2175
- static load(phpVersion: SupportedPHPVersion, options?: PHPWebLoaderOptions): Promise<WebPHP>;
2176
- static loadRuntime(phpVersion: SupportedPHPVersion, options?: PHPWebLoaderOptions): Promise<number>;
2177
- }
2178
- declare class WebPHPEndpoint implements Omit<IsomorphicLocalPHP, "setSapiName"> {
2179
- /** @inheritDoc @php-wasm/universal!RequestHandler.absoluteUrl */
2180
- absoluteUrl: string;
2181
- /** @inheritDoc @php-wasm/universal!RequestHandler.documentRoot */
2182
- documentRoot: string;
2183
- /** @inheritDoc */
2184
- constructor(requestHandler: PHPRequestHandler<WebPHP>, monitor?: EmscriptenDownloadMonitor);
2185
- /**
2186
- * @internal
2187
- * @deprecated
2188
- * Do not use this method directly in the code consuming
2189
- * the web API. It will change or even be removed without
2190
- * a warning.
2191
- */
2192
- protected __internal_getPHP(): WebPHP | undefined;
2193
- setPrimaryPHP(php: WebPHP): Promise<void>;
2194
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.pathToInternalUrl */
2195
- pathToInternalUrl(path: string): string;
2196
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.internalUrlToPath */
2197
- internalUrlToPath(internalUrl: string): string;
2198
- /**
2199
- * The onDownloadProgress event listener.
2200
- */
2201
- onDownloadProgress(callback: (progress: CustomEvent<ProgressEvent>) => void): Promise<void>;
2202
- /** @inheritDoc @php-wasm/universal!IsomorphicLocalPHP.mv */
2203
- mv(fromPath: string, toPath: string): Promise<void>;
2204
- /** @inheritDoc @php-wasm/universal!IsomorphicLocalPHP.rmdir */
2205
- rmdir(path: string, options?: RmDirOptions): Promise<void>;
2206
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.request */
2207
- request(request: PHPRequest): Promise<PHPResponse>;
2208
- /** @inheritDoc @php-wasm/web!WebPHP.run */
2209
- run(request: PHPRunOptions): Promise<PHPResponse>;
2210
- /** @inheritDoc @php-wasm/web!WebPHP.chdir */
2211
- chdir(path: string): void;
2212
- /** @inheritDoc @php-wasm/web!WebPHP.setSapiName */
2213
- setSapiName(newName: string): void;
2214
- /** @inheritDoc @php-wasm/web!WebPHP.mkdir */
2215
- mkdir(path: string): void;
2216
- /** @inheritDoc @php-wasm/web!WebPHP.mkdirTree */
2217
- mkdirTree(path: string): void;
2218
- /** @inheritDoc @php-wasm/web!WebPHP.readFileAsText */
2219
- readFileAsText(path: string): string;
2220
- /** @inheritDoc @php-wasm/web!WebPHP.readFileAsBuffer */
2221
- readFileAsBuffer(path: string): Uint8Array;
2222
- /** @inheritDoc @php-wasm/web!WebPHP.writeFile */
2223
- writeFile(path: string, data: string | Uint8Array): void;
2224
- /** @inheritDoc @php-wasm/web!WebPHP.unlink */
2225
- unlink(path: string): void;
2226
- /** @inheritDoc @php-wasm/web!WebPHP.listFiles */
2227
- listFiles(path: string, options?: ListFilesOptions): string[];
2228
- /** @inheritDoc @php-wasm/web!WebPHP.isDir */
2229
- isDir(path: string): boolean;
2230
- /** @inheritDoc @php-wasm/web!WebPHP.fileExists */
2231
- fileExists(path: string): boolean;
2232
- /** @inheritDoc @php-wasm/web!WebPHP.onMessage */
2233
- onMessage(listener: MessageListener): void;
2234
- /** @inheritDoc @php-wasm/web!WebPHP.defineConstant */
2235
- defineConstant(key: string, value: string | boolean | number | null): void;
2236
- /** @inheritDoc @php-wasm/web!WebPHP.addEventListener */
2237
- addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
2238
- /** @inheritDoc @php-wasm/web!WebPHP.removeEventListener */
2239
- removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void;
2458
+ export interface MountOptions {
2459
+ initialSync: {
2460
+ direction?: "opfs-to-memfs" | "memfs-to-opfs";
2461
+ onProgress?: SyncProgressCallback;
2462
+ };
2240
2463
  }
2241
2464
  export type SyncProgress = {
2242
2465
  /** The number of files that have been synced. */
@@ -2245,6 +2468,13 @@ export type SyncProgress = {
2245
2468
  total: number;
2246
2469
  };
2247
2470
  export type SyncProgressCallback = (progress: SyncProgress) => void;
2471
+ export type BindOpfsOptions = {
2472
+ php: PHP;
2473
+ opfs: FileSystemDirectoryHandle;
2474
+ initialSyncDirection?: MountOptions["initialSync"]["direction"];
2475
+ onProgress?: SyncProgressCallback;
2476
+ mountpoint: string;
2477
+ };
2248
2478
  /**
2249
2479
  * Represents the type of node in PHP file system.
2250
2480
  */
@@ -2294,22 +2524,26 @@ export type RenameOperation = {
2294
2524
  nodeType: FSNodeType;
2295
2525
  };
2296
2526
  export type FilesystemOperation = CreateOperation | UpdateFileOperation | DeleteOperation | RenameOperation;
2297
- declare class PlaygroundWorkerEndpoint extends WebPHPEndpoint {
2527
+ declare class PlaygroundWorkerEndpoint extends PHPWorker {
2298
2528
  /**
2299
2529
  * A string representing the scope of the Playground instance.
2300
2530
  */
2301
2531
  scope: string;
2302
2532
  /**
2303
- * A string representing the version of WordPress being used.
2533
+ * A string representing the requested version of WordPress.
2534
+ */
2535
+ requestedWordPressVersion: string;
2536
+ /**
2537
+ * A string representing the version of WordPress that was loaded.
2304
2538
  */
2305
- wordPressVersion: string;
2306
- constructor(requestHandler: PHPRequestHandler<WebPHP>, monitor: EmscriptenDownloadMonitor, scope: string, wordPressVersion: string);
2539
+ loadedWordPressVersion: string | undefined;
2540
+ constructor(monitor: EmscriptenDownloadMonitor, scope: string, requestedWordPressVersion: string);
2307
2541
  /**
2308
2542
  * @returns WordPress module details, including the static assets directory and default theme.
2309
2543
  */
2310
2544
  getWordPressModuleDetails(): Promise<{
2311
2545
  majorVersion: string;
2312
- staticAssetsDirectory: string;
2546
+ staticAssetsDirectory: string | undefined;
2313
2547
  }>;
2314
2548
  getSupportedWordPressVersions(): Promise<{
2315
2549
  all: {
@@ -2319,13 +2553,12 @@ declare class PlaygroundWorkerEndpoint extends WebPHPEndpoint {
2319
2553
  "6.4": string;
2320
2554
  "6.3": string;
2321
2555
  "6.2": string;
2322
- "6.1": string;
2323
2556
  };
2324
2557
  latest: string;
2325
2558
  }>;
2326
2559
  resetVirtualOpfs(): Promise<void>;
2327
2560
  reloadFilesFromOpfs(): Promise<void>;
2328
- bindOpfs(opfs: FileSystemDirectoryHandle, onProgress?: SyncProgressCallback): Promise<void>;
2561
+ bindOpfs(options: Omit<BindOpfsOptions, "php" | "onProgress">, onProgress?: SyncProgressCallback): Promise<void>;
2329
2562
  journalFSEvents(root: string, callback: (op: FilesystemOperation) => void): Promise<() => any>;
2330
2563
  replayFSJournal(events: FilesystemOperation[]): Promise<void>;
2331
2564
  }
@@ -2374,7 +2607,7 @@ export interface WebClientMixin extends ProgressReceiver {
2374
2607
  removeEventListener: PlaygroundWorkerEndpoint["removeEventListener"];
2375
2608
  /** @inheritDoc @php-wasm/universal!UniversalPHP.onMessage */
2376
2609
  onMessage: PlaygroundWorkerEndpoint["onMessage"];
2377
- bindOpfs(opfs: FileSystemDirectoryHandle, onProgress?: SyncProgressCallback): Promise<void>;
2610
+ bindOpfs(options: Omit<BindOpfsOptions, "php" | "onProgress">, onProgress?: SyncProgressCallback): Promise<void>;
2378
2611
  }
2379
2612
  /**
2380
2613
  * The Playground Client interface.
@@ -2402,6 +2635,15 @@ export interface StartPlaygroundOptions {
2402
2635
  * @private
2403
2636
  */
2404
2637
  sapiName?: string;
2638
+ /**
2639
+ * Called before the blueprint steps are run,
2640
+ * allows the caller to delay the Blueprint execution
2641
+ * once the Playground is booted.
2642
+ *
2643
+ * @returns
2644
+ */
2645
+ onBeforeBlueprint?: () => Promise<void>;
2646
+ siteSlug?: string;
2405
2647
  }
2406
2648
  /**
2407
2649
  * Loads playground in iframe and returns a PlaygroundClient instance.
@@ -2410,7 +2652,7 @@ export interface StartPlaygroundOptions {
2410
2652
  * @param options Options for loading the playground.
2411
2653
  * @returns A PlaygroundClient instance.
2412
2654
  */
2413
- export declare function startPlaygroundWeb({ iframe, blueprint, remoteUrl, progressTracker, disableProgressBar, onBlueprintStepCompleted, onClientConnected, sapiName, }: StartPlaygroundOptions): Promise<PlaygroundClient>;
2655
+ export declare function startPlaygroundWeb({ iframe, blueprint, remoteUrl, progressTracker, disableProgressBar, onBlueprintStepCompleted, onClientConnected, sapiName, onBeforeBlueprint, siteSlug, }: StartPlaygroundOptions): Promise<PlaygroundClient>;
2414
2656
  /**
2415
2657
  * @deprecated Use `startPlayground` instead.
2416
2658
  *