@wp-playground/common
Advanced tools
Comparing version 0.9.19 to 0.9.20
982
index.d.ts
@@ -1,976 +0,14 @@ | ||
// Generated by dts-bundle-generator v7.2.0 | ||
import { Remote } from 'comlink'; | ||
export interface PHPResponseData { | ||
/** | ||
* Response headers. | ||
*/ | ||
readonly headers: Record<string, string[]>; | ||
/** | ||
* Response body. Contains the output from `echo`, | ||
* `print`, inline HTML etc. | ||
*/ | ||
readonly bytes: ArrayBuffer; | ||
/** | ||
* Stderr contents, if any. | ||
*/ | ||
readonly errors: string; | ||
/** | ||
* The exit code of the script. `0` is a success, while | ||
* `1` and `2` indicate an error. | ||
*/ | ||
readonly exitCode: number; | ||
/** | ||
* Response HTTP status code, e.g. 200. | ||
*/ | ||
readonly httpStatusCode: number; | ||
} | ||
declare class PHPResponse implements PHPResponseData { | ||
/** @inheritDoc */ | ||
readonly headers: Record<string, string[]>; | ||
/** @inheritDoc */ | ||
readonly bytes: ArrayBuffer; | ||
/** @inheritDoc */ | ||
readonly errors: string; | ||
/** @inheritDoc */ | ||
readonly exitCode: number; | ||
/** @inheritDoc */ | ||
readonly httpStatusCode: number; | ||
constructor(httpStatusCode: number, headers: Record<string, string[]>, body: ArrayBuffer, errors?: string, exitCode?: number); | ||
static forHttpCode(httpStatusCode: number, text?: string): PHPResponse; | ||
static fromRawData(data: PHPResponseData): PHPResponse; | ||
toRawData(): PHPResponseData; | ||
/** | ||
* Response body as JSON. | ||
*/ | ||
get json(): any; | ||
/** | ||
* Response body as text. | ||
*/ | ||
get text(): string; | ||
} | ||
export type PHPRuntimeId = number; | ||
/** Other WebAssembly declarations, for compatibility with older versions of Typescript */ | ||
export declare namespace Emscripten { | ||
export interface RootFS extends Emscripten.FileSystemInstance { | ||
filesystems: Record<string, Emscripten.FileSystemType>; | ||
} | ||
export interface FileSystemType { | ||
mount(mount: FS.Mount): FS.FSNode; | ||
syncfs(mount: FS.Mount, populate: () => unknown, done: (err?: number | null) => unknown): void; | ||
} | ||
export type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER"; | ||
export type JSType = "number" | "string" | "array" | "boolean"; | ||
export type TypeCompatibleWithC = number | string | any[] | boolean; | ||
export type CIntType = "i8" | "i16" | "i32" | "i64"; | ||
export type CFloatType = "float" | "double"; | ||
export type CPointerType = "i8*" | "i16*" | "i32*" | "i64*" | "float*" | "double*" | "*"; | ||
export type CType = CIntType | CFloatType | CPointerType; | ||
export interface CCallOpts { | ||
async?: boolean | undefined; | ||
} | ||
type NamespaceToInstance<T> = { | ||
[K in keyof T]: T[K] extends (...args: any[]) => any ? T[K] : never; | ||
}; | ||
export type FileSystemInstance = NamespaceToInstance<typeof FS> & { | ||
mkdirTree(path: string): void; | ||
lookupPath(path: string, opts?: any): FS.Lookup; | ||
}; | ||
export interface EmscriptenModule { | ||
print(str: string): void; | ||
printErr(str: string): void; | ||
arguments: string[]; | ||
environment: Emscripten.EnvironmentType; | ||
preInit: Array<{ | ||
(): void; | ||
}>; | ||
preRun: Array<{ | ||
(): void; | ||
}>; | ||
postRun: Array<{ | ||
(): void; | ||
}>; | ||
onAbort: { | ||
(what: any): void; | ||
}; | ||
onRuntimeInitialized: { | ||
(): void; | ||
}; | ||
preinitializedWebGLContext: WebGLRenderingContext; | ||
noInitialRun: boolean; | ||
noExitRuntime: boolean; | ||
logReadFiles: boolean; | ||
filePackagePrefixURL: string; | ||
wasmBinary: ArrayBuffer; | ||
destroy(object: object): void; | ||
getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer; | ||
instantiateWasm(imports: WebAssembly.Imports, successCallback: (module: WebAssembly.Instance) => void): WebAssembly.Exports | undefined; | ||
locateFile(url: string, scriptDirectory: string): string; | ||
onCustomMessage(event: MessageEvent): void; | ||
HEAP: Int32Array; | ||
IHEAP: Int32Array; | ||
FHEAP: Float64Array; | ||
HEAP8: Int8Array; | ||
HEAP16: Int16Array; | ||
HEAP32: Int32Array; | ||
HEAPU8: Uint8Array; | ||
HEAPU16: Uint16Array; | ||
HEAPU32: Uint32Array; | ||
HEAPF32: Float32Array; | ||
HEAPF64: Float64Array; | ||
HEAP64: BigInt64Array; | ||
HEAPU64: BigUint64Array; | ||
TOTAL_STACK: number; | ||
TOTAL_MEMORY: number; | ||
FAST_MEMORY: number; | ||
addOnPreRun(cb: () => any): void; | ||
addOnInit(cb: () => any): void; | ||
addOnPreMain(cb: () => any): void; | ||
addOnExit(cb: () => any): void; | ||
addOnPostRun(cb: () => any): void; | ||
preloadedImages: any; | ||
preloadedAudios: any; | ||
_malloc(size: number): number; | ||
_free(ptr: number): void; | ||
} | ||
/** | ||
* A factory function is generated when setting the `MODULARIZE` build option | ||
* to `1` in your Emscripten build. It return a Promise that resolves to an | ||
* initialized, ready-to-call `EmscriptenModule` instance. | ||
* | ||
* By default, the factory function will be named `Module`. It's recommended to | ||
* use the `EXPORT_ES6` option, in which the factory function will be the | ||
* default export. If used without `EXPORT_ES6`, the factory function will be a | ||
* global variable. You can rename the variable using the `EXPORT_NAME` build | ||
* option. It's left to you to export any global variables as needed in your | ||
* application's types. | ||
* @param moduleOverrides Default properties for the initialized module. | ||
*/ | ||
export type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (moduleOverrides?: Partial<T>) => Promise<T>; | ||
export namespace FS { | ||
interface Lookup { | ||
path: string; | ||
node: FSNode; | ||
} | ||
interface Analyze { | ||
isRoot: boolean; | ||
exists: boolean; | ||
error: Error; | ||
name: string; | ||
path: Lookup["path"]; | ||
object: Lookup["node"]; | ||
parentExists: boolean; | ||
parentPath: Lookup["path"]; | ||
parentObject: Lookup["node"]; | ||
} | ||
interface Mount { | ||
type: Emscripten.FileSystemType; | ||
opts: object; | ||
mountpoint: string; | ||
mounts: Mount[]; | ||
root: FSNode; | ||
} | ||
class FSStream { | ||
constructor(); | ||
object: FSNode; | ||
readonly isRead: boolean; | ||
readonly isWrite: boolean; | ||
readonly isAppend: boolean; | ||
flags: number; | ||
position: number; | ||
} | ||
class FSNode { | ||
parent: FSNode; | ||
mount: Mount; | ||
mounted?: Mount; | ||
id: number; | ||
name: string; | ||
mode: number; | ||
rdev: number; | ||
readMode: number; | ||
writeMode: number; | ||
constructor(parent: FSNode, name: string, mode: number, rdev: number); | ||
read: boolean; | ||
write: boolean; | ||
readonly isFolder: boolean; | ||
readonly isDevice: boolean; | ||
} | ||
interface ErrnoError extends Error { | ||
name: "ErronoError"; | ||
errno: number; | ||
code: string; | ||
} | ||
function lookupPath(path: string, opts: any): Lookup; | ||
function getPath(node: FSNode): string; | ||
function analyzePath(path: string, dontResolveLastLink?: boolean): Analyze; | ||
function isFile(mode: number): boolean; | ||
function isDir(mode: number): boolean; | ||
function isLink(mode: number): boolean; | ||
function isChrdev(mode: number): boolean; | ||
function isBlkdev(mode: number): boolean; | ||
function isFIFO(mode: number): boolean; | ||
function isSocket(mode: number): boolean; | ||
function major(dev: number): number; | ||
function minor(dev: number): number; | ||
function makedev(ma: number, mi: number): number; | ||
function registerDevice(dev: number, ops: any): void; | ||
function syncfs(populate: boolean, callback: (e: any) => any): void; | ||
function syncfs(callback: (e: any) => any, populate?: boolean): void; | ||
function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any; | ||
function unmount(mountpoint: string): void; | ||
function mkdir(path: string, mode?: number): any; | ||
function mkdev(path: string, mode?: number, dev?: number): any; | ||
function symlink(oldpath: string, newpath: string): any; | ||
function rename(old_path: string, new_path: string): void; | ||
function rmdir(path: string): void; | ||
function readdir(path: string): any; | ||
function unlink(path: string): void; | ||
function readlink(path: string): string; | ||
function stat(path: string, dontFollow?: boolean): any; | ||
function lstat(path: string): any; | ||
function chmod(path: string, mode: number, dontFollow?: boolean): void; | ||
function lchmod(path: string, mode: number): void; | ||
function fchmod(fd: number, mode: number): void; | ||
function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void; | ||
function lchown(path: string, uid: number, gid: number): void; | ||
function fchown(fd: number, uid: number, gid: number): void; | ||
function truncate(path: string, len: number): void; | ||
function ftruncate(fd: number, len: number): void; | ||
function utime(path: string, atime: number, mtime: number): void; | ||
function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream; | ||
function close(stream: FSStream): void; | ||
function llseek(stream: FSStream, offset: number, whence: number): any; | ||
function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number; | ||
function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number; | ||
function allocate(stream: FSStream, offset: number, length: number): void; | ||
function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any; | ||
function ioctl(stream: FSStream, cmd: any, arg: any): any; | ||
function readFile(path: string, opts: { | ||
encoding: "binary"; | ||
flags?: string | undefined; | ||
}): Uint8Array; | ||
function readFile(path: string, opts: { | ||
encoding: "utf8"; | ||
flags?: string | undefined; | ||
}): string; | ||
function readFile(path: string, opts?: { | ||
flags?: string | undefined; | ||
}): Uint8Array; | ||
function writeFile(path: string, data: string | ArrayBufferView, opts?: { | ||
flags?: string | undefined; | ||
}): void; | ||
function cwd(): string; | ||
function chdir(path: string): void; | ||
function init(input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any)): void; | ||
function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode; | ||
function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void; | ||
function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode; | ||
} | ||
export const MEMFS: Emscripten.FileSystemType; | ||
export const NODEFS: Emscripten.FileSystemType; | ||
export const IDBFS: Emscripten.FileSystemType; | ||
type StringToType<R> = R extends Emscripten.JSType ? { | ||
number: number; | ||
string: string; | ||
array: number[] | string[] | boolean[] | Uint8Array | Int8Array; | ||
boolean: boolean; | ||
null: null; | ||
}[R] : never; | ||
type ArgsToType<T extends Array<Emscripten.JSType | null>> = Extract<{ | ||
[P in keyof T]: StringToType<T[P]>; | ||
}, any[]>; | ||
type ReturnToType<R extends Emscripten.JSType | null> = R extends null ? null : StringToType<Exclude<R, null>>; | ||
export function cwrap<I extends Array<Emscripten.JSType | null> | [ | ||
], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, opts?: Emscripten.CCallOpts): (...arg: ArgsToType<I>) => ReturnToType<R>; | ||
export function ccall<I extends Array<Emscripten.JSType | null> | [ | ||
], R extends Emscripten.JSType | null>(ident: string, returnType: R, argTypes: I, args: ArgsToType<I>, opts?: Emscripten.CCallOpts): ReturnToType<R>; | ||
export function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void; | ||
export function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number; | ||
export function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number; | ||
export function stackAlloc(size: number): number; | ||
export function stackSave(): number; | ||
export function stackRestore(ptr: number): void; | ||
export function UTF8ToString(ptr: number, maxBytesToRead?: number): string; | ||
export function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void; | ||
export function lengthBytesUTF8(str: string): number; | ||
export function allocateUTF8(str: string): number; | ||
export function allocateUTF8OnStack(str: string): number; | ||
export function UTF16ToString(ptr: number): string; | ||
export function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void; | ||
export function lengthBytesUTF16(str: string): number; | ||
export function UTF32ToString(ptr: number): string; | ||
export function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void; | ||
export function lengthBytesUTF32(str: string): number; | ||
export function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[]; | ||
export function intArrayToString(array: number[]): string; | ||
export function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void; | ||
export function writeArrayToMemory(array: number[], buffer: number): void; | ||
export function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void; | ||
export function addRunDependency(id: any): void; | ||
export function removeRunDependency(id: any): void; | ||
export function addFunction(func: (...args: any[]) => any, signature?: string): number; | ||
export function removeFunction(funcPtr: number): void; | ||
export const ALLOC_NORMAL: number; | ||
export const ALLOC_STACK: number; | ||
export const ALLOC_STATIC: number; | ||
export const ALLOC_DYNAMIC: number; | ||
export const ALLOC_NONE: number; | ||
export {}; | ||
} | ||
export interface RmDirOptions { | ||
/** | ||
* If true, recursively removes the directory and all its contents. | ||
* Default: true. | ||
*/ | ||
recursive?: boolean; | ||
} | ||
export interface ListFilesOptions { | ||
/** | ||
* If true, prepend given folder path to all file names. | ||
* Default: false. | ||
*/ | ||
prependPath: boolean; | ||
} | ||
export interface SemaphoreOptions { | ||
/** | ||
* The maximum number of concurrent locks. | ||
*/ | ||
concurrency: number; | ||
/** | ||
* The maximum time to wait for a lock to become available. | ||
*/ | ||
timeout?: number; | ||
} | ||
declare class Semaphore { | ||
private _running; | ||
private concurrency; | ||
private timeout?; | ||
private queue; | ||
constructor({ concurrency, timeout }: SemaphoreOptions); | ||
get remaining(): number; | ||
get running(): number; | ||
acquire(): Promise<() => void>; | ||
run<T>(fn: () => T | Promise<T>): Promise<T>; | ||
} | ||
export type PHPFactoryOptions = { | ||
isPrimary: boolean; | ||
}; | ||
export type PHPFactory = (options: PHPFactoryOptions) => Promise<PHP>; | ||
export interface ProcessManagerOptions { | ||
/** | ||
* The maximum number of PHP instances that can exist at | ||
* the same time. | ||
*/ | ||
maxPhpInstances?: number; | ||
/** | ||
* The number of milliseconds to wait for a PHP instance when | ||
* we have reached the maximum number of PHP instances and | ||
* cannot spawn a new one. If the timeout is reached, we assume | ||
* all the PHP instances are deadlocked and a throw MaxPhpInstancesError. | ||
* | ||
* Default: 5000 | ||
*/ | ||
timeout?: number; | ||
/** | ||
* The primary PHP instance that's never killed. This instance | ||
* contains the reference filesystem used by all other PHP instances. | ||
*/ | ||
primaryPhp?: PHP; | ||
/** | ||
* A factory function used for spawning new PHP instances. | ||
*/ | ||
phpFactory?: PHPFactory; | ||
} | ||
export interface SpawnedPHP { | ||
php: PHP; | ||
reap: () => void; | ||
} | ||
declare class PHPProcessManager implements AsyncDisposable { | ||
private primaryPhp?; | ||
private primaryIdle; | ||
private nextInstance; | ||
/** | ||
* All spawned PHP instances, including the primary PHP instance. | ||
* Used for bookkeeping and reaping all instances on dispose. | ||
*/ | ||
private allInstances; | ||
private phpFactory?; | ||
private maxPhpInstances; | ||
private semaphore; | ||
constructor(options?: ProcessManagerOptions); | ||
/** | ||
* Get the primary PHP instance. | ||
* | ||
* If the primary PHP instance is not set, it will be spawned | ||
* using the provided phpFactory. | ||
* | ||
* @throws {Error} when called twice before the first call is resolved. | ||
*/ | ||
getPrimaryPhp(): Promise<PHP>; | ||
/** | ||
* Get a PHP instance. | ||
* | ||
* It could be either the primary PHP instance, an idle disposable PHP instance, | ||
* or a newly spawned PHP instance – depending on the resource availability. | ||
* | ||
* @throws {MaxPhpInstancesError} when the maximum number of PHP instances is reached | ||
* and the waiting timeout is exceeded. | ||
*/ | ||
acquirePHPInstance(): Promise<SpawnedPHP>; | ||
/** | ||
* Initiated spawning of a new PHP instance. | ||
* This function is synchronous on purpose – it needs to synchronously | ||
* add the spawn promise to the allInstances array without waiting | ||
* for PHP to spawn. | ||
*/ | ||
private spawn; | ||
/** | ||
* Actually acquires the lock and spawns a new PHP instance. | ||
*/ | ||
private doSpawn; | ||
[Symbol.asyncDispose](): Promise<void>; | ||
} | ||
export type RewriteRule = { | ||
match: RegExp; | ||
replacement: string; | ||
}; | ||
export interface BaseConfiguration { | ||
/** | ||
* The directory in the PHP filesystem where the server will look | ||
* for the files to serve. Default: `/var/www`. | ||
*/ | ||
documentRoot?: string; | ||
/** | ||
* Request Handler URL. Used to populate $_SERVER details like HTTP_HOST. | ||
*/ | ||
absoluteUrl?: string; | ||
/** | ||
* Rewrite rules | ||
*/ | ||
rewriteRules?: RewriteRule[]; | ||
} | ||
export type PHPRequestHandlerFactoryArgs = PHPFactoryOptions & { | ||
requestHandler: PHPRequestHandler; | ||
}; | ||
export type PHPRequestHandlerConfiguration = BaseConfiguration & ({ | ||
/** | ||
* PHPProcessManager is required because the request handler needs | ||
* to make a decision for each request. | ||
* | ||
* Static assets are served using the primary PHP's filesystem, even | ||
* when serving 100 static files concurrently. No new PHP interpreter | ||
* is ever created as there's no need for it. | ||
* | ||
* Dynamic PHP requests, however, require grabbing an available PHP | ||
* interpreter, and that's where the PHPProcessManager comes in. | ||
*/ | ||
processManager: PHPProcessManager; | ||
} | { | ||
phpFactory: (requestHandler: PHPRequestHandlerFactoryArgs) => Promise<PHP>; | ||
/** | ||
* The maximum number of PHP instances that can exist at | ||
* the same time. | ||
*/ | ||
maxPhpInstances?: number; | ||
}); | ||
declare class PHPRequestHandler { | ||
#private; | ||
rewriteRules: RewriteRule[]; | ||
processManager: PHPProcessManager; | ||
/** | ||
* The request handler needs to decide whether to serve a static asset or | ||
* run the PHP interpreter. For static assets it should just reuse the primary | ||
* PHP even if there's 50 concurrent requests to serve. However, for | ||
* dynamic PHP requests, it needs to grab an available interpreter. | ||
* Therefore, it cannot just accept PHP as an argument as serving requests | ||
* requires access to ProcessManager. | ||
* | ||
* @param php - The PHP instance. | ||
* @param config - Request Handler configuration. | ||
*/ | ||
constructor(config: PHPRequestHandlerConfiguration); | ||
getPrimaryPhp(): Promise<PHP>; | ||
/** | ||
* Converts a path to an absolute URL based at the PHPRequestHandler | ||
* root. | ||
* | ||
* @param path The server path to convert to an absolute URL. | ||
* @returns The absolute URL. | ||
*/ | ||
pathToInternalUrl(path: string): string; | ||
/** | ||
* Converts an absolute URL based at the PHPRequestHandler to a relative path | ||
* without the server pathname and scope. | ||
* | ||
* @param internalUrl An absolute URL based at the PHPRequestHandler root. | ||
* @returns The relative path. | ||
*/ | ||
internalUrlToPath(internalUrl: string): string; | ||
/** | ||
* The absolute URL of this PHPRequestHandler instance. | ||
*/ | ||
get absoluteUrl(): string; | ||
/** | ||
* The directory in the PHP filesystem where the server will look | ||
* for the files to serve. Default: `/var/www`. | ||
*/ | ||
get documentRoot(): string; | ||
/** | ||
* Serves the request – either by serving a static file, or by | ||
* dispatching it to the PHP runtime. | ||
* | ||
* The request() method mode behaves like a web server and only works if | ||
* the PHP was initialized with a `requestHandler` option (which the online version | ||
* of WordPress Playground does by default). | ||
* | ||
* In the request mode, you pass an object containing the request information | ||
* (method, headers, body, etc.) and the path to the PHP file to run: | ||
* | ||
* ```ts | ||
* const php = PHP.load('7.4', { | ||
* requestHandler: { | ||
* documentRoot: "/www" | ||
* } | ||
* }) | ||
* php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`); | ||
* const result = await php.request({ | ||
* method: "GET", | ||
* headers: { | ||
* "Content-Type": "text/plain" | ||
* }, | ||
* body: "Hello world!", | ||
* path: "/www/index.php" | ||
* }); | ||
* // result.text === "Hello world!" | ||
* ``` | ||
* | ||
* The `request()` method cannot be used in conjunction with `cli()`. | ||
* | ||
* @example | ||
* ```js | ||
* const output = await php.request({ | ||
* method: 'GET', | ||
* url: '/index.php', | ||
* headers: { | ||
* 'X-foo': 'bar', | ||
* }, | ||
* body: { | ||
* foo: 'bar', | ||
* }, | ||
* }); | ||
* console.log(output.stdout); // "Hello world!" | ||
* ``` | ||
* | ||
* @param request - PHP Request data. | ||
*/ | ||
request(request: PHPRequest): Promise<PHPResponse>; | ||
} | ||
declare const __private__dont__use: unique symbol; | ||
export type UnmountFunction = (() => Promise<any>) | (() => any); | ||
export type MountHandler = (php: PHP, FS: Emscripten.RootFS, vfsMountPoint: string) => UnmountFunction | Promise<UnmountFunction>; | ||
declare class PHP implements Disposable { | ||
#private; | ||
protected [__private__dont__use]: any; | ||
requestHandler?: PHPRequestHandler; | ||
/** | ||
* An exclusive lock that prevent multiple requests from running at | ||
* the same time. | ||
*/ | ||
semaphore: Semaphore; | ||
/** | ||
* Initializes a PHP runtime. | ||
* | ||
* @internal | ||
* @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime. | ||
* @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized. | ||
*/ | ||
constructor(PHPRuntimeId?: PHPRuntimeId); | ||
/** | ||
* Adds an event listener for a PHP event. | ||
* @param eventType - The type of event to listen for. | ||
* @param listener - The listener function to be called when the event is triggered. | ||
*/ | ||
addEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void; | ||
/** | ||
* Removes an event listener for a PHP event. | ||
* @param eventType - The type of event to remove the listener from. | ||
* @param listener - The listener function to be removed. | ||
*/ | ||
removeEventListener(eventType: PHPEvent["type"], listener: PHPEventListener): void; | ||
dispatchEvent<Event extends PHPEvent>(event: Event): void; | ||
/** | ||
* Listens to message sent by the PHP code. | ||
* | ||
* To dispatch messages, call: | ||
* | ||
* post_message_to_js(string $data) | ||
* | ||
* Arguments: | ||
* $data (string) – Data to pass to JavaScript. | ||
* | ||
* @example | ||
* | ||
* ```ts | ||
* const php = await PHP.load('8.0'); | ||
* | ||
* php.onMessage( | ||
* // The data is always passed as a string | ||
* function (data: string) { | ||
* // Let's decode and log the data: | ||
* console.log(JSON.parse(data)); | ||
* } | ||
* ); | ||
* | ||
* // Now that we have a listener in place, let's | ||
* // dispatch a message: | ||
* await php.run({ | ||
* code: `<?php | ||
* post_message_to_js( | ||
* json_encode([ | ||
* 'post_id' => '15', | ||
* 'post_title' => 'This is a blog post!' | ||
* ]) | ||
* )); | ||
* `, | ||
* }); | ||
* ``` | ||
* | ||
* @param listener Callback function to handle the message. | ||
*/ | ||
onMessage(listener: MessageListener): void; | ||
setSpawnHandler(handler: SpawnHandler | string): Promise<void>; | ||
/** @deprecated Use PHPRequestHandler instead. */ | ||
get absoluteUrl(): string; | ||
/** @deprecated Use PHPRequestHandler instead. */ | ||
get documentRoot(): string; | ||
/** @deprecated Use PHPRequestHandler instead. */ | ||
pathToInternalUrl(path: string): string; | ||
/** @deprecated Use PHPRequestHandler instead. */ | ||
internalUrlToPath(internalUrl: string): string; | ||
initializeRuntime(runtimeId: PHPRuntimeId): void; | ||
/** @inheritDoc */ | ||
setSapiName(newName: string): Promise<void>; | ||
/** | ||
* Changes the current working directory in the PHP filesystem. | ||
* This is the directory that will be used as the base for relative paths. | ||
* For example, if the current working directory is `/root/php`, and the | ||
* path is `data`, the absolute path will be `/root/php/data`. | ||
* | ||
* @param path - The new working directory. | ||
*/ | ||
chdir(path: string): void; | ||
/** | ||
* Do not use. Use new PHPRequestHandler() instead. | ||
* @deprecated | ||
*/ | ||
request(request: PHPRequest): Promise<PHPResponse>; | ||
/** | ||
* Runs PHP code. | ||
* | ||
* This low-level method directly interacts with the WebAssembly | ||
* PHP interpreter. | ||
* | ||
* Every time you call run(), it prepares the PHP | ||
* environment and: | ||
* | ||
* * Resets the internal PHP state | ||
* * Populates superglobals ($_SERVER, $_GET, etc.) | ||
* * Handles file uploads | ||
* * Populates input streams (stdin, argv, etc.) | ||
* * Sets the current working directory | ||
* | ||
* You can use run() in two primary modes: | ||
* | ||
* ### Code snippet mode | ||
* | ||
* In this mode, you pass a string containing PHP code to run. | ||
* | ||
* ```ts | ||
* const result = await php.run({ | ||
* code: `<?php echo "Hello world!";` | ||
* }); | ||
* // result.text === "Hello world!" | ||
* ``` | ||
* | ||
* In this mode, information like __DIR__ or __FILE__ isn't very | ||
* useful because the code is not associated with any file. | ||
* | ||
* Under the hood, the PHP snippet is passed to the `zend_eval_string` | ||
* C function. | ||
* | ||
* ### File mode | ||
* | ||
* In the file mode, you pass a scriptPath and PHP executes a file | ||
* found at a that path: | ||
* | ||
* ```ts | ||
* php.writeFile( | ||
* "/www/index.php", | ||
* `<?php echo "Hello world!";"` | ||
* ); | ||
* const result = await php.run({ | ||
* scriptPath: "/www/index.php" | ||
* }); | ||
* // result.text === "Hello world!" | ||
* ``` | ||
* | ||
* In this mode, you can rely on path-related information like __DIR__ | ||
* or __FILE__. | ||
* | ||
* Under the hood, the PHP file is executed with the `php_execute_script` | ||
* C function. | ||
* | ||
* The `run()` method cannot be used in conjunction with `cli()`. | ||
* | ||
* @example | ||
* ```js | ||
* const result = await php.run(`<?php | ||
* $fp = fopen('php://stderr', 'w'); | ||
* fwrite($fp, "Hello, world!"); | ||
* `); | ||
* // result.errors === "Hello, world!" | ||
* ``` | ||
* | ||
* @param options - PHP runtime options. | ||
*/ | ||
run(request: PHPRunOptions): Promise<PHPResponse>; | ||
/** | ||
* Defines a constant in the PHP runtime. | ||
* @param key - The name of the constant. | ||
* @param value - The value of the constant. | ||
*/ | ||
defineConstant(key: string, value: string | boolean | number | null): void; | ||
/** | ||
* Recursively creates a directory with the given path in the PHP filesystem. | ||
* For example, if the path is `/root/php/data`, and `/root` already exists, | ||
* it will create the directories `/root/php` and `/root/php/data`. | ||
* | ||
* @param path - The directory path to create. | ||
*/ | ||
mkdir(path: string): void; | ||
/** | ||
* @deprecated Use mkdir instead. | ||
*/ | ||
mkdirTree(path: string): void; | ||
/** | ||
* Reads a file from the PHP filesystem and returns it as a string. | ||
* | ||
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist. | ||
* @param path - The file path to read. | ||
* @returns The file contents. | ||
*/ | ||
readFileAsText(path: string): string; | ||
/** | ||
* Reads a file from the PHP filesystem and returns it as an array buffer. | ||
* | ||
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist. | ||
* @param path - The file path to read. | ||
* @returns The file contents. | ||
*/ | ||
readFileAsBuffer(path: string): Uint8Array; | ||
/** | ||
* Overwrites data in a file in the PHP filesystem. | ||
* Creates a new file if one doesn't exist yet. | ||
* | ||
* @param path - The file path to write to. | ||
* @param data - The data to write to the file. | ||
*/ | ||
writeFile(path: string, data: string | Uint8Array): void; | ||
/** | ||
* Removes a file from the PHP filesystem. | ||
* | ||
* @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist. | ||
* @param path - The file path to remove. | ||
*/ | ||
unlink(path: string): void; | ||
/** | ||
* Moves a file or directory in the PHP filesystem to a | ||
* new location. | ||
* | ||
* @param oldPath The path to rename. | ||
* @param newPath The new path. | ||
*/ | ||
mv(fromPath: string, toPath: string): void; | ||
/** | ||
* Removes a directory from the PHP filesystem. | ||
* | ||
* @param path The directory path to remove. | ||
* @param options Options for the removal. | ||
*/ | ||
rmdir(path: string, options?: RmDirOptions): void; | ||
/** | ||
* Lists the files and directories in the given directory. | ||
* | ||
* @param path - The directory path to list. | ||
* @param options - Options for the listing. | ||
* @returns The list of files and directories in the given directory. | ||
*/ | ||
listFiles(path: string, options?: ListFilesOptions): string[]; | ||
/** | ||
* Checks if a directory exists in the PHP filesystem. | ||
* | ||
* @param path – The path to check. | ||
* @returns True if the path is a directory, false otherwise. | ||
*/ | ||
isDir(path: string): boolean; | ||
/** | ||
* Checks if a file (or a directory) exists in the PHP filesystem. | ||
* | ||
* @param path - The file path to check. | ||
* @returns True if the file exists, false otherwise. | ||
*/ | ||
fileExists(path: string): boolean; | ||
/** | ||
* Hot-swaps the PHP runtime for a new one without | ||
* interrupting the operations of this PHP instance. | ||
* | ||
* @param runtime | ||
* @param cwd. Internal, the VFS path to recreate in the new runtime. | ||
* This arg is temporary and will be removed once BasePHP | ||
* is fully decoupled from the request handler and | ||
* accepts a constructor-level cwd argument. | ||
*/ | ||
hotSwapPHPRuntime(runtime: number, cwd?: string): void; | ||
/** | ||
* Mounts a filesystem to a given path in the PHP filesystem. | ||
* | ||
* @param virtualFSPath - Where to mount it in the PHP virtual filesystem. | ||
* @param mountHandler - The mount handler to use. | ||
* @return Unmount function to unmount the filesystem. | ||
*/ | ||
mount(virtualFSPath: string, mountHandler: MountHandler): Promise<UnmountFunction>; | ||
/** | ||
* Starts a PHP CLI session with given arguments. | ||
* | ||
* This method can only be used when PHP was compiled with the CLI SAPI | ||
* and it cannot be used in conjunction with `run()`. | ||
* | ||
* Once this method finishes running, the PHP instance is no | ||
* longer usable and should be discarded. This is because PHP | ||
* internally cleans up all the resources and calls exit(). | ||
* | ||
* @param argv - The arguments to pass to the CLI. | ||
* @returns The exit code of the CLI session. | ||
*/ | ||
cli(argv: string[]): Promise<number>; | ||
setSkipShebang(shouldSkip: boolean): void; | ||
exit(code?: number): void; | ||
[Symbol.dispose](): void; | ||
} | ||
export type LimitedPHPApi = Pick<PHP, "request" | "defineConstant" | "addEventListener" | "removeEventListener" | "mkdir" | "mkdirTree" | "readFileAsText" | "readFileAsBuffer" | "writeFile" | "unlink" | "mv" | "rmdir" | "listFiles" | "isDir" | "fileExists" | "chdir" | "run" | "onMessage"> & { | ||
documentRoot: PHP["documentRoot"]; | ||
absoluteUrl: PHP["absoluteUrl"]; | ||
}; | ||
/** | ||
* Represents an event related to the PHP request. | ||
* Avoid adding new code here. @wp-playground/common should remain | ||
* as lean as possible. | ||
* | ||
* This package exists to avoid circular dependencies. Let's not | ||
* use it as a default place to add code that doesn't seem to fit | ||
* anywhere else. If there's no good place for your code, perhaps | ||
* it needs to be restructured? Or maybe there's a need for a new package? | ||
* Let's always consider these questions before adding new code here. | ||
*/ | ||
export interface PHPRequestEndEvent { | ||
type: "request.end"; | ||
} | ||
/** | ||
* Represents an error event related to the PHP request. | ||
*/ | ||
export interface PHPRequestErrorEvent { | ||
type: "request.error"; | ||
error: Error; | ||
source?: "request" | "php-wasm"; | ||
} | ||
/** | ||
* Represents a PHP runtime initialization event. | ||
*/ | ||
export interface PHPRuntimeInitializedEvent { | ||
type: "runtime.initialized"; | ||
} | ||
/** | ||
* Represents a PHP runtime destruction event. | ||
*/ | ||
export interface PHPRuntimeBeforeDestroyEvent { | ||
type: "runtime.beforedestroy"; | ||
} | ||
/** | ||
* Represents an event related to the PHP instance. | ||
* This is intentionally not an extension of CustomEvent | ||
* to make it isomorphic between different JavaScript runtimes. | ||
*/ | ||
export type PHPEvent = PHPRequestEndEvent | PHPRequestErrorEvent | PHPRuntimeInitializedEvent | PHPRuntimeBeforeDestroyEvent; | ||
/** | ||
* A callback function that handles PHP events. | ||
*/ | ||
export type PHPEventListener = (event: PHPEvent) => void; | ||
export type UniversalPHP = LimitedPHPApi | Remote<LimitedPHPApi>; | ||
export type MessageListener = (data: string) => Promise<string | Uint8Array | void> | string | void; | ||
export interface EventEmitter { | ||
on(event: string, listener: (...args: any[]) => void): this; | ||
emit(event: string, ...args: any[]): boolean; | ||
} | ||
export type ChildProcess = EventEmitter & { | ||
stdout: EventEmitter; | ||
stderr: EventEmitter; | ||
}; | ||
export type SpawnHandler = (command: string, args: string[]) => ChildProcess; | ||
export type HTTPMethod = "GET" | "POST" | "HEAD" | "OPTIONS" | "PATCH" | "PUT" | "DELETE"; | ||
export type PHPRequestHeaders = Record<string, string>; | ||
export interface PHPRequest { | ||
/** | ||
* Request method. Default: `GET`. | ||
*/ | ||
method?: HTTPMethod; | ||
/** | ||
* Request path or absolute URL. | ||
*/ | ||
url: string; | ||
/** | ||
* Request headers. | ||
*/ | ||
headers?: PHPRequestHeaders; | ||
/** | ||
* Request body. | ||
* If an object is given, the request will be encoded as multipart | ||
* and sent with a `multipart/form-data` header. | ||
*/ | ||
body?: string | Uint8Array | Record<string, string | Uint8Array | File>; | ||
} | ||
export interface PHPRunOptions { | ||
/** | ||
* Request path following the domain:port part. | ||
*/ | ||
relativeUri?: string; | ||
/** | ||
* Path of the .php file to execute. | ||
*/ | ||
scriptPath?: string; | ||
/** | ||
* Request protocol. | ||
*/ | ||
protocol?: string; | ||
/** | ||
* Request method. Default: `GET`. | ||
*/ | ||
method?: HTTPMethod; | ||
/** | ||
* Request headers. | ||
*/ | ||
headers?: PHPRequestHeaders; | ||
/** | ||
* Request body. | ||
*/ | ||
body?: string | Uint8Array; | ||
/** | ||
* Environment variables to set for this run. | ||
*/ | ||
env?: Record<string, string>; | ||
/** | ||
* $_SERVER entries to set for this run. | ||
*/ | ||
$_SERVER?: Record<string, string>; | ||
/** | ||
* The code snippet to eval instead of a php file. | ||
*/ | ||
code?: string; | ||
} | ||
import { UniversalPHP } from '../../../php-wasm/universal/src/index.ts'; | ||
export declare const RecommendedPHPVersion = "8.0"; | ||
export declare const unzipFile: (php: UniversalPHP, zipPath: string | File, extractToPath: string) => Promise<void>; | ||
export declare const unzipFile: (php: UniversalPHP, zipPath: string | File, extractToPath: string, overwriteFiles?: boolean) => Promise<void>; | ||
export declare const zipDirectory: (php: UniversalPHP, directoryPath: string) => Promise<Uint8Array>; | ||
export {}; |
27
index.js
@@ -1,3 +0,3 @@ | ||
function a(t){return`json_decode(base64_decode('${s(JSON.stringify(t))}'), true)`}function c(t){const e={};for(const i in t)e[i]=a(t[i]);return e}function s(t){return u(new TextEncoder().encode(t))}function u(t){const e=String.fromCodePoint(...t);return btoa(e)}const $="8.0",n="/tmp/file.zip",f=async(t,e,i)=>{if(e instanceof File){const o=e;e=n,await t.writeFile(e,new Uint8Array(await o.arrayBuffer()))}const r=c({zipPath:e,extractToPath:i});await t.run({code:`<?php | ||
function unzip($zipPath, $extractTo, $overwrite = true) | ||
function s(e){return`json_decode(base64_decode('${$(JSON.stringify(e))}'), true)`}function a(e){const t={};for(const i in e)t[i]=s(e[i]);return t}function $(e){return f(new TextEncoder().encode(e))}function f(e){const t=String.fromCodePoint(...e);return btoa(t)}const l="8.0",n="/tmp/file.zip",u=async(e,t,i,o=!0)=>{if(t instanceof File){const c=t;t=n,await e.writeFile(t,new Uint8Array(await c.arrayBuffer()))}const r=a({zipPath:t,extractToPath:i,overwriteFiles:o});await e.run({code:`<?php | ||
function unzip($zipPath, $extractTo, $overwriteFiles = true) | ||
{ | ||
@@ -10,5 +10,14 @@ if (!is_dir($extractTo)) { | ||
if ($res === TRUE) { | ||
$zip->extractTo($extractTo); | ||
$zip->close(); | ||
chmod($extractTo, 0777); | ||
for ($i = 0; $i < $zip->numFiles; $i++) { | ||
$filename = $zip->getNameIndex($i); | ||
$fileinfo = pathinfo($filename); | ||
$extractFilePath = rtrim($extractTo, '/') . '/' . $filename; | ||
// Check if file exists and $overwriteFiles is false | ||
if (!file_exists($extractFilePath) || $overwriteFiles) { | ||
// Extract file | ||
$zip->extractTo($extractTo, $filename); | ||
} | ||
} | ||
$zip->close(); | ||
chmod($extractTo, 0777); | ||
} else { | ||
@@ -18,4 +27,4 @@ throw new Exception("Could not unzip file"); | ||
} | ||
unzip(${r.zipPath}, ${r.extractToPath}); | ||
`}),await t.fileExists(n)&&await t.unlink(n)},p=async(t,e)=>{const i=`/tmp/file${Math.random()}.zip`,r=c({directoryPath:e,outputPath:i});await t.run({code:`<?php | ||
unzip(${r.zipPath}, ${r.extractToPath}, ${r.overwriteFiles}); | ||
`}),await e.fileExists(n)&&await e.unlink(n)},p=async(e,t)=>{const i=`/tmp/file${Math.random()}.zip`,o=a({directoryPath:t,outputPath:i});await e.run({code:`<?php | ||
function zipDirectory($directoryPath, $outputPath) { | ||
@@ -40,3 +49,3 @@ $zip = new ZipArchive; | ||
} | ||
zipDirectory(${r.directoryPath}, ${r.outputPath}); | ||
`});const o=await t.readFileAsBuffer(i);return t.unlink(i),o};export{$ as RecommendedPHPVersion,f as unzipFile,p as zipDirectory}; | ||
zipDirectory(${o.directoryPath}, ${o.outputPath}); | ||
`});const r=await e.readFileAsBuffer(i);return e.unlink(i),r};export{l as RecommendedPHPVersion,u as unzipFile,p as zipDirectory}; |
{ | ||
"name": "@wp-playground/common", | ||
"version": "0.9.19", | ||
"description": "Common exports and utilities for WordPress Playground", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/common/common-playground" | ||
}, | ||
"homepage": "https://developer.wordpress.org/playground", | ||
"author": "The WordPress contributors", | ||
"contributors": [ | ||
{ | ||
"name": "Adam Zielinski", | ||
"email": "adam@adamziel.com", | ||
"url": "https://github.com/adamziel" | ||
} | ||
], | ||
"main": "./index.js", | ||
"typings": "./index.d.ts", | ||
"license": "GPL-2.0-or-later", | ||
"type": "module", | ||
"engines": { | ||
"node": ">=18.18.0", | ||
"npm": ">=8.11.0" | ||
}, | ||
"publishConfig": { | ||
"access": "public", | ||
"directory": "../../../dist/packages/playground/common" | ||
}, | ||
"gitHead": "aafbbcdc4b0644885bd55d0ed67381952f0b16b6" | ||
"name": "@wp-playground/common", | ||
"version": "0.9.20", | ||
"description": "Common exports and utilities for WordPress Playground", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/common/common-playground" | ||
}, | ||
"homepage": "https://developer.wordpress.org/playground", | ||
"author": "The WordPress contributors", | ||
"contributors": [ | ||
{ | ||
"name": "Adam Zielinski", | ||
"email": "adam@adamziel.com", | ||
"url": "https://github.com/adamziel" | ||
} | ||
], | ||
"main": "./index.js", | ||
"typings": "./index.d.ts", | ||
"license": "GPL-2.0-or-later", | ||
"type": "module", | ||
"engines": { | ||
"node": ">=18.18.0", | ||
"npm": ">=8.11.0" | ||
}, | ||
"publishConfig": { | ||
"access": "public", | ||
"directory": "../../../dist/packages/playground/common" | ||
}, | ||
"gitHead": "f619fcb719128d247bec296b9339aff52101e948", | ||
"dependencies": { | ||
"comlink": "^4.4.1", | ||
"ini": "4.1.2", | ||
"@php-wasm/universal": "0.9.20", | ||
"@php-wasm/util": "0.9.20" | ||
} | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No README
QualityPackage does not have a README. This may indicate a failed publish or a low quality package.
Found 1 instance in 1 package
4
0
15
4777
4
63
1
+ Added@php-wasm/universal@0.9.20
+ Added@php-wasm/util@0.9.20
+ Addedcomlink@^4.4.1
+ Addedini@4.1.2
+ Added@php-wasm/logger@0.9.20(transitive)
+ Added@php-wasm/node-polyfills@0.9.20(transitive)
+ Added@php-wasm/progress@0.9.20(transitive)
+ Added@php-wasm/stream-compression@0.9.20(transitive)
+ Added@php-wasm/universal@0.9.20(transitive)
+ Added@php-wasm/util@0.9.20(transitive)
+ Addedcomlink@4.4.2(transitive)
+ Addedini@4.1.2(transitive)