@php-wasm/web 0.7.20 → 0.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/index.d.ts +790 -532
  2. package/index.js +799 -1289
  3. package/kitchen-sink/7_0_33/php_7_0.wasm +0 -0
  4. package/kitchen-sink/7_1_30/php_7_1.wasm +0 -0
  5. package/kitchen-sink/7_2_34/php_7_2.wasm +0 -0
  6. package/kitchen-sink/7_3_33/php_7_3.wasm +0 -0
  7. package/kitchen-sink/7_4_33/php_7_4.wasm +0 -0
  8. package/kitchen-sink/8_0_30/php_8_0.wasm +0 -0
  9. package/kitchen-sink/8_1_23/php_8_1.wasm +0 -0
  10. package/kitchen-sink/8_2_10/php_8_2.wasm +0 -0
  11. package/kitchen-sink/8_3_0/php_8_3.wasm +0 -0
  12. package/kitchen-sink/php_7_0.js +5 -5
  13. package/kitchen-sink/php_7_1.js +5 -5
  14. package/kitchen-sink/php_7_2.js +5 -5
  15. package/kitchen-sink/php_7_3.js +5 -5
  16. package/kitchen-sink/php_7_4.js +5 -5
  17. package/kitchen-sink/php_8_0.js +5 -5
  18. package/kitchen-sink/php_8_1.js +5 -5
  19. package/kitchen-sink/php_8_2.js +5 -5
  20. package/kitchen-sink/php_8_3.js +5 -5
  21. package/light/7_0_33/php_7_0.wasm +0 -0
  22. package/light/7_1_30/php_7_1.wasm +0 -0
  23. package/light/7_2_34/php_7_2.wasm +0 -0
  24. package/light/7_3_33/php_7_3.wasm +0 -0
  25. package/light/7_4_33/php_7_4.wasm +0 -0
  26. package/light/8_0_30/php_8_0.wasm +0 -0
  27. package/light/8_1_23/php_8_1.wasm +0 -0
  28. package/light/8_2_10/php_8_2.wasm +0 -0
  29. package/light/8_3_0/php_8_3.wasm +0 -0
  30. package/light/php_7_0.js +5 -5
  31. package/light/php_7_1.js +5 -5
  32. package/light/php_7_2.js +5 -5
  33. package/light/php_7_3.js +5 -5
  34. package/light/php_7_4.js +5 -5
  35. package/light/php_8_0.js +5 -5
  36. package/light/php_8_1.js +5 -5
  37. package/light/php_8_2.js +5 -5
  38. package/light/php_8_3.js +5 -5
  39. package/package.json +10 -6
