@php-wasm/universal 0.9.19 → 0.9.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ /** Other WebAssembly declarations, for compatibility with older versions of Typescript */
2
+ export declare namespace Emscripten {
3
+ export interface RootFS extends Emscripten.FileSystemInstance {
4
+ filesystems: Record<string, Emscripten.FileSystemType>;
5
+ }
6
+ export interface FileSystemType {
7
+ mount(mount: FS.Mount): FS.FSNode;
8
+ syncfs(mount: FS.Mount, populate: () => unknown, done: (err?: number | null) => unknown): void;
9
+ }
10
+ export type EnvironmentType = 'WEB' | 'NODE' | 'SHELL' | 'WORKER';
11
+ export type JSType = 'number' | 'string' | 'array' | 'boolean';
12
+ export type TypeCompatibleWithC = number | string | any[] | boolean;
13
+ export type CIntType = 'i8' | 'i16' | 'i32' | 'i64';
14
+ export type CFloatType = 'float' | 'double';
15
+ export type CPointerType = 'i8*' | 'i16*' | 'i32*' | 'i64*' | 'float*' | 'double*' | '*';
16
+ export type CType = CIntType | CFloatType | CPointerType;
17
+ export interface CCallOpts {
18
+ async?: boolean | undefined;
19
+ }
20
+ type NamespaceToInstance<T> = {
21
+ [K in keyof T]: T[K] extends (...args: any[]) => any ? T[K] : never;
22
+ };
23
+ export type FileSystemInstance = NamespaceToInstance<typeof FS> & {
24
+ mkdirTree(path: string): void;
25
+ lookupPath(path: string, opts?: any): FS.Lookup;
26
+ };
27
+ export interface EmscriptenModule {
28
+ print(str: string): void;
29
+ printErr(str: string): void;
30
+ arguments: string[];
31
+ environment: Emscripten.EnvironmentType;
32
+ preInit: Array<{
33
+ (): void;
34
+ }>;
35
+ preRun: Array<{
36
+ (): void;
37
+ }>;
38
+ postRun: Array<{
39
+ (): void;
40
+ }>;
41
+ onAbort: {
42
+ (what: any): void;
43
+ };
44
+ onRuntimeInitialized: {
45
+ (): void;
46
+ };
47
+ preinitializedWebGLContext: WebGLRenderingContext;
48
+ noInitialRun: boolean;
49
+ noExitRuntime: boolean;
50
+ logReadFiles: boolean;
51
+ filePackagePrefixURL: string;
52
+ wasmBinary: ArrayBuffer;
53
+ destroy(object: object): void;
54
+ getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;
55
+ instantiateWasm(imports: WebAssembly.Imports, successCallback: (module: WebAssembly.Instance) => void): WebAssembly.Exports | undefined;
56
+ locateFile(url: string, scriptDirectory: string): string;
57
+ onCustomMessage(event: MessageEvent): void;
58
+ HEAP: Int32Array;
59
+ IHEAP: Int32Array;
60
+ FHEAP: Float64Array;
61
+ HEAP8: Int8Array;
62
+ HEAP16: Int16Array;
63
+ HEAP32: Int32Array;
64
+ HEAPU8: Uint8Array;
65
+ HEAPU16: Uint16Array;
66
+ HEAPU32: Uint32Array;
67
+ HEAPF32: Float32Array;
68
+ HEAPF64: Float64Array;
69
+ HEAP64: BigInt64Array;
70
+ HEAPU64: BigUint64Array;
71
+ TOTAL_STACK: number;
72
+ TOTAL_MEMORY: number;
73
+ FAST_MEMORY: number;
74
+ addOnPreRun(cb: () => any): void;
75
+ addOnInit(cb: () => any): void;
76
+ addOnPreMain(cb: () => any): void;
77
+ addOnExit(cb: () => any): void;
78
+ addOnPostRun(cb: () => any): void;
79
+ preloadedImages: any;
80
+ preloadedAudios: any;
81
+ _malloc(size: number): number;
82
+ _free(ptr: number): void;
83
+ }
84
+ /**
85
+ * A factory function is generated when setting the `MODULARIZE` build option
86
+ * to `1` in your Emscripten build. It return a Promise that resolves to an
87
+ * initialized, ready-to-call `EmscriptenModule` instance.
88
+ *
89
+ * By default, the factory function will be named `Module`. It's recommended to
90
+ * use the `EXPORT_ES6` option, in which the factory function will be the
91
+ * default export. If used without `EXPORT_ES6`, the factory function will be a
92
+ * global variable. You can rename the variable using the `EXPORT_NAME` build
93
+ * option. It's left to you to export any global variables as needed in your
94
+ * application's types.
95
+ * @param moduleOverrides Default properties for the initialized module.
96
+ */
97
+ export type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (moduleOverrides?: Partial<T>) => Promise<T>;
98
+ export namespace FS {
99
+ interface Lookup {
100
+ path: string;
101
+ node: FSNode;
102
+ }
103
+ interface Analyze {
104
+ isRoot: boolean;
105
+ exists: boolean;
106
+ error: Error;
107
+ name: string;
108
+ path: Lookup['path'];
109
+ object: Lookup['node'];
110
+ parentExists: boolean;
111
+ parentPath: Lookup['path'];
112
+ parentObject: Lookup['node'];
113
+ }
114
+ interface Mount {
115
+ type: Emscripten.FileSystemType;
116
+ opts: object;
117
+ mountpoint: string;
118
+ mounts: Mount[];
119
+ root: FSNode;
120
+ }
121
+ class FSStream {
122
+ constructor();
123
+ object: FSNode;
124
+ readonly isRead: boolean;
125
+ readonly isWrite: boolean;
126
+ readonly isAppend: boolean;
127
+ flags: number;
128
+ position: number;
129
+ }
130
+ class FSNode {
131
+ parent: FSNode;
132
+ mount: Mount;
133
+ mounted?: Mount;
134
+ id: number;
135
+ name: string;
136
+ mode: number;
137
+ rdev: number;
138
+ readMode: number;
139
+ writeMode: number;
140
+ constructor(parent: FSNode, name: string, mode: number, rdev: number);
141
+ read: boolean;
142
+ write: boolean;
143
+ readonly isFolder: boolean;
144
+ readonly isDevice: boolean;
145
+ }
146
+ interface ErrnoError extends Error {
147
+ name: 'ErronoError';
148
+ errno: number;
149
+ code: string;
150
+ }
151
+ function lookupPath(path: string, opts: any): Lookup;
152
+ function getPath(node: FSNode): string;
153
+ function analyzePath(path: string, dontResolveLastLink?: boolean): Analyze;
154
+ function isFile(mode: number): boolean;
155
+ function isDir(mode: number): boolean;
156
+ function isLink(mode: number): boolean;
157
+ function isChrdev(mode: number): boolean;
158
+ function isBlkdev(mode: number): boolean;
159
+ function isFIFO(mode: number): boolean;
160
+ function isSocket(mode: number): boolean;
161
+ function major(dev: number): number;
162
+ function minor(dev: number): number;
163
+ function makedev(ma: number, mi: number): number;
164
+ function registerDevice(dev: number, ops: any): void;
165
+ function syncfs(populate: boolean, callback: (e: any) => any): void;
166
+ function syncfs(callback: (e: any) => any, populate?: boolean): void;
167
+ function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any;
168
+ function unmount(mountpoint: string): void;
169
+ function mkdir(path: string, mode?: number): any;
170
+ function mkdev(path: string, mode?: number, dev?: number): any;
171
+ function symlink(oldpath: string, newpath: string): any;
172
+ function rename(old_path: string, new_path: string): void;
173
+ function rmdir(path: string): void;
174
+ function readdir(path: string): any;
175
+ function unlink(path: string): void;
176
+ function readlink(path: string): string;
177
+ function stat(path: string, dontFollow?: boolean): any;
178
+ function lstat(path: string): any;
179
+ function chmod(path: string, mode: number, dontFollow?: boolean): void;
180
+ function lchmod(path: string, mode: number): void;
181
+ function fchmod(fd: number, mode: number): void;
182
+ function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void;
183
+ function lchown(path: string, uid: number, gid: number): void;
184
+ function fchown(fd: number, uid: number, gid: number): void;
185
+ function truncate(path: string, len: number): void;
186
+ function ftruncate(fd: number, len: number): void;
187
+ function utime(path: string, atime: number, mtime: number): void;
188
+ function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream;
189
+ function close(stream: FSStream): void;
190
+ function llseek(stream: FSStream, offset: number, whence: number): any;
191
+ function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number;
192
+ function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number;
193
+ function allocate(stream: FSStream, offset: number, length: number): void;
194
+ function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any;
195
+ function ioctl(stream: FSStream, cmd: any, arg: any): any;
196
+ function readFile(path: string, opts: {
197
+ encoding: 'binary';
198
+ flags?: string | undefined;
199
+ }): Uint8Array;
200
+ function readFile(path: string, opts: {
201
+ encoding: 'utf8';
202
+ flags?: string | undefined;
203
+ }): string;
204
+ function readFile(path: string, opts?: {
205
+ flags?: string | undefined;
206
+ }): Uint8Array;
207
+ function writeFile(path: string, data: string | ArrayBufferView, opts?: {
208
+ flags?: string | undefined;
209
+ }): void;
210
+ function cwd(): string;
211
+ function chdir(path: string): void;
212
+ function init(input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any)): void;
213
+ function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode;
214
+ function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void;
215
+ function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode;
216
+ }
217
+ export const MEMFS: Emscripten.FileSystemType;
218
+ export const NODEFS: Emscripten.FileSystemType;
219
+ export const IDBFS: Emscripten.FileSystemType;
220
+ type StringToType<R> = R extends Emscripten.JSType ? {
221
+ number: number;
222
+ string: string;
223
+ array: number[] | string[] | boolean[] | Uint8Array | Int8Array;
224
+ boolean: boolean;
225
+ null: null;
226
+ }[R] : never;
227
+ type ArgsToType<T extends Array<Emscripten.JSType | null>> = Extract<{
228
+ [P in keyof T]: StringToType<T[P]>;
229
+ }, any[]>;
230
+ type ReturnToType<R extends Emscripten.JSType | null> = R extends null ? null : StringToType<Exclude<R, null>>;
231
+ 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>;
232
+ 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>;
233
+ export function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void;
234
+ export function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number;
235
+ export function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number;
236
+ export function stackAlloc(size: number): number;
237
+ export function stackSave(): number;
238
+ export function stackRestore(ptr: number): void;
239
+ export function UTF8ToString(ptr: number, maxBytesToRead?: number): string;
240
+ export function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void;
241
+ export function lengthBytesUTF8(str: string): number;
242
+ export function allocateUTF8(str: string): number;
243
+ export function allocateUTF8OnStack(str: string): number;
244
+ export function UTF16ToString(ptr: number): string;
245
+ export function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void;
246
+ export function lengthBytesUTF16(str: string): number;
247
+ export function UTF32ToString(ptr: number): string;
248
+ export function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void;
249
+ export function lengthBytesUTF32(str: string): number;
250
+ export function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[];
251
+ export function intArrayToString(array: number[]): string;
252
+ export function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void;
253
+ export function writeArrayToMemory(array: number[], buffer: number): void;
254
+ export function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void;
255
+ export function addRunDependency(id: any): void;
256
+ export function removeRunDependency(id: any): void;
257
+ export function addFunction(func: (...args: any[]) => any, signature?: string): number;
258
+ export function removeFunction(funcPtr: number): void;
259
+ export const ALLOC_NORMAL: number;
260
+ export const ALLOC_STACK: number;
261
+ export const ALLOC_STATIC: number;
262
+ export const ALLOC_DYNAMIC: number;
263
+ export const ALLOC_NONE: number;
264
+ export {};
265
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Encodes a multipart/form-data request body.
3
+ *
4
+ * @param data - The form data to encode.
5
+ * @returns The encoded body and a correctly formatted content type header.
6
+ */
7
+ export declare function encodeAsMultipart(data: Record<string, string | Uint8Array | File>): Promise<{
8
+ bytes: Uint8Array;
9
+ contentType: string;
10
+ }>;
@@ -0,0 +1,30 @@
1
+ declare const kError: unique symbol;
2
+ declare const kMessage: unique symbol;
3
+ interface ErrorEventOptions {
4
+ error?: Error;
5
+ message?: string;
6
+ }
7
+ /**
8
+ * Class representing an error event.
9
+ *
10
+ * @extends Event
11
+ */
12
+ declare class ErrorEvent2 extends Event {
13
+ [kError]: any;
14
+ [kMessage]: any;
15
+ /**
16
+ * Create a new `ErrorEvent`.
17
+ *
18
+ * @param type The name of the event
19
+ * @param options A dictionary object that allows for setting
20
+ * attributes via object members of the same name.
21
+ */
22
+ constructor(type: 'error', options?: ErrorEventOptions);
23
+ get error(): any;
24
+ get message(): any;
25
+ }
26
+ export declare const ErrorEvent: typeof ErrorEvent2 | {
27
+ new (type: string, eventInitDict?: ErrorEventInit | undefined): ErrorEvent;
28
+ prototype: ErrorEvent;
29
+ };
30
+ export {};
@@ -0,0 +1,94 @@
1
+ import { Emscripten } from './emscripten-types';
2
+ export interface RmDirOptions {
3
+ /**
4
+ * If true, recursively removes the directory and all its contents.
5
+ * Default: true.
6
+ */
7
+ recursive?: boolean;
8
+ }
9
+ export interface ListFilesOptions {
10
+ /**
11
+ * If true, prepend given folder path to all file names.
12
+ * Default: false.
13
+ */
14
+ prependPath: boolean;
15
+ }
16
+ export declare class FSHelpers {
17
+ /**
18
+ * Reads a file from the PHP filesystem and returns it as a string.
19
+ *
20
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
21
+ * @param path - The file path to read.
22
+ * @returns The file contents.
23
+ */
24
+ static readFileAsText(FS: Emscripten.RootFS, path: string): string;
25
+ /**
26
+ * Reads a file from the PHP filesystem and returns it as an array buffer.
27
+ *
28
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
29
+ * @param path - The file path to read.
30
+ * @returns The file contents.
31
+ */
32
+ static readFileAsBuffer(FS: Emscripten.RootFS, path: string): Uint8Array;
33
+ /**
34
+ * Overwrites data in a file in the PHP filesystem.
35
+ * Creates a new file if one doesn't exist yet.
36
+ *
37
+ * @param path - The file path to write to.
38
+ * @param data - The data to write to the file.
39
+ */
40
+ static writeFile(FS: Emscripten.RootFS, path: string, data: string | Uint8Array): void;
41
+ /**
42
+ * Removes a file from the PHP filesystem.
43
+ *
44
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
45
+ * @param path - The file path to remove.
46
+ */
47
+ static unlink(FS: Emscripten.RootFS, path: string): void;
48
+ /**
49
+ * Moves a file or directory in the PHP filesystem to a
50
+ * new location.
51
+ *
52
+ * @param oldPath The path to rename.
53
+ * @param newPath The new path.
54
+ */
55
+ static mv(FS: Emscripten.RootFS, fromPath: string, toPath: string): void;
56
+ /**
57
+ * Removes a directory from the PHP filesystem.
58
+ *
59
+ * @param path The directory path to remove.
60
+ * @param options Options for the removal.
61
+ */
62
+ static rmdir(FS: Emscripten.RootFS, path: string, options?: RmDirOptions): void;
63
+ /**
64
+ * Lists the files and directories in the given directory.
65
+ *
66
+ * @param path - The directory path to list.
67
+ * @param options - Options for the listing.
68
+ * @returns The list of files and directories in the given directory.
69
+ */
70
+ static listFiles(FS: Emscripten.RootFS, path: string, options?: ListFilesOptions): string[];
71
+ /**
72
+ * Checks if a directory exists in the PHP filesystem.
73
+ *
74
+ * @param path – The path to check.
75
+ * @returns True if the path is a directory, false otherwise.
76
+ */
77
+ static isDir(FS: Emscripten.RootFS, path: string): boolean;
78
+ /**
79
+ * Checks if a file (or a directory) exists in the PHP filesystem.
80
+ *
81
+ * @param path - The file path to check.
82
+ * @returns True if the file exists, false otherwise.
83
+ */
84
+ static fileExists(FS: Emscripten.RootFS, path: string): boolean;
85
+ /**
86
+ * Recursively creates a directory with the given path in the PHP filesystem.
87
+ * For example, if the path is `/root/php/data`, and `/root` already exists,
88
+ * it will create the directories `/root/php` and `/root/php/data`.
89
+ *
90
+ * @param path - The directory path to create.
91
+ */
92
+ static mkdir(FS: Emscripten.RootFS, path: string): void;
93
+ static copyRecursive(FS: Emscripten.FileSystemInstance, fromPath: string, toPath: string): void;
94
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @public
3
+ */
4
+ export declare class HttpCookieStore {
5
+ cookies: Record<string, string>;
6
+ rememberCookiesFromResponseHeaders(headers: Record<string, string[]>): void;
7
+ getCookieRequestHeader(): string;
8
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ export type { MessageListener, PHPOutput, PHPRunOptions, UniversalPHP, PHPEvent, PHPEventListener, HTTPMethod, PHPRequest, PHPRequestHeaders, SpawnHandler, } from './universal-php';
2
+ export { FSHelpers } from './fs-helpers';
3
+ export type { ListFilesOptions, RmDirOptions } from './fs-helpers';
4
+ export { PHPWorker } from './php-worker';
5
+ export { getPhpIniEntries, setPhpIniEntries, withPHPIniValues } from './ini';
6
+ export { UnhandledRejectionsTarget } from './wasm-error-reporting';
7
+ export { HttpCookieStore } from './http-cookie-store';
8
+ export type { IteratePhpFilesOptions as IterateFilesOptions } from './iterate-files';
9
+ export { iteratePhpFiles as iterateFiles } from './iterate-files';
10
+ export { writeFilesStreamToPhp } from './write-files-stream-to-php';
11
+ export { PHPProcessManager } from './php-process-manager';
12
+ export type { MaxPhpInstancesError, PHPFactory, PHPFactoryOptions, ProcessManagerOptions, SpawnedPHP, } from './php-process-manager';
13
+ export { PHPResponse } from './php-response';
14
+ export type { PHPResponseData } from './php-response';
15
+ export type { ErrnoError } from './rethrow-file-system-error';
16
+ export { LatestSupportedPHPVersion, SupportedPHPVersions, SupportedPHPVersionsList, } from './supported-php-versions';
17
+ export type { SupportedPHPVersion } from './supported-php-versions';
18
+ export { SupportedPHPExtensionsList, SupportedPHPExtensionBundles, } from './supported-php-extensions';
19
+ export type { SupportedPHPExtension, SupportedPHPExtensionBundle, } from './supported-php-extensions';
20
+ export { PHP, __private__dont__use } from './php';
21
+ export type { MountHandler, UnmountFunction } from './php';
22
+ export { loadPHPRuntime } from './load-php-runtime';
23
+ export type * from './emscripten-types';
24
+ export type { DataModule, EmscriptenOptions, PHPLoaderModule, PHPRuntime, PHPRuntimeId, RuntimeType, } from './load-php-runtime';
25
+ export type { PHPRequestHandlerConfiguration, RewriteRule, } from './php-request-handler';
26
+ export { PHPRequestHandler, applyRewriteRules } from './php-request-handler';
27
+ export { rotatePHPRuntime } from './rotate-php-runtime';
28
+ export { writeFiles } from './write-files';
29
+ export type { FileTree } from './write-files';
30
+ export { DEFAULT_BASE_URL, ensurePathPrefix, removePathPrefix, toRelativeUrl, } from './urls';
31
+ export { isExitCodeZero } from './is-exit-code-zero';
32
+ export { proxyFileSystem } from './proxy-file-system';
package/lib/ini.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import { UniversalPHP } from './universal-php';
2
+ /**
3
+ * Reads the php.ini file and returns its entries.
4
+ *
5
+ * @param php The PHP instance.
6
+ * @param entries Optional. If provided, only the specified entries will be returned.
7
+ * @returns The php.ini entries.
8
+ */
9
+ export declare function getPhpIniEntries(php: UniversalPHP, entries?: string[]): Promise<{
10
+ [key: string]: any;
11
+ }>;
12
+ /**
13
+ * Rewrites the php.ini file with the given entries.
14
+ *
15
+ * @param php The PHP instance.
16
+ * @param entries The entries to write to the php.ini file.
17
+ */
18
+ export declare function setPhpIniEntries(php: UniversalPHP, entries: Record<string, unknown>): Promise<void>;
19
+ /**
20
+ * Sets php.ini values to the given values, executes a callback,
21
+ * and restores the original php.ini values. This is useful for
22
+ * running code with temporary php.ini values, such as when
23
+ * disabling network-related PHP functions just to run WordPress
24
+ * installer.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * await withPHPIniValues(
29
+ * php,
30
+ * {
31
+ * disable_functions: 'fsockopen',
32
+ * allow_url_fopen: '0',
33
+ * },
34
+ * async () => await runWpInstallationWizard(php, {
35
+ * options: {},
36
+ * })
37
+ * );
38
+ * ```
39
+ *
40
+ * @param php The PHP instance.
41
+ * @param phpIniValues The php.ini values to set.
42
+ * @param callback The callback to execute.
43
+ * @returns The result of the callback.
44
+ */
45
+ export declare function withPHPIniValues(php: UniversalPHP, phpIniValues: Record<string, string>, callback: () => Promise<any>): Promise<any>;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Check if the Emscripten-thrown error is an exit code 0 error.
3
+ *
4
+ * @param e The error to check
5
+ * @returns True if the error is an exit code 0 error
6
+ */
7
+ export declare function isExitCodeZero(e: any): boolean;
@@ -0,0 +1,26 @@
1
+ import { UniversalPHP } from './universal-php';
2
+ export type IteratePhpFilesOptions = {
3
+ /**
4
+ * Should yield paths relative to the root directory?
5
+ * If false, all paths will be absolute.
6
+ */
7
+ relativePaths?: boolean;
8
+ /**
9
+ * A prefix to add to all paths.
10
+ * Only used if `relativePaths` is true.
11
+ */
12
+ pathPrefix?: string;
13
+ /**
14
+ * A list of paths to exclude from the results.
15
+ */
16
+ exceptPaths?: string[];
17
+ };
18
+ /**
19
+ * Iterates over all files in a php directory and its subdirectories.
20
+ *
21
+ * @param php - The PHP instance.
22
+ * @param root - The root directory to start iterating from.
23
+ * @param options - Optional configuration.
24
+ * @returns All files found in the tree.
25
+ */
26
+ export declare function iteratePhpFiles(php: UniversalPHP, root: string, { relativePaths, pathPrefix, exceptPaths, }?: IteratePhpFilesOptions): AsyncGenerator<File>;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Loads the PHP runtime with the given arguments and data dependencies.
3
+ *
4
+ * This function handles the entire PHP initialization pipeline. In particular, it:
5
+ *
6
+ * * Instantiates the Emscripten PHP module
7
+ * * Wires it together with the data dependencies and loads them
8
+ * * Ensures is all happens in a correct order
9
+ * * Waits until the entire loading sequence is finished
10
+ *
11
+ * Basic usage:
12
+ *
13
+ * ```js
14
+ * const phpLoaderModule = await getPHPLoaderModule("7.4");
15
+ * const php = await loadPHPRuntime( phpLoaderModule );
16
+ * console.log(php.run(`<?php echo "Hello, world!"; `));
17
+ * // { stdout: ArrayBuffer containing the string "Hello, world!", stderr: [''], exitCode: 0 }
18
+ * ```
19
+ *
20
+ * **The PHP loader module:**
21
+ *
22
+ * In the basic usage example, `phpLoaderModule` is **not** a vanilla Emscripten module. Instead,
23
+ * it's an ESM module that wraps the regular Emscripten output and adds some
24
+ * extra functionality. It's generated by the Dockerfile shipped with this repo.
25
+ * Here's the API it provides:
26
+ *
27
+ * ```js
28
+ * // php.wasm size in bytes:
29
+ * export const dependenciesTotalSize = 5644199;
30
+ *
31
+ * // php.wasm filename:
32
+ * export const dependencyFilename = 'php.wasm';
33
+ *
34
+ * // Run Emscripten's generated module:
35
+ * export default function(jsEnv, emscriptenModuleArgs) {}
36
+ * ```
37
+ *
38
+ * **PHP Filesystem:**
39
+ *
40
+ * Once initialized, the PHP has its own filesystem separate from the project
41
+ * files. It's provided by [Emscripten and uses its FS library](https://emscripten.org/docs/api_reference/Filesystem-API.html).
42
+ *
43
+ * The API exposed to you via the PHP class is succinct and abstracts
44
+ * certain unintuitive parts of low-level filesystem interactions.
45
+ *
46
+ * Here's how to use it:
47
+ *
48
+ * ```js
49
+ * // Recursively create a /var/www directory
50
+ * php.mkdirTree('/var/www');
51
+ *
52
+ * console.log(php.fileExists('/var/www/file.txt'));
53
+ * // false
54
+ *
55
+ * php.writeFile('/var/www/file.txt', 'Hello from the filesystem!');
56
+ *
57
+ * console.log(php.fileExists('/var/www/file.txt'));
58
+ * // true
59
+ *
60
+ * console.log(php.readFile('/var/www/file.txt'));
61
+ * // "Hello from the filesystem!
62
+ *
63
+ * // Delete the file:
64
+ * php.unlink('/var/www/file.txt');
65
+ * ```
66
+ *
67
+ * For more details consult the PHP class directly.
68
+ *
69
+ * **Data dependencies:**
70
+ *
71
+ * Using existing PHP packages by manually recreating them file-by-file would
72
+ * be quite inconvenient. Fortunately, Emscripten provides a "data dependencies"
73
+ * feature.
74
+ *
75
+ * Data dependencies consist of a `dependency.data` file and a `dependency.js` loader and
76
+ * can be packaged with the [file_packager.py tool]( https://emscripten.org/docs/porting/files/packaging_files.html#packaging-using-the-file-packager-tool).
77
+ * This project requires wrapping the Emscripten-generated `dependency.js` file in an ES
78
+ * module as follows:
79
+ *
80
+ * 1. Prepend `export default function(emscriptenPHPModule) {'; `
81
+ * 2. Prepend `export const dependencyFilename = '<DATA FILE NAME>'; `
82
+ * 3. Prepend `export const dependenciesTotalSize = <DATA FILE SIZE>;`
83
+ * 4. Append `}`
84
+ *
85
+ * Be sure to use the `--export-name="emscriptenPHPModule"` file_packager.py option.
86
+ *
87
+ * You want the final output to look as follows:
88
+ *
89
+ * ```js
90
+ * export const dependenciesTotalSize = 5644199;
91
+ * export const dependencyFilename = 'dependency.data';
92
+ * export default function(emscriptenPHPModule) {
93
+ * // Emscripten-generated code:
94
+ * var Module = typeof emscriptenPHPModule !== 'undefined' ? emscriptenPHPModule : {};
95
+ * // ... the rest of it ...
96
+ * }
97
+ * ```
98
+ *
99
+ * Such a constructions enables loading the `dependency.js` as an ES Module using
100
+ * `import("/dependency.js")`.
101
+ *
102
+ * Once it's ready, you can load PHP and your data dependencies as follows:
103
+ *
104
+ * ```js
105
+ * const [phpLoaderModule, wordPressLoaderModule] = await Promise.all([
106
+ * getPHPLoaderModule("7.4"),
107
+ * import("/wp.js")
108
+ * ]);
109
+ * const php = await loadPHPRuntime(phpLoaderModule, {}, [wordPressLoaderModule]);
110
+ * ```
111
+ *
112
+ * @public
113
+ * @param phpLoaderModule - The ESM-wrapped Emscripten module. Consult the Dockerfile for the build process.
114
+ * @param phpModuleArgs - The Emscripten module arguments, see https://emscripten.org/docs/api_reference/module.html#affecting-execution.
115
+ * @returns Loaded runtime id.
116
+ */
117
+ export declare function loadPHPRuntime(phpLoaderModule: PHPLoaderModule, phpModuleArgs?: EmscriptenOptions): Promise<number>;
118
+ export type RuntimeType = 'NODE' | 'WEB' | 'WORKER';
119
+ export type PHPRuntimeId = number;
120
+ export declare function getLoadedRuntime(id: PHPRuntimeId): PHPRuntime;
121
+ export declare const currentJsRuntime: string;
122
+ export type PHPRuntime = any;
123
+ export type PHPLoaderModule = {
124
+ dependencyFilename: string;
125
+ dependenciesTotalSize: number;
126
+ init: (jsRuntime: string, options: EmscriptenOptions) => PHPRuntime;
127
+ };
128
+ export type DataModule = {
129
+ dependencyFilename: string;
130
+ dependenciesTotalSize: number;
131
+ default: (phpRuntime: PHPRuntime) => void;
132
+ };
133
+ export type EmscriptenOptions = {
134
+ onAbort?: (message: string) => void;
135
+ /**
136
+ * Set to true for debugging tricky WebAssembly errors.
137
+ */
138
+ debug?: boolean;
139
+ ENV?: Record<string, string>;
140
+ locateFile?: (path: string) => string;
141
+ noInitialRun?: boolean;
142
+ print?: (message: string) => void;
143
+ printErr?: (message: string) => void;
144
+ quit?: (status: number, toThrow: any) => void;
145
+ onRuntimeInitialized?: () => void;
146
+ monitorRunDependencies?: (left: number) => void;
147
+ onMessage?: (listener: EmscriptenMessageListener) => void;
148
+ instantiateWasm?: (info: WebAssembly.Imports, receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void) => void;
149
+ } & Record<string, any>;
150
+ export type EmscriptenMessageListener = (type: string, data: string) => void;