@php-wasm/universal 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.
package/index.js CHANGED
@@ -1,30 +1,30 @@
1
- var Y = (e, t, s) => {
2
- if (!t.has(e))
3
- throw TypeError("Cannot " + s);
1
+ var Y = (t, e, r) => {
2
+ if (!e.has(t))
3
+ throw TypeError("Cannot " + r);
4
4
  };
5
- var u = (e, t, s) => (Y(e, t, "read from private field"), s ? s.call(e) : t.get(e)), d = (e, t, s) => {
6
- if (t.has(e))
5
+ var u = (t, e, r) => (Y(t, e, "read from private field"), r ? r.call(t) : e.get(t)), p = (t, e, r) => {
6
+ if (e.has(t))
7
7
  throw TypeError("Cannot add the same private member more than once");
8
- t instanceof WeakSet ? t.add(e) : t.set(e, s);
9
- }, f = (e, t, s, r) => (Y(e, t, "write to private field"), r ? r.call(e, s) : t.set(e, s), s);
10
- var h = (e, t, s) => (Y(e, t, "access private method"), s);
8
+ e instanceof WeakSet ? e.add(t) : e.set(t, r);
9
+ }, f = (t, e, r, s) => (Y(t, e, "write to private field"), s ? s.call(t, r) : e.set(t, r), r);
10
+ var h = (t, e, r) => (Y(t, e, "access private method"), r);
11
11
  const currentJsRuntime$1 = function() {
12
- var e;
13
- return typeof process < "u" && ((e = process.release) == null ? void 0 : e.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : (
12
+ var t;
13
+ return typeof process < "u" && ((t = process.release) == null ? void 0 : t.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : (
14
14
  // @ts-ignore
15
15
  typeof WorkerGlobalScope < "u" && // @ts-ignore
16
16
  self instanceof WorkerGlobalScope ? "WORKER" : "NODE"
17
17
  );
18
18
  }();
19
19
  if (currentJsRuntime$1 === "NODE") {
20
- let e = function(s) {
21
- return new Promise(function(r, n) {
22
- s.onload = s.onerror = function(i) {
23
- s.onload = s.onerror = null, i.type === "load" ? r(s.result) : n(new Error("Failed to read the blob/file"));
20
+ let t = function(r) {
21
+ return new Promise(function(s, n) {
22
+ r.onload = r.onerror = function(i) {
23
+ r.onload = r.onerror = null, i.type === "load" ? s(r.result) : n(new Error("Failed to read the blob/file"));
24
24
  };
25
25
  });
26
- }, t = function() {
27
- const s = new Uint8Array([1, 2, 3, 4]), n = new File([s], "test").stream();
26
+ }, e = function() {
27
+ const r = new Uint8Array([1, 2, 3, 4]), n = new File([r], "test").stream();
28
28
  try {
29
29
  return n.getReader({ mode: "byob" }), !0;
30
30
  } catch {
@@ -32,109 +32,50 @@ if (currentJsRuntime$1 === "NODE") {
32
32
  }
33
33
  };
34
34
  if (typeof File > "u") {
35
- class s extends Blob {
35
+ class r extends Blob {
36
36
  constructor(n, i, o) {
37
37
  super(n);
38
- let c;
39
- o != null && o.lastModified && (c = /* @__PURE__ */ new Date()), (!c || isNaN(c.getFullYear())) && (c = /* @__PURE__ */ new Date()), this.lastModifiedDate = c, this.lastModified = c.getMilliseconds(), this.name = i || "";
38
+ let l;
39
+ o != null && o.lastModified && (l = /* @__PURE__ */ new Date()), (!l || isNaN(l.getFullYear())) && (l = /* @__PURE__ */ new Date()), this.lastModifiedDate = l, this.lastModified = l.getMilliseconds(), this.name = i || "";
40
40
  }
41
41
  }
42
- global.File = s;
42
+ global.File = r;
43
43
  }
44
44
  typeof Blob.prototype.arrayBuffer > "u" && (Blob.prototype.arrayBuffer = function() {
45
- const r = new FileReader();
46
- return r.readAsArrayBuffer(this), e(r);
45
+ const s = new FileReader();
46
+ return s.readAsArrayBuffer(this), t(s);
47
47
  }), typeof Blob.prototype.text > "u" && (Blob.prototype.text = function() {
48
- const r = new FileReader();
49
- return r.readAsText(this), e(r);
50
- }), (typeof Blob.prototype.stream > "u" || !t()) && (Blob.prototype.stream = function() {
51
- let s = 0;
52
- const r = this;
48
+ const s = new FileReader();
49
+ return s.readAsText(this), t(s);
50
+ }), (typeof Blob.prototype.stream > "u" || !e()) && (Blob.prototype.stream = function() {
51
+ let r = 0;
52
+ const s = this;
53
53
  return new ReadableStream({
54
54
  type: "bytes",
55
55
  // 0.5 MB seems like a reasonable chunk size, let's adjust
56
56
  // this if needed.
57
57
  autoAllocateChunkSize: 512 * 1024,
58
58
  async pull(n) {
59
- const i = n.byobRequest.view, c = await r.slice(
60
- s,
61
- s + i.byteLength
62
- ).arrayBuffer(), l = new Uint8Array(c);
63
- new Uint8Array(i.buffer).set(l);
64
- const a = l.byteLength;
65
- n.byobRequest.respond(a), s += a, s >= r.size && n.close();
59
+ const i = n.byobRequest.view, l = await s.slice(
60
+ r,
61
+ r + i.byteLength
62
+ ).arrayBuffer(), c = new Uint8Array(l);
63
+ new Uint8Array(i.buffer).set(c);
64
+ const a = c.byteLength;
65
+ n.byobRequest.respond(a), r += a, r >= s.size && n.close();
66
66
  }
67
67
  });
68
68
  });
69
69
  }
70
70
  if (currentJsRuntime$1 === "NODE" && typeof CustomEvent > "u") {
71
- class e extends Event {
72
- constructor(s, r = {}) {
73
- super(s, r), this.detail = r.detail;
71
+ class t extends Event {
72
+ constructor(r, s = {}) {
73
+ super(r, s), this.detail = s.detail;
74
74
  }
75
75
  initCustomEvent() {
76
76
  }
77
77
  }
78
- globalThis.CustomEvent = e;
79
- }
80
- const responseTexts = {
81
- 500: "Internal Server Error",
82
- 502: "Bad Gateway",
83
- 404: "Not Found",
84
- 403: "Forbidden",
85
- 401: "Unauthorized",
86
- 400: "Bad Request",
87
- 301: "Moved Permanently",
88
- 302: "Found",
89
- 307: "Temporary Redirect",
90
- 308: "Permanent Redirect",
91
- 204: "No Content",
92
- 201: "Created",
93
- 200: "OK"
94
- };
95
- class PHPResponse {
96
- constructor(t, s, r, n = "", i = 0) {
97
- this.httpStatusCode = t, this.headers = s, this.bytes = r, this.exitCode = i, this.errors = n;
98
- }
99
- static forHttpCode(t, s = "") {
100
- return new PHPResponse(
101
- t,
102
- {},
103
- new TextEncoder().encode(
104
- s || responseTexts[t] || ""
105
- )
106
- );
107
- }
108
- static fromRawData(t) {
109
- return new PHPResponse(
110
- t.httpStatusCode,
111
- t.headers,
112
- t.bytes,
113
- t.errors,
114
- t.exitCode
115
- );
116
- }
117
- toRawData() {
118
- return {
119
- headers: this.headers,
120
- bytes: this.bytes,
121
- errors: this.errors,
122
- exitCode: this.exitCode,
123
- httpStatusCode: this.httpStatusCode
124
- };
125
- }
126
- /**
127
- * Response body as JSON.
128
- */
129
- get json() {
130
- return JSON.parse(this.text);
131
- }
132
- /**
133
- * Response body as text.
134
- */
135
- get text() {
136
- return new TextDecoder().decode(this.bytes);
137
- }
78
+ globalThis.CustomEvent = t;
138
79
  }
139
80
  const FileErrorCodes = {
140
81
  0: "No error occurred. System call completed successfully.",
@@ -215,69 +156,78 @@ const FileErrorCodes = {
215
156
  75: "Cross-device link.",
216
157
  76: "Extension: Capabilities insufficient."
217
158
  };
218
- function getEmscriptenFsError(e) {
219
- const t = typeof e == "object" ? e == null ? void 0 : e.errno : null;
220
- if (t in FileErrorCodes)
221
- return FileErrorCodes[t];
159
+ function getEmscriptenFsError(t) {
160
+ const e = typeof t == "object" ? t == null ? void 0 : t.errno : null;
161
+ if (e in FileErrorCodes)
162
+ return FileErrorCodes[e];
222
163
  }
223
- function rethrowFileSystemError(e = "") {
224
- return function(s, r, n) {
164
+ function rethrowFileSystemError(t = "") {
165
+ return function(r, s, n) {
225
166
  const i = n.value;
226
167
  n.value = function(...o) {
227
168
  try {
228
169
  return i.apply(this, o);
229
- } catch (c) {
230
- const l = typeof c == "object" ? c == null ? void 0 : c.errno : null;
231
- if (l in FileErrorCodes) {
232
- const a = FileErrorCodes[l], p = typeof o[0] == "string" ? o[0] : null, m = p !== null ? e.replaceAll("{path}", p) : e;
170
+ } catch (l) {
171
+ const c = typeof l == "object" ? l == null ? void 0 : l.errno : null;
172
+ if (c in FileErrorCodes) {
173
+ const a = FileErrorCodes[c], d = typeof o[1] == "string" ? o[1] : null, m = d !== null ? t.replaceAll("{path}", d) : t;
233
174
  throw new Error(`${m}: ${a}`, {
234
- cause: c
175
+ cause: l
235
176
  });
236
177
  }
237
- throw c;
178
+ throw l;
238
179
  }
239
180
  };
240
181
  };
241
182
  }
242
- const logToConsole = (e, ...t) => {
243
- switch (typeof e.message == "string" ? e.message = prepareLogMessage(e.message) : e.message.message && typeof e.message.message == "string" && (e.message.message = prepareLogMessage(e.message.message)), e.severity) {
183
+ const logEventType = "playground-log", logEvent = (t, ...e) => {
184
+ logger.dispatchEvent(
185
+ new CustomEvent(logEventType, {
186
+ detail: {
187
+ log: t,
188
+ args: e
189
+ }
190
+ })
191
+ );
192
+ }, logToConsole = (t, ...e) => {
193
+ switch (typeof t.message == "string" ? t.message = prepareLogMessage(t.message) : t.message.message && typeof t.message.message == "string" && (t.message.message = prepareLogMessage(t.message.message)), t.severity) {
244
194
  case "Debug":
245
- console.debug(e.message, ...t);
195
+ console.debug(t.message, ...e);
246
196
  break;
247
197
  case "Info":
248
- console.info(e.message, ...t);
198
+ console.info(t.message, ...e);
249
199
  break;
250
200
  case "Warn":
251
- console.warn(e.message, ...t);
201
+ console.warn(t.message, ...e);
252
202
  break;
253
203
  case "Error":
254
- console.error(e.message, ...t);
204
+ console.error(t.message, ...e);
255
205
  break;
256
206
  case "Fatal":
257
- console.error(e.message, ...t);
207
+ console.error(t.message, ...e);
258
208
  break;
259
209
  default:
260
- console.log(e.message, ...t);
261
- }
262
- }, prepareLogMessage$1 = (e) => e instanceof Error ? [e.message, e.stack].join(`
263
- `) : JSON.stringify(e, null, 2), logs = [], addToLogArray = (e) => {
264
- logs.push(e);
265
- }, logToMemory = (e) => {
266
- if (e.raw === !0)
267
- addToLogArray(e.message);
210
+ console.log(t.message, ...e);
211
+ }
212
+ }, prepareLogMessage$1 = (t) => t instanceof Error ? [t.message, t.stack].join(`
213
+ `) : JSON.stringify(t, null, 2), logs = [], addToLogArray = (t) => {
214
+ logs.push(t);
215
+ }, logToMemory = (t) => {
216
+ if (t.raw === !0)
217
+ addToLogArray(t.message);
268
218
  else {
269
- const t = formatLogEntry(
270
- typeof e.message == "object" ? prepareLogMessage$1(e.message) : e.message,
271
- e.severity ?? "Info",
272
- e.prefix ?? "JavaScript"
219
+ const e = formatLogEntry(
220
+ typeof t.message == "object" ? prepareLogMessage$1(t.message) : t.message,
221
+ t.severity ?? "Info",
222
+ t.prefix ?? "JavaScript"
273
223
  );
274
- addToLogArray(t);
224
+ addToLogArray(e);
275
225
  }
276
226
  };
277
227
  class Logger extends EventTarget {
278
228
  // constructor
279
- constructor(t = []) {
280
- super(), this.handlers = t, this.fatalErrorEvent = "playground-fatal-error";
229
+ constructor(e = []) {
230
+ super(), this.handlers = e, this.fatalErrorEvent = "playground-fatal-error";
281
231
  }
282
232
  /**
283
233
  * Get all logs.
@@ -296,9 +246,9 @@ class Logger extends EventTarget {
296
246
  * @param raw boolean
297
247
  * @param args any
298
248
  */
299
- logMessage(t, ...s) {
300
- for (const r of this.handlers)
301
- r(t, ...s);
249
+ logMessage(e, ...r) {
250
+ for (const s of this.handlers)
251
+ s(e, ...r);
302
252
  }
303
253
  /**
304
254
  * Log message
@@ -306,15 +256,15 @@ class Logger extends EventTarget {
306
256
  * @param message any
307
257
  * @param args any
308
258
  */
309
- log(t, ...s) {
259
+ log(e, ...r) {
310
260
  this.logMessage(
311
261
  {
312
- message: t,
262
+ message: e,
313
263
  severity: void 0,
314
264
  prefix: "JavaScript",
315
265
  raw: !1
316
266
  },
317
- ...s
267
+ ...r
318
268
  );
319
269
  }
320
270
  /**
@@ -323,15 +273,15 @@ class Logger extends EventTarget {
323
273
  * @param message any
324
274
  * @param args any
325
275
  */
326
- debug(t, ...s) {
276
+ debug(e, ...r) {
327
277
  this.logMessage(
328
278
  {
329
- message: t,
279
+ message: e,
330
280
  severity: "Debug",
331
281
  prefix: "JavaScript",
332
282
  raw: !1
333
283
  },
334
- ...s
284
+ ...r
335
285
  );
336
286
  }
337
287
  /**
@@ -340,15 +290,15 @@ class Logger extends EventTarget {
340
290
  * @param message any
341
291
  * @param args any
342
292
  */
343
- info(t, ...s) {
293
+ info(e, ...r) {
344
294
  this.logMessage(
345
295
  {
346
- message: t,
296
+ message: e,
347
297
  severity: "Info",
348
298
  prefix: "JavaScript",
349
299
  raw: !1
350
300
  },
351
- ...s
301
+ ...r
352
302
  );
353
303
  }
354
304
  /**
@@ -357,15 +307,15 @@ class Logger extends EventTarget {
357
307
  * @param message any
358
308
  * @param args any
359
309
  */
360
- warn(t, ...s) {
310
+ warn(e, ...r) {
361
311
  this.logMessage(
362
312
  {
363
- message: t,
313
+ message: e,
364
314
  severity: "Warn",
365
315
  prefix: "JavaScript",
366
316
  raw: !1
367
317
  },
368
- ...s
318
+ ...r
369
319
  );
370
320
  }
371
321
  /**
@@ -374,75 +324,548 @@ class Logger extends EventTarget {
374
324
  * @param message any
375
325
  * @param args any
376
326
  */
377
- error(t, ...s) {
327
+ error(e, ...r) {
378
328
  this.logMessage(
379
329
  {
380
- message: t,
330
+ message: e,
381
331
  severity: "Error",
382
332
  prefix: "JavaScript",
383
333
  raw: !1
384
334
  },
385
- ...s
335
+ ...r
386
336
  );
387
337
  }
388
338
  }
389
339
  const getDefaultHandlers = () => {
390
340
  try {
391
341
  if (process.env.NODE_ENV === "test")
392
- return [logToMemory];
342
+ return [logToMemory, logEvent];
393
343
  } catch {
394
344
  }
395
- return [logToMemory, logToConsole];
396
- }, logger = new Logger(getDefaultHandlers()), prepareLogMessage = (e) => e.replace(/\t/g, ""), formatLogEntry = (e, t, s) => {
397
- const r = /* @__PURE__ */ new Date(), n = new Intl.DateTimeFormat("en-GB", {
345
+ return [logToMemory, logToConsole, logEvent];
346
+ }, logger = new Logger(getDefaultHandlers()), prepareLogMessage = (t) => t.replace(/\t/g, ""), formatLogEntry = (t, e, r) => {
347
+ const s = /* @__PURE__ */ new Date(), n = new Intl.DateTimeFormat("en-GB", {
398
348
  year: "numeric",
399
349
  month: "short",
400
350
  day: "2-digit",
401
351
  timeZone: "UTC"
402
- }).format(r).replace(/ /g, "-"), i = new Intl.DateTimeFormat("en-GB", {
352
+ }).format(s).replace(/ /g, "-"), i = new Intl.DateTimeFormat("en-GB", {
403
353
  hour: "2-digit",
404
354
  minute: "2-digit",
405
355
  second: "2-digit",
406
356
  hour12: !1,
407
357
  timeZone: "UTC",
408
358
  timeZoneName: "short"
409
- }).format(r), o = n + " " + i;
410
- return e = prepareLogMessage(e), `[${o}] ${s} ${t}: ${e}`;
411
- }, RuntimeId = Symbol("RuntimeId"), loadedRuntimes = /* @__PURE__ */ new Map();
359
+ }).format(s), o = n + " " + i;
360
+ return t = prepareLogMessage(t), `[${o}] ${r} ${e}: ${t}`;
361
+ }, SleepFinished = Symbol("SleepFinished");
362
+ function sleep(t) {
363
+ return new Promise((e) => {
364
+ setTimeout(() => e(SleepFinished), t);
365
+ });
366
+ }
367
+ class AcquireTimeoutError extends Error {
368
+ constructor() {
369
+ super("Acquiring lock timed out");
370
+ }
371
+ }
372
+ class Semaphore {
373
+ constructor({ concurrency: e, timeout: r }) {
374
+ this._running = 0, this.concurrency = e, this.timeout = r, this.queue = [];
375
+ }
376
+ get remaining() {
377
+ return this.concurrency - this.running;
378
+ }
379
+ get running() {
380
+ return this._running;
381
+ }
382
+ async acquire() {
383
+ for (; ; )
384
+ if (this._running >= this.concurrency) {
385
+ const e = new Promise((r) => {
386
+ this.queue.push(r);
387
+ });
388
+ this.timeout !== void 0 ? await Promise.race([e, sleep(this.timeout)]).then(
389
+ (r) => {
390
+ if (r === SleepFinished)
391
+ throw new AcquireTimeoutError();
392
+ }
393
+ ) : await e;
394
+ } else {
395
+ this._running++;
396
+ let e = !1;
397
+ return () => {
398
+ e || (e = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
399
+ };
400
+ }
401
+ }
402
+ async run(e) {
403
+ const r = await this.acquire();
404
+ try {
405
+ return await e();
406
+ } finally {
407
+ r();
408
+ }
409
+ }
410
+ }
411
+ function joinPaths(...t) {
412
+ let e = t.join("/");
413
+ const r = e[0] === "/", s = e.substring(e.length - 1) === "/";
414
+ return e = normalizePath(e), !e && !r && (e = "."), e && s && (e += "/"), e;
415
+ }
416
+ function dirname(t) {
417
+ if (t === "/")
418
+ return "/";
419
+ t = normalizePath(t);
420
+ const e = t.lastIndexOf("/");
421
+ return e === -1 ? "" : e === 0 ? "/" : t.substr(0, e);
422
+ }
423
+ function normalizePath(t) {
424
+ const e = t[0] === "/";
425
+ return t = normalizePathsArray(
426
+ t.split("/").filter((r) => !!r),
427
+ !e
428
+ ).join("/"), (e ? "/" : "") + t.replace(/\/$/, "");
429
+ }
430
+ function normalizePathsArray(t, e) {
431
+ let r = 0;
432
+ for (let s = t.length - 1; s >= 0; s--) {
433
+ const n = t[s];
434
+ n === "." ? t.splice(s, 1) : n === ".." ? (t.splice(s, 1), r++) : r && (t.splice(s, 1), r--);
435
+ }
436
+ if (e)
437
+ for (; r; r--)
438
+ t.unshift("..");
439
+ return t;
440
+ }
441
+ function splitShellCommand(t) {
442
+ let s = 0, n = "";
443
+ const i = [];
444
+ let o = "";
445
+ for (let l = 0; l < t.length; l++) {
446
+ const c = t[l];
447
+ c === "\\" ? ((t[l + 1] === '"' || t[l + 1] === "'") && l++, o += t[l]) : s === 0 ? c === '"' || c === "'" ? (s = 1, n = c) : c.match(/\s/) ? (o.trim().length && i.push(o.trim()), o = c) : i.length && !o ? o = i.pop() + c : o += c : s === 1 && (c === n ? (s = 0, n = "") : o += c);
448
+ }
449
+ return o && i.push(o.trim()), i;
450
+ }
451
+ function createSpawnHandler(t) {
452
+ return function(e, r = [], s = {}) {
453
+ const n = new ChildProcess(), i = new ProcessApi(n);
454
+ return setTimeout(async () => {
455
+ let o = [];
456
+ if (r.length)
457
+ o = [e, ...r];
458
+ else if (typeof e == "string")
459
+ o = splitShellCommand(e);
460
+ else if (Array.isArray(e))
461
+ o = e;
462
+ else
463
+ throw new Error("Invalid command ", e);
464
+ try {
465
+ await t(o, i, s);
466
+ } catch (l) {
467
+ n.emit("error", l), typeof l == "object" && l !== null && "message" in l && typeof l.message == "string" && i.stderr(l.message), i.exit(1);
468
+ }
469
+ n.emit("spawn", !0);
470
+ }), n;
471
+ };
472
+ }
473
+ class EventEmitter {
474
+ constructor() {
475
+ this.listeners = {};
476
+ }
477
+ emit(e, r) {
478
+ this.listeners[e] && this.listeners[e].forEach(function(s) {
479
+ s(r);
480
+ });
481
+ }
482
+ on(e, r) {
483
+ this.listeners[e] || (this.listeners[e] = []), this.listeners[e].push(r);
484
+ }
485
+ }
486
+ class ProcessApi extends EventEmitter {
487
+ constructor(e) {
488
+ super(), this.childProcess = e, this.exited = !1, this.stdinData = [], e.on("stdin", (r) => {
489
+ this.stdinData ? this.stdinData.push(r.slice()) : this.emit("stdin", r);
490
+ });
491
+ }
492
+ stdout(e) {
493
+ typeof e == "string" && (e = new TextEncoder().encode(e)), this.childProcess.stdout.emit("data", e);
494
+ }
495
+ stdoutEnd() {
496
+ this.childProcess.stdout.emit("end", {});
497
+ }
498
+ stderr(e) {
499
+ typeof e == "string" && (e = new TextEncoder().encode(e)), this.childProcess.stderr.emit("data", e);
500
+ }
501
+ stderrEnd() {
502
+ this.childProcess.stderr.emit("end", {});
503
+ }
504
+ exit(e) {
505
+ this.exited || (this.exited = !0, this.childProcess.emit("exit", e));
506
+ }
507
+ flushStdin() {
508
+ if (this.stdinData)
509
+ for (let e = 0; e < this.stdinData.length; e++)
510
+ this.emit("stdin", this.stdinData[e]);
511
+ this.stdinData = null;
512
+ }
513
+ }
514
+ let lastPid = 9743;
515
+ class ChildProcess extends EventEmitter {
516
+ constructor(e = lastPid++) {
517
+ super(), this.pid = e, this.stdout = new EventEmitter(), this.stderr = new EventEmitter();
518
+ const r = this;
519
+ this.stdin = {
520
+ write: (s) => {
521
+ r.emit("stdin", s);
522
+ }
523
+ };
524
+ }
525
+ }
526
+ var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (t, e, r, s) => {
527
+ for (var n = s > 1 ? void 0 : s ? __getOwnPropDesc(e, r) : e, i = t.length - 1, o; i >= 0; i--)
528
+ (o = t[i]) && (n = (s ? o(e, r, n) : o(n)) || n);
529
+ return s && n && __defProp(e, r, n), n;
530
+ };
531
+ const _FSHelpers = class g {
532
+ static readFileAsText(e, r) {
533
+ return new TextDecoder().decode(g.readFileAsBuffer(e, r));
534
+ }
535
+ static readFileAsBuffer(e, r) {
536
+ return e.readFile(r);
537
+ }
538
+ static writeFile(e, r, s) {
539
+ e.writeFile(r, s);
540
+ }
541
+ static unlink(e, r) {
542
+ e.unlink(r);
543
+ }
544
+ /**
545
+ * Moves a file or directory in the PHP filesystem to a
546
+ * new location.
547
+ *
548
+ * @param oldPath The path to rename.
549
+ * @param newPath The new path.
550
+ */
551
+ static mv(e, r, s) {
552
+ try {
553
+ const n = e.lookupPath(r).node.mount, i = g.fileExists(e, s) ? e.lookupPath(s).node.mount : e.lookupPath(dirname(s)).node.mount;
554
+ n.mountpoint !== i.mountpoint ? (g.copyRecursive(e, r, s), g.rmdir(e, r, { recursive: !0 })) : e.rename(r, s);
555
+ } catch (n) {
556
+ const i = getEmscriptenFsError(n);
557
+ throw i ? new Error(
558
+ `Could not move ${r} to ${s}: ${i}`,
559
+ {
560
+ cause: n
561
+ }
562
+ ) : n;
563
+ }
564
+ }
565
+ static rmdir(e, r, s = { recursive: !0 }) {
566
+ s != null && s.recursive && g.listFiles(e, r).forEach((n) => {
567
+ const i = `${r}/${n}`;
568
+ g.isDir(e, i) ? g.rmdir(e, i, s) : g.unlink(e, i);
569
+ }), e.rmdir(r);
570
+ }
571
+ static listFiles(e, r, s = { prependPath: !1 }) {
572
+ if (!g.fileExists(e, r))
573
+ return [];
574
+ try {
575
+ const n = e.readdir(r).filter(
576
+ (i) => i !== "." && i !== ".."
577
+ );
578
+ if (s.prependPath) {
579
+ const i = r.replace(/\/$/, "");
580
+ return n.map((o) => `${i}/${o}`);
581
+ }
582
+ return n;
583
+ } catch (n) {
584
+ return logger.error(n, { path: r }), [];
585
+ }
586
+ }
587
+ static isDir(e, r) {
588
+ return g.fileExists(e, r) ? e.isDir(e.lookupPath(r).node.mode) : !1;
589
+ }
590
+ static fileExists(e, r) {
591
+ try {
592
+ return e.lookupPath(r), !0;
593
+ } catch {
594
+ return !1;
595
+ }
596
+ }
597
+ static mkdir(e, r) {
598
+ e.mkdirTree(r);
599
+ }
600
+ static copyRecursive(e, r, s) {
601
+ const n = e.lookupPath(r).node;
602
+ if (e.isDir(n.mode)) {
603
+ e.mkdirTree(s);
604
+ const i = e.readdir(r).filter(
605
+ (o) => o !== "." && o !== ".."
606
+ );
607
+ for (const o of i)
608
+ g.copyRecursive(
609
+ e,
610
+ joinPaths(r, o),
611
+ joinPaths(s, o)
612
+ );
613
+ } else
614
+ e.writeFile(s, e.readFile(r));
615
+ }
616
+ };
617
+ __decorateClass([
618
+ rethrowFileSystemError('Could not read "{path}"')
619
+ ], _FSHelpers, "readFileAsText", 1);
620
+ __decorateClass([
621
+ rethrowFileSystemError('Could not read "{path}"')
622
+ ], _FSHelpers, "readFileAsBuffer", 1);
623
+ __decorateClass([
624
+ rethrowFileSystemError('Could not write to "{path}"')
625
+ ], _FSHelpers, "writeFile", 1);
626
+ __decorateClass([
627
+ rethrowFileSystemError('Could not unlink "{path}"')
628
+ ], _FSHelpers, "unlink", 1);
629
+ __decorateClass([
630
+ rethrowFileSystemError('Could not remove directory "{path}"')
631
+ ], _FSHelpers, "rmdir", 1);
632
+ __decorateClass([
633
+ rethrowFileSystemError('Could not list files in "{path}"')
634
+ ], _FSHelpers, "listFiles", 1);
635
+ __decorateClass([
636
+ rethrowFileSystemError('Could not stat "{path}"')
637
+ ], _FSHelpers, "isDir", 1);
638
+ __decorateClass([
639
+ rethrowFileSystemError('Could not stat "{path}"')
640
+ ], _FSHelpers, "fileExists", 1);
641
+ __decorateClass([
642
+ rethrowFileSystemError('Could not create directory "{path}"')
643
+ ], _FSHelpers, "mkdir", 1);
644
+ __decorateClass([
645
+ rethrowFileSystemError('Could not copy files from "{path}"')
646
+ ], _FSHelpers, "copyRecursive", 1);
647
+ let FSHelpers = _FSHelpers;
648
+ const _private = /* @__PURE__ */ new WeakMap();
649
+ class PHPWorker {
650
+ /** @inheritDoc */
651
+ constructor(e, r) {
652
+ this.absoluteUrl = "", this.documentRoot = "", _private.set(this, {
653
+ monitor: r
654
+ }), e && this.__internal_setRequestHandler(e);
655
+ }
656
+ __internal_setRequestHandler(e) {
657
+ this.absoluteUrl = e.absoluteUrl, this.documentRoot = e.documentRoot, _private.set(this, {
658
+ ..._private.get(this),
659
+ requestHandler: e
660
+ });
661
+ }
662
+ /**
663
+ * @internal
664
+ * @deprecated
665
+ * Do not use this method directly in the code consuming
666
+ * the web API. It will change or even be removed without
667
+ * a warning.
668
+ */
669
+ __internal_getPHP() {
670
+ return _private.get(this).php;
671
+ }
672
+ async setPrimaryPHP(e) {
673
+ _private.set(this, {
674
+ ..._private.get(this),
675
+ php: e
676
+ });
677
+ }
678
+ /** @inheritDoc @php-wasm/universal!PHPRequestHandler.pathToInternalUrl */
679
+ pathToInternalUrl(e) {
680
+ return _private.get(this).requestHandler.pathToInternalUrl(e);
681
+ }
682
+ /** @inheritDoc @php-wasm/universal!PHPRequestHandler.internalUrlToPath */
683
+ internalUrlToPath(e) {
684
+ return _private.get(this).requestHandler.internalUrlToPath(e);
685
+ }
686
+ /**
687
+ * The onDownloadProgress event listener.
688
+ */
689
+ async onDownloadProgress(e) {
690
+ var r;
691
+ return (r = _private.get(this).monitor) == null ? void 0 : r.addEventListener("progress", e);
692
+ }
693
+ /** @inheritDoc @php-wasm/universal!PHP.mv */
694
+ async mv(e, r) {
695
+ return _private.get(this).php.mv(e, r);
696
+ }
697
+ /** @inheritDoc @php-wasm/universal!PHP.rmdir */
698
+ async rmdir(e, r) {
699
+ return _private.get(this).php.rmdir(e, r);
700
+ }
701
+ /** @inheritDoc @php-wasm/universal!PHPRequestHandler.request */
702
+ async request(e) {
703
+ return await _private.get(this).requestHandler.request(e);
704
+ }
705
+ /** @inheritDoc @php-wasm/universal!/PHP.run */
706
+ async run(e) {
707
+ const { php: r, reap: s } = await _private.get(this).requestHandler.processManager.acquirePHPInstance();
708
+ try {
709
+ return await r.run(e);
710
+ } finally {
711
+ s();
712
+ }
713
+ }
714
+ /** @inheritDoc @php-wasm/universal!/PHP.chdir */
715
+ chdir(e) {
716
+ return _private.get(this).php.chdir(e);
717
+ }
718
+ /** @inheritDoc @php-wasm/universal!/PHP.setSapiName */
719
+ setSapiName(e) {
720
+ _private.get(this).php.setSapiName(e);
721
+ }
722
+ /** @inheritDoc @php-wasm/universal!/PHP.mkdir */
723
+ mkdir(e) {
724
+ return _private.get(this).php.mkdir(e);
725
+ }
726
+ /** @inheritDoc @php-wasm/universal!/PHP.mkdirTree */
727
+ mkdirTree(e) {
728
+ return _private.get(this).php.mkdirTree(e);
729
+ }
730
+ /** @inheritDoc @php-wasm/universal!/PHP.readFileAsText */
731
+ readFileAsText(e) {
732
+ return _private.get(this).php.readFileAsText(e);
733
+ }
734
+ /** @inheritDoc @php-wasm/universal!/PHP.readFileAsBuffer */
735
+ readFileAsBuffer(e) {
736
+ return _private.get(this).php.readFileAsBuffer(e);
737
+ }
738
+ /** @inheritDoc @php-wasm/universal!/PHP.writeFile */
739
+ writeFile(e, r) {
740
+ return _private.get(this).php.writeFile(e, r);
741
+ }
742
+ /** @inheritDoc @php-wasm/universal!/PHP.unlink */
743
+ unlink(e) {
744
+ return _private.get(this).php.unlink(e);
745
+ }
746
+ /** @inheritDoc @php-wasm/universal!/PHP.listFiles */
747
+ listFiles(e, r) {
748
+ return _private.get(this).php.listFiles(e, r);
749
+ }
750
+ /** @inheritDoc @php-wasm/universal!/PHP.isDir */
751
+ isDir(e) {
752
+ return _private.get(this).php.isDir(e);
753
+ }
754
+ /** @inheritDoc @php-wasm/universal!/PHP.fileExists */
755
+ fileExists(e) {
756
+ return _private.get(this).php.fileExists(e);
757
+ }
758
+ /** @inheritDoc @php-wasm/universal!/PHP.onMessage */
759
+ onMessage(e) {
760
+ _private.get(this).php.onMessage(e);
761
+ }
762
+ /** @inheritDoc @php-wasm/universal!/PHP.defineConstant */
763
+ defineConstant(e, r) {
764
+ _private.get(this).php.defineConstant(e, r);
765
+ }
766
+ /** @inheritDoc @php-wasm/universal!/PHP.addEventListener */
767
+ addEventListener(e, r) {
768
+ _private.get(this).php.addEventListener(e, r);
769
+ }
770
+ /** @inheritDoc @php-wasm/universal!/PHP.removeEventListener */
771
+ removeEventListener(e, r) {
772
+ _private.get(this).php.removeEventListener(e, r);
773
+ }
774
+ }
775
+ const responseTexts = {
776
+ 500: "Internal Server Error",
777
+ 502: "Bad Gateway",
778
+ 404: "Not Found",
779
+ 403: "Forbidden",
780
+ 401: "Unauthorized",
781
+ 400: "Bad Request",
782
+ 301: "Moved Permanently",
783
+ 302: "Found",
784
+ 307: "Temporary Redirect",
785
+ 308: "Permanent Redirect",
786
+ 204: "No Content",
787
+ 201: "Created",
788
+ 200: "OK"
789
+ };
790
+ class PHPResponse {
791
+ constructor(e, r, s, n = "", i = 0) {
792
+ this.httpStatusCode = e, this.headers = r, this.bytes = s, this.exitCode = i, this.errors = n;
793
+ }
794
+ static forHttpCode(e, r = "") {
795
+ return new PHPResponse(
796
+ e,
797
+ {},
798
+ new TextEncoder().encode(
799
+ r || responseTexts[e] || ""
800
+ )
801
+ );
802
+ }
803
+ static fromRawData(e) {
804
+ return new PHPResponse(
805
+ e.httpStatusCode,
806
+ e.headers,
807
+ e.bytes,
808
+ e.errors,
809
+ e.exitCode
810
+ );
811
+ }
812
+ toRawData() {
813
+ return {
814
+ headers: this.headers,
815
+ bytes: this.bytes,
816
+ errors: this.errors,
817
+ exitCode: this.exitCode,
818
+ httpStatusCode: this.httpStatusCode
819
+ };
820
+ }
821
+ /**
822
+ * Response body as JSON.
823
+ */
824
+ get json() {
825
+ return JSON.parse(this.text);
826
+ }
827
+ /**
828
+ * Response body as text.
829
+ */
830
+ get text() {
831
+ return new TextDecoder().decode(this.bytes);
832
+ }
833
+ }
834
+ const RuntimeId = Symbol("RuntimeId"), loadedRuntimes = /* @__PURE__ */ new Map();
412
835
  let lastRuntimeId = 0;
413
- async function loadPHPRuntime(e, t = {}) {
414
- const [s, r, n] = makePromise(), i = e.init(currentJsRuntime, {
415
- onAbort(c) {
416
- n(c), logger.error(c);
836
+ async function loadPHPRuntime(t, e = {}) {
837
+ const [r, s, n] = makePromise(), i = t.init(currentJsRuntime, {
838
+ onAbort(l) {
839
+ n(l), logger.error(l);
417
840
  },
418
841
  ENV: {},
419
842
  // Emscripten sometimes prepends a '/' to the path, which
420
843
  // breaks vite dev mode. An identity `locateFile` function
421
844
  // fixes it.
422
- locateFile: (c) => c,
423
- ...t,
845
+ locateFile: (l) => l,
846
+ ...e,
424
847
  noInitialRun: !0,
425
848
  onRuntimeInitialized() {
426
- t.onRuntimeInitialized && t.onRuntimeInitialized(), r();
849
+ e.onRuntimeInitialized && e.onRuntimeInitialized(), s();
427
850
  }
428
851
  });
429
- await s;
852
+ await r;
430
853
  const o = ++lastRuntimeId;
431
- return i.id = o, i.originalExit = i._exit, i._exit = function(c) {
432
- return loadedRuntimes.delete(o), i.originalExit(c);
854
+ return i.id = o, i.originalExit = i._exit, i._exit = function(l) {
855
+ return loadedRuntimes.delete(o), i.originalExit(l);
433
856
  }, i[RuntimeId] = o, loadedRuntimes.set(o, i), o;
434
857
  }
435
- function getLoadedRuntime(e) {
436
- return loadedRuntimes.get(e);
858
+ function getLoadedRuntime(t) {
859
+ return loadedRuntimes.get(t);
437
860
  }
438
861
  const currentJsRuntime = function() {
439
- var e;
440
- return typeof process < "u" && ((e = process.release) == null ? void 0 : e.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
862
+ var t;
863
+ return typeof process < "u" && ((t = process.release) == null ? void 0 : t.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
441
864
  }(), makePromise = () => {
442
- const e = [], t = new Promise((s, r) => {
443
- e.push(s, r);
865
+ const t = [], e = new Promise((r, s) => {
866
+ t.push(r, s);
444
867
  });
445
- return e.unshift(t), e;
868
+ return t.unshift(e), t;
446
869
  }, kError = Symbol("error"), kMessage = Symbol("message");
447
870
  class ErrorEvent2 extends Event {
448
871
  /**
@@ -452,8 +875,8 @@ class ErrorEvent2 extends Event {
452
875
  * @param options A dictionary object that allows for setting
453
876
  * attributes via object members of the same name.
454
877
  */
455
- constructor(t, s = {}) {
456
- super(t), this[kError] = s.error === void 0 ? null : s.error, this[kMessage] = s.message === void 0 ? "" : s.message;
878
+ constructor(e, r = {}) {
879
+ super(e), this[kError] = r.error === void 0 ? null : r.error, this[kMessage] = r.message === void 0 ? "" : r.message;
457
880
  }
458
881
  get error() {
459
882
  return this[kError];
@@ -465,78 +888,75 @@ class ErrorEvent2 extends Event {
465
888
  Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: !0 });
466
889
  Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: !0 });
467
890
  const ErrorEvent = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : ErrorEvent2;
468
- function isExitCodeZero(e) {
469
- return e instanceof Error ? "exitCode" in e && (e == null ? void 0 : e.exitCode) === 0 || (e == null ? void 0 : e.name) === "ExitStatus" && "status" in e && e.status === 0 : !1;
891
+ function isExitCodeZero(t) {
892
+ return t instanceof Error ? "exitCode" in t && (t == null ? void 0 : t.exitCode) === 0 || (t == null ? void 0 : t.name) === "ExitStatus" && "status" in t && t.status === 0 : !1;
470
893
  }
471
894
  class UnhandledRejectionsTarget extends EventTarget {
472
895
  constructor() {
473
896
  super(...arguments), this.listenersCount = 0;
474
897
  }
475
- addEventListener(t, s) {
476
- ++this.listenersCount, super.addEventListener(t, s);
898
+ addEventListener(e, r) {
899
+ ++this.listenersCount, super.addEventListener(e, r);
477
900
  }
478
- removeEventListener(t, s) {
479
- --this.listenersCount, super.removeEventListener(t, s);
901
+ removeEventListener(e, r) {
902
+ --this.listenersCount, super.removeEventListener(e, r);
480
903
  }
481
904
  hasListeners() {
482
905
  return this.listenersCount > 0;
483
906
  }
484
907
  }
485
- function improveWASMErrorReporting(e) {
486
- e.asm = {
487
- ...e.asm
488
- };
489
- const t = new UnhandledRejectionsTarget();
490
- for (const s in e.asm)
491
- if (typeof e.asm[s] == "function") {
492
- const r = e.asm[s];
493
- e.asm[s] = function(...n) {
908
+ function improveWASMErrorReporting(t) {
909
+ const e = new UnhandledRejectionsTarget();
910
+ for (const r in t.wasmExports)
911
+ if (typeof t.wasmExports[r] == "function") {
912
+ const s = t.wasmExports[r];
913
+ t.wasmExports[r] = function(...n) {
494
914
  var i;
495
915
  try {
496
- return r(...n);
916
+ return s(...n);
497
917
  } catch (o) {
498
918
  if (!(o instanceof Error))
499
919
  throw o;
500
- const c = clarifyErrorMessage(
920
+ const l = clarifyErrorMessage(
501
921
  o,
502
- (i = e.lastAsyncifyStackSource) == null ? void 0 : i.stack
922
+ (i = t.lastAsyncifyStackSource) == null ? void 0 : i.stack
503
923
  );
504
- if (e.lastAsyncifyStackSource && (o.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
505
- t.dispatchEvent(
924
+ if (t.lastAsyncifyStackSource && (o.cause = t.lastAsyncifyStackSource), e.hasListeners()) {
925
+ e.dispatchEvent(
506
926
  new ErrorEvent("error", {
507
927
  error: o,
508
- message: c
928
+ message: l
509
929
  })
510
930
  );
511
931
  return;
512
932
  }
513
- throw isExitCodeZero(o) || showCriticalErrorBox(c), o;
933
+ throw isExitCodeZero(o) || showCriticalErrorBox(l), o;
514
934
  }
515
935
  };
516
936
  }
517
- return t;
937
+ return e;
518
938
  }
519
939
  let functionsMaybeMissingFromAsyncify = [];
520
940
  function getFunctionsMaybeMissingFromAsyncify() {
521
941
  return functionsMaybeMissingFromAsyncify;
522
942
  }
523
- function clarifyErrorMessage(e, t) {
524
- if (e.message === "unreachable") {
525
- let s = UNREACHABLE_ERROR;
526
- t || (s += `
943
+ function clarifyErrorMessage(t, e) {
944
+ if (t.message === "unreachable") {
945
+ let r = UNREACHABLE_ERROR;
946
+ e || (r += `
527
947
 
528
948
  This stack trace is lacking. For a better one initialize
529
949
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
530
950
 
531
951
  `), functionsMaybeMissingFromAsyncify = extractPHPFunctionsFromStack(
532
- t || e.stack || ""
952
+ e || t.stack || ""
533
953
  );
534
- for (const r of functionsMaybeMissingFromAsyncify)
535
- s += ` * ${r}
954
+ for (const s of functionsMaybeMissingFromAsyncify)
955
+ r += ` * ${s}
536
956
  `;
537
- return s;
957
+ return r;
538
958
  }
539
- return e.message;
959
+ return t.message;
540
960
  }
541
961
  const UNREACHABLE_ERROR = `
542
962
  "unreachable" WASM instruction executed.
@@ -564,213 +984,43 @@ CLI option:
564
984
 
565
985
  `, redBg = "\x1B[41m", bold = "\x1B[1m", reset = "\x1B[0m", eol = "\x1B[K";
566
986
  let logged = !1;
567
- function showCriticalErrorBox(e) {
568
- if (!logged && (logged = !0, !(e != null && e.trim().startsWith("Program terminated with exit")))) {
987
+ function showCriticalErrorBox(t) {
988
+ if (!logged && (logged = !0, !(t != null && t.trim().startsWith("Program terminated with exit")))) {
569
989
  logger.log(`${redBg}
570
990
  ${eol}
571
991
  ${bold} WASM ERROR${reset}${redBg}`);
572
- for (const t of e.split(`
992
+ for (const e of t.split(`
573
993
  `))
574
- logger.log(`${eol} ${t} `);
994
+ logger.log(`${eol} ${e} `);
575
995
  logger.log(`${reset}`);
576
996
  }
577
997
  }
578
- function extractPHPFunctionsFromStack(e) {
579
- try {
580
- const t = e.split(`
581
- `).slice(1).map((s) => {
582
- const r = s.trim().substring(3).split(" ");
583
- return {
584
- fn: r.length >= 2 ? r[0] : "<unknown>",
585
- isWasm: s.includes("wasm://")
586
- };
587
- }).filter(
588
- ({ fn: s, isWasm: r }) => r && !s.startsWith("dynCall_") && !s.startsWith("invoke_")
589
- ).map(({ fn: s }) => s);
590
- return Array.from(new Set(t));
591
- } catch {
592
- return [];
593
- }
594
- }
595
- const SleepFinished = Symbol("SleepFinished");
596
- function sleep(e) {
597
- return new Promise((t) => {
598
- setTimeout(() => t(SleepFinished), e);
599
- });
600
- }
601
- class AcquireTimeoutError extends Error {
602
- constructor() {
603
- super("Acquiring lock timed out");
604
- }
605
- }
606
- class Semaphore {
607
- constructor({ concurrency: t, timeout: s }) {
608
- this._running = 0, this.concurrency = t, this.timeout = s, this.queue = [];
609
- }
610
- get remaining() {
611
- return this.concurrency - this.running;
612
- }
613
- get running() {
614
- return this._running;
615
- }
616
- async acquire() {
617
- for (; ; )
618
- if (this._running >= this.concurrency) {
619
- const t = new Promise((s) => {
620
- this.queue.push(s);
621
- });
622
- this.timeout !== void 0 ? await Promise.race([t, sleep(this.timeout)]).then(
623
- (s) => {
624
- if (s === SleepFinished)
625
- throw new AcquireTimeoutError();
626
- }
627
- ) : await t;
628
- } else {
629
- this._running++;
630
- let t = !1;
631
- return () => {
632
- t || (t = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
633
- };
634
- }
635
- }
636
- async run(t) {
637
- const s = await this.acquire();
638
- try {
639
- return await t();
640
- } finally {
641
- s();
642
- }
643
- }
644
- }
645
- function joinPaths(...e) {
646
- let t = e.join("/");
647
- const s = t[0] === "/", r = t.substring(t.length - 1) === "/";
648
- return t = normalizePath(t), !t && !s && (t = "."), t && r && (t += "/"), t;
649
- }
650
- function dirname(e) {
651
- if (e === "/")
652
- return "/";
653
- e = normalizePath(e);
654
- const t = e.lastIndexOf("/");
655
- return t === -1 ? "" : t === 0 ? "/" : e.substr(0, t);
656
- }
657
- function normalizePath(e) {
658
- const t = e[0] === "/";
659
- return e = normalizePathsArray(
660
- e.split("/").filter((s) => !!s),
661
- !t
662
- ).join("/"), (t ? "/" : "") + e.replace(/\/$/, "");
663
- }
664
- function normalizePathsArray(e, t) {
665
- let s = 0;
666
- for (let r = e.length - 1; r >= 0; r--) {
667
- const n = e[r];
668
- n === "." ? e.splice(r, 1) : n === ".." ? (e.splice(r, 1), s++) : s && (e.splice(r, 1), s--);
669
- }
670
- if (t)
671
- for (; s; s--)
672
- e.unshift("..");
673
- return e;
674
- }
675
- function splitShellCommand(e) {
676
- let r = 0, n = "";
677
- const i = [];
678
- let o = "";
679
- for (let c = 0; c < e.length; c++) {
680
- const l = e[c];
681
- l === "\\" ? ((e[c + 1] === '"' || e[c + 1] === "'") && c++, o += e[c]) : r === 0 ? l === '"' || l === "'" ? (r = 1, n = l) : l.match(/\s/) ? (o.trim().length && i.push(o.trim()), o = l) : i.length && !o ? o = i.pop() + l : o += l : r === 1 && (l === n ? (r = 0, n = "") : o += l);
682
- }
683
- return o && i.push(o.trim()), i;
684
- }
685
- function createSpawnHandler(e) {
686
- return function(t, s = [], r = {}) {
687
- const n = new ChildProcess(), i = new ProcessApi(n);
688
- return setTimeout(async () => {
689
- let o = [];
690
- if (s.length)
691
- o = [t, ...s];
692
- else if (typeof t == "string")
693
- o = splitShellCommand(t);
694
- else if (Array.isArray(t))
695
- o = t;
696
- else
697
- throw new Error("Invalid command ", t);
698
- try {
699
- await e(o, i, r);
700
- } catch (c) {
701
- n.emit("error", c), typeof c == "object" && c !== null && "message" in c && typeof c.message == "string" && i.stderr(c.message), i.exit(1);
702
- }
703
- n.emit("spawn", !0);
704
- }), n;
705
- };
706
- }
707
- class EventEmitter {
708
- constructor() {
709
- this.listeners = {};
710
- }
711
- emit(t, s) {
712
- this.listeners[t] && this.listeners[t].forEach(function(r) {
713
- r(s);
714
- });
715
- }
716
- on(t, s) {
717
- this.listeners[t] || (this.listeners[t] = []), this.listeners[t].push(s);
718
- }
719
- }
720
- class ProcessApi extends EventEmitter {
721
- constructor(t) {
722
- super(), this.childProcess = t, this.exited = !1, this.stdinData = [], t.on("stdin", (s) => {
723
- this.stdinData ? this.stdinData.push(s.slice()) : this.emit("stdin", s);
724
- });
725
- }
726
- stdout(t) {
727
- typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stdout.emit("data", t);
728
- }
729
- stdoutEnd() {
730
- this.childProcess.stdout.emit("end", {});
731
- }
732
- stderr(t) {
733
- typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stderr.emit("data", t);
734
- }
735
- stderrEnd() {
736
- this.childProcess.stderr.emit("end", {});
737
- }
738
- exit(t) {
739
- this.exited || (this.exited = !0, this.childProcess.emit("exit", t));
740
- }
741
- flushStdin() {
742
- if (this.stdinData)
743
- for (let t = 0; t < this.stdinData.length; t++)
744
- this.emit("stdin", this.stdinData[t]);
745
- this.stdinData = null;
746
- }
747
- }
748
- let lastPid = 9743;
749
- class ChildProcess extends EventEmitter {
750
- constructor(t = lastPid++) {
751
- super(), this.pid = t, this.stdout = new EventEmitter(), this.stderr = new EventEmitter();
752
- const s = this;
753
- this.stdin = {
754
- write: (r) => {
755
- s.emit("stdin", r);
756
- }
757
- };
998
+ function extractPHPFunctionsFromStack(t) {
999
+ try {
1000
+ const e = t.split(`
1001
+ `).slice(1).map((r) => {
1002
+ const s = r.trim().substring(3).split(" ");
1003
+ return {
1004
+ fn: s.length >= 2 ? s[0] : "<unknown>",
1005
+ isWasm: r.includes("wasm://")
1006
+ };
1007
+ }).filter(
1008
+ ({ fn: r, isWasm: s }) => s && !r.startsWith("dynCall_") && !r.startsWith("invoke_")
1009
+ ).map(({ fn: r }) => r);
1010
+ return Array.from(new Set(e));
1011
+ } catch {
1012
+ return [];
758
1013
  }
759
1014
  }
760
- var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, s, r) => {
761
- for (var n = r > 1 ? void 0 : r ? __getOwnPropDesc(t, s) : t, i = e.length - 1, o; i >= 0; i--)
762
- (o = e[i]) && (n = (r ? o(t, s, n) : o(n)) || n);
763
- return r && n && __defProp(t, s, n), n;
764
- };
765
1015
  const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
766
1016
  class PHPExecutionFailureError extends Error {
767
- constructor(t, s, r) {
768
- super(t), this.response = s, this.source = r;
1017
+ constructor(e, r, s) {
1018
+ super(e), this.response = r, this.source = s;
769
1019
  }
770
1020
  }
771
1021
  const PHP_INI_PATH = "/internal/shared/php.ini", AUTO_PREPEND_SCRIPT = "/internal/shared/auto_prepend_file.php";
772
- var b, v, x, P, R, C, X, M, ee, N, te, O, se, L, re, B, ne, U, ie, j, oe, $, ae, D, ce, k, Z, q, le, z, ue, W, de;
773
- class BasePHP {
1022
+ var S, E, x, v, R, M, ee, N, te, U, re, O, se, L, ne, D, ie, j, oe, $, ae, B, le, q, ce, I, K, z, ue, W, pe, G, de;
1023
+ class PHP {
774
1024
  /**
775
1025
  * Initializes a PHP runtime.
776
1026
  *
@@ -778,7 +1028,7 @@ class BasePHP {
778
1028
  * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
779
1029
  * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
780
1030
  */
781
- constructor(e) {
1031
+ constructor(t) {
782
1032
  /**
783
1033
  * Prepares the $_SERVER entries for the PHP runtime.
784
1034
  *
@@ -788,71 +1038,118 @@ class BasePHP {
788
1038
  * was provided.
789
1039
  * @returns Computed $_SERVER entries.
790
1040
  */
791
- d(this, C);
792
- d(this, M);
793
- d(this, N);
794
- d(this, O);
795
- d(this, L);
796
- d(this, B);
797
- d(this, U);
798
- d(this, j);
799
- d(this, $);
800
- d(this, D);
801
- d(this, k);
802
- d(this, q);
803
- d(this, z);
804
- d(this, W);
805
- d(this, b, void 0);
806
- d(this, v, void 0);
807
- d(this, x, void 0);
808
- d(this, P, void 0);
809
- d(this, R, void 0);
810
- f(this, v, !1), f(this, x, null), f(this, P, /* @__PURE__ */ new Map()), f(this, R, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e);
811
- }
812
- addEventListener(e, t) {
813
- u(this, P).has(e) || u(this, P).set(e, /* @__PURE__ */ new Set()), u(this, P).get(e).add(t);
814
- }
815
- removeEventListener(e, t) {
816
- var s;
817
- (s = u(this, P).get(e)) == null || s.delete(t);
818
- }
819
- dispatchEvent(e) {
820
- const t = u(this, P).get(e.type);
821
- if (t)
822
- for (const s of t)
823
- s(e);
1041
+ p(this, M);
1042
+ p(this, N);
1043
+ p(this, U);
1044
+ p(this, O);
1045
+ p(this, L);
1046
+ p(this, D);
1047
+ p(this, j);
1048
+ p(this, $);
1049
+ p(this, B);
1050
+ p(this, q);
1051
+ p(this, I);
1052
+ p(this, z);
1053
+ p(this, W);
1054
+ p(this, G);
1055
+ p(this, S, void 0);
1056
+ p(this, E, void 0);
1057
+ p(this, x, void 0);
1058
+ p(this, v, void 0);
1059
+ p(this, R, void 0);
1060
+ f(this, E, !1), f(this, x, null), f(this, v, /* @__PURE__ */ new Map()), f(this, R, []), this.semaphore = new Semaphore({ concurrency: 1 }), t !== void 0 && this.initializeRuntime(t);
824
1061
  }
825
- /** @inheritDoc */
826
- async onMessage(e) {
827
- u(this, R).push(e);
1062
+ /**
1063
+ * Adds an event listener for a PHP event.
1064
+ * @param eventType - The type of event to listen for.
1065
+ * @param listener - The listener function to be called when the event is triggered.
1066
+ */
1067
+ addEventListener(t, e) {
1068
+ u(this, v).has(t) || u(this, v).set(t, /* @__PURE__ */ new Set()), u(this, v).get(t).add(e);
1069
+ }
1070
+ /**
1071
+ * Removes an event listener for a PHP event.
1072
+ * @param eventType - The type of event to remove the listener from.
1073
+ * @param listener - The listener function to be removed.
1074
+ */
1075
+ removeEventListener(t, e) {
1076
+ var r;
1077
+ (r = u(this, v).get(t)) == null || r.delete(e);
1078
+ }
1079
+ dispatchEvent(t) {
1080
+ const e = u(this, v).get(t.type);
1081
+ if (e)
1082
+ for (const r of e)
1083
+ r(t);
1084
+ }
1085
+ /**
1086
+ * Listens to message sent by the PHP code.
1087
+ *
1088
+ * To dispatch messages, call:
1089
+ *
1090
+ * post_message_to_js(string $data)
1091
+ *
1092
+ * Arguments:
1093
+ * $data (string) – Data to pass to JavaScript.
1094
+ *
1095
+ * @example
1096
+ *
1097
+ * ```ts
1098
+ * const php = await PHP.load('8.0');
1099
+ *
1100
+ * php.onMessage(
1101
+ * // The data is always passed as a string
1102
+ * function (data: string) {
1103
+ * // Let's decode and log the data:
1104
+ * console.log(JSON.parse(data));
1105
+ * }
1106
+ * );
1107
+ *
1108
+ * // Now that we have a listener in place, let's
1109
+ * // dispatch a message:
1110
+ * await php.run({
1111
+ * code: `<?php
1112
+ * post_message_to_js(
1113
+ * json_encode([
1114
+ * 'post_id' => '15',
1115
+ * 'post_title' => 'This is a blog post!'
1116
+ * ])
1117
+ * ));
1118
+ * `,
1119
+ * });
1120
+ * ```
1121
+ *
1122
+ * @param listener Callback function to handle the message.
1123
+ */
1124
+ onMessage(t) {
1125
+ u(this, R).push(t);
828
1126
  }
829
- /** @inheritDoc */
830
1127
  async setSpawnHandler(handler) {
831
1128
  typeof handler == "string" && (handler = createSpawnHandler(eval(handler))), this[__private__dont__use].spawnProcess = handler;
832
1129
  }
833
- /** @inheritDoc */
1130
+ /** @deprecated Use PHPRequestHandler instead. */
834
1131
  get absoluteUrl() {
835
1132
  return this.requestHandler.absoluteUrl;
836
1133
  }
837
- /** @inheritDoc */
1134
+ /** @deprecated Use PHPRequestHandler instead. */
838
1135
  get documentRoot() {
839
1136
  return this.requestHandler.documentRoot;
840
1137
  }
841
- /** @inheritDoc */
842
- pathToInternalUrl(e) {
843
- return this.requestHandler.pathToInternalUrl(e);
1138
+ /** @deprecated Use PHPRequestHandler instead. */
1139
+ pathToInternalUrl(t) {
1140
+ return this.requestHandler.pathToInternalUrl(t);
844
1141
  }
845
- /** @inheritDoc */
846
- internalUrlToPath(e) {
847
- return this.requestHandler.internalUrlToPath(e);
1142
+ /** @deprecated Use PHPRequestHandler instead. */
1143
+ internalUrlToPath(t) {
1144
+ return this.requestHandler.internalUrlToPath(t);
848
1145
  }
849
- initializeRuntime(e) {
1146
+ initializeRuntime(t) {
850
1147
  if (this[__private__dont__use])
851
1148
  throw new Error("PHP runtime already initialized.");
852
- const t = getLoadedRuntime(e);
853
- if (!t)
1149
+ const e = getLoadedRuntime(t);
1150
+ if (!e)
854
1151
  throw new Error("Invalid PHP runtime id.");
855
- this[__private__dont__use] = t, this[__private__dont__use].ccall(
1152
+ this[__private__dont__use] = e, this[__private__dont__use].ccall(
856
1153
  "wasm_set_phpini_path",
857
1154
  null,
858
1155
  ["string"],
@@ -898,95 +1195,175 @@ class BasePHP {
898
1195
  require_once $file;
899
1196
  }
900
1197
  `
901
- ), t.onMessage = async (s) => {
902
- for (const r of u(this, R)) {
903
- const n = await r(s);
1198
+ ), e.onMessage = async (r) => {
1199
+ for (const s of u(this, R)) {
1200
+ const n = await s(r);
904
1201
  if (n)
905
1202
  return n;
906
1203
  }
907
1204
  return "";
908
- }, f(this, x, improveWASMErrorReporting(t)), this.dispatchEvent({
1205
+ }, f(this, x, improveWASMErrorReporting(e)), this.dispatchEvent({
909
1206
  type: "runtime.initialized"
910
1207
  });
911
1208
  }
912
1209
  /** @inheritDoc */
913
- async setSapiName(e) {
1210
+ async setSapiName(t) {
914
1211
  if (this[__private__dont__use].ccall(
915
1212
  "wasm_set_sapi_name",
916
1213
  NUMBER,
917
1214
  [STRING],
918
- [e]
1215
+ [t]
919
1216
  ) !== 0)
920
1217
  throw new Error(
921
1218
  "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
922
1219
  );
923
- f(this, b, e);
1220
+ f(this, S, t);
924
1221
  }
925
- /** @inheritDoc */
926
- chdir(e) {
927
- this[__private__dont__use].FS.chdir(e);
1222
+ /**
1223
+ * Changes the current working directory in the PHP filesystem.
1224
+ * This is the directory that will be used as the base for relative paths.
1225
+ * For example, if the current working directory is `/root/php`, and the
1226
+ * path is `data`, the absolute path will be `/root/php/data`.
1227
+ *
1228
+ * @param path - The new working directory.
1229
+ */
1230
+ chdir(t) {
1231
+ this[__private__dont__use].FS.chdir(t);
928
1232
  }
929
1233
  /**
930
1234
  * Do not use. Use new PHPRequestHandler() instead.
931
1235
  * @deprecated
932
1236
  */
933
- async request(e) {
1237
+ async request(t) {
934
1238
  if (logger.warn(
935
1239
  "PHP.request() is deprecated. Please use new PHPRequestHandler() instead."
936
1240
  ), !this.requestHandler)
937
1241
  throw new Error("No request handler available.");
938
- return this.requestHandler.request(e);
1242
+ return this.requestHandler.request(t);
939
1243
  }
940
- /** @inheritDoc */
941
- async run(e) {
942
- const t = await this.semaphore.acquire();
943
- let s;
1244
+ /**
1245
+ * Runs PHP code.
1246
+ *
1247
+ * This low-level method directly interacts with the WebAssembly
1248
+ * PHP interpreter.
1249
+ *
1250
+ * Every time you call run(), it prepares the PHP
1251
+ * environment and:
1252
+ *
1253
+ * * Resets the internal PHP state
1254
+ * * Populates superglobals ($_SERVER, $_GET, etc.)
1255
+ * * Handles file uploads
1256
+ * * Populates input streams (stdin, argv, etc.)
1257
+ * * Sets the current working directory
1258
+ *
1259
+ * You can use run() in two primary modes:
1260
+ *
1261
+ * ### Code snippet mode
1262
+ *
1263
+ * In this mode, you pass a string containing PHP code to run.
1264
+ *
1265
+ * ```ts
1266
+ * const result = await php.run({
1267
+ * code: `<?php echo "Hello world!";`
1268
+ * });
1269
+ * // result.text === "Hello world!"
1270
+ * ```
1271
+ *
1272
+ * In this mode, information like __DIR__ or __FILE__ isn't very
1273
+ * useful because the code is not associated with any file.
1274
+ *
1275
+ * Under the hood, the PHP snippet is passed to the `zend_eval_string`
1276
+ * C function.
1277
+ *
1278
+ * ### File mode
1279
+ *
1280
+ * In the file mode, you pass a scriptPath and PHP executes a file
1281
+ * found at a that path:
1282
+ *
1283
+ * ```ts
1284
+ * php.writeFile(
1285
+ * "/www/index.php",
1286
+ * `<?php echo "Hello world!";"`
1287
+ * );
1288
+ * const result = await php.run({
1289
+ * scriptPath: "/www/index.php"
1290
+ * });
1291
+ * // result.text === "Hello world!"
1292
+ * ```
1293
+ *
1294
+ * In this mode, you can rely on path-related information like __DIR__
1295
+ * or __FILE__.
1296
+ *
1297
+ * Under the hood, the PHP file is executed with the `php_execute_script`
1298
+ * C function.
1299
+ *
1300
+ * The `run()` method cannot be used in conjunction with `cli()`.
1301
+ *
1302
+ * @example
1303
+ * ```js
1304
+ * const result = await php.run(`<?php
1305
+ * $fp = fopen('php://stderr', 'w');
1306
+ * fwrite($fp, "Hello, world!");
1307
+ * `);
1308
+ * // result.errors === "Hello, world!"
1309
+ * ```
1310
+ *
1311
+ * @param options - PHP runtime options.
1312
+ */
1313
+ async run(t) {
1314
+ const e = await this.semaphore.acquire();
1315
+ let r;
944
1316
  try {
945
- if (u(this, v) || (h(this, M, ee).call(this), f(this, v, !0)), e.scriptPath && !this.fileExists(e.scriptPath))
1317
+ if (u(this, E) || (h(this, N, te).call(this), f(this, E, !0)), t.scriptPath && !this.fileExists(t.scriptPath))
946
1318
  throw new Error(
947
- `The script path "${e.scriptPath}" does not exist.`
1319
+ `The script path "${t.scriptPath}" does not exist.`
948
1320
  );
949
- h(this, O, se).call(this, e.relativeUri || ""), h(this, j, oe).call(this, e.method || "GET");
950
- const r = normalizeHeaders(e.headers || {}), n = r.host || "example.com:443", i = h(this, U, ie).call(this, n, e.protocol || "http");
951
- h(this, L, re).call(this, n), h(this, B, ne).call(this, i), h(this, $, ae).call(this, r), e.body && (s = h(this, D, ce).call(this, e.body)), typeof e.code == "string" ? (this.writeFile("/internal/eval.php", e.code), h(this, k, Z).call(this, "/internal/eval.php")) : h(this, k, Z).call(this, e.scriptPath || "");
952
- const o = h(this, C, X).call(this, e.$_SERVER, r, i);
1321
+ h(this, O, se).call(this, t.relativeUri || ""), h(this, $, ae).call(this, t.method || "GET");
1322
+ const s = normalizeHeaders(t.headers || {}), n = s.host || "example.com:443", i = h(this, j, oe).call(this, n, t.protocol || "http");
1323
+ h(this, L, ne).call(this, n), h(this, D, ie).call(this, i), h(this, B, le).call(this, s), t.body && (r = h(this, q, ce).call(this, t.body)), typeof t.code == "string" ? (this.writeFile("/internal/eval.php", t.code), h(this, I, K).call(this, "/internal/eval.php")) : h(this, I, K).call(this, t.scriptPath || "");
1324
+ const o = h(this, M, ee).call(this, t.$_SERVER, s, i);
953
1325
  for (const a in o)
954
- h(this, q, le).call(this, a, o[a]);
955
- const c = e.env || {};
956
- for (const a in c)
957
- h(this, z, ue).call(this, a, c[a]);
958
- const l = await h(this, W, de).call(this);
959
- if (l.exitCode !== 0) {
960
- logger.warn("PHP.run() output was:", l.text);
1326
+ h(this, z, ue).call(this, a, o[a]);
1327
+ const l = t.env || {};
1328
+ for (const a in l)
1329
+ h(this, W, pe).call(this, a, l[a]);
1330
+ const c = await h(this, G, de).call(this);
1331
+ if (c.exitCode !== 0) {
1332
+ logger.warn("PHP.run() output was:", c.text);
961
1333
  const a = new PHPExecutionFailureError(
962
- `PHP.run() failed with exit code ${l.exitCode} and the following output: ` + l.errors,
963
- l,
1334
+ `PHP.run() failed with exit code ${c.exitCode} and the following output: ` + c.errors,
1335
+ c,
964
1336
  "request"
965
1337
  );
966
1338
  throw logger.error(a), a;
967
1339
  }
968
- return l;
969
- } catch (r) {
1340
+ return c;
1341
+ } catch (s) {
970
1342
  throw this.dispatchEvent({
971
1343
  type: "request.error",
972
- error: r,
1344
+ error: s,
973
1345
  // Distinguish between PHP request and PHP-wasm errors
974
- source: r.source ?? "php-wasm"
975
- }), r;
1346
+ source: s.source ?? "php-wasm"
1347
+ }), s;
976
1348
  } finally {
977
1349
  try {
978
- s && this[__private__dont__use].free(s);
1350
+ r && this[__private__dont__use].free(r);
979
1351
  } finally {
980
- t(), this.dispatchEvent({
1352
+ e(), this.dispatchEvent({
981
1353
  type: "request.end"
982
1354
  });
983
1355
  }
984
1356
  }
985
1357
  }
986
- defineConstant(e, t) {
987
- let s = {};
1358
+ /**
1359
+ * Defines a constant in the PHP runtime.
1360
+ * @param key - The name of the constant.
1361
+ * @param value - The value of the constant.
1362
+ */
1363
+ defineConstant(t, e) {
1364
+ let r = {};
988
1365
  try {
989
- s = JSON.parse(
1366
+ r = JSON.parse(
990
1367
  this.fileExists("/internal/shared/consts.json") && this.readFileAsText("/internal/shared/consts.json") || "{}"
991
1368
  );
992
1369
  } catch {
@@ -994,78 +1371,116 @@ class BasePHP {
994
1371
  this.writeFile(
995
1372
  "/internal/shared/consts.json",
996
1373
  JSON.stringify({
997
- ...s,
998
- [e]: t
1374
+ ...r,
1375
+ [t]: e
999
1376
  })
1000
1377
  );
1001
1378
  }
1002
- mkdir(e) {
1003
- this[__private__dont__use].FS.mkdirTree(e);
1379
+ /**
1380
+ * Recursively creates a directory with the given path in the PHP filesystem.
1381
+ * For example, if the path is `/root/php/data`, and `/root` already exists,
1382
+ * it will create the directories `/root/php` and `/root/php/data`.
1383
+ *
1384
+ * @param path - The directory path to create.
1385
+ */
1386
+ mkdir(t) {
1387
+ return FSHelpers.mkdir(this[__private__dont__use].FS, t);
1004
1388
  }
1005
- mkdirTree(e) {
1006
- this.mkdir(e);
1389
+ /**
1390
+ * @deprecated Use mkdir instead.
1391
+ */
1392
+ mkdirTree(t) {
1393
+ return FSHelpers.mkdir(this[__private__dont__use].FS, t);
1007
1394
  }
1008
- readFileAsText(e) {
1009
- return new TextDecoder().decode(this.readFileAsBuffer(e));
1395
+ /**
1396
+ * Reads a file from the PHP filesystem and returns it as a string.
1397
+ *
1398
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
1399
+ * @param path - The file path to read.
1400
+ * @returns The file contents.
1401
+ */
1402
+ readFileAsText(t) {
1403
+ return FSHelpers.readFileAsText(this[__private__dont__use].FS, t);
1010
1404
  }
1011
- readFileAsBuffer(e) {
1012
- return this[__private__dont__use].FS.readFile(e);
1405
+ /**
1406
+ * Reads a file from the PHP filesystem and returns it as an array buffer.
1407
+ *
1408
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
1409
+ * @param path - The file path to read.
1410
+ * @returns The file contents.
1411
+ */
1412
+ readFileAsBuffer(t) {
1413
+ return FSHelpers.readFileAsBuffer(this[__private__dont__use].FS, t);
1013
1414
  }
1014
- writeFile(e, t) {
1015
- this[__private__dont__use].FS.writeFile(e, t);
1415
+ /**
1416
+ * Overwrites data in a file in the PHP filesystem.
1417
+ * Creates a new file if one doesn't exist yet.
1418
+ *
1419
+ * @param path - The file path to write to.
1420
+ * @param data - The data to write to the file.
1421
+ */
1422
+ writeFile(t, e) {
1423
+ return FSHelpers.writeFile(this[__private__dont__use].FS, t, e);
1016
1424
  }
1017
- unlink(e) {
1018
- this[__private__dont__use].FS.unlink(e);
1425
+ /**
1426
+ * Removes a file from the PHP filesystem.
1427
+ *
1428
+ * @throws {@link @php-wasm/universal:ErrnoError} – If the file doesn't exist.
1429
+ * @param path - The file path to remove.
1430
+ */
1431
+ unlink(t) {
1432
+ return FSHelpers.unlink(this[__private__dont__use].FS, t);
1019
1433
  }
1020
- /** @inheritDoc */
1021
- mv(e, t) {
1022
- const s = this[__private__dont__use].FS;
1023
- try {
1024
- const r = s.lookupPath(e).node.mount, n = this.fileExists(t) ? s.lookupPath(t).node.mount : s.lookupPath(dirname(t)).node.mount;
1025
- r.mountpoint !== n.mountpoint ? (copyRecursive(s, e, t), this.rmdir(e, { recursive: !0 })) : s.rename(e, t);
1026
- } catch (r) {
1027
- const n = getEmscriptenFsError(r);
1028
- throw n ? new Error(
1029
- `Could not move ${e} to ${t}: ${n}`,
1030
- {
1031
- cause: r
1032
- }
1033
- ) : r;
1034
- }
1434
+ /**
1435
+ * Moves a file or directory in the PHP filesystem to a
1436
+ * new location.
1437
+ *
1438
+ * @param oldPath The path to rename.
1439
+ * @param newPath The new path.
1440
+ */
1441
+ mv(t, e) {
1442
+ return FSHelpers.mv(this[__private__dont__use].FS, t, e);
1035
1443
  }
1036
- rmdir(e, t = { recursive: !0 }) {
1037
- t != null && t.recursive && this.listFiles(e).forEach((s) => {
1038
- const r = `${e}/${s}`;
1039
- this.isDir(r) ? this.rmdir(r, t) : this.unlink(r);
1040
- }), this[__private__dont__use].FS.rmdir(e);
1444
+ /**
1445
+ * Removes a directory from the PHP filesystem.
1446
+ *
1447
+ * @param path The directory path to remove.
1448
+ * @param options Options for the removal.
1449
+ */
1450
+ rmdir(t, e = { recursive: !0 }) {
1451
+ return FSHelpers.rmdir(this[__private__dont__use].FS, t, e);
1041
1452
  }
1042
- listFiles(e, t = { prependPath: !1 }) {
1043
- if (!this.fileExists(e))
1044
- return [];
1045
- try {
1046
- const s = this[__private__dont__use].FS.readdir(e).filter(
1047
- (r) => r !== "." && r !== ".."
1048
- );
1049
- if (t.prependPath) {
1050
- const r = e.replace(/\/$/, "");
1051
- return s.map((n) => `${r}/${n}`);
1052
- }
1053
- return s;
1054
- } catch (s) {
1055
- return logger.error(s, { path: e }), [];
1056
- }
1453
+ /**
1454
+ * Lists the files and directories in the given directory.
1455
+ *
1456
+ * @param path - The directory path to list.
1457
+ * @param options - Options for the listing.
1458
+ * @returns The list of files and directories in the given directory.
1459
+ */
1460
+ listFiles(t, e = { prependPath: !1 }) {
1461
+ return FSHelpers.listFiles(
1462
+ this[__private__dont__use].FS,
1463
+ t,
1464
+ e
1465
+ );
1057
1466
  }
1058
- isDir(e) {
1059
- return this.fileExists(e) ? this[__private__dont__use].FS.isDir(
1060
- this[__private__dont__use].FS.lookupPath(e).node.mode
1061
- ) : !1;
1467
+ /**
1468
+ * Checks if a directory exists in the PHP filesystem.
1469
+ *
1470
+ * @param path – The path to check.
1471
+ * @returns True if the path is a directory, false otherwise.
1472
+ */
1473
+ isDir(t) {
1474
+ return FSHelpers.isDir(this[__private__dont__use].FS, t);
1062
1475
  }
1063
- fileExists(e) {
1064
- try {
1065
- return this[__private__dont__use].FS.lookupPath(e), !0;
1066
- } catch {
1067
- return !1;
1068
- }
1476
+ /**
1477
+ * Checks if a file (or a directory) exists in the PHP filesystem.
1478
+ *
1479
+ * @param path - The file path to check.
1480
+ * @returns True if the file exists, false otherwise.
1481
+ */
1482
+ fileExists(t) {
1483
+ return FSHelpers.fileExists(this[__private__dont__use].FS, t);
1069
1484
  }
1070
1485
  /**
1071
1486
  * Hot-swaps the PHP runtime for a new one without
@@ -1077,183 +1492,242 @@ class BasePHP {
1077
1492
  * is fully decoupled from the request handler and
1078
1493
  * accepts a constructor-level cwd argument.
1079
1494
  */
1080
- hotSwapPHPRuntime(e, t) {
1081
- const s = this[__private__dont__use].FS;
1495
+ hotSwapPHPRuntime(t, e) {
1496
+ const r = this[__private__dont__use].FS;
1082
1497
  try {
1083
1498
  this.exit();
1084
1499
  } catch {
1085
1500
  }
1086
- this.initializeRuntime(e), u(this, b) && this.setSapiName(u(this, b)), t && copyFS(s, this[__private__dont__use].FS, t);
1501
+ this.initializeRuntime(t), u(this, S) && this.setSapiName(u(this, S)), e && copyFS(r, this[__private__dont__use].FS, e);
1502
+ }
1503
+ /**
1504
+ * Mounts a filesystem to a given path in the PHP filesystem.
1505
+ *
1506
+ * @param virtualFSPath - Where to mount it in the PHP virtual filesystem.
1507
+ * @param mountHandler - The mount handler to use.
1508
+ * @return Unmount function to unmount the filesystem.
1509
+ */
1510
+ async mount(t, e) {
1511
+ return await e(
1512
+ this,
1513
+ this[__private__dont__use].FS,
1514
+ t
1515
+ );
1516
+ }
1517
+ /**
1518
+ * Starts a PHP CLI session with given arguments.
1519
+ *
1520
+ * This method can only be used when PHP was compiled with the CLI SAPI
1521
+ * and it cannot be used in conjunction with `run()`.
1522
+ *
1523
+ * Once this method finishes running, the PHP instance is no
1524
+ * longer usable and should be discarded. This is because PHP
1525
+ * internally cleans up all the resources and calls exit().
1526
+ *
1527
+ * @param argv - The arguments to pass to the CLI.
1528
+ * @returns The exit code of the CLI session.
1529
+ */
1530
+ async cli(t) {
1531
+ for (const e of t)
1532
+ this[__private__dont__use].ccall(
1533
+ "wasm_add_cli_arg",
1534
+ null,
1535
+ [STRING],
1536
+ [e]
1537
+ );
1538
+ try {
1539
+ return await this[__private__dont__use].ccall(
1540
+ "run_cli",
1541
+ null,
1542
+ [],
1543
+ [],
1544
+ {
1545
+ async: !0
1546
+ }
1547
+ );
1548
+ } catch (e) {
1549
+ if (isExitCodeZero(e))
1550
+ return 0;
1551
+ throw e;
1552
+ }
1087
1553
  }
1088
- exit(e = 0) {
1554
+ setSkipShebang(t) {
1555
+ this[__private__dont__use].ccall(
1556
+ "wasm_set_skip_shebang",
1557
+ null,
1558
+ [NUMBER],
1559
+ [t ? 1 : 0]
1560
+ );
1561
+ }
1562
+ exit(t = 0) {
1089
1563
  this.dispatchEvent({
1090
1564
  type: "runtime.beforedestroy"
1091
1565
  });
1092
1566
  try {
1093
- this[__private__dont__use]._exit(e);
1567
+ this[__private__dont__use]._exit(t);
1094
1568
  } catch {
1095
1569
  }
1096
- f(this, v, !1), f(this, x, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1570
+ f(this, E, !1), f(this, x, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1097
1571
  }
1098
1572
  [Symbol.dispose]() {
1099
- u(this, v) && this.exit(0);
1573
+ u(this, E) && this.exit(0);
1100
1574
  }
1101
1575
  }
1102
- b = new WeakMap(), v = new WeakMap(), x = new WeakMap(), P = new WeakMap(), R = new WeakMap(), C = new WeakSet(), X = function(e, t, s) {
1103
- const r = {
1104
- ...e || {}
1576
+ S = new WeakMap(), E = new WeakMap(), x = new WeakMap(), v = new WeakMap(), R = new WeakMap(), M = new WeakSet(), ee = function(t, e, r) {
1577
+ const s = {
1578
+ ...t || {}
1105
1579
  };
1106
- r.HTTPS = r.HTTPS || s === 443 ? "on" : "off";
1107
- for (const n in t) {
1580
+ s.HTTPS = s.HTTPS || r === 443 ? "on" : "off";
1581
+ for (const n in e) {
1108
1582
  let i = "HTTP_";
1109
- ["content-type", "content-length"].includes(n.toLowerCase()) && (i = ""), r[`${i}${n.toUpperCase().replace(/-/g, "_")}`] = t[n];
1583
+ ["content-type", "content-length"].includes(n.toLowerCase()) && (i = ""), s[`${i}${n.toUpperCase().replace(/-/g, "_")}`] = e[n];
1110
1584
  }
1111
- return r;
1112
- }, M = new WeakSet(), ee = function() {
1113
- this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1585
+ return s;
1114
1586
  }, N = new WeakSet(), te = function() {
1115
- const e = "/internal/headers.json";
1116
- if (!this.fileExists(e))
1587
+ this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1588
+ }, U = new WeakSet(), re = function() {
1589
+ const t = "/internal/headers.json";
1590
+ if (!this.fileExists(t))
1117
1591
  throw new Error(
1118
1592
  "SAPI Error: Could not find response headers file."
1119
1593
  );
1120
- const t = JSON.parse(this.readFileAsText(e)), s = {};
1121
- for (const r of t.headers) {
1122
- if (!r.includes(": "))
1594
+ const e = JSON.parse(this.readFileAsText(t)), r = {};
1595
+ for (const s of e.headers) {
1596
+ if (!s.includes(": "))
1123
1597
  continue;
1124
- const n = r.indexOf(": "), i = r.substring(0, n).toLowerCase(), o = r.substring(n + 2);
1125
- i in s || (s[i] = []), s[i].push(o);
1598
+ const n = s.indexOf(": "), i = s.substring(0, n).toLowerCase(), o = s.substring(n + 2);
1599
+ i in r || (r[i] = []), r[i].push(o);
1126
1600
  }
1127
1601
  return {
1128
- headers: s,
1129
- httpStatusCode: t.status
1602
+ headers: r,
1603
+ httpStatusCode: e.status
1130
1604
  };
1131
- }, O = new WeakSet(), se = function(e) {
1605
+ }, O = new WeakSet(), se = function(t) {
1132
1606
  if (this[__private__dont__use].ccall(
1133
1607
  "wasm_set_request_uri",
1134
1608
  null,
1135
1609
  [STRING],
1136
- [e]
1137
- ), e.includes("?")) {
1138
- const t = e.substring(e.indexOf("?") + 1);
1610
+ [t]
1611
+ ), t.includes("?")) {
1612
+ const e = t.substring(t.indexOf("?") + 1);
1139
1613
  this[__private__dont__use].ccall(
1140
1614
  "wasm_set_query_string",
1141
1615
  null,
1142
1616
  [STRING],
1143
- [t]
1617
+ [e]
1144
1618
  );
1145
1619
  }
1146
- }, L = new WeakSet(), re = function(e) {
1620
+ }, L = new WeakSet(), ne = function(t) {
1147
1621
  this[__private__dont__use].ccall(
1148
1622
  "wasm_set_request_host",
1149
1623
  null,
1150
1624
  [STRING],
1151
- [e]
1625
+ [t]
1152
1626
  );
1153
- }, B = new WeakSet(), ne = function(e) {
1627
+ }, D = new WeakSet(), ie = function(t) {
1154
1628
  this[__private__dont__use].ccall(
1155
1629
  "wasm_set_request_port",
1156
1630
  null,
1157
1631
  [NUMBER],
1158
- [e]
1632
+ [t]
1159
1633
  );
1160
- }, U = new WeakSet(), ie = function(e, t) {
1161
- let s;
1634
+ }, j = new WeakSet(), oe = function(t, e) {
1635
+ let r;
1162
1636
  try {
1163
- s = parseInt(new URL(e).port, 10);
1637
+ r = parseInt(new URL(t).port, 10);
1164
1638
  } catch {
1165
1639
  }
1166
- return (!s || isNaN(s) || s === 80) && (s = t === "https" ? 443 : 80), s;
1167
- }, j = new WeakSet(), oe = function(e) {
1640
+ return (!r || isNaN(r) || r === 80) && (r = e === "https" ? 443 : 80), r;
1641
+ }, $ = new WeakSet(), ae = function(t) {
1168
1642
  this[__private__dont__use].ccall(
1169
1643
  "wasm_set_request_method",
1170
1644
  null,
1171
1645
  [STRING],
1172
- [e]
1646
+ [t]
1173
1647
  );
1174
- }, $ = new WeakSet(), ae = function(e) {
1175
- e.cookie && this[__private__dont__use].ccall(
1648
+ }, B = new WeakSet(), le = function(t) {
1649
+ t.cookie && this[__private__dont__use].ccall(
1176
1650
  "wasm_set_cookies",
1177
1651
  null,
1178
1652
  [STRING],
1179
- [e.cookie]
1180
- ), e["content-type"] && this[__private__dont__use].ccall(
1653
+ [t.cookie]
1654
+ ), t["content-type"] && this[__private__dont__use].ccall(
1181
1655
  "wasm_set_content_type",
1182
1656
  null,
1183
1657
  [STRING],
1184
- [e["content-type"]]
1185
- ), e["content-length"] && this[__private__dont__use].ccall(
1658
+ [t["content-type"]]
1659
+ ), t["content-length"] && this[__private__dont__use].ccall(
1186
1660
  "wasm_set_content_length",
1187
1661
  null,
1188
1662
  [NUMBER],
1189
- [parseInt(e["content-length"], 10)]
1663
+ [parseInt(t["content-length"], 10)]
1190
1664
  );
1191
- }, D = new WeakSet(), ce = function(e) {
1192
- let t, s;
1193
- typeof e == "string" ? (logger.warn(
1665
+ }, q = new WeakSet(), ce = function(t) {
1666
+ let e, r;
1667
+ typeof t == "string" ? (logger.warn(
1194
1668
  "Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"
1195
- ), s = this[__private__dont__use].lengthBytesUTF8(e), t = s + 1) : (s = e.byteLength, t = e.byteLength);
1196
- const r = this[__private__dont__use].malloc(t);
1197
- if (!r)
1669
+ ), r = this[__private__dont__use].lengthBytesUTF8(t), e = r + 1) : (r = t.byteLength, e = t.byteLength);
1670
+ const s = this[__private__dont__use].malloc(e);
1671
+ if (!s)
1198
1672
  throw new Error("Could not allocate memory for the request body.");
1199
- return typeof e == "string" ? this[__private__dont__use].stringToUTF8(
1200
- e,
1201
- r,
1202
- t + 1
1203
- ) : this[__private__dont__use].HEAPU8.set(e, r), this[__private__dont__use].ccall(
1673
+ return typeof t == "string" ? this[__private__dont__use].stringToUTF8(
1674
+ t,
1675
+ s,
1676
+ e + 1
1677
+ ) : this[__private__dont__use].HEAPU8.set(t, s), this[__private__dont__use].ccall(
1204
1678
  "wasm_set_request_body",
1205
1679
  null,
1206
1680
  [NUMBER],
1207
- [r]
1681
+ [s]
1208
1682
  ), this[__private__dont__use].ccall(
1209
1683
  "wasm_set_content_length",
1210
1684
  null,
1211
1685
  [NUMBER],
1212
- [s]
1213
- ), r;
1214
- }, k = new WeakSet(), Z = function(e) {
1686
+ [r]
1687
+ ), s;
1688
+ }, I = new WeakSet(), K = function(t) {
1215
1689
  this[__private__dont__use].ccall(
1216
1690
  "wasm_set_path_translated",
1217
1691
  null,
1218
1692
  [STRING],
1219
- [e]
1693
+ [t]
1220
1694
  );
1221
- }, q = new WeakSet(), le = function(e, t) {
1695
+ }, z = new WeakSet(), ue = function(t, e) {
1222
1696
  this[__private__dont__use].ccall(
1223
1697
  "wasm_add_SERVER_entry",
1224
1698
  null,
1225
1699
  [STRING, STRING],
1226
- [e, t]
1700
+ [t, e]
1227
1701
  );
1228
- }, z = new WeakSet(), ue = function(e, t) {
1702
+ }, W = new WeakSet(), pe = function(t, e) {
1229
1703
  this[__private__dont__use].ccall(
1230
1704
  "wasm_add_ENV_entry",
1231
1705
  null,
1232
1706
  [STRING, STRING],
1233
- [e, t]
1707
+ [t, e]
1234
1708
  );
1235
- }, W = new WeakSet(), de = async function() {
1709
+ }, G = new WeakSet(), de = async function() {
1236
1710
  var n;
1237
- let e, t;
1711
+ let t, e;
1238
1712
  try {
1239
- e = await new Promise((i, o) => {
1240
- var l;
1241
- t = (a) => {
1713
+ t = await new Promise((i, o) => {
1714
+ var c;
1715
+ e = (a) => {
1242
1716
  logger.error(a), logger.error(a.error);
1243
- const p = new Error("Rethrown");
1244
- p.cause = a.error, p.betterMessage = a.message, o(p);
1245
- }, (l = u(this, x)) == null || l.addEventListener(
1717
+ const d = new Error("Rethrown");
1718
+ d.cause = a.error, d.betterMessage = a.message, o(d);
1719
+ }, (c = u(this, x)) == null || c.addEventListener(
1246
1720
  "error",
1247
- t
1721
+ e
1248
1722
  );
1249
- const c = this[__private__dont__use].ccall(
1723
+ const l = this[__private__dont__use].ccall(
1250
1724
  "wasm_sapi_handle_request",
1251
1725
  NUMBER,
1252
1726
  [],
1253
1727
  [],
1254
1728
  { async: !0 }
1255
1729
  );
1256
- return c instanceof Promise ? c.then(i, o) : i(c);
1730
+ return l instanceof Promise ? l.then(i, o) : i(l);
1257
1731
  });
1258
1732
  } catch (i) {
1259
1733
  for (const a in this)
@@ -1263,194 +1737,148 @@ b = new WeakMap(), v = new WeakMap(), x = new WeakMap(), P = new WeakMap(), R =
1263
1737
  );
1264
1738
  });
1265
1739
  this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1266
- const o = i, c = "betterMessage" in o ? o.betterMessage : o.message, l = new Error(c);
1267
- throw l.cause = o, logger.error(l), l;
1740
+ const o = i, l = "betterMessage" in o ? o.betterMessage : o.message, c = new Error(l);
1741
+ throw c.cause = o, logger.error(c), c;
1268
1742
  } finally {
1269
- (n = u(this, x)) == null || n.removeEventListener("error", t);
1743
+ (n = u(this, x)) == null || n.removeEventListener("error", e);
1270
1744
  }
1271
- const { headers: s, httpStatusCode: r } = h(this, N, te).call(this);
1745
+ const { headers: r, httpStatusCode: s } = h(this, U, re).call(this);
1272
1746
  return new PHPResponse(
1273
- e === 0 ? r : 500,
1274
- s,
1747
+ t === 0 ? s : 500,
1748
+ r,
1275
1749
  this.readFileAsBuffer("/internal/stdout"),
1276
1750
  this.readFileAsText("/internal/stderr"),
1277
- e
1751
+ t
1278
1752
  );
1279
1753
  };
1280
- __decorateClass([
1281
- rethrowFileSystemError('Could not create directory "{path}"')
1282
- ], BasePHP.prototype, "mkdir", 1);
1283
- __decorateClass([
1284
- rethrowFileSystemError('Could not create directory "{path}"')
1285
- ], BasePHP.prototype, "mkdirTree", 1);
1286
- __decorateClass([
1287
- rethrowFileSystemError('Could not read "{path}"')
1288
- ], BasePHP.prototype, "readFileAsText", 1);
1289
- __decorateClass([
1290
- rethrowFileSystemError('Could not read "{path}"')
1291
- ], BasePHP.prototype, "readFileAsBuffer", 1);
1292
- __decorateClass([
1293
- rethrowFileSystemError('Could not write to "{path}"')
1294
- ], BasePHP.prototype, "writeFile", 1);
1295
- __decorateClass([
1296
- rethrowFileSystemError('Could not unlink "{path}"')
1297
- ], BasePHP.prototype, "unlink", 1);
1298
- __decorateClass([
1299
- rethrowFileSystemError('Could not remove directory "{path}"')
1300
- ], BasePHP.prototype, "rmdir", 1);
1301
- __decorateClass([
1302
- rethrowFileSystemError('Could not list files in "{path}"')
1303
- ], BasePHP.prototype, "listFiles", 1);
1304
- __decorateClass([
1305
- rethrowFileSystemError('Could not stat "{path}"')
1306
- ], BasePHP.prototype, "isDir", 1);
1307
- __decorateClass([
1308
- rethrowFileSystemError('Could not stat "{path}"')
1309
- ], BasePHP.prototype, "fileExists", 1);
1310
- function normalizeHeaders(e) {
1311
- const t = {};
1312
- for (const s in e)
1313
- t[s.toLowerCase()] = e[s];
1314
- return t;
1754
+ function normalizeHeaders(t) {
1755
+ const e = {};
1756
+ for (const r in t)
1757
+ e[r.toLowerCase()] = t[r];
1758
+ return e;
1315
1759
  }
1316
- function copyFS(e, t, s) {
1317
- let r;
1760
+ function copyFS(t, e, r) {
1761
+ let s;
1318
1762
  try {
1319
- r = e.lookupPath(s);
1763
+ s = t.lookupPath(r);
1320
1764
  } catch {
1321
1765
  return;
1322
1766
  }
1323
- if (!("contents" in r.node))
1767
+ if (!("contents" in s.node))
1324
1768
  return;
1325
- if (!e.isDir(r.node.mode)) {
1326
- t.writeFile(s, e.readFile(s));
1769
+ if (!t.isDir(s.node.mode)) {
1770
+ e.writeFile(r, t.readFile(r));
1327
1771
  return;
1328
1772
  }
1329
- t.mkdirTree(s);
1330
- const n = e.readdir(s).filter((i) => i !== "." && i !== "..");
1773
+ e.mkdirTree(r);
1774
+ const n = t.readdir(r).filter((i) => i !== "." && i !== "..");
1331
1775
  for (const i of n)
1332
- copyFS(e, t, joinPaths(s, i));
1776
+ copyFS(t, e, joinPaths(r, i));
1333
1777
  }
1334
- function copyRecursive(e, t, s) {
1335
- const r = e.lookupPath(t).node;
1336
- if (e.isDir(r.mode)) {
1337
- e.mkdirTree(s);
1338
- const n = e.readdir(t).filter(
1339
- (i) => i !== "." && i !== ".."
1340
- );
1341
- for (const i of n)
1342
- copyRecursive(
1343
- e,
1344
- joinPaths(t, i),
1345
- joinPaths(s, i)
1346
- );
1347
- } else
1348
- e.writeFile(s, e.readFile(t));
1349
- }
1350
- const { hasOwnProperty } = Object.prototype, encode = (e, t = {}) => {
1351
- typeof t == "string" && (t = { section: t }), t.align = t.align === !0, t.newline = t.newline === !0, t.sort = t.sort === !0, t.whitespace = t.whitespace === !0 || t.align === !0, t.platform = t.platform || typeof process < "u" && process.platform, t.bracketedArray = t.bracketedArray !== !1;
1352
- const s = t.platform === "win32" ? `\r
1778
+ const { hasOwnProperty } = Object.prototype, encode = (t, e = {}) => {
1779
+ typeof e == "string" && (e = { section: e }), e.align = e.align === !0, e.newline = e.newline === !0, e.sort = e.sort === !0, e.whitespace = e.whitespace === !0 || e.align === !0, e.platform = e.platform || typeof process < "u" && process.platform, e.bracketedArray = e.bracketedArray !== !1;
1780
+ const r = e.platform === "win32" ? `\r
1353
1781
  ` : `
1354
- `, r = t.whitespace ? " = " : "=", n = [], i = t.sort ? Object.keys(e).sort() : Object.keys(e);
1782
+ `, s = e.whitespace ? " = " : "=", n = [], i = e.sort ? Object.keys(t).sort() : Object.keys(t);
1355
1783
  let o = 0;
1356
- t.align && (o = safe(
1357
- i.filter((a) => e[a] === null || Array.isArray(e[a]) || typeof e[a] != "object").map((a) => Array.isArray(e[a]) ? `${a}[]` : a).concat([""]).reduce((a, p) => safe(a).length >= safe(p).length ? a : p)
1784
+ e.align && (o = safe(
1785
+ i.filter((a) => t[a] === null || Array.isArray(t[a]) || typeof t[a] != "object").map((a) => Array.isArray(t[a]) ? `${a}[]` : a).concat([""]).reduce((a, d) => safe(a).length >= safe(d).length ? a : d)
1358
1786
  ).length);
1359
- let c = "";
1360
- const l = t.bracketedArray ? "[]" : "";
1787
+ let l = "";
1788
+ const c = e.bracketedArray ? "[]" : "";
1361
1789
  for (const a of i) {
1362
- const p = e[a];
1363
- if (p && Array.isArray(p))
1364
- for (const m of p)
1365
- c += safe(`${a}${l}`).padEnd(o, " ") + r + safe(m) + s;
1790
+ const d = t[a];
1791
+ if (d && Array.isArray(d))
1792
+ for (const m of d)
1793
+ l += safe(`${a}${c}`).padEnd(o, " ") + s + safe(m) + r;
1366
1794
  else
1367
- p && typeof p == "object" ? n.push(a) : c += safe(a).padEnd(o, " ") + r + safe(p) + s;
1795
+ d && typeof d == "object" ? n.push(a) : l += safe(a).padEnd(o, " ") + s + safe(d) + r;
1368
1796
  }
1369
- t.section && c.length && (c = "[" + safe(t.section) + "]" + (t.newline ? s + s : s) + c);
1797
+ e.section && l.length && (l = "[" + safe(e.section) + "]" + (e.newline ? r + r : r) + l);
1370
1798
  for (const a of n) {
1371
- const p = splitSections(a, ".").join("\\."), m = (t.section ? t.section + "." : "") + p, y = encode(e[a], {
1372
- ...t,
1799
+ const d = splitSections(a, ".").join("\\."), m = (e.section ? e.section + "." : "") + d, y = encode(t[a], {
1800
+ ...e,
1373
1801
  section: m
1374
1802
  });
1375
- c.length && y.length && (c += s), c += y;
1803
+ l.length && y.length && (l += r), l += y;
1376
1804
  }
1377
- return c;
1805
+ return l;
1378
1806
  };
1379
- function splitSections(e, t) {
1380
- var s = 0, r = 0, n = 0, i = [];
1807
+ function splitSections(t, e) {
1808
+ var r = 0, s = 0, n = 0, i = [];
1381
1809
  do
1382
- if (n = e.indexOf(t, s), n !== -1) {
1383
- if (s = n + t.length, n > 0 && e[n - 1] === "\\")
1810
+ if (n = t.indexOf(e, r), n !== -1) {
1811
+ if (r = n + e.length, n > 0 && t[n - 1] === "\\")
1384
1812
  continue;
1385
- i.push(e.slice(r, n)), r = n + t.length;
1813
+ i.push(t.slice(s, n)), s = n + e.length;
1386
1814
  }
1387
1815
  while (n !== -1);
1388
- return i.push(e.slice(r)), i;
1816
+ return i.push(t.slice(s)), i;
1389
1817
  }
1390
- const decode = (e, t = {}) => {
1391
- t.bracketedArray = t.bracketedArray !== !1;
1392
- const s = /* @__PURE__ */ Object.create(null);
1393
- let r = s, n = null;
1394
- const i = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i, o = e.split(/[\r\n]+/g), c = {};
1818
+ const decode = (t, e = {}) => {
1819
+ e.bracketedArray = e.bracketedArray !== !1;
1820
+ const r = /* @__PURE__ */ Object.create(null);
1821
+ let s = r, n = null;
1822
+ const i = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i, o = t.split(/[\r\n]+/g), l = {};
1395
1823
  for (const a of o) {
1396
1824
  if (!a || a.match(/^\s*[;#]/) || a.match(/^\s*$/))
1397
1825
  continue;
1398
- const p = a.match(i);
1399
- if (!p)
1826
+ const d = a.match(i);
1827
+ if (!d)
1400
1828
  continue;
1401
- if (p[1] !== void 0) {
1402
- if (n = unsafe(p[1]), n === "__proto__") {
1403
- r = /* @__PURE__ */ Object.create(null);
1829
+ if (d[1] !== void 0) {
1830
+ if (n = unsafe(d[1]), n === "__proto__") {
1831
+ s = /* @__PURE__ */ Object.create(null);
1404
1832
  continue;
1405
1833
  }
1406
- r = s[n] = s[n] || /* @__PURE__ */ Object.create(null);
1834
+ s = r[n] = r[n] || /* @__PURE__ */ Object.create(null);
1407
1835
  continue;
1408
1836
  }
1409
- const m = unsafe(p[2]);
1837
+ const m = unsafe(d[2]);
1410
1838
  let y;
1411
- t.bracketedArray ? y = m.length > 2 && m.slice(-2) === "[]" : (c[m] = ((c == null ? void 0 : c[m]) || 0) + 1, y = c[m] > 1);
1839
+ e.bracketedArray ? y = m.length > 2 && m.slice(-2) === "[]" : (l[m] = ((l == null ? void 0 : l[m]) || 0) + 1, y = l[m] > 1);
1412
1840
  const _ = y ? m.slice(0, -2) : m;
1413
1841
  if (_ === "__proto__")
1414
1842
  continue;
1415
- const A = p[3] ? unsafe(p[4]) : !0, K = A === "true" || A === "false" || A === "null" ? JSON.parse(A) : A;
1416
- y && (hasOwnProperty.call(r, _) ? Array.isArray(r[_]) || (r[_] = [r[_]]) : r[_] = []), Array.isArray(r[_]) ? r[_].push(K) : r[_] = K;
1843
+ const A = d[3] ? unsafe(d[4]) : !0, X = A === "true" || A === "false" || A === "null" ? JSON.parse(A) : A;
1844
+ y && (hasOwnProperty.call(s, _) ? Array.isArray(s[_]) || (s[_] = [s[_]]) : s[_] = []), Array.isArray(s[_]) ? s[_].push(X) : s[_] = X;
1417
1845
  }
1418
- const l = [];
1419
- for (const a of Object.keys(s)) {
1420
- if (!hasOwnProperty.call(s, a) || typeof s[a] != "object" || Array.isArray(s[a]))
1846
+ const c = [];
1847
+ for (const a of Object.keys(r)) {
1848
+ if (!hasOwnProperty.call(r, a) || typeof r[a] != "object" || Array.isArray(r[a]))
1421
1849
  continue;
1422
- const p = splitSections(a, ".");
1423
- r = s;
1424
- const m = p.pop(), y = m.replace(/\\\./g, ".");
1425
- for (const _ of p)
1426
- _ !== "__proto__" && ((!hasOwnProperty.call(r, _) || typeof r[_] != "object") && (r[_] = /* @__PURE__ */ Object.create(null)), r = r[_]);
1427
- r === s && y === m || (r[y] = s[a], l.push(a));
1428
- }
1429
- for (const a of l)
1430
- delete s[a];
1431
- return s;
1432
- }, isQuoted = (e) => e.startsWith('"') && e.endsWith('"') || e.startsWith("'") && e.endsWith("'"), safe = (e) => typeof e != "string" || e.match(/[=\r\n]/) || e.match(/^\[/) || e.length > 1 && isQuoted(e) || e !== e.trim() ? JSON.stringify(e) : e.split(";").join("\\;").split("#").join("\\#"), unsafe = (e) => {
1433
- if (e = (e || "").trim(), isQuoted(e)) {
1434
- e.charAt(0) === "'" && (e = e.slice(1, -1));
1850
+ const d = splitSections(a, ".");
1851
+ s = r;
1852
+ const m = d.pop(), y = m.replace(/\\\./g, ".");
1853
+ for (const _ of d)
1854
+ _ !== "__proto__" && ((!hasOwnProperty.call(s, _) || typeof s[_] != "object") && (s[_] = /* @__PURE__ */ Object.create(null)), s = s[_]);
1855
+ s === r && y === m || (s[y] = r[a], c.push(a));
1856
+ }
1857
+ for (const a of c)
1858
+ delete r[a];
1859
+ return r;
1860
+ }, isQuoted = (t) => t.startsWith('"') && t.endsWith('"') || t.startsWith("'") && t.endsWith("'"), safe = (t) => typeof t != "string" || t.match(/[=\r\n]/) || t.match(/^\[/) || t.length > 1 && isQuoted(t) || t !== t.trim() ? JSON.stringify(t) : t.split(";").join("\\;").split("#").join("\\#"), unsafe = (t) => {
1861
+ if (t = (t || "").trim(), isQuoted(t)) {
1862
+ t.charAt(0) === "'" && (t = t.slice(1, -1));
1435
1863
  try {
1436
- e = JSON.parse(e);
1864
+ t = JSON.parse(t);
1437
1865
  } catch {
1438
1866
  }
1439
1867
  } else {
1440
- let t = !1, s = "";
1441
- for (let r = 0, n = e.length; r < n; r++) {
1442
- const i = e.charAt(r);
1443
- if (t)
1444
- "\\;#".indexOf(i) !== -1 ? s += i : s += "\\" + i, t = !1;
1868
+ let e = !1, r = "";
1869
+ for (let s = 0, n = t.length; s < n; s++) {
1870
+ const i = t.charAt(s);
1871
+ if (e)
1872
+ "\\;#".indexOf(i) !== -1 ? r += i : r += "\\" + i, e = !1;
1445
1873
  else {
1446
1874
  if (";#".indexOf(i) !== -1)
1447
1875
  break;
1448
- i === "\\" ? t = !0 : s += i;
1876
+ i === "\\" ? e = !0 : r += i;
1449
1877
  }
1450
1878
  }
1451
- return t && (s += "\\"), s.trim();
1879
+ return e && (r += "\\"), r.trim();
1452
1880
  }
1453
- return e;
1881
+ return t;
1454
1882
  };
1455
1883
  var ini = {
1456
1884
  parse: decode,
@@ -1460,112 +1888,112 @@ var ini = {
1460
1888
  safe,
1461
1889
  unsafe
1462
1890
  };
1463
- async function getPhpIniEntries(e, t) {
1464
- const s = ini.parse(await e.readFileAsText(PHP_INI_PATH));
1465
- if (t === void 0)
1466
- return s;
1467
- const r = {};
1468
- for (const n of t)
1469
- r[n] = s[n];
1470
- return r;
1891
+ async function getPhpIniEntries(t, e) {
1892
+ const r = ini.parse(await t.readFileAsText(PHP_INI_PATH));
1893
+ if (e === void 0)
1894
+ return r;
1895
+ const s = {};
1896
+ for (const n of e)
1897
+ s[n] = r[n];
1898
+ return s;
1471
1899
  }
1472
- async function setPhpIniEntries(e, t) {
1473
- const s = ini.parse(await e.readFileAsText(PHP_INI_PATH));
1474
- for (const [r, n] of Object.entries(t))
1475
- n == null ? delete s[r] : s[r] = n;
1476
- await e.writeFile(PHP_INI_PATH, ini.stringify(s));
1900
+ async function setPhpIniEntries(t, e) {
1901
+ const r = ini.parse(await t.readFileAsText(PHP_INI_PATH));
1902
+ for (const [s, n] of Object.entries(e))
1903
+ n == null ? delete r[s] : r[s] = n;
1904
+ await t.writeFile(PHP_INI_PATH, ini.stringify(r));
1477
1905
  }
1478
- async function withPHPIniValues(e, t, s) {
1479
- const r = await e.readFileAsText(PHP_INI_PATH);
1906
+ async function withPHPIniValues(t, e, r) {
1907
+ const s = await t.readFileAsText(PHP_INI_PATH);
1480
1908
  try {
1481
- return await setPhpIniEntries(e, t), await s();
1909
+ return await setPhpIniEntries(t, e), await r();
1482
1910
  } finally {
1483
- await e.writeFile(PHP_INI_PATH, r);
1911
+ await t.writeFile(PHP_INI_PATH, s);
1484
1912
  }
1485
1913
  }
1486
1914
  class HttpCookieStore {
1487
1915
  constructor() {
1488
1916
  this.cookies = {};
1489
1917
  }
1490
- rememberCookiesFromResponseHeaders(t) {
1491
- if (t != null && t["set-cookie"])
1492
- for (const s of t["set-cookie"])
1918
+ rememberCookiesFromResponseHeaders(e) {
1919
+ if (e != null && e["set-cookie"])
1920
+ for (const r of e["set-cookie"])
1493
1921
  try {
1494
- if (!s.includes("="))
1922
+ if (!r.includes("="))
1495
1923
  continue;
1496
- const r = s.indexOf("="), n = s.substring(0, r), i = s.substring(r + 1).split(";")[0];
1924
+ const s = r.indexOf("="), n = r.substring(0, s), i = r.substring(s + 1).split(";")[0];
1497
1925
  this.cookies[n] = i;
1498
- } catch (r) {
1499
- logger.error(r);
1926
+ } catch (s) {
1927
+ logger.error(s);
1500
1928
  }
1501
1929
  }
1502
1930
  getCookieRequestHeader() {
1503
- const t = [];
1504
- for (const s in this.cookies)
1505
- t.push(`${s}=${this.cookies[s]}`);
1506
- return t.join("; ");
1931
+ const e = [];
1932
+ for (const r in this.cookies)
1933
+ e.push(`${r}=${this.cookies[r]}`);
1934
+ return e.join("; ");
1507
1935
  }
1508
1936
  }
1509
- function concatUint8Array(...e) {
1510
- const t = new Uint8Array(
1511
- e.reduce((r, n) => r + n.length, 0)
1937
+ function concatUint8Array(...t) {
1938
+ const e = new Uint8Array(
1939
+ t.reduce((s, n) => s + n.length, 0)
1512
1940
  );
1513
- let s = 0;
1514
- for (const r of e)
1515
- t.set(r, s), s += r.length;
1516
- return t;
1941
+ let r = 0;
1942
+ for (const s of t)
1943
+ e.set(s, r), r += s.length;
1944
+ return e;
1517
1945
  }
1518
- function concatBytes(e) {
1519
- if (e === void 0) {
1520
- let t = new Uint8Array();
1946
+ function concatBytes(t) {
1947
+ if (t === void 0) {
1948
+ let e = new Uint8Array();
1521
1949
  return new TransformStream({
1522
- transform(s) {
1523
- t = concatUint8Array(t, s);
1950
+ transform(r) {
1951
+ e = concatUint8Array(e, r);
1524
1952
  },
1525
- flush(s) {
1526
- s.enqueue(t);
1953
+ flush(r) {
1954
+ r.enqueue(e);
1527
1955
  }
1528
1956
  });
1529
1957
  } else {
1530
- const t = new ArrayBuffer(e || 0);
1531
- let s = 0;
1958
+ const e = new ArrayBuffer(t || 0);
1959
+ let r = 0;
1532
1960
  return new TransformStream({
1533
- transform(r) {
1534
- new Uint8Array(t).set(r, s), s += r.byteLength;
1961
+ transform(s) {
1962
+ new Uint8Array(e).set(s, r), r += s.byteLength;
1535
1963
  },
1536
- flush(r) {
1537
- r.enqueue(new Uint8Array(t));
1964
+ flush(s) {
1965
+ s.enqueue(new Uint8Array(e));
1538
1966
  }
1539
1967
  });
1540
1968
  }
1541
1969
  }
1542
- function limitBytes(e, t) {
1543
- if (t === 0)
1970
+ function limitBytes(t, e) {
1971
+ if (e === 0)
1544
1972
  return new ReadableStream({
1545
1973
  start(n) {
1546
1974
  n.close();
1547
1975
  }
1548
1976
  });
1549
- const s = e.getReader({ mode: "byob" });
1550
- let r = 0;
1977
+ const r = t.getReader({ mode: "byob" });
1978
+ let s = 0;
1551
1979
  return new ReadableStream({
1552
1980
  async pull(n) {
1553
- const { value: i, done: o } = await s.read(
1554
- new Uint8Array(t - r)
1981
+ const { value: i, done: o } = await r.read(
1982
+ new Uint8Array(e - s)
1555
1983
  );
1556
1984
  if (o) {
1557
- s.releaseLock(), n.close();
1985
+ r.releaseLock(), n.close();
1558
1986
  return;
1559
1987
  }
1560
- r += i.length, n.enqueue(i), r >= t && (s.releaseLock(), n.close());
1988
+ s += i.length, n.enqueue(i), s >= e && (r.releaseLock(), n.close());
1561
1989
  },
1562
1990
  cancel() {
1563
- s.cancel();
1991
+ r.cancel();
1564
1992
  }
1565
1993
  });
1566
1994
  }
1567
- async function collectBytes(e, t) {
1568
- return t !== void 0 && (e = limitBytes(e, t)), await e.pipeThrough(concatBytes(t)).getReader().read().then(({ value: s }) => s);
1995
+ async function collectBytes(t, e) {
1996
+ return e !== void 0 && (t = limitBytes(t, e)), await t.pipeThrough(concatBytes(e)).getReader().read().then(({ value: r }) => r);
1569
1997
  }
1570
1998
  class StreamedFile extends File {
1571
1999
  /**
@@ -1575,8 +2003,8 @@ class StreamedFile extends File {
1575
2003
  * @param name The name of the file.
1576
2004
  * @param type The MIME type of the file.
1577
2005
  */
1578
- constructor(t, s, r) {
1579
- super([], s, { type: r }), this.readableStream = t;
2006
+ constructor(e, r, s) {
2007
+ super([], r, { type: s }), this.readableStream = e;
1580
2008
  }
1581
2009
  /**
1582
2010
  * Overrides the slice() method of the File class.
@@ -1612,80 +2040,80 @@ class StreamedFile extends File {
1612
2040
  }
1613
2041
  }
1614
2042
  ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symbol.asyncIterator] = async function* () {
1615
- const e = this.getReader();
2043
+ const t = this.getReader();
1616
2044
  try {
1617
2045
  for (; ; ) {
1618
- const { done: t, value: s } = await e.read();
1619
- if (t)
2046
+ const { done: e, value: r } = await t.read();
2047
+ if (e)
1620
2048
  return;
1621
- yield s;
2049
+ yield r;
1622
2050
  }
1623
2051
  } finally {
1624
- e.releaseLock();
2052
+ t.releaseLock();
1625
2053
  }
1626
2054
  }, ReadableStream.prototype.iterate = // @ts-ignore
1627
2055
  ReadableStream.prototype[Symbol.asyncIterator]);
1628
- function streamReadFileFromPHP(e, t) {
2056
+ function streamReadFileFromPHP(t, e) {
1629
2057
  return new ReadableStream({
1630
- async pull(s) {
1631
- const r = await e.readFileAsBuffer(t);
1632
- s.enqueue(r), s.close();
2058
+ async pull(r) {
2059
+ const s = await t.readFileAsBuffer(e);
2060
+ r.enqueue(s), r.close();
1633
2061
  }
1634
2062
  });
1635
2063
  }
1636
- async function* iteratePhpFiles(e, t, {
1637
- relativePaths: s = !0,
1638
- pathPrefix: r,
2064
+ async function* iteratePhpFiles(t, e, {
2065
+ relativePaths: r = !0,
2066
+ pathPrefix: s,
1639
2067
  exceptPaths: n = []
1640
2068
  } = {}) {
1641
- t = normalizePath(t);
1642
- const i = [t];
2069
+ e = normalizePath(e);
2070
+ const i = [e];
1643
2071
  for (; i.length; ) {
1644
2072
  const o = i.pop();
1645
2073
  if (!o)
1646
2074
  return;
1647
- const c = await e.listFiles(o);
1648
- for (const l of c) {
1649
- const a = `${o}/${l}`;
1650
- if (n.includes(a.substring(t.length + 1)))
2075
+ const l = await t.listFiles(o);
2076
+ for (const c of l) {
2077
+ const a = `${o}/${c}`;
2078
+ if (n.includes(a.substring(e.length + 1)))
1651
2079
  continue;
1652
- await e.isDir(a) ? i.push(a) : yield new StreamedFile(
1653
- streamReadFileFromPHP(e, a),
1654
- s ? joinPaths(
1655
- r || "",
1656
- a.substring(t.length + 1)
2080
+ await t.isDir(a) ? i.push(a) : yield new StreamedFile(
2081
+ streamReadFileFromPHP(t, a),
2082
+ r ? joinPaths(
2083
+ s || "",
2084
+ a.substring(e.length + 1)
1657
2085
  ) : a
1658
2086
  );
1659
2087
  }
1660
2088
  }
1661
2089
  }
1662
- function writeFilesStreamToPhp(e, t) {
2090
+ function writeFilesStreamToPhp(t, e) {
1663
2091
  return new WritableStream({
1664
- async write(s) {
1665
- const r = joinPaths(t, s.name);
1666
- s.type === "directory" ? await e.mkdir(r) : (await e.mkdir(dirname(r)), await e.writeFile(
1667
- r,
1668
- new Uint8Array(await s.arrayBuffer())
2092
+ async write(r) {
2093
+ const s = joinPaths(e, r.name);
2094
+ r.type === "directory" ? await t.mkdir(s) : (await t.mkdir(dirname(s)), await t.writeFile(
2095
+ s,
2096
+ new Uint8Array(await r.arrayBuffer())
1669
2097
  ));
1670
2098
  }
1671
2099
  });
1672
2100
  }
1673
2101
  class MaxPhpInstancesError extends Error {
1674
- constructor(t) {
2102
+ constructor(e) {
1675
2103
  super(
1676
- `Requested more concurrent PHP instances than the limit (${t}).`
2104
+ `Requested more concurrent PHP instances than the limit (${e}).`
1677
2105
  ), this.name = this.constructor.name;
1678
2106
  }
1679
2107
  }
1680
2108
  class PHPProcessManager {
1681
- constructor(t) {
1682
- this.primaryIdle = !0, this.nextInstance = null, this.allInstances = [], this.maxPhpInstances = (t == null ? void 0 : t.maxPhpInstances) ?? 5, this.phpFactory = t == null ? void 0 : t.phpFactory, this.primaryPhp = t == null ? void 0 : t.primaryPhp, this.semaphore = new Semaphore({
2109
+ constructor(e) {
2110
+ this.primaryIdle = !0, this.nextInstance = null, this.allInstances = [], this.maxPhpInstances = (e == null ? void 0 : e.maxPhpInstances) ?? 5, this.phpFactory = e == null ? void 0 : e.phpFactory, this.primaryPhp = e == null ? void 0 : e.primaryPhp, this.semaphore = new Semaphore({
1683
2111
  concurrency: this.maxPhpInstances,
1684
2112
  /**
1685
2113
  * Wait up to 5 seconds for resources to become available
1686
2114
  * before assuming that all the PHP instances are deadlocked.
1687
2115
  */
1688
- timeout: (t == null ? void 0 : t.timeout) || 5e3
2116
+ timeout: (e == null ? void 0 : e.timeout) || 5e3
1689
2117
  });
1690
2118
  }
1691
2119
  /**
@@ -1702,8 +2130,8 @@ class PHPProcessManager {
1702
2130
  "phpFactory or primaryPhp must be set before calling getPrimaryPhp()."
1703
2131
  );
1704
2132
  if (!this.primaryPhp) {
1705
- const t = await this.spawn({ isPrimary: !0 });
1706
- this.primaryPhp = t.php;
2133
+ const e = await this.spawn({ isPrimary: !0 });
2134
+ this.primaryPhp = e.php;
1707
2135
  }
1708
2136
  return this.primaryPhp;
1709
2137
  }
@@ -1722,8 +2150,8 @@ class PHPProcessManager {
1722
2150
  php: await this.getPrimaryPhp(),
1723
2151
  reap: () => this.primaryIdle = !0
1724
2152
  };
1725
- const t = this.nextInstance || this.spawn({ isPrimary: !1 });
1726
- return this.semaphore.remaining > 0 ? this.nextInstance = this.spawn({ isPrimary: !1 }) : this.nextInstance = null, await t;
2153
+ const e = this.nextInstance || this.spawn({ isPrimary: !1 });
2154
+ return this.semaphore.remaining > 0 ? this.nextInstance = this.spawn({ isPrimary: !1 }) : this.nextInstance = null, await e;
1727
2155
  }
1728
2156
  /**
1729
2157
  * Initiated spawning of a new PHP instance.
@@ -1731,53 +2159,53 @@ class PHPProcessManager {
1731
2159
  * add the spawn promise to the allInstances array without waiting
1732
2160
  * for PHP to spawn.
1733
2161
  */
1734
- spawn(t) {
1735
- if (t.isPrimary && this.allInstances.length > 0)
2162
+ spawn(e) {
2163
+ if (e.isPrimary && this.allInstances.length > 0)
1736
2164
  throw new Error(
1737
2165
  "Requested spawning a primary PHP instance when another primary instance already started spawning."
1738
2166
  );
1739
- const s = this.doSpawn(t);
1740
- this.allInstances.push(s);
1741
- const r = () => {
2167
+ const r = this.doSpawn(e);
2168
+ this.allInstances.push(r);
2169
+ const s = () => {
1742
2170
  this.allInstances = this.allInstances.filter(
1743
- (n) => n !== s
2171
+ (n) => n !== r
1744
2172
  );
1745
2173
  };
1746
- return s.catch((n) => {
1747
- throw r(), n;
2174
+ return r.catch((n) => {
2175
+ throw s(), n;
1748
2176
  }).then((n) => ({
1749
2177
  ...n,
1750
2178
  reap: () => {
1751
- r(), n.reap();
2179
+ s(), n.reap();
1752
2180
  }
1753
2181
  }));
1754
2182
  }
1755
2183
  /**
1756
2184
  * Actually acquires the lock and spawns a new PHP instance.
1757
2185
  */
1758
- async doSpawn(t) {
1759
- let s;
2186
+ async doSpawn(e) {
2187
+ let r;
1760
2188
  try {
1761
- s = await this.semaphore.acquire();
1762
- } catch (r) {
1763
- throw r instanceof AcquireTimeoutError ? new MaxPhpInstancesError(this.maxPhpInstances) : r;
2189
+ r = await this.semaphore.acquire();
2190
+ } catch (s) {
2191
+ throw s instanceof AcquireTimeoutError ? new MaxPhpInstancesError(this.maxPhpInstances) : s;
1764
2192
  }
1765
2193
  try {
1766
- const r = await this.phpFactory(t);
2194
+ const s = await this.phpFactory(e);
1767
2195
  return {
1768
- php: r,
2196
+ php: s,
1769
2197
  reap() {
1770
- r.exit(), s();
2198
+ s.exit(), r();
1771
2199
  }
1772
2200
  };
1773
- } catch (r) {
1774
- throw s(), r;
2201
+ } catch (s) {
2202
+ throw r(), s;
1775
2203
  }
1776
2204
  }
1777
2205
  async [Symbol.asyncDispose]() {
1778
2206
  this.primaryPhp && this.primaryPhp.exit(), await Promise.all(
1779
2207
  this.allInstances.map(
1780
- (t) => t.then(({ reap: s }) => s())
2208
+ (e) => e.then(({ reap: r }) => r())
1781
2209
  )
1782
2210
  );
1783
2211
  }
@@ -1800,49 +2228,42 @@ const SupportedPHPVersions = [
1800
2228
  ], SupportedPHPExtensionBundles = {
1801
2229
  "kitchen-sink": SupportedPHPExtensionsList,
1802
2230
  light: []
1803
- };
1804
- function isLocalPHP(e) {
1805
- return !(e instanceof BasePHP);
1806
- }
1807
- function isRemotePHP(e) {
1808
- return !isLocalPHP(e);
1809
- }
1810
- const DEFAULT_BASE_URL = "http://example.com";
1811
- function toRelativeUrl(e) {
1812
- return e.toString().substring(e.origin.length);
2231
+ }, DEFAULT_BASE_URL = "http://example.com";
2232
+ function toRelativeUrl(t) {
2233
+ return t.toString().substring(t.origin.length);
1813
2234
  }
1814
- function removePathPrefix(e, t) {
1815
- return !t || !e.startsWith(t) ? e : e.substring(t.length);
2235
+ function removePathPrefix(t, e) {
2236
+ return !e || !t.startsWith(e) ? t : t.substring(e.length);
1816
2237
  }
1817
- function ensurePathPrefix(e, t) {
1818
- return !t || e.startsWith(t) ? e : t + e;
2238
+ function ensurePathPrefix(t, e) {
2239
+ return !e || t.startsWith(e) ? t : e + t;
1819
2240
  }
1820
- async function encodeAsMultipart(e) {
1821
- const t = `----${Math.random().toString(36).slice(2)}`, s = `multipart/form-data; boundary=${t}`, r = new TextEncoder(), n = [];
1822
- for (const [l, a] of Object.entries(e))
1823
- n.push(`--${t}\r
1824
- `), n.push(`Content-Disposition: form-data; name="${l}"`), a instanceof File && n.push(`; filename="${a.name}"`), n.push(`\r
2241
+ async function encodeAsMultipart(t) {
2242
+ const e = `----${Math.random().toString(36).slice(2)}`, r = `multipart/form-data; boundary=${e}`, s = new TextEncoder(), n = [];
2243
+ for (const [c, a] of Object.entries(t))
2244
+ n.push(`--${e}\r
2245
+ `), n.push(`Content-Disposition: form-data; name="${c}"`), a instanceof File && n.push(`; filename="${a.name}"`), n.push(`\r
1825
2246
  `), a instanceof File && (n.push("Content-Type: application/octet-stream"), n.push(`\r
1826
2247
  `)), n.push(`\r
1827
2248
  `), a instanceof File ? n.push(await fileToUint8Array(a)) : n.push(a), n.push(`\r
1828
2249
  `);
1829
- n.push(`--${t}--\r
2250
+ n.push(`--${e}--\r
1830
2251
  `);
1831
- const i = n.reduce((l, a) => l + a.length, 0), o = new Uint8Array(i);
1832
- let c = 0;
1833
- for (const l of n)
2252
+ const i = n.reduce((c, a) => c + a.length, 0), o = new Uint8Array(i);
2253
+ let l = 0;
2254
+ for (const c of n)
1834
2255
  o.set(
1835
- typeof l == "string" ? r.encode(l) : l,
1836
- c
1837
- ), c += l.length;
1838
- return { bytes: o, contentType: s };
2256
+ typeof c == "string" ? s.encode(c) : c,
2257
+ l
2258
+ ), l += c.length;
2259
+ return { bytes: o, contentType: r };
1839
2260
  }
1840
- function fileToUint8Array(e) {
1841
- return new Promise((t) => {
1842
- const s = new FileReader();
1843
- s.onload = () => {
1844
- t(new Uint8Array(s.result));
1845
- }, s.readAsArrayBuffer(e);
2261
+ function fileToUint8Array(t) {
2262
+ return new Promise((e) => {
2263
+ const r = new FileReader();
2264
+ r.onload = () => {
2265
+ e(new Uint8Array(r.result));
2266
+ }, r.readAsArrayBuffer(t);
1846
2267
  });
1847
2268
  }
1848
2269
  const _default = "application/octet-stream", asx = "video/x-ms-asf", atom = "application/atom+xml", avi = "video/x-msvideo", avif = "image/avif", bin = "application/octet-stream", bmp = "image/x-ms-bmp", cco = "application/x-cocoa", css = "text/css", data = "application/octet-stream", deb = "application/octet-stream", der = "application/x-x509-ca-cert", dmg = "application/octet-stream", doc = "application/msword", docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", eot = "application/vnd.ms-fontobject", flv = "video/x-flv", gif = "image/gif", gz = "application/gzip", hqx = "application/mac-binhex40", htc = "text/x-component", html = "text/html", ico = "image/x-icon", iso = "application/octet-stream", jad = "text/vnd.sun.j2me.app-descriptor", jar = "application/java-archive", jardiff = "application/x-java-archive-diff", jng = "image/x-jng", jnlp = "application/x-java-jnlp-file", jpg = "image/jpeg", jpeg = "image/jpeg", js = "application/javascript", json = "application/json", kml = "application/vnd.google-earth.kml+xml", kmz = "application/vnd.google-earth.kmz", m3u8 = "application/vnd.apple.mpegurl", m4a = "audio/x-m4a", m4v = "video/x-m4v", md = "text/plain", mid = "audio/midi", mml = "text/mathml", mng = "video/x-mng", mov = "video/quicktime", mp3 = "audio/mpeg", mp4 = "video/mp4", mpeg = "video/mpeg", msi = "application/octet-stream", odg = "application/vnd.oasis.opendocument.graphics", odp = "application/vnd.oasis.opendocument.presentation", ods = "application/vnd.oasis.opendocument.spreadsheet", odt = "application/vnd.oasis.opendocument.text", ogg = "audio/ogg", otf = "font/otf", pdf = "application/pdf", pl = "application/x-perl", png = "image/png", ppt = "application/vnd.ms-powerpoint", pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation", prc = "application/x-pilot", ps = "application/postscript", ra = "audio/x-realaudio", rar = "application/x-rar-compressed", rpm = "application/x-redhat-package-manager", rss = "application/rss+xml", rtf = "application/rtf", run = "application/x-makeself", sea = "application/x-sea", sit = "application/x-stuffit", svg = "image/svg+xml", swf = "application/x-shockwave-flash", tcl = "application/x-tcl", tar = "application/x-tar", tif = "image/tiff", ts = "video/mp2t", ttf = "font/ttf", txt = "text/plain", wasm = "application/wasm", wbmp = "image/vnd.wap.wbmp", webm = "video/webm", webp = "image/webp", wml = "text/vnd.wap.wml", wmlc = "application/vnd.wap.wmlc", wmv = "video/x-ms-wmv", woff = "font/woff", woff2 = "font/woff2", xhtml = "application/xhtml+xml", xls = "application/vnd.ms-excel", xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xml = "text/xml", xpi = "application/x-xpinstall", xspf = "application/xspf+xml", zip = "application/zip", mimeTypes = {
@@ -1941,7 +2362,7 @@ const _default = "application/octet-stream", asx = "video/x-ms-asf", atom = "app
1941
2362
  xspf,
1942
2363
  zip
1943
2364
  };
1944
- var g, S, I, E, F, w, H, T, G, pe, V, he, J, fe, Q, me;
2365
+ var w, F, C, b, H, P, T, k, V, he, J, fe, Q, me, Z, _e;
1945
2366
  class PHPRequestHandler {
1946
2367
  /**
1947
2368
  * The request handler needs to decide whether to serve a static asset or
@@ -1954,18 +2375,18 @@ class PHPRequestHandler {
1954
2375
  * @param php - The PHP instance.
1955
2376
  * @param config - Request Handler configuration.
1956
2377
  */
1957
- constructor(t) {
2378
+ constructor(e) {
1958
2379
  /**
1959
2380
  * Serves a static file from the PHP filesystem.
1960
2381
  *
1961
2382
  * @param fsPath - Absolute path of the static file to serve.
1962
2383
  * @returns The response.
1963
2384
  */
1964
- d(this, G);
2385
+ p(this, V);
1965
2386
  /**
1966
2387
  * Spawns a new PHP instance and dispatches a request to it.
1967
2388
  */
1968
- d(this, V);
2389
+ p(this, J);
1969
2390
  /**
1970
2391
  * Runs the requested PHP file with all the request and $_SERVER
1971
2392
  * superglobals populated.
@@ -1973,7 +2394,7 @@ class PHPRequestHandler {
1973
2394
  * @param request - The request.
1974
2395
  * @returns The response.
1975
2396
  */
1976
- d(this, J);
2397
+ p(this, Q);
1977
2398
  /**
1978
2399
  * Resolve the requested path to the filesystem path of the requested PHP file.
1979
2400
  *
@@ -1983,40 +2404,40 @@ class PHPRequestHandler {
1983
2404
  * @throws {Error} If the requested path doesn't exist.
1984
2405
  * @returns The resolved filesystem path.
1985
2406
  */
1986
- d(this, Q);
1987
- d(this, g, void 0);
1988
- d(this, S, void 0);
1989
- d(this, I, void 0);
1990
- d(this, E, void 0);
1991
- d(this, F, void 0);
1992
- d(this, w, void 0);
1993
- d(this, H, void 0);
1994
- d(this, T, void 0);
2407
+ p(this, Z);
2408
+ p(this, w, void 0);
2409
+ p(this, F, void 0);
2410
+ p(this, C, void 0);
2411
+ p(this, b, void 0);
2412
+ p(this, H, void 0);
2413
+ p(this, P, void 0);
2414
+ p(this, T, void 0);
2415
+ p(this, k, void 0);
1995
2416
  const {
1996
- documentRoot: s = "/www/",
1997
- absoluteUrl: r = typeof location == "object" ? location == null ? void 0 : location.href : "",
2417
+ documentRoot: r = "/www/",
2418
+ absoluteUrl: s = typeof location == "object" ? location == null ? void 0 : location.href : "",
1998
2419
  rewriteRules: n = []
1999
- } = t;
2000
- "processManager" in t ? this.processManager = t.processManager : this.processManager = new PHPProcessManager({
2001
- phpFactory: async (c) => {
2002
- const l = await t.phpFactory({
2003
- ...c,
2420
+ } = e;
2421
+ "processManager" in e ? this.processManager = e.processManager : this.processManager = new PHPProcessManager({
2422
+ phpFactory: async (l) => {
2423
+ const c = await e.phpFactory({
2424
+ ...l,
2004
2425
  requestHandler: this
2005
2426
  });
2006
- return l.requestHandler = this, l;
2427
+ return c.requestHandler = this, c;
2007
2428
  },
2008
- maxPhpInstances: t.maxPhpInstances
2009
- }), f(this, T, new HttpCookieStore()), f(this, g, s);
2010
- const i = new URL(r);
2011
- f(this, I, i.hostname), f(this, E, i.port ? Number(i.port) : i.protocol === "https:" ? 443 : 80), f(this, S, (i.protocol || "").replace(":", ""));
2012
- const o = u(this, E) !== 443 && u(this, E) !== 80;
2013
- f(this, F, [
2014
- u(this, I),
2015
- o ? `:${u(this, E)}` : ""
2016
- ].join("")), f(this, w, i.pathname.replace(/\/+$/, "")), f(this, H, [
2017
- `${u(this, S)}://`,
2018
- u(this, F),
2019
- u(this, w)
2429
+ maxPhpInstances: e.maxPhpInstances
2430
+ }), f(this, k, new HttpCookieStore()), f(this, w, r);
2431
+ const i = new URL(s);
2432
+ f(this, C, i.hostname), f(this, b, i.port ? Number(i.port) : i.protocol === "https:" ? 443 : 80), f(this, F, (i.protocol || "").replace(":", ""));
2433
+ const o = u(this, b) !== 443 && u(this, b) !== 80;
2434
+ f(this, H, [
2435
+ u(this, C),
2436
+ o ? `:${u(this, b)}` : ""
2437
+ ].join("")), f(this, P, i.pathname.replace(/\/+$/, "")), f(this, T, [
2438
+ `${u(this, F)}://`,
2439
+ u(this, H),
2440
+ u(this, P)
2020
2441
  ].join("")), this.rewriteRules = n;
2021
2442
  }
2022
2443
  async getPrimaryPhp() {
@@ -2029,8 +2450,8 @@ class PHPRequestHandler {
2029
2450
  * @param path The server path to convert to an absolute URL.
2030
2451
  * @returns The absolute URL.
2031
2452
  */
2032
- pathToInternalUrl(t) {
2033
- return `${this.absoluteUrl}${t}`;
2453
+ pathToInternalUrl(e) {
2454
+ return `${this.absoluteUrl}${e}`;
2034
2455
  }
2035
2456
  /**
2036
2457
  * Converts an absolute URL based at the PHPRequestHandler to a relative path
@@ -2039,22 +2460,22 @@ class PHPRequestHandler {
2039
2460
  * @param internalUrl An absolute URL based at the PHPRequestHandler root.
2040
2461
  * @returns The relative path.
2041
2462
  */
2042
- internalUrlToPath(t) {
2043
- const s = new URL(t);
2044
- return s.pathname.startsWith(u(this, w)) && (s.pathname = s.pathname.slice(u(this, w).length)), toRelativeUrl(s);
2463
+ internalUrlToPath(e) {
2464
+ const r = new URL(e);
2465
+ return r.pathname.startsWith(u(this, P)) && (r.pathname = r.pathname.slice(u(this, P).length)), toRelativeUrl(r);
2045
2466
  }
2046
2467
  /**
2047
2468
  * The absolute URL of this PHPRequestHandler instance.
2048
2469
  */
2049
2470
  get absoluteUrl() {
2050
- return u(this, H);
2471
+ return u(this, T);
2051
2472
  }
2052
2473
  /**
2053
2474
  * The directory in the PHP filesystem where the server will look
2054
2475
  * for the files to serve. Default: `/var/www`.
2055
2476
  */
2056
2477
  get documentRoot() {
2057
- return u(this, g);
2478
+ return u(this, w);
2058
2479
  }
2059
2480
  /**
2060
2481
  * Serves the request – either by serving a static file, or by
@@ -2104,23 +2525,23 @@ class PHPRequestHandler {
2104
2525
  *
2105
2526
  * @param request - PHP Request data.
2106
2527
  */
2107
- async request(t) {
2108
- const s = t.url.startsWith("http://") || t.url.startsWith("https://"), r = new URL(
2528
+ async request(e) {
2529
+ const r = e.url.startsWith("http://") || e.url.startsWith("https://"), s = new URL(
2109
2530
  // Remove the hash part of the URL as it's not meant for the server.
2110
- t.url.split("#")[0],
2111
- s ? void 0 : DEFAULT_BASE_URL
2531
+ e.url.split("#")[0],
2532
+ r ? void 0 : DEFAULT_BASE_URL
2112
2533
  ), n = applyRewriteRules(
2113
2534
  removePathPrefix(
2114
- decodeURIComponent(r.pathname),
2115
- u(this, w)
2535
+ decodeURIComponent(s.pathname),
2536
+ u(this, P)
2116
2537
  ),
2117
2538
  this.rewriteRules
2118
- ), i = joinPaths(u(this, g), n);
2119
- return seemsLikeAPHPRequestHandlerPath(i) ? h(this, V, he).call(this, t, r) : h(this, G, pe).call(this, await this.processManager.getPrimaryPhp(), i);
2539
+ ), i = joinPaths(u(this, w), n);
2540
+ return seemsLikeAPHPRequestHandlerPath(i) ? h(this, J, fe).call(this, e, s) : h(this, V, he).call(this, await this.processManager.getPrimaryPhp(), i);
2120
2541
  }
2121
2542
  }
2122
- g = new WeakMap(), S = new WeakMap(), I = new WeakMap(), E = new WeakMap(), F = new WeakMap(), w = new WeakMap(), H = new WeakMap(), T = new WeakMap(), G = new WeakSet(), pe = function(t, s) {
2123
- if (!t.fileExists(s))
2543
+ w = new WeakMap(), F = new WeakMap(), C = new WeakMap(), b = new WeakMap(), H = new WeakMap(), P = new WeakMap(), T = new WeakMap(), k = new WeakMap(), V = new WeakSet(), he = function(e, r) {
2544
+ if (!e.fileExists(r))
2124
2545
  return new PHPResponse(
2125
2546
  404,
2126
2547
  // Let the service worker know that no static file was found
@@ -2130,108 +2551,108 @@ g = new WeakMap(), S = new WeakMap(), I = new WeakMap(), E = new WeakMap(), F =
2130
2551
  },
2131
2552
  new TextEncoder().encode("404 File not found")
2132
2553
  );
2133
- const r = t.readFileAsBuffer(s);
2554
+ const s = e.readFileAsBuffer(r);
2134
2555
  return new PHPResponse(
2135
2556
  200,
2136
2557
  {
2137
- "content-length": [`${r.byteLength}`],
2558
+ "content-length": [`${s.byteLength}`],
2138
2559
  // @TODO: Infer the content-type from the arrayBuffer instead of the file path.
2139
2560
  // The code below won't return the correct mime-type if the extension
2140
2561
  // was tampered with.
2141
- "content-type": [inferMimeType(s)],
2562
+ "content-type": [inferMimeType(r)],
2142
2563
  "accept-ranges": ["bytes"],
2143
2564
  "cache-control": ["public, max-age=0"]
2144
2565
  },
2145
- r
2566
+ s
2146
2567
  );
2147
- }, V = new WeakSet(), he = async function(t, s) {
2148
- let r;
2568
+ }, J = new WeakSet(), fe = async function(e, r) {
2569
+ let s;
2149
2570
  try {
2150
- r = await this.processManager.acquirePHPInstance();
2571
+ s = await this.processManager.acquirePHPInstance();
2151
2572
  } catch (n) {
2152
2573
  return n instanceof MaxPhpInstancesError ? PHPResponse.forHttpCode(502) : PHPResponse.forHttpCode(500);
2153
2574
  }
2154
2575
  try {
2155
- return await h(this, J, fe).call(this, r.php, t, s);
2576
+ return await h(this, Q, me).call(this, s.php, e, r);
2156
2577
  } finally {
2157
- r.reap();
2578
+ s.reap();
2158
2579
  }
2159
- }, J = new WeakSet(), fe = async function(t, s, r) {
2580
+ }, Q = new WeakSet(), me = async function(e, r, s) {
2160
2581
  let n = "GET";
2161
2582
  const i = {
2162
- host: u(this, F),
2163
- ...normalizeHeaders(s.headers || {}),
2164
- cookie: u(this, T).getCookieRequestHeader()
2583
+ host: u(this, H),
2584
+ ...normalizeHeaders(r.headers || {}),
2585
+ cookie: u(this, k).getCookieRequestHeader()
2165
2586
  };
2166
- let o = s.body;
2587
+ let o = r.body;
2167
2588
  if (typeof o == "object" && !(o instanceof Uint8Array)) {
2168
2589
  n = "POST";
2169
- const { bytes: l, contentType: a } = await encodeAsMultipart(o);
2170
- o = l, i["content-type"] = a;
2590
+ const { bytes: c, contentType: a } = await encodeAsMultipart(o);
2591
+ o = c, i["content-type"] = a;
2171
2592
  }
2172
- let c;
2593
+ let l;
2173
2594
  try {
2174
- c = h(this, Q, me).call(this, t, decodeURIComponent(r.pathname));
2595
+ l = h(this, Z, _e).call(this, e, decodeURIComponent(s.pathname));
2175
2596
  } catch {
2176
2597
  return PHPResponse.forHttpCode(404);
2177
2598
  }
2178
2599
  try {
2179
- const l = await t.run({
2600
+ const c = await e.run({
2180
2601
  relativeUri: ensurePathPrefix(
2181
- toRelativeUrl(r),
2182
- u(this, w)
2602
+ toRelativeUrl(s),
2603
+ u(this, P)
2183
2604
  ),
2184
- protocol: u(this, S),
2185
- method: s.method || n,
2605
+ protocol: u(this, F),
2606
+ method: r.method || n,
2186
2607
  $_SERVER: {
2187
2608
  REMOTE_ADDR: "127.0.0.1",
2188
- DOCUMENT_ROOT: u(this, g),
2189
- HTTPS: u(this, H).startsWith("https://") ? "on" : ""
2609
+ DOCUMENT_ROOT: u(this, w),
2610
+ HTTPS: u(this, T).startsWith("https://") ? "on" : ""
2190
2611
  },
2191
2612
  body: o,
2192
- scriptPath: c,
2613
+ scriptPath: l,
2193
2614
  headers: i
2194
2615
  });
2195
- return u(this, T).rememberCookiesFromResponseHeaders(
2196
- l.headers
2197
- ), l;
2198
- } catch (l) {
2199
- const a = l;
2616
+ return u(this, k).rememberCookiesFromResponseHeaders(
2617
+ c.headers
2618
+ ), c;
2619
+ } catch (c) {
2620
+ const a = c;
2200
2621
  if (a != null && a.response)
2201
2622
  return a.response;
2202
- throw l;
2623
+ throw c;
2203
2624
  }
2204
- }, Q = new WeakSet(), me = function(t, s) {
2205
- let r = removePathPrefix(s, u(this, w));
2206
- r = applyRewriteRules(r, this.rewriteRules), r.includes(".php") ? r = r.split(".php")[0] + ".php" : t.isDir(`${u(this, g)}${r}`) ? (r.endsWith("/") || (r = `${r}/`), r = `${r}index.php`) : r = "/index.php";
2207
- let n = `${u(this, g)}${r}`;
2208
- if (t.fileExists(n) || (n = `${u(this, g)}/index.php`), t.fileExists(n))
2625
+ }, Z = new WeakSet(), _e = function(e, r) {
2626
+ let s = removePathPrefix(r, u(this, P));
2627
+ s = applyRewriteRules(s, this.rewriteRules), s.includes(".php") ? s = s.split(".php")[0] + ".php" : e.isDir(`${u(this, w)}${s}`) ? (s.endsWith("/") || (s = `${s}/`), s = `${s}index.php`) : s = "/index.php";
2628
+ let n = `${u(this, w)}${s}`;
2629
+ if (e.fileExists(n) || (n = `${u(this, w)}/index.php`), e.fileExists(n))
2209
2630
  return n;
2210
2631
  throw new Error(`File not found: ${n}`);
2211
2632
  };
2212
- function inferMimeType(e) {
2213
- const t = e.split(".").pop();
2214
- return mimeTypes[t] || mimeTypes._default;
2633
+ function inferMimeType(t) {
2634
+ const e = t.split(".").pop();
2635
+ return mimeTypes[e] || mimeTypes._default;
2215
2636
  }
2216
- function seemsLikeAPHPRequestHandlerPath(e) {
2217
- return seemsLikeAPHPFile(e) || seemsLikeADirectoryRoot(e);
2637
+ function seemsLikeAPHPRequestHandlerPath(t) {
2638
+ return seemsLikeAPHPFile(t) || seemsLikeADirectoryRoot(t);
2218
2639
  }
2219
- function seemsLikeAPHPFile(e) {
2220
- return e.endsWith(".php") || e.includes(".php/");
2640
+ function seemsLikeAPHPFile(t) {
2641
+ return t.endsWith(".php") || t.includes(".php/");
2221
2642
  }
2222
- function seemsLikeADirectoryRoot(e) {
2223
- return !e.split("/").pop().includes(".");
2643
+ function seemsLikeADirectoryRoot(t) {
2644
+ return !t.split("/").pop().includes(".");
2224
2645
  }
2225
- function applyRewriteRules(e, t) {
2226
- for (const s of t)
2227
- if (new RegExp(s.match).test(e))
2228
- return e.replace(s.match, s.replacement);
2229
- return e;
2646
+ function applyRewriteRules(t, e) {
2647
+ for (const r of e)
2648
+ if (new RegExp(r.match).test(t))
2649
+ return t.replace(r.match, r.replacement);
2650
+ return t;
2230
2651
  }
2231
2652
  function rotatePHPRuntime({
2232
- php: e,
2233
- cwd: t,
2234
- recreateRuntime: s,
2653
+ php: t,
2654
+ cwd: e,
2655
+ recreateRuntime: r,
2235
2656
  /*
2236
2657
  * 400 is an arbitrary number that should trigger a rotation
2237
2658
  * way before the memory gets too fragmented. If it doesn't,
@@ -2240,53 +2661,55 @@ function rotatePHPRuntime({
2240
2661
  * fragmentation.
2241
2662
  * * Resetting HEAP to its initial value.
2242
2663
  */
2243
- maxRequests: r = 400
2664
+ maxRequests: s = 400
2244
2665
  }) {
2245
2666
  let n = 0;
2246
2667
  async function i() {
2247
- if (++n < r)
2668
+ if (++n < s)
2248
2669
  return;
2249
2670
  n = 0;
2250
- const o = await e.semaphore.acquire();
2671
+ const o = await t.semaphore.acquire();
2251
2672
  try {
2252
- e.hotSwapPHPRuntime(await s(), t);
2673
+ t.hotSwapPHPRuntime(await r(), e);
2253
2674
  } finally {
2254
2675
  o();
2255
2676
  }
2256
2677
  }
2257
- return e.addEventListener("request.end", i), function() {
2258
- e.removeEventListener("request.end", i);
2678
+ return t.addEventListener("request.end", i), function() {
2679
+ t.removeEventListener("request.end", i);
2259
2680
  };
2260
2681
  }
2261
- async function writeFiles(e, t, s, { rmRoot: r = !1 } = {}) {
2262
- r && await e.isDir(t) && await e.rmdir(t, { recursive: !0 });
2263
- for (const [n, i] of Object.entries(s)) {
2264
- const o = joinPaths(t, n);
2265
- await e.fileExists(dirname(o)) || await e.mkdir(dirname(o)), await e.writeFile(o, i);
2682
+ async function writeFiles(t, e, r, { rmRoot: s = !1 } = {}) {
2683
+ s && await t.isDir(e) && await t.rmdir(e, { recursive: !0 });
2684
+ for (const [n, i] of Object.entries(r)) {
2685
+ const o = joinPaths(e, n);
2686
+ await t.fileExists(dirname(o)) || await t.mkdir(dirname(o)), i instanceof Uint8Array || typeof i == "string" ? await t.writeFile(o, i) : await writeFiles(t, o, i);
2266
2687
  }
2267
2688
  }
2268
- function proxyFileSystem(e, t, s) {
2269
- const r = Object.getOwnPropertySymbols(e)[0];
2270
- for (const n of s)
2271
- t.fileExists(n) || t.mkdir(n), e.fileExists(n) || e.mkdir(n), t[r].FS.mount(
2689
+ function proxyFileSystem(t, e, r) {
2690
+ const s = Object.getOwnPropertySymbols(t)[0];
2691
+ for (const n of r)
2692
+ e.fileExists(n) || e.mkdir(n), t.fileExists(n) || t.mkdir(n), e[s].FS.mount(
2272
2693
  // @ts-ignore
2273
- t[r].PROXYFS,
2694
+ e[s].PROXYFS,
2274
2695
  {
2275
2696
  root: n,
2276
2697
  // @ts-ignore
2277
- fs: e[r].FS
2698
+ fs: t[s].FS
2278
2699
  },
2279
2700
  n
2280
2701
  );
2281
2702
  }
2282
2703
  export {
2283
- BasePHP,
2284
2704
  DEFAULT_BASE_URL,
2705
+ FSHelpers,
2285
2706
  HttpCookieStore,
2286
2707
  LatestSupportedPHPVersion,
2708
+ PHP,
2287
2709
  PHPProcessManager,
2288
2710
  PHPRequestHandler,
2289
2711
  PHPResponse,
2712
+ PHPWorker,
2290
2713
  SupportedPHPExtensionBundles,
2291
2714
  SupportedPHPExtensionsList,
2292
2715
  SupportedPHPVersions,
@@ -2297,13 +2720,10 @@ export {
2297
2720
  ensurePathPrefix,
2298
2721
  getPhpIniEntries,
2299
2722
  isExitCodeZero,
2300
- isLocalPHP,
2301
- isRemotePHP,
2302
2723
  iteratePhpFiles as iterateFiles,
2303
2724
  loadPHPRuntime,
2304
2725
  proxyFileSystem,
2305
2726
  removePathPrefix,
2306
- rethrowFileSystemError,
2307
2727
  rotatePHPRuntime,
2308
2728
  setPhpIniEntries,
2309
2729
  toRelativeUrl,