package/index.js CHANGED
@@ -1,14 +1,4 @@
1
- var O = (e, t, r) => {
2
- if (!t.has(e))
3
- throw TypeError("Cannot " + r);
4
- };
5
- var p = (e, t, r) => (O(e, t, "read from private field"), r ? r.call(e) : t.get(e)), d = (e, t, r) => {
6
- if (t.has(e))
7
- throw TypeError("Cannot add the same private member more than once");
8
- t instanceof WeakSet ? t.add(e) : t.set(e, r);
9
- }, _ = (e, t, r, s) => (O(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
- var h = (e, t, r) => (O(e, t, "access private method"), r);
11
- const currentJsRuntime$1 = function() {
1
+ const K = function() {
12
2
  var e;
13
3
  return typeof process < "u" && ((e = process.release) == null ? void 0 : e.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : (
14
4
  // @ts-ignore
@@ -16,25 +6,25 @@ const currentJsRuntime$1 = function() {
16
6
  self instanceof WorkerGlobalScope ? "WORKER" : "NODE"
17
7
  );
18
8
  }();
19
- if (currentJsRuntime$1 === "NODE") {
9
+ if (K === "NODE") {
20
10
  let e = function(r) {
21
- return new Promise(function(s, n) {
11
+ return new Promise(function(n, s) {
22
12
  r.onload = r.onerror = function(o) {
23
- r.onload = r.onerror = null, o.type === "load" ? s(r.result) : n(new Error("Failed to read the blob/file"));
13
+ r.onload = r.onerror = null, o.type === "load" ? n(r.result) : s(new Error("Failed to read the blob/file"));
24
14
  };
25
15
  });
26
16
  }, t = function() {
27
- const r = new Uint8Array([1, 2, 3, 4]), n = new File([r], "test").stream();
17
+ const r = new Uint8Array([1, 2, 3, 4]), s = new File([r], "test").stream();
28
18
  try {
29
- return n.getReader({ mode: "byob" }), !0;
19
+ return s.getReader({ mode: "byob" }), !0;
30
20
  } catch {
31
21
  return !1;
32
22
  }
33
23
  };
34
24
  if (typeof File > "u") {
35
25
  class r extends Blob {
36
- constructor(n, o, i) {
37
- super(n);
26
+ constructor(s, o, i) {
27
+ super(s);
38
28
  let a;
39
29
  i != null && i.lastModified && (a = /* @__PURE__ */ new Date()), (!a || isNaN(a.getFullYear())) && (a = /* @__PURE__ */ new Date()), this.lastModifiedDate = a, this.lastModified = a.getMilliseconds(), this.name = o || "";
40
30
  }
@@ -42,101 +32,42 @@ if (currentJsRuntime$1 === "NODE") {
42
32
  global.File = r;
43
33
  }
44
34
  typeof Blob.prototype.arrayBuffer > "u" && (Blob.prototype.arrayBuffer = function() {
45
- const s = new FileReader();
46
- return s.readAsArrayBuffer(this), e(s);
35
+ const n = new FileReader();
36
+ return n.readAsArrayBuffer(this), e(n);
47
37
  }), typeof Blob.prototype.text > "u" && (Blob.prototype.text = function() {
48
- const s = new FileReader();
49
- return s.readAsText(this), e(s);
38
+ const n = new FileReader();
39
+ return n.readAsText(this), e(n);
50
40
  }), (typeof Blob.prototype.stream > "u" || !t()) && (Blob.prototype.stream = function() {
51
41
  let r = 0;
52
- const s = this;
42
+ const n = this;
53
43
  return new ReadableStream({
54
44
  type: "bytes",
55
45
  // 0.5 MB seems like a reasonable chunk size, let's adjust
56
46
  // this if needed.
57
47
  autoAllocateChunkSize: 512 * 1024,
58
- async pull(n) {
59
- const o = n.byobRequest.view, a = await s.slice(
48
+ async pull(s) {
49
+ const o = s.byobRequest.view, a = await n.slice(
60
50
  r,
61
51
  r + o.byteLength
62
- ).arrayBuffer(), l = new Uint8Array(a);
63
- new Uint8Array(o.buffer).set(l);
64
- const c = l.byteLength;
65
- n.byobRequest.respond(c), r += c, r >= s.size && n.close();
52
+ ).arrayBuffer(), u = new Uint8Array(a);
53
+ new Uint8Array(o.buffer).set(u);
54
+ const l = u.byteLength;
55
+ s.byobRequest.respond(l), r += l, r >= n.size && s.close();
66
56
  }
67
57
  });
68
58
  });
69
59
  }
70
- if (currentJsRuntime$1 === "NODE" && typeof CustomEvent > "u") {
60
+ if (K === "NODE" && typeof CustomEvent > "u") {
71
61
  class e extends Event {
72
- constructor(r, s = {}) {
73
- super(r, s), this.detail = s.detail;
62
+ constructor(r, n = {}) {
63
+ super(r, n), this.detail = n.detail;
74
64
  }
75
65
  initCustomEvent() {
76
66
  }
77
67
  }
78
68
  globalThis.CustomEvent = e;
79
69
  }
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, r, s, n = "", o = 0) {
97
- this.httpStatusCode = t, this.headers = r, this.bytes = s, this.exitCode = o, this.errors = n;
98
- }
99
- static forHttpCode(t, r = "") {
100
- return new PHPResponse(
101
- t,
102
- {},
103
- new TextEncoder().encode(
104
- r || 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
- }
138
- }
139
- const FileErrorCodes = {
70
+ const x = {
140
71
  0: "No error occurred. System call completed successfully.",
141
72
  1: "Argument list too long.",
142
73
  2: "Permission denied.",
@@ -215,22 +146,22 @@ const FileErrorCodes = {
215
146
  75: "Cross-device link.",
216
147
  76: "Extension: Capabilities insufficient."
217
148
  };
218
- function getEmscriptenFsError(e) {
149
+ function ue(e) {
219
150
  const t = typeof e == "object" ? e == null ? void 0 : e.errno : null;
220
- if (t in FileErrorCodes)
221
- return FileErrorCodes[t];
151
+ if (t in x)
152
+ return x[t];
222
153
  }
223
- function rethrowFileSystemError(e = "") {
224
- return function(r, s, n) {
225
- const o = n.value;
226
- n.value = function(...i) {
154
+ function y(e = "") {
155
+ return function(r, n, s) {
156
+ const o = s.value;
157
+ s.value = function(...i) {
227
158
  try {
228
159
  return o.apply(this, i);
229
160
  } catch (a) {
230
- const l = typeof a == "object" ? a == null ? void 0 : a.errno : null;
231
- if (l in FileErrorCodes) {
232
- const c = FileErrorCodes[l], u = typeof i[0] == "string" ? i[0] : null, m = u !== null ? e.replaceAll("{path}", u) : e;
233
- throw new Error(`${m}: ${c}`, {
161
+ const u = typeof a == "object" ? a == null ? void 0 : a.errno : null;
162
+ if (u in x) {
163
+ const l = x[u], c = typeof i[1] == "string" ? i[1] : null, d = c !== null ? e.replaceAll("{path}", c) : e;
164
+ throw new Error(`${d}: ${l}`, {
234
165
  cause: a
235
166
  });
236
167
  }
@@ -239,8 +170,17 @@ function rethrowFileSystemError(e = "") {
239
170
  };
240
171
  };
241
172
  }
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) {
173
+ const le = "playground-log", B = (e, ...t) => {
174
+ v.dispatchEvent(
175
+ new CustomEvent(le, {
176
+ detail: {
177
+ log: e,
178
+ args: t
179
+ }
180
+ })
181
+ );
182
+ }, de = (e, ...t) => {
183
+ switch (typeof e.message == "string" ? e.message = W(e.message) : e.message.message && typeof e.message.message == "string" && (e.message.message = W(e.message.message)), e.severity) {
244
184
  case "Debug":
245
185
  console.debug(e.message, ...t);
246
186
  break;
@@ -259,22 +199,22 @@ const logToConsole = (e, ...t) => {
259
199
  default:
260
200
  console.log(e.message, ...t);
261
201
  }
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) => {
202
+ }, fe = (e) => e instanceof Error ? [e.message, e.stack].join(`
203
+ `) : JSON.stringify(e, null, 2), Y = [], $ = (e) => {
204
+ Y.push(e);
205
+ }, N = (e) => {
266
206
  if (e.raw === !0)
267
- addToLogArray(e.message);
207
+ $(e.message);
268
208
  else {
269
- const t = formatLogEntry(
270
- typeof e.message == "object" ? prepareLogMessage$1(e.message) : e.message,
209
+ const t = ye(
210
+ typeof e.message == "object" ? fe(e.message) : e.message,
271
211
  e.severity ?? "Info",
272
212
  e.prefix ?? "JavaScript"
273
213
  );
274
- addToLogArray(t);
214
+ $(t);
275
215
  }
276
216
  };
277
- class Logger extends EventTarget {
217
+ class me extends EventTarget {
278
218
  // constructor
279
219
  constructor(t = []) {
280
220
  super(), this.handlers = t, this.fatalErrorEvent = "playground-fatal-error";
@@ -284,7 +224,7 @@ class Logger extends EventTarget {
284
224
  * @returns string[]
285
225
  */
286
226
  getLogs() {
287
- return this.handlers.includes(logToMemory) ? [...logs] : (this.error(`Logs aren't stored because the logToMemory handler isn't registered.
227
+ return this.handlers.includes(N) ? [...Y] : (this.error(`Logs aren't stored because the logToMemory handler isn't registered.
288
228
  If you're using a custom logger instance, make sure to register logToMemory handler.
289
229
  `), []);
290
230
  }
@@ -297,8 +237,8 @@ class Logger extends EventTarget {
297
237
  * @param args any
298
238
  */
299
239
  logMessage(t, ...r) {
300
- for (const s of this.handlers)
301
- s(t, ...r);
240
+ for (const n of this.handlers)
241
+ n(t, ...r);
302
242
  }
303
243
  /**
304
244
  * Log message
@@ -386,224 +326,40 @@ class Logger extends EventTarget {
386
326
  );
387
327
  }
388
328
  }
389
- const getDefaultHandlers = () => {
329
+ const pe = () => {
390
330
  try {
391
331
  if (process.env.NODE_ENV === "test")
392
- return [logToMemory];
332
+ return [N, B];
393
333
  } catch {
394
334
  }
395
- return [logToMemory, logToConsole];
396
- }, logger = new Logger(getDefaultHandlers()), prepareLogMessage = (e) => e.replace(/\t/g, ""), formatLogEntry = (e, t, r) => {
397
- const s = /* @__PURE__ */ new Date(), n = new Intl.DateTimeFormat("en-GB", {
335
+ return [N, de, B];
336
+ }, v = new me(pe()), W = (e) => e.replace(/\t/g, ""), ye = (e, t, r) => {
337
+ const n = /* @__PURE__ */ new Date(), s = new Intl.DateTimeFormat("en-GB", {
398
338
  year: "numeric",
399
339
  month: "short",
400
340
  day: "2-digit",
401
341
  timeZone: "UTC"
402
- }).format(s).replace(/ /g, "-"), o = new Intl.DateTimeFormat("en-GB", {
342
+ }).format(n).replace(/ /g, "-"), o = new Intl.DateTimeFormat("en-GB", {
403
343
  hour: "2-digit",
404
344
  minute: "2-digit",
405
345
  second: "2-digit",
406
346
  hour12: !1,
407
347
  timeZone: "UTC",
408
348
  timeZoneName: "short"
409
- }).format(s), i = n + " " + o;
410
- return e = prepareLogMessage(e), `[${i}] ${r} ${t}: ${e}`;
411
- }, RuntimeId = Symbol("RuntimeId"), loadedRuntimes = /* @__PURE__ */ new Map();
412
- let lastRuntimeId = 0;
413
- async function loadPHPRuntime(e, t = {}) {
414
- const [r, s, n] = makePromise(), o = e.init(currentJsRuntime, {
415
- onAbort(a) {
416
- n(a), logger.error(a);
417
- },
418
- ENV: {},
419
- // Emscripten sometimes prepends a '/' to the path, which
420
- // breaks vite dev mode. An identity `locateFile` function
421
- // fixes it.
422
- locateFile: (a) => a,
423
- ...t,
424
- noInitialRun: !0,
425
- onRuntimeInitialized() {
426
- t.onRuntimeInitialized && t.onRuntimeInitialized(), s();
427
- }
428
- });
429
- await r;
430
- const i = ++lastRuntimeId;
431
- return o.id = i, o.originalExit = o._exit, o._exit = function(a) {
432
- return loadedRuntimes.delete(i), o.originalExit(a);
433
- }, o[RuntimeId] = i, loadedRuntimes.set(i, o), i;
434
- }
435
- function getLoadedRuntime(e) {
436
- return loadedRuntimes.get(e);
437
- }
438
- 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";
441
- }(), makePromise = () => {
442
- const e = [], t = new Promise((r, s) => {
443
- e.push(r, s);
444
- });
445
- return e.unshift(t), e;
446
- }, kError = Symbol("error"), kMessage = Symbol("message");
447
- class ErrorEvent2 extends Event {
448
- /**
449
- * Create a new `ErrorEvent`.
450
- *
451
- * @param type The name of the event
452
- * @param options A dictionary object that allows for setting
453
- * attributes via object members of the same name.
454
- */
455
- constructor(t, r = {}) {
456
- super(t), this[kError] = r.error === void 0 ? null : r.error, this[kMessage] = r.message === void 0 ? "" : r.message;
457
- }
458
- get error() {
459
- return this[kError];
460
- }
461
- get message() {
462
- return this[kMessage];
463
- }
464
- }
465
- Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: !0 });
466
- Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: !0 });
467
- 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;
470
- }
471
- class UnhandledRejectionsTarget extends EventTarget {
472
- constructor() {
473
- super(...arguments), this.listenersCount = 0;
474
- }
475
- addEventListener(t, r) {
476
- ++this.listenersCount, super.addEventListener(t, r);
477
- }
478
- removeEventListener(t, r) {
479
- --this.listenersCount, super.removeEventListener(t, r);
480
- }
481
- hasListeners() {
482
- return this.listenersCount > 0;
483
- }
484
- }
485
- function improveWASMErrorReporting(e) {
486
- e.asm = {
487
- ...e.asm
488
- };
489
- const t = new UnhandledRejectionsTarget();
490
- for (const r in e.asm)
491
- if (typeof e.asm[r] == "function") {
492
- const s = e.asm[r];
493
- e.asm[r] = function(...n) {
494
- var o;
495
- try {
496
- return s(...n);
497
- } catch (i) {
498
- if (!(i instanceof Error))
499
- throw i;
500
- const a = clarifyErrorMessage(
501
- i,
502
- (o = e.lastAsyncifyStackSource) == null ? void 0 : o.stack
503
- );
504
- if (e.lastAsyncifyStackSource && (i.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
505
- t.dispatchEvent(
506
- new ErrorEvent("error", {
507
- error: i,
508
- message: a
509
- })
510
- );
511
- return;
512
- }
513
- throw isExitCodeZero(i) || showCriticalErrorBox(a), i;
514
- }
515
- };
516
- }
517
- return t;
518
- }
519
- let functionsMaybeMissingFromAsyncify = [];
520
- function getFunctionsMaybeMissingFromAsyncify() {
521
- return functionsMaybeMissingFromAsyncify;
522
- }
523
- function clarifyErrorMessage(e, t) {
524
- if (e.message === "unreachable") {
525
- let r = UNREACHABLE_ERROR;
526
- t || (r += `
527
-
528
- This stack trace is lacking. For a better one initialize
529
- the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
530
-
531
- `), functionsMaybeMissingFromAsyncify = extractPHPFunctionsFromStack(
532
- t || e.stack || ""
533
- );
534
- for (const s of functionsMaybeMissingFromAsyncify)
535
- r += ` * ${s}
536
- `;
537
- return r;
538
- }
539
- return e.message;
540
- }
541
- const UNREACHABLE_ERROR = `
542
- "unreachable" WASM instruction executed.
543
-
544
- The typical reason is a PHP function missing from the ASYNCIFY_ONLY
545
- list when building PHP.wasm.
546
-
547
- You will need to file a new issue in the WordPress Playground repository
548
- and paste this error message there:
549
-
550
- https://github.com/WordPress/wordpress-playground/issues/new
551
-
552
- If you're a core developer, the typical fix is to:
553
-
554
- * Isolate a minimal reproduction of the error
555
- * Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
556
- * Run 'npm run fix-asyncify'
557
- * Commit the changes, push to the repo, release updated NPM packages
558
-
559
- Below is a list of all the PHP functions found in the stack trace to
560
- help with the minimal reproduction. If they're all already listed in
561
- the Dockerfile, you'll need to trigger this error again with long stack
562
- traces enabled. In node.js, you can do it using the --stack-trace-limit=100
563
- CLI option:
564
-
565
- `, redBg = "\x1B[41m", bold = "\x1B[1m", reset = "\x1B[0m", eol = "\x1B[K";
566
- let logged = !1;
567
- function showCriticalErrorBox(e) {
568
- if (!logged && (logged = !0, !(e != null && e.trim().startsWith("Program terminated with exit")))) {
569
- logger.log(`${redBg}
570
- ${eol}
571
- ${bold} WASM ERROR${reset}${redBg}`);
572
- for (const t of e.split(`
573
- `))
574
- logger.log(`${eol} ${t} `);
575
- logger.log(`${reset}`);
576
- }
577
- }
578
- function extractPHPFunctionsFromStack(e) {
579
- try {
580
- const t = e.split(`
581
- `).slice(1).map((r) => {
582
- const s = r.trim().substring(3).split(" ");
583
- return {
584
- fn: s.length >= 2 ? s[0] : "<unknown>",
585
- isWasm: r.includes("wasm://")
586
- };
587
- }).filter(
588
- ({ fn: r, isWasm: s }) => s && !r.startsWith("dynCall_") && !r.startsWith("invoke_")
589
- ).map(({ fn: r }) => r);
590
- return Array.from(new Set(t));
591
- } catch {
592
- return [];
593
- }
594
- }
595
- const SleepFinished = Symbol("SleepFinished");
596
- function sleep(e) {
349
+ }).format(n), i = s + " " + o;
350
+ return e = W(e), `[${i}] ${r} ${t}: ${e}`;
351
+ }, Z = Symbol("SleepFinished");
352
+ function he(e) {
597
353
  return new Promise((t) => {
598
- setTimeout(() => t(SleepFinished), e);
354
+ setTimeout(() => t(Z), e);
599
355
  });
600
356
  }
601
- class AcquireTimeoutError extends Error {
357
+ class we extends Error {
602
358
  constructor() {
603
359
  super("Acquiring lock timed out");
604
360
  }
605
361
  }
606
- class Semaphore {
362
+ class ge {
607
363
  constructor({ concurrency: t, timeout: r }) {
608
364
  this._running = 0, this.concurrency = t, this.timeout = r, this.queue = [];
609
365
  }
@@ -619,10 +375,10 @@ class Semaphore {
619
375
  const t = new Promise((r) => {
620
376
  this.queue.push(r);
621
377
  });
622
- this.timeout !== void 0 ? await Promise.race([t, sleep(this.timeout)]).then(
378
+ this.timeout !== void 0 ? await Promise.race([t, he(this.timeout)]).then(
623
379
  (r) => {
624
- if (r === SleepFinished)
625
- throw new AcquireTimeoutError();
380
+ if (r === Z)
381
+ throw new we();
626
382
  }
627
383
  ) : await t;
628
384
  } else {
@@ -642,716 +398,262 @@ class Semaphore {
642
398
  }
643
399
  }
644
400
  }
645
- class PhpWasmError extends Error {
401
+ class j extends Error {
646
402
  constructor(t, r) {
647
403
  super(t), this.userFriendlyMessage = r, this.userFriendlyMessage || (this.userFriendlyMessage = t);
648
404
  }
649
405
  }
650
- function joinPaths(...e) {
406
+ function b(...e) {
651
407
  let t = e.join("/");
652
- const r = t[0] === "/", s = t.substring(t.length - 1) === "/";
653
- return t = normalizePath(t), !t && !r && (t = "."), t && s && (t += "/"), t;
408
+ const r = t[0] === "/", n = t.substring(t.length - 1) === "/";
409
+ return t = H(t), !t && !r && (t = "."), t && n && (t += "/"), t;
654
410
  }
655
- function dirname(e) {
411
+ function be(e) {
656
412
  if (e === "/")
657
413
  return "/";
658
- e = normalizePath(e);
414
+ e = H(e);
659
415
  const t = e.lastIndexOf("/");
660
416
  return t === -1 ? "" : t === 0 ? "/" : e.substr(0, t);
661
417
  }
662
- function normalizePath(e) {
418
+ function Ee(e) {
419
+ if (e === "/")
420
+ return "/";
421
+ e = H(e);
422
+ const t = e.lastIndexOf("/");
423
+ return t === -1 ? e : e.substr(t + 1);
424
+ }
425
+ function H(e) {
663
426
  const t = e[0] === "/";
664
- return e = normalizePathsArray(
427
+ return e = ke(
665
428
  e.split("/").filter((r) => !!r),
666
429
  !t
667
430
  ).join("/"), (t ? "/" : "") + e.replace(/\/$/, "");
668
431
  }
669
- function normalizePathsArray(e, t) {
432
+ function ke(e, t) {
670
433
  let r = 0;
671
- for (let s = e.length - 1; s >= 0; s--) {
672
- const n = e[s];
673
- n === "." ? e.splice(s, 1) : n === ".." ? (e.splice(s, 1), r++) : r && (e.splice(s, 1), r--);
434
+ for (let n = e.length - 1; n >= 0; n--) {
435
+ const s = e[n];
436
+ s === "." ? e.splice(n, 1) : s === ".." ? (e.splice(n, 1), r++) : r && (e.splice(n, 1), r--);
674
437
  }
675
438
  if (t)
676
439
  for (; r; r--)
677
440
  e.unshift("..");
678
441
  return e;
679
442
  }
680
- function splitShellCommand(e) {
681
- let s = 0, n = "";
682
- const o = [];
683
- let i = "";
684
- for (let a = 0; a < e.length; a++) {
685
- const l = e[a];
686
- l === "\\" ? ((e[a + 1] === '"' || e[a + 1] === "'") && a++, i += e[a]) : s === 0 ? l === '"' || l === "'" ? (s = 1, n = l) : l.match(/\s/) ? (i.trim().length && o.push(i.trim()), i = l) : o.length && !i ? i = o.pop() + l : i += l : s === 1 && (l === n ? (s = 0, n = "") : i += l);
687
- }
688
- return i && o.push(i.trim()), o;
689
- }
690
- function createSpawnHandler(e) {
691
- return function(t, r = [], s = {}) {
692
- const n = new ChildProcess(), o = new ProcessApi(n);
693
- return setTimeout(async () => {
694
- let i = [];
695
- if (r.length)
696
- i = [t, ...r];
697
- else if (typeof t == "string")
698
- i = splitShellCommand(t);
699
- else if (Array.isArray(t))
700
- i = t;
701
- else
702
- throw new Error("Invalid command ", t);
703
- try {
704
- await e(i, o, s);
705
- } catch (a) {
706
- n.emit("error", a), typeof a == "object" && a !== null && "message" in a && typeof a.message == "string" && o.stderr(a.message), o.exit(1);
707
- }
708
- n.emit("spawn", !0);
709
- }), n;
710
- };
711
- }
712
- class EventEmitter {
713
- constructor() {
714
- this.listeners = {};
715
- }
716
- emit(t, r) {
717
- this.listeners[t] && this.listeners[t].forEach(function(s) {
718
- s(r);
719
- });
720
- }
721
- on(t, r) {
722
- this.listeners[t] || (this.listeners[t] = []), this.listeners[t].push(r);
723
- }
724
- }
725
- class ProcessApi extends EventEmitter {
726
- constructor(t) {
727
- super(), this.childProcess = t, this.exited = !1, this.stdinData = [], t.on("stdin", (r) => {
728
- this.stdinData ? this.stdinData.push(r.slice()) : this.emit("stdin", r);
729
- });
730
- }
731
- stdout(t) {
732
- typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stdout.emit("data", t);
733
- }
734
- stdoutEnd() {
735
- this.childProcess.stdout.emit("end", {});
736
- }
737
- stderr(t) {
738
- typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stderr.emit("data", t);
739
- }
740
- stderrEnd() {
741
- this.childProcess.stderr.emit("end", {});
742
- }
743
- exit(t) {
744
- this.exited || (this.exited = !0, this.childProcess.emit("exit", t));
745
- }
746
- flushStdin() {
747
- if (this.stdinData)
748
- for (let t = 0; t < this.stdinData.length; t++)
749
- this.emit("stdin", this.stdinData[t]);
750
- this.stdinData = null;
751
- }
752
- }
753
- let lastPid = 9743;
754
- class ChildProcess extends EventEmitter {
755
- constructor(t = lastPid++) {
756
- super(), this.pid = t, this.stdout = new EventEmitter(), this.stderr = new EventEmitter();
757
- const r = this;
758
- this.stdin = {
759
- write: (s) => {
760
- r.emit("stdin", s);
761
- }
762
- };
763
- }
764
- }
765
- var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, r, s) => {
766
- for (var n = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, o = e.length - 1, i; o >= 0; o--)
767
- (i = e[o]) && (n = (s ? i(t, r, n) : i(n)) || n);
768
- return s && n && __defProp(t, r, n), n;
443
+ var ve = Object.defineProperty, Pe = Object.getOwnPropertyDescriptor, h = (e, t, r, n) => {
444
+ for (var s = n > 1 ? void 0 : n ? Pe(t, r) : t, o = e.length - 1, i; o >= 0; o--)
445
+ (i = e[o]) && (s = (n ? i(t, r, s) : i(s)) || s);
446
+ return n && s && ve(t, r, s), s;
769
447
  };
770
- const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
771
- class PHPExecutionFailureError extends Error {
772
- constructor(t, r, s) {
773
- super(t), this.response = r, this.source = s;
774
- }
775
- }
776
- const PHP_INI_PATH = "/internal/shared/php.ini", AUTO_PREPEND_SCRIPT = "/internal/shared/auto_prepend_file.php";
777
- var E, g, w, y, P, R, B, S, W, x, U, T, q, k, z, C, $, F, V, H, j, M, G, N, J, b, D, A, Q, I, Y, L, Z;
778
- class BasePHP {
779
- /**
780
- * Initializes a PHP runtime.
781
- *
782
- * @internal
783
- * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
784
- * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
785
- */
786
- constructor(e) {
787
- /**
788
- * Prepares the $_SERVER entries for the PHP runtime.
789
- *
790
- * @param defaults Default entries to include in $_SERVER.
791
- * @param headers HTTP headers to include in $_SERVER (as HTTP_ prefixed entries).
792
- * @param port HTTP port, used to determine infer $_SERVER['HTTPS'] value if none
793
- * was provided.
794
- * @returns Computed $_SERVER entries.
795
- */
796
- d(this, R);
797
- d(this, S);
798
- d(this, x);
799
- d(this, T);
800
- d(this, k);
801
- d(this, C);
802
- d(this, F);
803
- d(this, H);
804
- d(this, M);
805
- d(this, N);
806
- d(this, b);
807
- d(this, A);
808
- d(this, I);
809
- d(this, L);
810
- d(this, E, void 0);
811
- d(this, g, void 0);
812
- d(this, w, void 0);
813
- d(this, y, void 0);
814
- d(this, P, void 0);
815
- _(this, g, !1), _(this, w, null), _(this, y, /* @__PURE__ */ new Map()), _(this, P, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e);
816
- }
817
- addEventListener(e, t) {
818
- p(this, y).has(e) || p(this, y).set(e, /* @__PURE__ */ new Set()), p(this, y).get(e).add(t);
819
- }
820
- removeEventListener(e, t) {
821
- var r;
822
- (r = p(this, y).get(e)) == null || r.delete(t);
823
- }
824
- dispatchEvent(e) {
825
- const t = p(this, y).get(e.type);
826
- if (t)
827
- for (const r of t)
828
- r(e);
448
+ const p = class m {
449
+ static readFileAsText(t, r) {
450
+ return new TextDecoder().decode(m.readFileAsBuffer(t, r));
829
451
  }
830
- /** @inheritDoc */
831
- async onMessage(e) {
832
- p(this, P).push(e);
452
+ static readFileAsBuffer(t, r) {
453
+ return t.readFile(r);
833
454
  }
834
- /** @inheritDoc */
835
- async setSpawnHandler(handler) {
836
- typeof handler == "string" && (handler = createSpawnHandler(eval(handler))), this[__private__dont__use].spawnProcess = handler;
455
+ static writeFile(t, r, n) {
456
+ t.writeFile(r, n);
837
457
  }
838
- /** @inheritDoc */
839
- get absoluteUrl() {
840
- return this.requestHandler.absoluteUrl;
841
- }
842
- /** @inheritDoc */
843
- get documentRoot() {
844
- return this.requestHandler.documentRoot;
845
- }
846
- /** @inheritDoc */
847
- pathToInternalUrl(e) {
848
- return this.requestHandler.pathToInternalUrl(e);
849
- }
850
- /** @inheritDoc */
851
- internalUrlToPath(e) {
852
- return this.requestHandler.internalUrlToPath(e);
853
- }
854
- initializeRuntime(e) {
855
- if (this[__private__dont__use])
856
- throw new Error("PHP runtime already initialized.");
857
- const t = getLoadedRuntime(e);
858
- if (!t)
859
- throw new Error("Invalid PHP runtime id.");
860
- this[__private__dont__use] = t, this[__private__dont__use].ccall(
861
- "wasm_set_phpini_path",
862
- null,
863
- ["string"],
864
- [PHP_INI_PATH]
865
- ), this.fileExists(PHP_INI_PATH) || this.writeFile(
866
- PHP_INI_PATH,
867
- [
868
- "auto_prepend_file=" + AUTO_PREPEND_SCRIPT,
869
- "memory_limit=256M",
870
- "ignore_repeated_errors = 1",
871
- "error_reporting = E_ALL",
872
- "display_errors = 1",
873
- "html_errors = 1",
874
- "display_startup_errors = On",
875
- "log_errors = 1",
876
- "always_populate_raw_post_data = -1",
877
- "upload_max_filesize = 2000M",
878
- "post_max_size = 2000M",
879
- "disable_functions = curl_exec,curl_multi_exec",
880
- "allow_url_fopen = Off",
881
- "allow_url_include = Off",
882
- "session.save_path = /home/web_user",
883
- "implicit_flush = 1",
884
- "output_buffering = 0",
885
- "max_execution_time = 0",
886
- "max_input_time = -1"
887
- ].join(`
888
- `)
889
- ), this.fileExists(AUTO_PREPEND_SCRIPT) || this.writeFile(
890
- AUTO_PREPEND_SCRIPT,
891
- `<?php
892
- // Define constants set via defineConstant() calls
893
- if(file_exists('/internal/shared/consts.json')) {
894
- $consts = json_decode(file_get_contents('/internal/shared/consts.json'), true);
895
- foreach ($consts as $const => $value) {
896
- if (!defined($const) && is_scalar($value)) {
897
- define($const, $value);
898
- }
899
- }
900
- }
901
- // Preload all the files from /internal/shared/preload
902
- foreach (glob('/internal/shared/preload/*.php') as $file) {
903
- require_once $file;
904
- }
905
- `
906
- ), t.onMessage = async (r) => {
907
- for (const s of p(this, P)) {
908
- const n = await s(r);
909
- if (n)
910
- return n;
911
- }
912
- return "";
913
- }, _(this, w, improveWASMErrorReporting(t)), this.dispatchEvent({
914
- type: "runtime.initialized"
915
- });
916
- }
917
- /** @inheritDoc */
918
- async setSapiName(e) {
919
- if (this[__private__dont__use].ccall(
920
- "wasm_set_sapi_name",
921
- NUMBER,
922
- [STRING],
923
- [e]
924
- ) !== 0)
925
- throw new Error(
926
- "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
927
- );
928
- _(this, E, e);
929
- }
930
- /** @inheritDoc */
931
- chdir(e) {
932
- this[__private__dont__use].FS.chdir(e);
458
+ static unlink(t, r) {
459
+ t.unlink(r);
933
460
  }
934
461
  /**
935
- * Do not use. Use new PHPRequestHandler() instead.
936
- * @deprecated
462
+ * Moves a file or directory in the PHP filesystem to a
463
+ * new location.
464
+ *
465
+ * @param oldPath The path to rename.
466
+ * @param newPath The new path.
937
467
  */
938
- async request(e) {
939
- if (logger.warn(
940
- "PHP.request() is deprecated. Please use new PHPRequestHandler() instead."
941
- ), !this.requestHandler)
942
- throw new Error("No request handler available.");
943
- return this.requestHandler.request(e);
944
- }
945
- /** @inheritDoc */
946
- async run(e) {
947
- const t = await this.semaphore.acquire();
948
- let r;
949
- try {
950
- if (p(this, g) || (h(this, S, W).call(this), _(this, g, !0)), e.scriptPath && !this.fileExists(e.scriptPath))
951
- throw new Error(
952
- `The script path "${e.scriptPath}" does not exist.`
953
- );
954
- h(this, T, q).call(this, e.relativeUri || ""), h(this, H, j).call(this, e.method || "GET");
955
- const s = normalizeHeaders(e.headers || {}), n = s.host || "example.com:443", o = h(this, F, V).call(this, n, e.protocol || "http");
956
- h(this, k, z).call(this, n), h(this, C, $).call(this, o), h(this, M, G).call(this, s), e.body && (r = h(this, N, J).call(this, e.body)), typeof e.code == "string" ? (this.writeFile("/internal/eval.php", e.code), h(this, b, D).call(this, "/internal/eval.php")) : h(this, b, D).call(this, e.scriptPath || "");
957
- const i = h(this, R, B).call(this, e.$_SERVER, s, o);
958
- for (const c in i)
959
- h(this, A, Q).call(this, c, i[c]);
960
- const a = e.env || {};
961
- for (const c in a)
962
- h(this, I, Y).call(this, c, a[c]);
963
- const l = await h(this, L, Z).call(this);
964
- if (l.exitCode !== 0) {
965
- logger.warn("PHP.run() output was:", l.text);
966
- const c = new PHPExecutionFailureError(
967
- `PHP.run() failed with exit code ${l.exitCode} and the following output: ` + l.errors,
968
- l,
969
- "request"
970
- );
971
- throw logger.error(c), c;
972
- }
973
- return l;
974
- } catch (s) {
975
- throw this.dispatchEvent({
976
- type: "request.error",
977
- error: s,
978
- // Distinguish between PHP request and PHP-wasm errors
979
- source: s.source ?? "php-wasm"
980
- }), s;
981
- } finally {
982
- try {
983
- r && this[__private__dont__use].free(r);
984
- } finally {
985
- t(), this.dispatchEvent({
986
- type: "request.end"
987
- });
988
- }
989
- }
990
- }
991
- defineConstant(e, t) {
992
- let r = {};
468
+ static mv(t, r, n) {
993
469
  try {
994
- r = JSON.parse(
995
- this.fileExists("/internal/shared/consts.json") && this.readFileAsText("/internal/shared/consts.json") || "{}"
996
- );
997
- } catch {
998
- }
999
- this.writeFile(
1000
- "/internal/shared/consts.json",
1001
- JSON.stringify({
1002
- ...r,
1003
- [e]: t
1004
- })
1005
- );
1006
- }
1007
- mkdir(e) {
1008
- this[__private__dont__use].FS.mkdirTree(e);
1009
- }
1010
- mkdirTree(e) {
1011
- this.mkdir(e);
1012
- }
1013
- readFileAsText(e) {
1014
- return new TextDecoder().decode(this.readFileAsBuffer(e));
1015
- }
1016
- readFileAsBuffer(e) {
1017
- return this[__private__dont__use].FS.readFile(e);
1018
- }
1019
- writeFile(e, t) {
1020
- this[__private__dont__use].FS.writeFile(e, t);
1021
- }
1022
- unlink(e) {
1023
- this[__private__dont__use].FS.unlink(e);
1024
- }
1025
- /** @inheritDoc */
1026
- mv(e, t) {
1027
- const r = this[__private__dont__use].FS;
1028
- try {
1029
- const s = r.lookupPath(e).node.mount, n = this.fileExists(t) ? r.lookupPath(t).node.mount : r.lookupPath(dirname(t)).node.mount;
1030
- s.mountpoint !== n.mountpoint ? (copyRecursive(r, e, t), this.rmdir(e, { recursive: !0 })) : r.rename(e, t);
470
+ const s = t.lookupPath(r).node.mount, o = m.fileExists(t, n) ? t.lookupPath(n).node.mount : t.lookupPath(be(n)).node.mount;
471
+ s.mountpoint !== o.mountpoint ? (m.copyRecursive(t, r, n), m.rmdir(t, r, { recursive: !0 })) : t.rename(r, n);
1031
472
  } catch (s) {
1032
- const n = getEmscriptenFsError(s);
1033
- throw n ? new Error(
1034
- `Could not move ${e} to ${t}: ${n}`,
473
+ const o = ue(s);
474
+ throw o ? new Error(
475
+ `Could not move ${r} to ${n}: ${o}`,
1035
476
  {
1036
477
  cause: s
1037
478
  }
1038
479
  ) : s;
1039
480
  }
1040
481
  }
1041
- rmdir(e, t = { recursive: !0 }) {
1042
- t != null && t.recursive && this.listFiles(e).forEach((r) => {
1043
- const s = `${e}/${r}`;
1044
- this.isDir(s) ? this.rmdir(s, t) : this.unlink(s);
1045
- }), this[__private__dont__use].FS.rmdir(e);
482
+ static rmdir(t, r, n = { recursive: !0 }) {
483
+ n != null && n.recursive && m.listFiles(t, r).forEach((s) => {
484
+ const o = `${r}/${s}`;
485
+ m.isDir(t, o) ? m.rmdir(t, o, n) : m.unlink(t, o);
486
+ }), t.rmdir(r);
1046
487
  }
1047
- listFiles(e, t = { prependPath: !1 }) {
1048
- if (!this.fileExists(e))
488
+ static listFiles(t, r, n = { prependPath: !1 }) {
489
+ if (!m.fileExists(t, r))
1049
490
  return [];
1050
491
  try {
1051
- const r = this[__private__dont__use].FS.readdir(e).filter(
1052
- (s) => s !== "." && s !== ".."
492
+ const s = t.readdir(r).filter(
493
+ (o) => o !== "." && o !== ".."
1053
494
  );
1054
- if (t.prependPath) {
1055
- const s = e.replace(/\/$/, "");
1056
- return r.map((n) => `${s}/${n}`);
495
+ if (n.prependPath) {
496
+ const o = r.replace(/\/$/, "");
497
+ return s.map((i) => `${o}/${i}`);
1057
498
  }
1058
- return r;
1059
- } catch (r) {
1060
- return logger.error(r, { path: e }), [];
499
+ return s;
500
+ } catch (s) {
501
+ return v.error(s, { path: r }), [];
1061
502
  }
1062
503
  }
1063
- isDir(e) {
1064
- return this.fileExists(e) ? this[__private__dont__use].FS.isDir(
1065
- this[__private__dont__use].FS.lookupPath(e).node.mode
1066
- ) : !1;
504
+ static isDir(t, r) {
505
+ return m.fileExists(t, r) ? t.isDir(t.lookupPath(r).node.mode) : !1;
1067
506
  }
1068
- fileExists(e) {
507
+ static fileExists(t, r) {
1069
508
  try {
1070
- return this[__private__dont__use].FS.lookupPath(e), !0;
509
+ return t.lookupPath(r), !0;
1071
510
  } catch {
1072
511
  return !1;
1073
512
  }
1074
513
  }
1075
- /**
1076
- * Hot-swaps the PHP runtime for a new one without
1077
- * interrupting the operations of this PHP instance.
1078
- *
1079
- * @param runtime
1080
- * @param cwd. Internal, the VFS path to recreate in the new runtime.
1081
- * This arg is temporary and will be removed once BasePHP
1082
- * is fully decoupled from the request handler and
1083
- * accepts a constructor-level cwd argument.
1084
- */
1085
- hotSwapPHPRuntime(e, t) {
1086
- const r = this[__private__dont__use].FS;
1087
- try {
1088
- this.exit();
1089
- } catch {
1090
- }
1091
- this.initializeRuntime(e), p(this, E) && this.setSapiName(p(this, E)), t && copyFS(r, this[__private__dont__use].FS, t);
1092
- }
1093
- exit(e = 0) {
1094
- this.dispatchEvent({
1095
- type: "runtime.beforedestroy"
1096
- });
1097
- try {
1098
- this[__private__dont__use]._exit(e);
1099
- } catch {
1100
- }
1101
- _(this, g, !1), _(this, w, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
514
+ static mkdir(t, r) {
515
+ t.mkdirTree(r);
1102
516
  }
1103
- [Symbol.dispose]() {
1104
- p(this, g) && this.exit(0);
517
+ static copyRecursive(t, r, n) {
518
+ const s = t.lookupPath(r).node;
519
+ if (t.isDir(s.mode)) {
520
+ t.mkdirTree(n);
521
+ const o = t.readdir(r).filter(
522
+ (i) => i !== "." && i !== ".."
523
+ );
524
+ for (const i of o)
525
+ m.copyRecursive(
526
+ t,
527
+ b(r, i),
528
+ b(n, i)
529
+ );
530
+ } else
531
+ t.writeFile(n, t.readFile(r));
1105
532
  }
1106
- }
1107
- E = new WeakMap(), g = new WeakMap(), w = new WeakMap(), y = new WeakMap(), P = new WeakMap(), R = new WeakSet(), B = function(e, t, r) {
1108
- const s = {
1109
- ...e || {}
1110
- };
1111
- s.HTTPS = s.HTTPS || r === 443 ? "on" : "off";
1112
- for (const n in t) {
1113
- let o = "HTTP_";
1114
- ["content-type", "content-length"].includes(n.toLowerCase()) && (o = ""), s[`${o}${n.toUpperCase().replace(/-/g, "_")}`] = t[n];
533
+ };
534
+ h([
535
+ y('Could not read "{path}"')
536
+ ], p, "readFileAsText", 1);
537
+ h([
538
+ y('Could not read "{path}"')
539
+ ], p, "readFileAsBuffer", 1);
540
+ h([
541
+ y('Could not write to "{path}"')
542
+ ], p, "writeFile", 1);
543
+ h([
544
+ y('Could not unlink "{path}"')
545
+ ], p, "unlink", 1);
546
+ h([
547
+ y('Could not remove directory "{path}"')
548
+ ], p, "rmdir", 1);
549
+ h([
550
+ y('Could not list files in "{path}"')
551
+ ], p, "listFiles", 1);
552
+ h([
553
+ y('Could not stat "{path}"')
554
+ ], p, "isDir", 1);
555
+ h([
556
+ y('Could not stat "{path}"')
557
+ ], p, "fileExists", 1);
558
+ h([
559
+ y('Could not create directory "{path}"')
560
+ ], p, "mkdir", 1);
561
+ h([
562
+ y('Could not copy files from "{path}"')
563
+ ], p, "copyRecursive", 1);
564
+ let R = p;
565
+ const Te = {
566
+ 500: "Internal Server Error",
567
+ 502: "Bad Gateway",
568
+ 404: "Not Found",
569
+ 403: "Forbidden",
570
+ 401: "Unauthorized",
571
+ 400: "Bad Request",
572
+ 301: "Moved Permanently",
573
+ 302: "Found",
574
+ 307: "Temporary Redirect",
575
+ 308: "Permanent Redirect",
576
+ 204: "No Content",
577
+ 201: "Created",
578
+ 200: "OK"
579
+ };
580
+ class O {
581
+ constructor(t, r, n, s = "", o = 0) {
582
+ this.httpStatusCode = t, this.headers = r, this.bytes = n, this.exitCode = o, this.errors = s;
1115
583
  }
1116
- return s;
1117
- }, S = new WeakSet(), W = function() {
1118
- this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1119
- }, x = new WeakSet(), U = function() {
1120
- const e = "/internal/headers.json";
1121
- if (!this.fileExists(e))
1122
- throw new Error(
1123
- "SAPI Error: Could not find response headers file."
584
+ static forHttpCode(t, r = "") {
585
+ return new O(
586
+ t,
587
+ {},
588
+ new TextEncoder().encode(
589
+ r || Te[t] || ""
590
+ )
1124
591
  );
1125
- const t = JSON.parse(this.readFileAsText(e)), r = {};
1126
- for (const s of t.headers) {
1127
- if (!s.includes(": "))
1128
- continue;
1129
- const n = s.indexOf(": "), o = s.substring(0, n).toLowerCase(), i = s.substring(n + 2);
1130
- o in r || (r[o] = []), r[o].push(i);
1131
592
  }
1132
- return {
1133
- headers: r,
1134
- httpStatusCode: t.status
1135
- };
1136
- }, T = new WeakSet(), q = function(e) {
1137
- if (this[__private__dont__use].ccall(
1138
- "wasm_set_request_uri",
1139
- null,
1140
- [STRING],
1141
- [e]
1142
- ), e.includes("?")) {
1143
- const t = e.substring(e.indexOf("?") + 1);
1144
- this[__private__dont__use].ccall(
1145
- "wasm_set_query_string",
1146
- null,
1147
- [STRING],
1148
- [t]
593
+ static fromRawData(t) {
594
+ return new O(
595
+ t.httpStatusCode,
596
+ t.headers,
597
+ t.bytes,
598
+ t.errors,
599
+ t.exitCode
1149
600
  );
1150
601
  }
1151
- }, k = new WeakSet(), z = function(e) {
1152
- this[__private__dont__use].ccall(
1153
- "wasm_set_request_host",
1154
- null,
1155
- [STRING],
1156
- [e]
1157
- );
1158
- }, C = new WeakSet(), $ = function(e) {
1159
- this[__private__dont__use].ccall(
1160
- "wasm_set_request_port",
1161
- null,
1162
- [NUMBER],
1163
- [e]
1164
- );
1165
- }, F = new WeakSet(), V = function(e, t) {
1166
- let r;
1167
- try {
1168
- r = parseInt(new URL(e).port, 10);
1169
- } catch {
1170
- }
1171
- return (!r || isNaN(r) || r === 80) && (r = t === "https" ? 443 : 80), r;
1172
- }, H = new WeakSet(), j = function(e) {
1173
- this[__private__dont__use].ccall(
1174
- "wasm_set_request_method",
1175
- null,
1176
- [STRING],
1177
- [e]
1178
- );
1179
- }, M = new WeakSet(), G = function(e) {
1180
- e.cookie && this[__private__dont__use].ccall(
1181
- "wasm_set_cookies",
1182
- null,
1183
- [STRING],
1184
- [e.cookie]
1185
- ), e["content-type"] && this[__private__dont__use].ccall(
1186
- "wasm_set_content_type",
1187
- null,
1188
- [STRING],
1189
- [e["content-type"]]
1190
- ), e["content-length"] && this[__private__dont__use].ccall(
1191
- "wasm_set_content_length",
1192
- null,
1193
- [NUMBER],
1194
- [parseInt(e["content-length"], 10)]
1195
- );
1196
- }, N = new WeakSet(), J = function(e) {
1197
- let t, r;
1198
- typeof e == "string" ? (logger.warn(
1199
- "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"
1200
- ), r = this[__private__dont__use].lengthBytesUTF8(e), t = r + 1) : (r = e.byteLength, t = e.byteLength);
1201
- const s = this[__private__dont__use].malloc(t);
1202
- if (!s)
1203
- throw new Error("Could not allocate memory for the request body.");
1204
- return typeof e == "string" ? this[__private__dont__use].stringToUTF8(
1205
- e,
1206
- s,
1207
- t + 1
1208
- ) : this[__private__dont__use].HEAPU8.set(e, s), this[__private__dont__use].ccall(
1209
- "wasm_set_request_body",
1210
- null,
1211
- [NUMBER],
1212
- [s]
1213
- ), this[__private__dont__use].ccall(
1214
- "wasm_set_content_length",
1215
- null,
1216
- [NUMBER],
1217
- [r]
1218
- ), s;
1219
- }, b = new WeakSet(), D = function(e) {
1220
- this[__private__dont__use].ccall(
1221
- "wasm_set_path_translated",
1222
- null,
1223
- [STRING],
1224
- [e]
1225
- );
1226
- }, A = new WeakSet(), Q = function(e, t) {
1227
- this[__private__dont__use].ccall(
1228
- "wasm_add_SERVER_entry",
1229
- null,
1230
- [STRING, STRING],
1231
- [e, t]
1232
- );
1233
- }, I = new WeakSet(), Y = function(e, t) {
1234
- this[__private__dont__use].ccall(
1235
- "wasm_add_ENV_entry",
1236
- null,
1237
- [STRING, STRING],
1238
- [e, t]
1239
- );
1240
- }, L = new WeakSet(), Z = async function() {
1241
- var n;
1242
- let e, t;
1243
- try {
1244
- e = await new Promise((o, i) => {
1245
- var l;
1246
- t = (c) => {
1247
- logger.error(c), logger.error(c.error);
1248
- const u = new Error("Rethrown");
1249
- u.cause = c.error, u.betterMessage = c.message, i(u);
1250
- }, (l = p(this, w)) == null || l.addEventListener(
1251
- "error",
1252
- t
1253
- );
1254
- const a = this[__private__dont__use].ccall(
1255
- "wasm_sapi_handle_request",
1256
- NUMBER,
1257
- [],
1258
- [],
1259
- { async: !0 }
1260
- );
1261
- return a instanceof Promise ? a.then(o, i) : o(a);
1262
- });
1263
- } catch (o) {
1264
- for (const c in this)
1265
- typeof this[c] == "function" && (this[c] = () => {
1266
- throw new Error(
1267
- "PHP runtime has crashed – see the earlier error for details."
1268
- );
1269
- });
1270
- this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1271
- const i = o, a = "betterMessage" in i ? i.betterMessage : i.message, l = new Error(a);
1272
- throw l.cause = i, logger.error(l), l;
1273
- } finally {
1274
- (n = p(this, w)) == null || n.removeEventListener("error", t);
602
+ toRawData() {
603
+ return {
604
+ headers: this.headers,
605
+ bytes: this.bytes,
606
+ errors: this.errors,
607
+ exitCode: this.exitCode,
608
+ httpStatusCode: this.httpStatusCode
609
+ };
1275
610
  }
1276
- const { headers: r, httpStatusCode: s } = h(this, x, U).call(this);
1277
- return new PHPResponse(
1278
- e === 0 ? s : 500,
1279
- r,
1280
- this.readFileAsBuffer("/internal/stdout"),
1281
- this.readFileAsText("/internal/stderr"),
1282
- e
1283
- );
1284
- };
1285
- __decorateClass([
1286
- rethrowFileSystemError('Could not create directory "{path}"')
1287
- ], BasePHP.prototype, "mkdir", 1);
1288
- __decorateClass([
1289
- rethrowFileSystemError('Could not create directory "{path}"')
1290
- ], BasePHP.prototype, "mkdirTree", 1);
1291
- __decorateClass([
1292
- rethrowFileSystemError('Could not read "{path}"')
1293
- ], BasePHP.prototype, "readFileAsText", 1);
1294
- __decorateClass([
1295
- rethrowFileSystemError('Could not read "{path}"')
1296
- ], BasePHP.prototype, "readFileAsBuffer", 1);
1297
- __decorateClass([
1298
- rethrowFileSystemError('Could not write to "{path}"')
1299
- ], BasePHP.prototype, "writeFile", 1);
1300
- __decorateClass([
1301
- rethrowFileSystemError('Could not unlink "{path}"')
1302
- ], BasePHP.prototype, "unlink", 1);
1303
- __decorateClass([
1304
- rethrowFileSystemError('Could not remove directory "{path}"')
1305
- ], BasePHP.prototype, "rmdir", 1);
1306
- __decorateClass([
1307
- rethrowFileSystemError('Could not list files in "{path}"')
1308
- ], BasePHP.prototype, "listFiles", 1);
1309
- __decorateClass([
1310
- rethrowFileSystemError('Could not stat "{path}"')
1311
- ], BasePHP.prototype, "isDir", 1);
1312
- __decorateClass([
1313
- rethrowFileSystemError('Could not stat "{path}"')
1314
- ], BasePHP.prototype, "fileExists", 1);
1315
- function normalizeHeaders(e) {
1316
- const t = {};
1317
- for (const r in e)
1318
- t[r.toLowerCase()] = e[r];
1319
- return t;
1320
- }
1321
- function copyFS(e, t, r) {
1322
- let s;
1323
- try {
1324
- s = e.lookupPath(r);
1325
- } catch {
1326
- return;
611
+ /**
612
+ * Response body as JSON.
613
+ */
614
+ get json() {
615
+ return JSON.parse(this.text);
1327
616
  }
1328
- if (!("contents" in s.node))
1329
- return;
1330
- if (!e.isDir(s.node.mode)) {
1331
- t.writeFile(r, e.readFile(r));
1332
- return;
617
+ /**
618
+ * Response body as text.
619
+ */
620
+ get text() {
621
+ return new TextDecoder().decode(this.bytes);
1333
622
  }
1334
- t.mkdirTree(r);
1335
- const n = e.readdir(r).filter((o) => o !== "." && o !== "..");
1336
- for (const o of n)
1337
- copyFS(e, t, joinPaths(r, o));
1338
623
  }
1339
- function copyRecursive(e, t, r) {
1340
- const s = e.lookupPath(t).node;
1341
- if (e.isDir(s.mode)) {
1342
- e.mkdirTree(r);
1343
- const n = e.readdir(t).filter(
1344
- (o) => o !== "." && o !== ".."
1345
- );
1346
- for (const o of n)
1347
- copyRecursive(
1348
- e,
1349
- joinPaths(t, o),
1350
- joinPaths(r, o)
1351
- );
1352
- } else
1353
- e.writeFile(r, e.readFile(t));
624
+ const Re = Symbol("RuntimeId"), _ = /* @__PURE__ */ new Map();
625
+ let Ce = 0;
626
+ async function xe(e, t = {}) {
627
+ const [r, n, s] = Se(), o = e.init(Oe, {
628
+ onAbort(a) {
629
+ s(a), v.error(a);
630
+ },
631
+ ENV: {},
632
+ // Emscripten sometimes prepends a '/' to the path, which
633
+ // breaks vite dev mode. An identity `locateFile` function
634
+ // fixes it.
635
+ locateFile: (a) => a,
636
+ ...t,
637
+ noInitialRun: !0,
638
+ onRuntimeInitialized() {
639
+ t.onRuntimeInitialized && t.onRuntimeInitialized(), n();
640
+ }
641
+ });
642
+ await r;
643
+ const i = ++Ce;
644
+ return o.id = i, o.originalExit = o._exit, o._exit = function(a) {
645
+ return _.delete(i), o.originalExit(a);
646
+ }, o[Re] = i, _.set(i, o), i;
1354
647
  }
648
+ const Oe = function() {
649
+ var e;
650
+ 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";
651
+ }(), Se = () => {
652
+ const e = [], t = new Promise((r, n) => {
653
+ e.push(r, n);
654
+ });
655
+ return e.unshift(t), e;
656
+ }, w = Symbol("__private__dont__use");
1355
657
  ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symbol.asyncIterator] = async function* () {
1356
658
  const e = this.getReader();
1357
659
  try {
@@ -1366,7 +668,7 @@ ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symb
1366
668
  }
1367
669
  }, ReadableStream.prototype.iterate = // @ts-ignore
1368
670
  ReadableStream.prototype[Symbol.asyncIterator]);
1369
- const SupportedPHPVersions = [
671
+ const De = [
1370
672
  "8.3",
1371
673
  "8.2",
1372
674
  "8.1",
@@ -1376,23 +678,23 @@ const SupportedPHPVersions = [
1376
678
  "7.2",
1377
679
  "7.1",
1378
680
  "7.0"
1379
- ], LatestSupportedPHPVersion = SupportedPHPVersions[0];
681
+ ], Ae = De[0];
1380
682
  /**
1381
683
  * @license
1382
684
  * Copyright 2019 Google LLC
1383
685
  * SPDX-License-Identifier: Apache-2.0
1384
686
  */
1385
- const proxyMarker = Symbol("Comlink.proxy"), createEndpoint = Symbol("Comlink.endpoint"), releaseProxy = Symbol("Comlink.releaseProxy"), finalizer = Symbol("Comlink.finalizer"), throwMarker = Symbol("Comlink.thrown"), isObject = (e) => typeof e == "object" && e !== null || typeof e == "function", proxyTransferHandler = {
1386
- canHandle: (e) => isObject(e) && e[proxyMarker],
687
+ const Q = Symbol("Comlink.proxy"), Me = Symbol("Comlink.endpoint"), Le = Symbol("Comlink.releaseProxy"), L = Symbol("Comlink.finalizer"), C = Symbol("Comlink.thrown"), X = (e) => typeof e == "object" && e !== null || typeof e == "function", Ne = {
688
+ canHandle: (e) => X(e) && e[Q],
1387
689
  serialize(e) {
1388
690
  const { port1: t, port2: r } = new MessageChannel();
1389
- return expose(e, t), [r, [r]];
691
+ return M(e, t), [r, [r]];
1390
692
  },
1391
693
  deserialize(e) {
1392
- return e.start(), wrap(e);
694
+ return e.start(), F(e);
1393
695
  }
1394
- }, throwTransferHandler = {
1395
- canHandle: (e) => isObject(e) && throwMarker in e,
696
+ }, We = {
697
+ canHandle: (e) => X(e) && C in e,
1396
698
  serialize({ value: e }) {
1397
699
  let t;
1398
700
  return e instanceof Error ? t = {
@@ -1407,191 +709,191 @@ const proxyMarker = Symbol("Comlink.proxy"), createEndpoint = Symbol("Comlink.en
1407
709
  deserialize(e) {
1408
710
  throw e.isError ? Object.assign(new Error(e.value.message), e.value) : e.value;
1409
711
  }
1410
- }, transferHandlers = /* @__PURE__ */ new Map([
1411
- ["proxy", proxyTransferHandler],
1412
- ["throw", throwTransferHandler]
712
+ }, k = /* @__PURE__ */ new Map([
713
+ ["proxy", Ne],
714
+ ["throw", We]
1413
715
  ]);
1414
- function isAllowedOrigin(e, t) {
716
+ function Ie(e, t) {
1415
717
  for (const r of e)
1416
718
  if (t === r || r === "*" || r instanceof RegExp && r.test(t))
1417
719
  return !0;
1418
720
  return !1;
1419
721
  }
1420
- function expose(e, t = globalThis, r = ["*"]) {
1421
- t.addEventListener("message", function s(n) {
1422
- if (!n || !n.data)
722
+ function M(e, t = globalThis, r = ["*"]) {
723
+ t.addEventListener("message", function n(s) {
724
+ if (!s || !s.data)
1423
725
  return;
1424
- if (!isAllowedOrigin(r, n.origin)) {
1425
- console.warn(`Invalid origin '${n.origin}' for comlink proxy`);
726
+ if (!Ie(r, s.origin)) {
727
+ console.warn(`Invalid origin '${s.origin}' for comlink proxy`);
1426
728
  return;
1427
729
  }
1428
- const { id: o, type: i, path: a } = Object.assign({ path: [] }, n.data), l = (n.data.argumentList || []).map(fromWireValue);
1429
- let c;
730
+ const { id: o, type: i, path: a } = Object.assign({ path: [] }, s.data), u = (s.data.argumentList || []).map(g);
731
+ let l;
1430
732
  try {
1431
- const u = a.slice(0, -1).reduce((f, v) => f[v], e), m = a.reduce((f, v) => f[v], e);
733
+ const c = a.slice(0, -1).reduce((f, P) => f[P], e), d = a.reduce((f, P) => f[P], e);
1432
734
  switch (i) {
1433
735
  case "GET":
1434
- c = m;
736
+ l = d;
1435
737
  break;
1436
738
  case "SET":
1437
- u[a.slice(-1)[0]] = fromWireValue(n.data.value), c = !0;
739
+ c[a.slice(-1)[0]] = g(s.data.value), l = !0;
1438
740
  break;
1439
741
  case "APPLY":
1440
- c = m.apply(u, l);
742
+ l = d.apply(c, u);
1441
743
  break;
1442
744
  case "CONSTRUCT":
1443
745
  {
1444
- const f = new m(...l);
1445
- c = proxy(f);
746
+ const f = new d(...u);
747
+ l = ne(f);
1446
748
  }
1447
749
  break;
1448
750
  case "ENDPOINT":
1449
751
  {
1450
- const { port1: f, port2: v } = new MessageChannel();
1451
- expose(e, v), c = transfer(f, [f]);
752
+ const { port1: f, port2: P } = new MessageChannel();
753
+ M(e, P), l = $e(f, [f]);
1452
754
  }
1453
755
  break;
1454
756
  case "RELEASE":
1455
- c = void 0;
757
+ l = void 0;
1456
758
  break;
1457
759
  default:
1458
760
  return;
1459
761
  }
1460
- } catch (u) {
1461
- c = { value: u, [throwMarker]: 0 };
762
+ } catch (c) {
763
+ l = { value: c, [C]: 0 };
1462
764
  }
1463
- Promise.resolve(c).catch((u) => ({ value: u, [throwMarker]: 0 })).then((u) => {
1464
- const [m, f] = toWireValue(u);
1465
- t.postMessage(Object.assign(Object.assign({}, m), { id: o }), f), i === "RELEASE" && (t.removeEventListener("message", s), closeEndPoint(t), finalizer in e && typeof e[finalizer] == "function" && e[finalizer]());
1466
- }).catch((u) => {
1467
- const [m, f] = toWireValue({
765
+ Promise.resolve(l).catch((c) => ({ value: c, [C]: 0 })).then((c) => {
766
+ const [d, f] = A(c);
767
+ t.postMessage(Object.assign(Object.assign({}, d), { id: o }), f), i === "RELEASE" && (t.removeEventListener("message", n), ee(t), L in e && typeof e[L] == "function" && e[L]());
768
+ }).catch((c) => {
769
+ const [d, f] = A({
1468
770
  value: new TypeError("Unserializable return value"),
1469
- [throwMarker]: 0
771
+ [C]: 0
1470
772
  });
1471
- t.postMessage(Object.assign(Object.assign({}, m), { id: o }), f);
773
+ t.postMessage(Object.assign(Object.assign({}, d), { id: o }), f);
1472
774
  });
1473
775
  }), t.start && t.start();
1474
776
  }
1475
- function isMessagePort(e) {
777
+ function He(e) {
1476
778
  return e.constructor.name === "MessagePort";
1477
779
  }
1478
- function closeEndPoint(e) {
1479
- isMessagePort(e) && e.close();
780
+ function ee(e) {
781
+ He(e) && e.close();
1480
782
  }
1481
- function wrap(e, t) {
1482
- return createProxy(e, [], t);
783
+ function F(e, t) {
784
+ return I(e, [], t);
1483
785
  }
1484
- function throwIfProxyReleased(e) {
786
+ function T(e) {
1485
787
  if (e)
1486
788
  throw new Error("Proxy has been released and is not useable");
1487
789
  }
1488
- function releaseEndpoint(e) {
1489
- return requestResponseMessage(e, {
790
+ function te(e) {
791
+ return E(e, {
1490
792
  type: "RELEASE"
1491
793
  }).then(() => {
1492
- closeEndPoint(e);
794
+ ee(e);
1493
795
  });
1494
796
  }
1495
- const proxyCounter = /* @__PURE__ */ new WeakMap(), proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((e) => {
1496
- const t = (proxyCounter.get(e) || 0) - 1;
1497
- proxyCounter.set(e, t), t === 0 && releaseEndpoint(e);
797
+ const S = /* @__PURE__ */ new WeakMap(), D = "FinalizationRegistry" in globalThis && new FinalizationRegistry((e) => {
798
+ const t = (S.get(e) || 0) - 1;
799
+ S.set(e, t), t === 0 && te(e);
1498
800
  });
1499
- function registerProxy(e, t) {
1500
- const r = (proxyCounter.get(t) || 0) + 1;
1501
- proxyCounter.set(t, r), proxyFinalizers && proxyFinalizers.register(e, t, e);
801
+ function Fe(e, t) {
802
+ const r = (S.get(t) || 0) + 1;
803
+ S.set(t, r), D && D.register(e, t, e);
1502
804
  }
1503
- function unregisterProxy(e) {
1504
- proxyFinalizers && proxyFinalizers.unregister(e);
805
+ function ze(e) {
806
+ D && D.unregister(e);
1505
807
  }
1506
- function createProxy(e, t = [], r = function() {
808
+ function I(e, t = [], r = function() {
1507
809
  }) {
1508
- let s = !1;
1509
- const n = new Proxy(r, {
810
+ let n = !1;
811
+ const s = new Proxy(r, {
1510
812
  get(o, i) {
1511
- if (throwIfProxyReleased(s), i === releaseProxy)
813
+ if (T(n), i === Le)
1512
814
  return () => {
1513
- unregisterProxy(n), releaseEndpoint(e), s = !0;
815
+ ze(s), te(e), n = !0;
1514
816
  };
1515
817
  if (i === "then") {
1516
818
  if (t.length === 0)
1517
- return { then: () => n };
1518
- const a = requestResponseMessage(e, {
819
+ return { then: () => s };
820
+ const a = E(e, {
1519
821
  type: "GET",
1520
- path: t.map((l) => l.toString())
1521
- }).then(fromWireValue);
822
+ path: t.map((u) => u.toString())
823
+ }).then(g);
1522
824
  return a.then.bind(a);
1523
825
  }
1524
- return createProxy(e, [...t, i]);
826
+ return I(e, [...t, i]);
1525
827
  },
1526
828
  set(o, i, a) {
1527
- throwIfProxyReleased(s);
1528
- const [l, c] = toWireValue(a);
1529
- return requestResponseMessage(e, {
829
+ T(n);
830
+ const [u, l] = A(a);
831
+ return E(e, {
1530
832
  type: "SET",
1531
- path: [...t, i].map((u) => u.toString()),
1532
- value: l
1533
- }, c).then(fromWireValue);
833
+ path: [...t, i].map((c) => c.toString()),
834
+ value: u
835
+ }, l).then(g);
1534
836
  },
1535
837
  apply(o, i, a) {
1536
- throwIfProxyReleased(s);
1537
- const l = t[t.length - 1];
1538
- if (l === createEndpoint)
1539
- return requestResponseMessage(e, {
838
+ T(n);
839
+ const u = t[t.length - 1];
840
+ if (u === Me)
841
+ return E(e, {
1540
842
  type: "ENDPOINT"
1541
- }).then(fromWireValue);
1542
- if (l === "bind")
1543
- return createProxy(e, t.slice(0, -1));
1544
- const [c, u] = processArguments(a);
1545
- return requestResponseMessage(e, {
843
+ }).then(g);
844
+ if (u === "bind")
845
+ return I(e, t.slice(0, -1));
846
+ const [l, c] = q(a);
847
+ return E(e, {
1546
848
  type: "APPLY",
1547
- path: t.map((m) => m.toString()),
1548
- argumentList: c
1549
- }, u).then(fromWireValue);
849
+ path: t.map((d) => d.toString()),
850
+ argumentList: l
851
+ }, c).then(g);
1550
852
  },
1551
853
  construct(o, i) {
1552
- throwIfProxyReleased(s);
1553
- const [a, l] = processArguments(i);
1554
- return requestResponseMessage(e, {
854
+ T(n);
855
+ const [a, u] = q(i);
856
+ return E(e, {
1555
857
  type: "CONSTRUCT",
1556
- path: t.map((c) => c.toString()),
858
+ path: t.map((l) => l.toString()),
1557
859
  argumentList: a
1558
- }, l).then(fromWireValue);
860
+ }, u).then(g);
1559
861
  }
1560
862
  });
1561
- return registerProxy(n, e), n;
863
+ return Fe(s, e), s;
1562
864
  }
1563
- function myFlat(e) {
865
+ function Be(e) {
1564
866
  return Array.prototype.concat.apply([], e);
1565
867
  }
1566
- function processArguments(e) {
1567
- const t = e.map(toWireValue);
1568
- return [t.map((r) => r[0]), myFlat(t.map((r) => r[1]))];
868
+ function q(e) {
869
+ const t = e.map(A);
870
+ return [t.map((r) => r[0]), Be(t.map((r) => r[1]))];
1569
871
  }
1570
- const transferCache = /* @__PURE__ */ new WeakMap();
1571
- function transfer(e, t) {
1572
- return transferCache.set(e, t), e;
872
+ const re = /* @__PURE__ */ new WeakMap();
873
+ function $e(e, t) {
874
+ return re.set(e, t), e;
1573
875
  }
1574
- function proxy(e) {
1575
- return Object.assign(e, { [proxyMarker]: !0 });
876
+ function ne(e) {
877
+ return Object.assign(e, { [Q]: !0 });
1576
878
  }
1577
- function windowEndpoint(e, t = globalThis, r = "*") {
879
+ function se(e, t = globalThis, r = "*") {
1578
880
  return {
1579
- postMessage: (s, n) => e.postMessage(s, r, n),
881
+ postMessage: (n, s) => e.postMessage(n, r, s),
1580
882
  addEventListener: t.addEventListener.bind(t),
1581
883
  removeEventListener: t.removeEventListener.bind(t)
1582
884
  };
1583
885
  }
1584
- function toWireValue(e) {
1585
- for (const [t, r] of transferHandlers)
886
+ function A(e) {
887
+ for (const [t, r] of k)
1586
888
  if (r.canHandle(e)) {
1587
- const [s, n] = r.serialize(e);
889
+ const [n, s] = r.serialize(e);
1588
890
  return [
1589
891
  {
1590
892
  type: "HANDLER",
1591
893
  name: t,
1592
- value: s
894
+ value: n
1593
895
  },
1594
- n
896
+ s
1595
897
  ];
1596
898
  }
1597
899
  return [
@@ -1599,66 +901,66 @@ function toWireValue(e) {
1599
901
  type: "RAW",
1600
902
  value: e
1601
903
  },
1602
- transferCache.get(e) || []
904
+ re.get(e) || []
1603
905
  ];
1604
906
  }
1605
- function fromWireValue(e) {
907
+ function g(e) {
1606
908
  switch (e.type) {
1607
909
  case "HANDLER":
1608
- return transferHandlers.get(e.name).deserialize(e.value);
910
+ return k.get(e.name).deserialize(e.value);
1609
911
  case "RAW":
1610
912
  return e.value;
1611
913
  }
1612
914
  }
1613
- function requestResponseMessage(e, t, r) {
1614
- return new Promise((s) => {
1615
- const n = generateUUID();
915
+ function E(e, t, r) {
916
+ return new Promise((n) => {
917
+ const s = je();
1616
918
  e.addEventListener("message", function o(i) {
1617
- !i.data || !i.data.id || i.data.id !== n || (e.removeEventListener("message", o), s(i.data));
1618
- }), e.start && e.start(), e.postMessage(Object.assign({ id: n }, t), r);
919
+ !i.data || !i.data.id || i.data.id !== s || (e.removeEventListener("message", o), n(i.data));
920
+ }), e.start && e.start(), e.postMessage(Object.assign({ id: s }, t), r);
1619
921
  });
1620
922
  }
1621
- function generateUUID() {
923
+ function je() {
1622
924
  return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
1623
925
  }
1624
- function consumeAPI(e, t = void 0) {
1625
- setupTransferHandlers();
1626
- const r = e instanceof Worker ? e : windowEndpoint(e, t), s = wrap(r), n = proxyClone(s);
1627
- return new Proxy(n, {
926
+ function tt(e, t = void 0) {
927
+ oe();
928
+ const r = e instanceof Worker ? e : se(e, t), n = F(r), s = z(n);
929
+ return new Proxy(s, {
1628
930
  get: (o, i) => i === "isConnected" ? async () => {
1629
931
  for (; ; )
1630
932
  try {
1631
- await runWithTimeout(s.isConnected(), 200);
933
+ await _e(n.isConnected(), 200);
1632
934
  break;
1633
935
  } catch {
1634
936
  }
1635
- } : s[i]
937
+ } : n[i]
1636
938
  });
1637
939
  }
1638
- async function runWithTimeout(e, t) {
1639
- return new Promise((r, s) => {
1640
- setTimeout(s, t), e.then(r);
940
+ async function _e(e, t) {
941
+ return new Promise((r, n) => {
942
+ setTimeout(n, t), e.then(r);
1641
943
  });
1642
944
  }
1643
- function exposeAPI(e, t) {
1644
- setupTransferHandlers();
945
+ function rt(e, t) {
946
+ oe();
1645
947
  const r = Promise.resolve();
1646
- let s, n;
1647
- const o = new Promise((l, c) => {
1648
- s = l, n = c;
1649
- }), i = proxyClone(e), a = new Proxy(i, {
1650
- get: (l, c) => c === "isConnected" ? () => r : c === "isReady" ? () => o : c in l ? l[c] : t == null ? void 0 : t[c]
948
+ let n, s;
949
+ const o = new Promise((u, l) => {
950
+ n = u, s = l;
951
+ }), i = z(e), a = new Proxy(i, {
952
+ get: (u, l) => l === "isConnected" ? () => r : l === "isReady" ? () => o : l in u ? u[l] : t == null ? void 0 : t[l]
1651
953
  });
1652
- return expose(
954
+ return M(
1653
955
  a,
1654
- typeof window < "u" ? windowEndpoint(self.parent) : void 0
1655
- ), [s, n, a];
956
+ typeof window < "u" ? se(self.parent) : void 0
957
+ ), [n, s, a];
1656
958
  }
1657
- let isTransferHandlersSetup = !1;
1658
- function setupTransferHandlers() {
1659
- if (isTransferHandlersSetup)
959
+ let J = !1;
960
+ function oe() {
961
+ if (J)
1660
962
  return;
1661
- isTransferHandlersSetup = !0, transferHandlers.set("EVENT", {
963
+ J = !0, k.set("EVENT", {
1662
964
  canHandle: (r) => r instanceof CustomEvent,
1663
965
  serialize: (r) => [
1664
966
  {
@@ -1667,49 +969,49 @@ function setupTransferHandlers() {
1667
969
  []
1668
970
  ],
1669
971
  deserialize: (r) => r
1670
- }), transferHandlers.set("FUNCTION", {
972
+ }), k.set("FUNCTION", {
1671
973
  canHandle: (r) => typeof r == "function",
1672
974
  serialize(r) {
1673
- const { port1: s, port2: n } = new MessageChannel();
1674
- return expose(r, s), [n, [n]];
975
+ const { port1: n, port2: s } = new MessageChannel();
976
+ return M(r, n), [s, [s]];
1675
977
  },
1676
978
  deserialize(r) {
1677
- return r.start(), wrap(r);
979
+ return r.start(), F(r);
1678
980
  }
1679
- }), transferHandlers.set("PHPResponse", {
981
+ }), k.set("PHPResponse", {
1680
982
  canHandle: (r) => typeof r == "object" && r !== null && "headers" in r && "bytes" in r && "errors" in r && "exitCode" in r && "httpStatusCode" in r,
1681
983
  serialize(r) {
1682
984
  return [r.toRawData(), []];
1683
985
  },
1684
986
  deserialize(r) {
1685
- return PHPResponse.fromRawData(r);
987
+ return O.fromRawData(r);
1686
988
  }
1687
989
  });
1688
- const e = transferHandlers.get("throw"), t = e == null ? void 0 : e.serialize;
990
+ const e = k.get("throw"), t = e == null ? void 0 : e.serialize;
1689
991
  e.serialize = ({ value: r }) => {
1690
- const s = t({ value: r });
1691
- return r.response && (s[0].value.response = r.response), r.source && (s[0].value.source = r.source), s;
992
+ const n = t({ value: r });
993
+ return r.response && (n[0].value.response = r.response), r.source && (n[0].value.source = r.source), n;
1692
994
  };
1693
995
  }
1694
- function proxyClone(e) {
996
+ function z(e) {
1695
997
  return new Proxy(e, {
1696
998
  get(t, r) {
1697
999
  switch (typeof t[r]) {
1698
1000
  case "function":
1699
- return (...s) => t[r](...s);
1001
+ return (...n) => t[r](...n);
1700
1002
  case "object":
1701
- return t[r] === null ? t[r] : proxyClone(t[r]);
1003
+ return t[r] === null ? t[r] : z(t[r]);
1702
1004
  case "undefined":
1703
1005
  case "number":
1704
1006
  case "string":
1705
1007
  return t[r];
1706
1008
  default:
1707
- return proxy(t[r]);
1009
+ return ne(t[r]);
1708
1010
  }
1709
1011
  }
1710
1012
  });
1711
1013
  }
1712
- async function getPHPLoaderModule(e = LatestSupportedPHPVersion, t = "light") {
1014
+ async function qe(e = Ae, t = "light") {
1713
1015
  if (t === "kitchen-sink")
1714
1016
  switch (e) {
1715
1017
  case "8.3":
@@ -1754,7 +1056,7 @@ async function getPHPLoaderModule(e = LatestSupportedPHPVersion, t = "light") {
1754
1056
  }
1755
1057
  throw new Error(`Unsupported PHP version ${e}`);
1756
1058
  }
1757
- const fakeWebsocket = () => ({
1059
+ const Je = () => ({
1758
1060
  websocket: {
1759
1061
  decorator: (e) => class extends e {
1760
1062
  constructor() {
@@ -1769,169 +1071,30 @@ const fakeWebsocket = () => ({
1769
1071
  }
1770
1072
  }
1771
1073
  });
1772
- class WebPHP extends BasePHP {
1773
- /**
1774
- * Creates a new PHP instance.
1775
- *
1776
- * Dynamically imports the PHP module, initializes the runtime,
1777
- * and sets up networking. It's a shorthand for the lower-level
1778
- * functions like `getPHPLoaderModule`, `loadPHPRuntime`, and
1779
- * `PHP.initializeRuntime`
1780
- *
1781
- * @param phpVersion The PHP Version to load
1782
- * @param options The options to use when loading PHP
1783
- * @returns A new PHP instance
1784
- */
1785
- static async load(t, r = {}) {
1786
- return new WebPHP(await WebPHP.loadRuntime(t, r));
1787
- }
1788
- static async loadRuntime(t, r = {}) {
1789
- var o;
1790
- const s = r.loadAllExtensions ? "kitchen-sink" : "light", n = await getPHPLoaderModule(t, s);
1791
- return (o = r.onPhpLoaderModuleLoaded) == null || o.call(r, n), await loadPHPRuntime(n, {
1792
- ...r.emscriptenOptions || {},
1793
- ...fakeWebsocket()
1794
- });
1795
- }
1796
- }
1797
- const _private = /* @__PURE__ */ new WeakMap();
1798
- class WebPHPEndpoint {
1799
- /** @inheritDoc */
1800
- constructor(t, r) {
1801
- _private.set(this, {
1802
- monitor: r,
1803
- requestHandler: t
1804
- }), this.absoluteUrl = t.absoluteUrl, this.documentRoot = t.documentRoot;
1805
- }
1806
- /**
1807
- * @internal
1808
- * @deprecated
1809
- * Do not use this method directly in the code consuming
1810
- * the web API. It will change or even be removed without
1811
- * a warning.
1812
- */
1813
- __internal_getPHP() {
1814
- return _private.get(this).php;
1815
- }
1816
- async setPrimaryPHP(t) {
1817
- _private.set(this, {
1818
- ..._private.get(this),
1819
- php: t
1820
- });
1821
- }
1822
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.pathToInternalUrl */
1823
- pathToInternalUrl(t) {
1824
- return _private.get(this).requestHandler.pathToInternalUrl(t);
1825
- }
1826
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.internalUrlToPath */
1827
- internalUrlToPath(t) {
1828
- return _private.get(this).requestHandler.internalUrlToPath(t);
1829
- }
1830
- /**
1831
- * The onDownloadProgress event listener.
1832
- */
1833
- async onDownloadProgress(t) {
1834
- var r;
1835
- return (r = _private.get(this).monitor) == null ? void 0 : r.addEventListener("progress", t);
1836
- }
1837
- /** @inheritDoc @php-wasm/universal!IsomorphicLocalPHP.mv */
1838
- async mv(t, r) {
1839
- return _private.get(this).php.mv(t, r);
1840
- }
1841
- /** @inheritDoc @php-wasm/universal!IsomorphicLocalPHP.rmdir */
1842
- async rmdir(t, r) {
1843
- return _private.get(this).php.rmdir(t, r);
1844
- }
1845
- /** @inheritDoc @php-wasm/universal!PHPRequestHandler.request */
1846
- async request(t) {
1847
- return await _private.get(this).requestHandler.request(t);
1848
- }
1849
- /** @inheritDoc @php-wasm/web!WebPHP.run */
1850
- async run(t) {
1851
- const { php: r, reap: s } = await _private.get(this).requestHandler.processManager.acquirePHPInstance();
1852
- try {
1853
- return await r.run(t);
1854
- } finally {
1855
- s();
1856
- }
1857
- }
1858
- /** @inheritDoc @php-wasm/web!WebPHP.chdir */
1859
- chdir(t) {
1860
- return _private.get(this).php.chdir(t);
1861
- }
1862
- /** @inheritDoc @php-wasm/web!WebPHP.setSapiName */
1863
- setSapiName(t) {
1864
- _private.get(this).php.setSapiName(t);
1865
- }
1866
- /** @inheritDoc @php-wasm/web!WebPHP.mkdir */
1867
- mkdir(t) {
1868
- return _private.get(this).php.mkdir(t);
1869
- }
1870
- /** @inheritDoc @php-wasm/web!WebPHP.mkdirTree */
1871
- mkdirTree(t) {
1872
- return _private.get(this).php.mkdirTree(t);
1873
- }
1874
- /** @inheritDoc @php-wasm/web!WebPHP.readFileAsText */
1875
- readFileAsText(t) {
1876
- return _private.get(this).php.readFileAsText(t);
1877
- }
1878
- /** @inheritDoc @php-wasm/web!WebPHP.readFileAsBuffer */
1879
- readFileAsBuffer(t) {
1880
- return _private.get(this).php.readFileAsBuffer(t);
1881
- }
1882
- /** @inheritDoc @php-wasm/web!WebPHP.writeFile */
1883
- writeFile(t, r) {
1884
- return _private.get(this).php.writeFile(t, r);
1885
- }
1886
- /** @inheritDoc @php-wasm/web!WebPHP.unlink */
1887
- unlink(t) {
1888
- return _private.get(this).php.unlink(t);
1889
- }
1890
- /** @inheritDoc @php-wasm/web!WebPHP.listFiles */
1891
- listFiles(t, r) {
1892
- return _private.get(this).php.listFiles(t, r);
1893
- }
1894
- /** @inheritDoc @php-wasm/web!WebPHP.isDir */
1895
- isDir(t) {
1896
- return _private.get(this).php.isDir(t);
1897
- }
1898
- /** @inheritDoc @php-wasm/web!WebPHP.fileExists */
1899
- fileExists(t) {
1900
- return _private.get(this).php.fileExists(t);
1901
- }
1902
- /** @inheritDoc @php-wasm/web!WebPHP.onMessage */
1903
- onMessage(t) {
1904
- _private.get(this).php.onMessage(t);
1905
- }
1906
- /** @inheritDoc @php-wasm/web!WebPHP.defineConstant */
1907
- defineConstant(t, r) {
1908
- _private.get(this).php.defineConstant(t, r);
1909
- }
1910
- /** @inheritDoc @php-wasm/web!WebPHP.addEventListener */
1911
- addEventListener(t, r) {
1912
- _private.get(this).php.addEventListener(t, r);
1913
- }
1914
- /** @inheritDoc @php-wasm/web!WebPHP.removeEventListener */
1915
- removeEventListener(t, r) {
1916
- _private.get(this).php.removeEventListener(t, r);
1917
- }
1074
+ async function st(e, t = {}) {
1075
+ var s;
1076
+ const r = t.loadAllExtensions ? "kitchen-sink" : "light", n = await qe(e, r);
1077
+ return (s = t.onPhpLoaderModuleLoaded) == null || s.call(t, n), await xe(n, {
1078
+ ...t.emscriptenOptions || {},
1079
+ ...Je()
1080
+ });
1918
1081
  }
1919
- function responseTo(e, t) {
1082
+ function Ve(e, t) {
1920
1083
  return {
1921
1084
  type: "response",
1922
1085
  requestId: e,
1923
1086
  response: t
1924
1087
  };
1925
1088
  }
1926
- async function registerServiceWorker(e, t, r) {
1927
- const s = navigator.serviceWorker;
1928
- if (!s)
1929
- throw window.isSecureContext ? new PhpWasmError(
1089
+ async function ot(e, t, r) {
1090
+ const n = navigator.serviceWorker;
1091
+ if (!n)
1092
+ throw window.isSecureContext ? new j(
1930
1093
  "Service workers are not supported in your browser."
1931
- ) : new PhpWasmError(
1094
+ ) : new j(
1932
1095
  "WordPress Playground uses service workers and may only work on HTTPS and http://localhost/ sites, but the current site is neither."
1933
1096
  );
1934
- await (await s.register(r, {
1097
+ await (await n.register(r, {
1935
1098
  type: "module",
1936
1099
  // Always bypass HTTP cache when fetching the new Service Worker script:
1937
1100
  updateViaCache: "none"
@@ -1940,45 +1103,392 @@ async function registerServiceWorker(e, t, r) {
1940
1103
  async function(i) {
1941
1104
  if (t && i.data.scope !== t)
1942
1105
  return;
1943
- const a = i.data.args || [], l = i.data.method, c = await e[l](...a);
1944
- i.source.postMessage(responseTo(i.data.requestId, c));
1106
+ const a = i.data.args || [], u = i.data.method, l = await e[u](...a);
1107
+ i.source.postMessage(Ve(i.data.requestId, l));
1945
1108
  }
1946
- ), s.startMessages();
1109
+ ), n.startMessages();
1110
+ }
1111
+ function it(e, t) {
1112
+ window.addEventListener("message", (r) => {
1113
+ r.source === e.contentWindow && (t && r.origin !== t || typeof r.data != "object" || r.data.type !== "relay" || window.parent.postMessage(r.data, "*"));
1114
+ }), window.addEventListener("message", (r) => {
1115
+ var n;
1116
+ r.source === window.parent && (typeof r.data != "object" || r.data.type !== "relay" || (n = e == null ? void 0 : e.contentWindow) == null || n.postMessage(r.data));
1117
+ });
1947
1118
  }
1948
- async function spawnPHPWorkerThread(e, t = {}) {
1949
- e = addQueryParams(e, t);
1119
+ async function at(e, t = {}) {
1120
+ e = Ue(e, t);
1950
1121
  const r = new Worker(e, { type: "module" });
1951
- return new Promise((s, n) => {
1122
+ return new Promise((n, s) => {
1952
1123
  r.onerror = (i) => {
1953
1124
  const a = new Error(
1954
1125
  `WebWorker failed to load at ${e}. ${i.message ? `Original error: ${i.message}` : ""}`
1955
1126
  );
1956
- a.filename = i.filename, n(a);
1127
+ a.filename = i.filename, s(a);
1957
1128
  };
1958
1129
  function o(i) {
1959
- i.data === "worker-script-started" && (s(r), r.removeEventListener("message", o));
1130
+ i.data === "worker-script-started" && (n(r), r.removeEventListener("message", o));
1960
1131
  }
1961
1132
  r.addEventListener("message", o);
1962
1133
  });
1963
1134
  }
1964
- function addQueryParams(e, t) {
1135
+ function Ue(e, t) {
1965
1136
  if (!Object.entries(t).length)
1966
1137
  return e + "";
1967
1138
  const r = new URL(e);
1968
- for (const [s, n] of Object.entries(t))
1969
- if (Array.isArray(n))
1970
- for (const o of n)
1971
- r.searchParams.append(s, o);
1139
+ for (const [n, s] of Object.entries(t))
1140
+ if (Array.isArray(s))
1141
+ for (const o of s)
1142
+ r.searchParams.append(n, o);
1972
1143
  else
1973
- r.searchParams.set(s, n);
1144
+ r.searchParams.set(n, s);
1974
1145
  return r.toString();
1975
1146
  }
1147
+ function Ge(e, t, r = () => {
1148
+ }) {
1149
+ function n() {
1150
+ t = Ye(t);
1151
+ const o = e[w].FS, i = Ke(o, (c) => {
1152
+ if (c.path.startsWith(t))
1153
+ r(c);
1154
+ else if (c.operation === "RENAME" && c.toPath.startsWith(t))
1155
+ for (const d of ie(
1156
+ e,
1157
+ c.path,
1158
+ c.toPath
1159
+ ))
1160
+ r(d);
1161
+ }), a = {};
1162
+ for (const [c] of Object.entries(i))
1163
+ a[c] = o[c];
1164
+ function u() {
1165
+ for (const [c, d] of Object.entries(i))
1166
+ o[c] = function(...f) {
1167
+ return d(...f), a[c].apply(this, f);
1168
+ };
1169
+ }
1170
+ function l() {
1171
+ for (const [c, d] of Object.entries(a))
1172
+ e[w].FS[c] = d;
1173
+ }
1174
+ e[w].journal = {
1175
+ bind: u,
1176
+ unbind: l
1177
+ }, u();
1178
+ }
1179
+ e.addEventListener("runtime.initialized", n), e[w] && n();
1180
+ function s() {
1181
+ e[w].journal.unbind(), delete e[w].journal;
1182
+ }
1183
+ return e.addEventListener("runtime.beforedestroy", s), function() {
1184
+ return e.removeEventListener("runtime.initialized", n), e.removeEventListener("runtime.beforedestroy", s), e[w].journal.unbind();
1185
+ };
1186
+ }
1187
+ const Ke = (e, t = () => {
1188
+ }) => ({
1189
+ write(r) {
1190
+ t({
1191
+ operation: "WRITE",
1192
+ path: r.path,
1193
+ nodeType: "file"
1194
+ });
1195
+ },
1196
+ truncate(r) {
1197
+ let n;
1198
+ typeof r == "string" ? n = e.lookupPath(r, {
1199
+ follow: !0
1200
+ }).node : n = r, t({
1201
+ operation: "WRITE",
1202
+ path: e.getPath(n),
1203
+ nodeType: "file"
1204
+ });
1205
+ },
1206
+ unlink(r) {
1207
+ t({
1208
+ operation: "DELETE",
1209
+ path: r,
1210
+ nodeType: "file"
1211
+ });
1212
+ },
1213
+ mknod(r, n) {
1214
+ e.isFile(n) && t({
1215
+ operation: "CREATE",
1216
+ path: r,
1217
+ nodeType: "file"
1218
+ });
1219
+ },
1220
+ mkdir(r) {
1221
+ t({
1222
+ operation: "CREATE",
1223
+ path: r,
1224
+ nodeType: "directory"
1225
+ });
1226
+ },
1227
+ rmdir(r) {
1228
+ t({
1229
+ operation: "DELETE",
1230
+ path: r,
1231
+ nodeType: "directory"
1232
+ });
1233
+ },
1234
+ rename(r, n) {
1235
+ try {
1236
+ const s = e.lookupPath(r, {
1237
+ follow: !0
1238
+ }), o = e.lookupPath(n, {
1239
+ parent: !0
1240
+ }).path;
1241
+ t({
1242
+ operation: "RENAME",
1243
+ nodeType: e.isDir(s.node.mode) ? "directory" : "file",
1244
+ path: s.path,
1245
+ toPath: b(o, Ee(n))
1246
+ });
1247
+ } catch {
1248
+ }
1249
+ }
1250
+ });
1251
+ function* ie(e, t, r) {
1252
+ if (e.isDir(t)) {
1253
+ yield {
1254
+ operation: "CREATE",
1255
+ path: r,
1256
+ nodeType: "directory"
1257
+ };
1258
+ for (const n of e.listFiles(t))
1259
+ yield* ie(
1260
+ e,
1261
+ b(t, n),
1262
+ b(r, n)
1263
+ );
1264
+ } else
1265
+ yield {
1266
+ operation: "CREATE",
1267
+ path: r,
1268
+ nodeType: "file"
1269
+ }, yield {
1270
+ operation: "WRITE",
1271
+ nodeType: "file",
1272
+ path: r
1273
+ };
1274
+ }
1275
+ function Ye(e) {
1276
+ return e.replace(/\/$/, "").replace(/\/\/+/g, "/");
1277
+ }
1278
+ function ct(e, t = { initialSync: {} }) {
1279
+ return t = {
1280
+ ...t,
1281
+ initialSync: {
1282
+ ...t.initialSync,
1283
+ direction: t.initialSync.direction ?? "opfs-to-memfs"
1284
+ }
1285
+ }, async function(r, n, s) {
1286
+ return t.initialSync.direction === "opfs-to-memfs" ? (R.fileExists(n, s) && R.rmdir(n, s), R.mkdir(n, s), await Ze(n, e, s)) : await ae(
1287
+ n,
1288
+ e,
1289
+ s,
1290
+ t.initialSync.onProgress
1291
+ ), Xe(r, e, s);
1292
+ };
1293
+ }
1294
+ async function Ze(e, t, r) {
1295
+ R.mkdir(e, r);
1296
+ const n = new ge({
1297
+ concurrency: 40
1298
+ }), s = [], o = [
1299
+ [t, r]
1300
+ ];
1301
+ for (; o.length > 0; ) {
1302
+ const [i, a] = o.pop();
1303
+ for await (const u of i.values()) {
1304
+ const l = n.run(async () => {
1305
+ const c = b(
1306
+ a,
1307
+ u.name
1308
+ );
1309
+ if (u.kind === "directory") {
1310
+ try {
1311
+ e.mkdir(c);
1312
+ } catch (d) {
1313
+ if ((d == null ? void 0 : d.errno) !== 20)
1314
+ throw v.error(d), d;
1315
+ }
1316
+ o.push([u, c]);
1317
+ } else if (u.kind === "file") {
1318
+ const d = await u.getFile(), f = new Uint8Array(await d.arrayBuffer());
1319
+ e.createDataFile(
1320
+ a,
1321
+ u.name,
1322
+ f,
1323
+ !0,
1324
+ !0,
1325
+ !0
1326
+ );
1327
+ }
1328
+ s.splice(s.indexOf(l), 1);
1329
+ });
1330
+ s.push(l);
1331
+ }
1332
+ for (; o.length === 0 && s.length > 0; )
1333
+ await Promise.any(s);
1334
+ }
1335
+ }
1336
+ async function ae(e, t, r, n) {
1337
+ e.mkdirTree(r);
1338
+ const s = [];
1339
+ async function o(u, l) {
1340
+ await Promise.all(
1341
+ e.readdir(u).filter(
1342
+ (c) => c !== "." && c !== ".."
1343
+ ).map(async (c) => {
1344
+ const d = b(u, c);
1345
+ if (!Qe(e, d)) {
1346
+ s.push([l, d, c]);
1347
+ return;
1348
+ }
1349
+ const f = await l.getDirectoryHandle(c, {
1350
+ create: !0
1351
+ });
1352
+ return await o(d, f);
1353
+ })
1354
+ );
1355
+ }
1356
+ await o(r, t);
1357
+ let i = 0;
1358
+ const a = s.map(
1359
+ ([u, l, c]) => ce(u, c, e, l).then(() => {
1360
+ n == null || n({ files: ++i, total: s.length });
1361
+ })
1362
+ );
1363
+ await Promise.all(a);
1364
+ }
1365
+ function Qe(e, t) {
1366
+ return e.isDir(e.lookupPath(t, { follow: !0 }).node.mode);
1367
+ }
1368
+ async function ce(e, t, r, n) {
1369
+ let s;
1370
+ try {
1371
+ s = r.readFile(n, {
1372
+ encoding: "binary"
1373
+ });
1374
+ } catch {
1375
+ return;
1376
+ }
1377
+ const o = await e.getFileHandle(t, { create: !0 }), i = o.createWritable !== void 0 ? (
1378
+ // Google Chrome, Firefox, probably more browsers
1379
+ await o.createWritable()
1380
+ ) : (
1381
+ // Safari
1382
+ await o.createSyncAccessHandle()
1383
+ );
1384
+ try {
1385
+ await i.truncate(0), await i.write(s);
1386
+ } finally {
1387
+ await i.close();
1388
+ }
1389
+ }
1390
+ function Xe(e, t, r) {
1391
+ const n = [], s = Ge(e, r, (a) => {
1392
+ n.push(a);
1393
+ }), o = new et(e, t, r);
1394
+ async function i() {
1395
+ const a = await e.semaphore.acquire();
1396
+ try {
1397
+ for (; n.length; )
1398
+ await o.processEntry(n.shift());
1399
+ } finally {
1400
+ a();
1401
+ }
1402
+ }
1403
+ return e.addEventListener("request.end", i), function() {
1404
+ s(), e.removeEventListener("request.end", i);
1405
+ };
1406
+ }
1407
+ class et {
1408
+ constructor(t, r, n) {
1409
+ this.php = t, this.opfs = r, this.memfsRoot = V(n);
1410
+ }
1411
+ toOpfsPath(t) {
1412
+ return V(t.substring(this.memfsRoot.length));
1413
+ }
1414
+ async processEntry(t) {
1415
+ if (!t.path.startsWith(this.memfsRoot) || t.path === this.memfsRoot)
1416
+ return;
1417
+ const r = this.toOpfsPath(t.path), n = await G(this.opfs, r), s = U(r);
1418
+ if (s)
1419
+ try {
1420
+ if (t.operation === "DELETE")
1421
+ try {
1422
+ await n.removeEntry(s, {
1423
+ recursive: !0
1424
+ });
1425
+ } catch {
1426
+ }
1427
+ else if (t.operation === "CREATE")
1428
+ t.nodeType === "directory" ? await n.getDirectoryHandle(s, {
1429
+ create: !0
1430
+ }) : await n.getFileHandle(s, {
1431
+ create: !0
1432
+ });
1433
+ else if (t.operation === "WRITE")
1434
+ await ce(
1435
+ n,
1436
+ s,
1437
+ this.php[w].FS,
1438
+ t.path
1439
+ );
1440
+ else if (t.operation === "RENAME" && t.toPath.startsWith(this.memfsRoot)) {
1441
+ const o = this.toOpfsPath(t.toPath), i = await G(
1442
+ this.opfs,
1443
+ o
1444
+ ), a = U(o);
1445
+ if (t.nodeType === "directory") {
1446
+ const u = await i.getDirectoryHandle(
1447
+ s,
1448
+ {
1449
+ create: !0
1450
+ }
1451
+ );
1452
+ await ae(
1453
+ this.php[w].FS,
1454
+ u,
1455
+ t.toPath
1456
+ ), await n.removeEntry(s, {
1457
+ recursive: !0
1458
+ });
1459
+ } else
1460
+ (await n.getFileHandle(s)).move(i, a);
1461
+ }
1462
+ } catch (o) {
1463
+ throw v.log({ entry: t, name: s }), v.error(o), o;
1464
+ }
1465
+ }
1466
+ }
1467
+ function V(e) {
1468
+ return e.replace(/\/$/, "").replace(/\/\/+/g, "/");
1469
+ }
1470
+ function U(e) {
1471
+ return e.substring(e.lastIndexOf("/") + 1);
1472
+ }
1473
+ async function G(e, t) {
1474
+ const r = t.replace(/^\/+|\/+$/g, "").replace(/\/+/, "/");
1475
+ if (!r)
1476
+ return e;
1477
+ const n = r.split("/");
1478
+ let s = e;
1479
+ for (let o = 0; o < n.length - 1; o++) {
1480
+ const i = n[o];
1481
+ s = await s.getDirectoryHandle(i, { create: !0 });
1482
+ }
1483
+ return s;
1484
+ }
1976
1485
  export {
1977
- WebPHP,
1978
- WebPHPEndpoint,
1979
- consumeAPI,
1980
- exposeAPI,
1981
- getPHPLoaderModule,
1982
- registerServiceWorker,
1983
- spawnPHPWorkerThread
1486
+ tt as consumeAPI,
1487
+ ct as createDirectoryHandleMountHandler,
1488
+ rt as exposeAPI,
1489
+ qe as getPHPLoaderModule,
1490
+ st as loadWebRuntime,
1491
+ ot as registerServiceWorker,
1492
+ it as setupPostMessageRelay,
1493
+ at as spawnPHPWorkerThread
1984
1494
  };