@php-wasm/web 0.1.9 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1323 @@
1
+ const W = [
2
+ "8.2",
3
+ "8.1",
4
+ "8.0",
5
+ "7.4",
6
+ "7.3",
7
+ "7.2",
8
+ "7.1",
9
+ "7.0",
10
+ "5.6"
11
+ ], Y = W[0], ve = W;
12
+ class K {
13
+ #e;
14
+ #t;
15
+ /**
16
+ * @param server - The PHP server to browse.
17
+ * @param config - The browser configuration.
18
+ */
19
+ constructor(e, r = {}) {
20
+ this.server = e, this.#e = {}, this.#t = {
21
+ handleRedirects: !1,
22
+ maxRedirects: 4,
23
+ ...r
24
+ };
25
+ }
26
+ /**
27
+ * Sends the request to the server.
28
+ *
29
+ * When cookies are present in the response, this method stores
30
+ * them and sends them with any subsequent requests.
31
+ *
32
+ * When a redirection is present in the response, this method
33
+ * follows it by discarding a response and sending a subsequent
34
+ * request.
35
+ *
36
+ * @param request - The request.
37
+ * @param redirects - Internal. The number of redirects handled so far.
38
+ * @returns PHPRequestHandler response.
39
+ */
40
+ async request(e, r = 0) {
41
+ const n = await this.server.request({
42
+ ...e,
43
+ headers: {
44
+ ...e.headers,
45
+ cookie: this.#s()
46
+ }
47
+ });
48
+ if (n.headers["set-cookie"] && this.#r(n.headers["set-cookie"]), this.#t.handleRedirects && n.headers.location && r < this.#t.maxRedirects) {
49
+ const s = new URL(
50
+ n.headers.location[0],
51
+ this.server.absoluteUrl
52
+ );
53
+ return this.request(
54
+ {
55
+ url: s.toString(),
56
+ method: "GET",
57
+ headers: {}
58
+ },
59
+ r + 1
60
+ );
61
+ }
62
+ return n;
63
+ }
64
+ #r(e) {
65
+ for (const r of e)
66
+ try {
67
+ if (!r.includes("="))
68
+ continue;
69
+ const n = r.indexOf("="), s = r.substring(0, n), a = r.substring(n + 1).split(";")[0];
70
+ this.#e[s] = a;
71
+ } catch (n) {
72
+ console.error(n);
73
+ }
74
+ }
75
+ #s() {
76
+ const e = [];
77
+ for (const r in this.#e)
78
+ e.push(`${r}=${this.#e[r]}`);
79
+ return e.join("; ");
80
+ }
81
+ }
82
+ const Q = "http://example.com";
83
+ function N(t) {
84
+ return t.toString().substring(t.origin.length);
85
+ }
86
+ function M(t, e) {
87
+ return !e || !t.startsWith(e) ? t : t.substring(e.length);
88
+ }
89
+ function X(t, e) {
90
+ return !e || t.startsWith(e) ? t : e + t;
91
+ }
92
+ class Z {
93
+ constructor({ concurrency: e }) {
94
+ this._running = 0, this.concurrency = e, this.queue = [];
95
+ }
96
+ get running() {
97
+ return this._running;
98
+ }
99
+ async acquire() {
100
+ for (; ; )
101
+ if (this._running >= this.concurrency)
102
+ await new Promise((e) => this.queue.push(e));
103
+ else
104
+ return this._running++, () => {
105
+ this._running--, this.queue.length > 0 && this.queue.shift()();
106
+ };
107
+ }
108
+ }
109
+ class O {
110
+ constructor(e, r, n, s = "", a = 0) {
111
+ this.httpStatusCode = e, this.headers = r, this.body = n, this.exitCode = a, this.errors = s;
112
+ }
113
+ /**
114
+ * Response body as JSON.
115
+ */
116
+ get json() {
117
+ return JSON.parse(this.text);
118
+ }
119
+ /**
120
+ * Response body as text.
121
+ */
122
+ get text() {
123
+ return new TextDecoder().decode(this.body);
124
+ }
125
+ /**
126
+ * Response body as bytes.
127
+ */
128
+ get bytes() {
129
+ return this.body;
130
+ }
131
+ }
132
+ class ee {
133
+ #e;
134
+ #t;
135
+ #r;
136
+ #s;
137
+ #i;
138
+ #n;
139
+ #o;
140
+ #a;
141
+ #c;
142
+ /**
143
+ * @param php - The PHP instance.
144
+ * @param config - Request Handler configuration.
145
+ */
146
+ constructor(e, r = {}) {
147
+ this.#a = new Z({ concurrency: 1 });
148
+ const {
149
+ documentRoot: n = "/www/",
150
+ absoluteUrl: s = location.origin,
151
+ isStaticFilePath: a = () => !1
152
+ } = r;
153
+ this.php = e, this.#e = n, this.#c = a;
154
+ const i = new URL(s);
155
+ this.#r = i.hostname, this.#s = i.port ? Number(i.port) : i.protocol === "https:" ? 443 : 80, this.#t = (i.protocol || "").replace(":", "");
156
+ const o = this.#s !== 443 && this.#s !== 80;
157
+ this.#i = [
158
+ this.#r,
159
+ o ? `:${this.#s}` : ""
160
+ ].join(""), this.#n = i.pathname.replace(/\/+$/, ""), this.#o = [
161
+ `${this.#t}://`,
162
+ this.#i,
163
+ this.#n
164
+ ].join("");
165
+ }
166
+ /**
167
+ * Converts a path to an absolute URL based at the PHPRequestHandler
168
+ * root.
169
+ *
170
+ * @param path The server path to convert to an absolute URL.
171
+ * @returns The absolute URL.
172
+ */
173
+ pathToInternalUrl(e) {
174
+ return `${this.absoluteUrl}${e}`;
175
+ }
176
+ /**
177
+ * Converts an absolute URL based at the PHPRequestHandler to a relative path
178
+ * without the server pathname and scope.
179
+ *
180
+ * @param internalUrl An absolute URL based at the PHPRequestHandler root.
181
+ * @returns The relative path.
182
+ */
183
+ internalUrlToPath(e) {
184
+ const r = new URL(e);
185
+ return r.pathname.startsWith(this.#n) && (r.pathname = r.pathname.slice(this.#n.length)), N(r);
186
+ }
187
+ get isRequestRunning() {
188
+ return this.#a.running > 0;
189
+ }
190
+ /**
191
+ * The absolute URL of this PHPRequestHandler instance.
192
+ */
193
+ get absoluteUrl() {
194
+ return this.#o;
195
+ }
196
+ /**
197
+ * The absolute URL of this PHPRequestHandler instance.
198
+ */
199
+ get documentRoot() {
200
+ return this.#e;
201
+ }
202
+ /**
203
+ * Serves the request – either by serving a static file, or by
204
+ * dispatching it to the PHP runtime.
205
+ *
206
+ * @param request - The request.
207
+ * @returns The response.
208
+ */
209
+ async request(e) {
210
+ const r = e.url.startsWith("http://") || e.url.startsWith("https://"), n = new URL(
211
+ e.url,
212
+ r ? void 0 : Q
213
+ ), s = M(
214
+ n.pathname,
215
+ this.#n
216
+ );
217
+ return this.#c(s) ? this.#l(s) : await this.#u(e, n);
218
+ }
219
+ /**
220
+ * Serves a static file from the PHP filesystem.
221
+ *
222
+ * @param path - The requested static file path.
223
+ * @returns The response.
224
+ */
225
+ #l(e) {
226
+ const r = `${this.#e}${e}`;
227
+ if (!this.php.fileExists(r))
228
+ return new O(
229
+ 404,
230
+ {},
231
+ new TextEncoder().encode("404 File not found")
232
+ );
233
+ const n = this.php.readFileAsBuffer(r);
234
+ return new O(
235
+ 200,
236
+ {
237
+ "content-length": [`${n.byteLength}`],
238
+ // @TODO: Infer the content-type from the arrayBuffer instead of the file path.
239
+ // The code below won't return the correct mime-type if the extension
240
+ // was tampered with.
241
+ "content-type": [te(r)],
242
+ "accept-ranges": ["bytes"],
243
+ "cache-control": ["public, max-age=0"]
244
+ },
245
+ n
246
+ );
247
+ }
248
+ /**
249
+ * Runs the requested PHP file with all the request and $_SERVER
250
+ * superglobals populated.
251
+ *
252
+ * @param request - The request.
253
+ * @returns The response.
254
+ */
255
+ async #u(e, r) {
256
+ const n = await this.#a.acquire();
257
+ try {
258
+ this.php.addServerGlobalEntry("DOCUMENT_ROOT", this.#e), this.php.addServerGlobalEntry(
259
+ "HTTPS",
260
+ this.#o.startsWith("https://") ? "on" : ""
261
+ );
262
+ let s = "GET";
263
+ const a = [];
264
+ if (e.files) {
265
+ s = "POST";
266
+ for (const c in e.files) {
267
+ const l = e.files[c];
268
+ a.push({
269
+ key: c,
270
+ name: l.name,
271
+ type: l.type,
272
+ data: new Uint8Array(await l.arrayBuffer())
273
+ });
274
+ }
275
+ }
276
+ const i = {
277
+ host: this.#i
278
+ };
279
+ let o;
280
+ return e.formData !== void 0 ? (s = "POST", i["content-type"] = "application/x-www-form-urlencoded", o = new URLSearchParams(
281
+ e.formData
282
+ ).toString()) : o = e.body, await this.php.run({
283
+ relativeUri: X(
284
+ N(r),
285
+ this.#n
286
+ ),
287
+ protocol: this.#t,
288
+ method: e.method || s,
289
+ body: o,
290
+ fileInfos: a,
291
+ scriptPath: this.#h(r.pathname),
292
+ headers: {
293
+ ...i,
294
+ ...e.headers || {}
295
+ }
296
+ });
297
+ } finally {
298
+ n();
299
+ }
300
+ }
301
+ /**
302
+ * Resolve the requested path to the filesystem path of the requested PHP file.
303
+ *
304
+ * Fall back to index.php as if there was a url rewriting rule in place.
305
+ *
306
+ * @param requestedPath - The requested pathname.
307
+ * @returns The resolved filesystem path.
308
+ */
309
+ #h(e) {
310
+ let r = M(e, this.#n);
311
+ r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
312
+ const n = `${this.#e}${r}`;
313
+ return this.php.fileExists(n) ? n : `${this.#e}/index.php`;
314
+ }
315
+ }
316
+ function te(t) {
317
+ switch (t.split(".").pop()) {
318
+ case "css":
319
+ return "text/css";
320
+ case "js":
321
+ return "application/javascript";
322
+ case "png":
323
+ return "image/png";
324
+ case "jpg":
325
+ case "jpeg":
326
+ return "image/jpeg";
327
+ case "gif":
328
+ return "image/gif";
329
+ case "svg":
330
+ return "image/svg+xml";
331
+ case "woff":
332
+ return "font/woff";
333
+ case "woff2":
334
+ return "font/woff2";
335
+ case "ttf":
336
+ return "font/ttf";
337
+ case "otf":
338
+ return "font/otf";
339
+ case "eot":
340
+ return "font/eot";
341
+ case "ico":
342
+ return "image/x-icon";
343
+ case "html":
344
+ return "text/html";
345
+ case "json":
346
+ return "application/json";
347
+ case "xml":
348
+ return "application/xml";
349
+ case "txt":
350
+ case "md":
351
+ return "text/plain";
352
+ default:
353
+ return "application-octet-stream";
354
+ }
355
+ }
356
+ const I = {
357
+ 0: "No error occurred. System call completed successfully.",
358
+ 1: "Argument list too long.",
359
+ 2: "Permission denied.",
360
+ 3: "Address in use.",
361
+ 4: "Address not available.",
362
+ 5: "Address family not supported.",
363
+ 6: "Resource unavailable, or operation would block.",
364
+ 7: "Connection already in progress.",
365
+ 8: "Bad file descriptor.",
366
+ 9: "Bad message.",
367
+ 10: "Device or resource busy.",
368
+ 11: "Operation canceled.",
369
+ 12: "No child processes.",
370
+ 13: "Connection aborted.",
371
+ 14: "Connection refused.",
372
+ 15: "Connection reset.",
373
+ 16: "Resource deadlock would occur.",
374
+ 17: "Destination address required.",
375
+ 18: "Mathematics argument out of domain of function.",
376
+ 19: "Reserved.",
377
+ 20: "File exists.",
378
+ 21: "Bad address.",
379
+ 22: "File too large.",
380
+ 23: "Host is unreachable.",
381
+ 24: "Identifier removed.",
382
+ 25: "Illegal byte sequence.",
383
+ 26: "Operation in progress.",
384
+ 27: "Interrupted function.",
385
+ 28: "Invalid argument.",
386
+ 29: "I/O error.",
387
+ 30: "Socket is connected.",
388
+ 31: "There is a directory under that path.",
389
+ 32: "Too many levels of symbolic links.",
390
+ 33: "File descriptor value too large.",
391
+ 34: "Too many links.",
392
+ 35: "Message too large.",
393
+ 36: "Reserved.",
394
+ 37: "Filename too long.",
395
+ 38: "Network is down.",
396
+ 39: "Connection aborted by network.",
397
+ 40: "Network unreachable.",
398
+ 41: "Too many files open in system.",
399
+ 42: "No buffer space available.",
400
+ 43: "No such device.",
401
+ 44: "There is no such file or directory OR the parent directory does not exist.",
402
+ 45: "Executable file format error.",
403
+ 46: "No locks available.",
404
+ 47: "Reserved.",
405
+ 48: "Not enough space.",
406
+ 49: "No message of the desired type.",
407
+ 50: "Protocol not available.",
408
+ 51: "No space left on device.",
409
+ 52: "Function not supported.",
410
+ 53: "The socket is not connected.",
411
+ 54: "Not a directory or a symbolic link to a directory.",
412
+ 55: "Directory not empty.",
413
+ 56: "State not recoverable.",
414
+ 57: "Not a socket.",
415
+ 58: "Not supported, or operation not supported on socket.",
416
+ 59: "Inappropriate I/O control operation.",
417
+ 60: "No such device or address.",
418
+ 61: "Value too large to be stored in data type.",
419
+ 62: "Previous owner died.",
420
+ 63: "Operation not permitted.",
421
+ 64: "Broken pipe.",
422
+ 65: "Protocol error.",
423
+ 66: "Protocol not supported.",
424
+ 67: "Protocol wrong type for socket.",
425
+ 68: "Result too large.",
426
+ 69: "Read-only file system.",
427
+ 70: "Invalid seek.",
428
+ 71: "No such process.",
429
+ 72: "Reserved.",
430
+ 73: "Connection timed out.",
431
+ 74: "Text file busy.",
432
+ 75: "Cross-device link.",
433
+ 76: "Extension: Capabilities insufficient."
434
+ };
435
+ function g(t = "") {
436
+ return function(r, n, s) {
437
+ const a = s.value;
438
+ s.value = function(...i) {
439
+ try {
440
+ return a.apply(this, i);
441
+ } catch (o) {
442
+ const c = typeof o == "object" ? o?.errno : null;
443
+ if (c in I) {
444
+ const l = I[c], u = typeof i[0] == "string" ? i[0] : null, p = u !== null ? t.replaceAll("{path}", u) : t;
445
+ throw new Error(`${p}: ${l}`, {
446
+ cause: o
447
+ });
448
+ }
449
+ throw o;
450
+ }
451
+ };
452
+ };
453
+ }
454
+ var re = Object.defineProperty, ne = Object.getOwnPropertyDescriptor, y = (t, e, r, n) => {
455
+ for (var s = n > 1 ? void 0 : n ? ne(e, r) : e, a = t.length - 1, i; a >= 0; a--)
456
+ (i = t[a]) && (s = (n ? i(e, r, s) : i(s)) || s);
457
+ return n && s && re(e, r, s), s;
458
+ };
459
+ const h = "string", w = "number", S = [], se = function() {
460
+ return typeof window < "u" && !{}.TEST ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
461
+ }();
462
+ class m {
463
+ /**
464
+ * Initializes a PHP runtime.
465
+ *
466
+ * @internal
467
+ * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
468
+ * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
469
+ */
470
+ constructor(e, r) {
471
+ this.#t = [], this.#r = !1, e !== void 0 && this.initializeRuntime(e), r && (this.requestHandler = new K(
472
+ new ee(this, r)
473
+ ));
474
+ }
475
+ #e;
476
+ #t;
477
+ #r;
478
+ initializeRuntime(e) {
479
+ if (this.#e)
480
+ throw new Error("PHP runtime already initialized.");
481
+ if (!S[e])
482
+ throw new Error("Invalid PHP runtime id.");
483
+ this.#e = S[e];
484
+ }
485
+ /** @inheritDoc */
486
+ setPhpIniPath(e) {
487
+ if (this.#r)
488
+ throw new Error("Cannot set PHP ini path after calling run().");
489
+ this.#e.ccall("wasm_set_phpini_path", null, ["string"], [e]);
490
+ }
491
+ /** @inheritDoc */
492
+ setPhpIniEntry(e, r) {
493
+ if (this.#r)
494
+ throw new Error("Cannot set PHP ini entries after calling run().");
495
+ this.#t.push([e, r]);
496
+ }
497
+ /** @inheritDoc */
498
+ chdir(e) {
499
+ this.#e.FS.chdir(e);
500
+ }
501
+ /** @inheritDoc */
502
+ async request(e, r) {
503
+ if (!this.requestHandler)
504
+ throw new Error("No request handler available.");
505
+ return this.requestHandler.request(e, r);
506
+ }
507
+ /** @inheritDoc */
508
+ async run(e = {}) {
509
+ this.#r || (this.#s(), this.#r = !0), this.#u(e.scriptPath || ""), this.#n(e.relativeUri || ""), this.#a(e.method || "GET");
510
+ const { host: r, ...n } = {
511
+ host: "example.com:443",
512
+ ...ie(e.headers || {})
513
+ };
514
+ if (this.#o(r, e.protocol || "http"), this.#c(n), e.body && this.#l(e.body), e.fileInfos)
515
+ for (const s of e.fileInfos)
516
+ this.#h(s);
517
+ return e.code && this.#d(" ?>" + e.code), await this.#f();
518
+ }
519
+ #s() {
520
+ if (this.#t.length > 0) {
521
+ const e = this.#t.map(([r, n]) => `${r}=${n}`).join(`
522
+ `) + `
523
+
524
+ `;
525
+ this.#e.ccall(
526
+ "wasm_set_phpini_entries",
527
+ null,
528
+ [h],
529
+ [e]
530
+ );
531
+ }
532
+ this.#e.ccall("php_wasm_init", null, [], []);
533
+ }
534
+ cli(e) {
535
+ for (const r of e)
536
+ this.#e.ccall("wasm_add_cli_arg", null, [h], [r]);
537
+ return this.#e.ccall("run_cli", null, [], [], { async: !0 });
538
+ }
539
+ #i() {
540
+ const e = "/tmp/headers.json";
541
+ if (!this.fileExists(e))
542
+ throw new Error(
543
+ "SAPI Error: Could not find response headers file."
544
+ );
545
+ const r = JSON.parse(this.readFileAsText(e)), n = {};
546
+ for (const s of r.headers) {
547
+ if (!s.includes(": "))
548
+ continue;
549
+ const a = s.indexOf(": "), i = s.substring(0, a).toLowerCase(), o = s.substring(a + 2);
550
+ i in n || (n[i] = []), n[i].push(o);
551
+ }
552
+ return {
553
+ headers: n,
554
+ httpStatusCode: r.status
555
+ };
556
+ }
557
+ #n(e) {
558
+ if (this.#e.ccall("wasm_set_request_uri", null, [h], [e]), e.includes("?")) {
559
+ const r = e.substring(e.indexOf("?") + 1);
560
+ this.#e.ccall(
561
+ "wasm_set_query_string",
562
+ null,
563
+ [h],
564
+ [r]
565
+ );
566
+ }
567
+ }
568
+ #o(e, r) {
569
+ this.#e.ccall("wasm_set_request_host", null, [h], [e]);
570
+ let n;
571
+ try {
572
+ n = parseInt(new URL(e).port, 10);
573
+ } catch {
574
+ }
575
+ (!n || isNaN(n) || n === 80) && (n = r === "https" ? 443 : 80), this.#e.ccall("wasm_set_request_port", null, [w], [n]), (r === "https" || !r && n === 443) && this.addServerGlobalEntry("HTTPS", "on");
576
+ }
577
+ #a(e) {
578
+ this.#e.ccall("wasm_set_request_method", null, [h], [e]);
579
+ }
580
+ setSkipShebang(e) {
581
+ this.#e.ccall(
582
+ "wasm_set_skip_shebang",
583
+ null,
584
+ [w],
585
+ [e ? 1 : 0]
586
+ );
587
+ }
588
+ #c(e) {
589
+ e.cookie && this.#e.ccall(
590
+ "wasm_set_cookies",
591
+ null,
592
+ [h],
593
+ [e.cookie]
594
+ ), e["content-type"] && this.#e.ccall(
595
+ "wasm_set_content_type",
596
+ null,
597
+ [h],
598
+ [e["content-type"]]
599
+ ), e["content-length"] && this.#e.ccall(
600
+ "wasm_set_content_length",
601
+ null,
602
+ [w],
603
+ [parseInt(e["content-length"], 10)]
604
+ );
605
+ for (const r in e)
606
+ this.addServerGlobalEntry(
607
+ `HTTP_${r.toUpperCase().replace(/-/g, "_")}`,
608
+ e[r]
609
+ );
610
+ }
611
+ #l(e) {
612
+ this.#e.ccall("wasm_set_request_body", null, [h], [e]), this.#e.ccall(
613
+ "wasm_set_content_length",
614
+ null,
615
+ [w],
616
+ [e.length]
617
+ );
618
+ }
619
+ #u(e) {
620
+ this.#e.ccall("wasm_set_path_translated", null, [h], [e]);
621
+ }
622
+ addServerGlobalEntry(e, r) {
623
+ this.#e.ccall(
624
+ "wasm_add_SERVER_entry",
625
+ null,
626
+ [h, h],
627
+ [e, r]
628
+ );
629
+ }
630
+ /**
631
+ * Adds file information to $_FILES superglobal in PHP.
632
+ *
633
+ * In particular:
634
+ * * Creates the file data in the filesystem
635
+ * * Registers the file details in PHP
636
+ *
637
+ * @param fileInfo - File details
638
+ */
639
+ #h(e) {
640
+ const { key: r, name: n, type: s, data: a } = e, i = `/tmp/${Math.random().toFixed(20)}`;
641
+ this.writeFile(i, a);
642
+ const o = 0;
643
+ this.#e.ccall(
644
+ "wasm_add_uploaded_file",
645
+ null,
646
+ [h, h, h, h, w, w],
647
+ [r, n, s, i, o, a.byteLength]
648
+ );
649
+ }
650
+ #d(e) {
651
+ this.#e.ccall("wasm_set_php_code", null, [h], [e]);
652
+ }
653
+ async #f() {
654
+ const e = await await this.#e.ccall(
655
+ "wasm_sapi_handle_request",
656
+ w,
657
+ [],
658
+ []
659
+ ), { headers: r, httpStatusCode: n } = this.#i();
660
+ return new O(
661
+ n,
662
+ r,
663
+ this.readFileAsBuffer("/tmp/stdout"),
664
+ this.readFileAsText("/tmp/stderr"),
665
+ e
666
+ );
667
+ }
668
+ mkdirTree(e) {
669
+ this.#e.FS.mkdirTree(e);
670
+ }
671
+ readFileAsText(e) {
672
+ return new TextDecoder().decode(this.readFileAsBuffer(e));
673
+ }
674
+ readFileAsBuffer(e) {
675
+ return this.#e.FS.readFile(e);
676
+ }
677
+ writeFile(e, r) {
678
+ this.#e.FS.writeFile(e, r);
679
+ }
680
+ unlink(e) {
681
+ this.#e.FS.unlink(e);
682
+ }
683
+ listFiles(e) {
684
+ if (!this.fileExists(e))
685
+ return [];
686
+ try {
687
+ return this.#e.FS.readdir(e).filter(
688
+ (r) => r !== "." && r !== ".."
689
+ );
690
+ } catch (r) {
691
+ return console.error(r, { path: e }), [];
692
+ }
693
+ }
694
+ isDir(e) {
695
+ return this.fileExists(e) ? this.#e.FS.isDir(
696
+ this.#e.FS.lookupPath(e).node.mode
697
+ ) : !1;
698
+ }
699
+ fileExists(e) {
700
+ try {
701
+ return this.#e.FS.lookupPath(e), !0;
702
+ } catch {
703
+ return !1;
704
+ }
705
+ }
706
+ mount(e, r) {
707
+ this.#e.FS.mount(
708
+ this.#e.FS.filesystems.NODEFS,
709
+ e,
710
+ r
711
+ );
712
+ }
713
+ }
714
+ y([
715
+ g('Could not create directory "{path}"')
716
+ ], m.prototype, "mkdirTree", 1);
717
+ y([
718
+ g('Could not read "{path}"')
719
+ ], m.prototype, "readFileAsText", 1);
720
+ y([
721
+ g('Could not read "{path}"')
722
+ ], m.prototype, "readFileAsBuffer", 1);
723
+ y([
724
+ g('Could not write to "{path}"')
725
+ ], m.prototype, "writeFile", 1);
726
+ y([
727
+ g('Could not unlink "{path}"')
728
+ ], m.prototype, "unlink", 1);
729
+ y([
730
+ g('Could not list files in "{path}"')
731
+ ], m.prototype, "listFiles", 1);
732
+ y([
733
+ g('Could not stat "{path}"')
734
+ ], m.prototype, "isDir", 1);
735
+ y([
736
+ g('Could not stat "{path}"')
737
+ ], m.prototype, "fileExists", 1);
738
+ y([
739
+ g("Could not mount a directory")
740
+ ], m.prototype, "mount", 1);
741
+ function ie(t) {
742
+ const e = {};
743
+ for (const r in t)
744
+ e[r.toLowerCase()] = t[r];
745
+ return e;
746
+ }
747
+ async function oe(t, e = {}, r = []) {
748
+ let n, s;
749
+ const a = new Promise((c) => {
750
+ s = c;
751
+ }), i = new Promise((c) => {
752
+ n = c;
753
+ }), o = t.init(se, {
754
+ onAbort(c) {
755
+ console.error("WASM aborted: "), console.error(c);
756
+ },
757
+ ENV: {},
758
+ // Emscripten sometimes prepends a '/' to the path, which
759
+ // breaks vite dev mode. An identity `locateFile` function
760
+ // fixes it.
761
+ locateFile: (c) => c,
762
+ ...e,
763
+ noInitialRun: !0,
764
+ onRuntimeInitialized() {
765
+ e.onRuntimeInitialized && e.onRuntimeInitialized(), n();
766
+ },
767
+ monitorRunDependencies(c) {
768
+ c === 0 && (delete o.monitorRunDependencies, s());
769
+ }
770
+ });
771
+ for (const { default: c } of r)
772
+ c(o);
773
+ return r.length || s(), await a, await i, S.push(o), S.length - 1;
774
+ }
775
+ /**
776
+ * @license
777
+ * Copyright 2019 Google LLC
778
+ * SPDX-License-Identifier: Apache-2.0
779
+ */
780
+ const D = Symbol("Comlink.proxy"), ae = Symbol("Comlink.endpoint"), ce = Symbol("Comlink.releaseProxy"), C = Symbol("Comlink.finalizer"), v = Symbol("Comlink.thrown"), z = (t) => typeof t == "object" && t !== null || typeof t == "function", le = {
781
+ canHandle: (t) => z(t) && t[D],
782
+ serialize(t) {
783
+ const { port1: e, port2: r } = new MessageChannel();
784
+ return F(t, e), [r, [r]];
785
+ },
786
+ deserialize(t) {
787
+ return t.start(), L(t);
788
+ }
789
+ }, ue = {
790
+ canHandle: (t) => z(t) && v in t,
791
+ serialize({ value: t }) {
792
+ let e;
793
+ return t instanceof Error ? e = {
794
+ isError: !0,
795
+ value: {
796
+ message: t.message,
797
+ name: t.name,
798
+ stack: t.stack
799
+ }
800
+ } : e = { isError: !1, value: t }, [e, []];
801
+ },
802
+ deserialize(t) {
803
+ throw t.isError ? Object.assign(new Error(t.value.message), t.value) : t.value;
804
+ }
805
+ }, _ = /* @__PURE__ */ new Map([
806
+ ["proxy", le],
807
+ ["throw", ue]
808
+ ]);
809
+ function he(t, e) {
810
+ for (const r of t)
811
+ if (e === r || r === "*" || r instanceof RegExp && r.test(e))
812
+ return !0;
813
+ return !1;
814
+ }
815
+ function F(t, e = globalThis, r = ["*"]) {
816
+ e.addEventListener("message", function n(s) {
817
+ if (!s || !s.data)
818
+ return;
819
+ if (!he(r, s.origin)) {
820
+ console.warn(`Invalid origin '${s.origin}' for comlink proxy`);
821
+ return;
822
+ }
823
+ const { id: a, type: i, path: o } = Object.assign({ path: [] }, s.data), c = (s.data.argumentList || []).map(P);
824
+ let l;
825
+ try {
826
+ const u = o.slice(0, -1).reduce((f, E) => f[E], t), p = o.reduce((f, E) => f[E], t);
827
+ switch (i) {
828
+ case "GET":
829
+ l = p;
830
+ break;
831
+ case "SET":
832
+ u[o.slice(-1)[0]] = P(s.data.value), l = !0;
833
+ break;
834
+ case "APPLY":
835
+ l = p.apply(u, c);
836
+ break;
837
+ case "CONSTRUCT":
838
+ {
839
+ const f = new p(...c);
840
+ l = B(f);
841
+ }
842
+ break;
843
+ case "ENDPOINT":
844
+ {
845
+ const { port1: f, port2: E } = new MessageChannel();
846
+ F(t, E), l = ge(f, [f]);
847
+ }
848
+ break;
849
+ case "RELEASE":
850
+ l = void 0;
851
+ break;
852
+ default:
853
+ return;
854
+ }
855
+ } catch (u) {
856
+ l = { value: u, [v]: 0 };
857
+ }
858
+ Promise.resolve(l).catch((u) => ({ value: u, [v]: 0 })).then((u) => {
859
+ const [p, f] = T(u);
860
+ e.postMessage(Object.assign(Object.assign({}, p), { id: a }), f), i === "RELEASE" && (e.removeEventListener("message", n), j(e), C in t && typeof t[C] == "function" && t[C]());
861
+ }).catch((u) => {
862
+ const [p, f] = T({
863
+ value: new TypeError("Unserializable return value"),
864
+ [v]: 0
865
+ });
866
+ e.postMessage(Object.assign(Object.assign({}, p), { id: a }), f);
867
+ });
868
+ }), e.start && e.start();
869
+ }
870
+ function de(t) {
871
+ return t.constructor.name === "MessagePort";
872
+ }
873
+ function j(t) {
874
+ de(t) && t.close();
875
+ }
876
+ function L(t, e) {
877
+ return A(t, [], e);
878
+ }
879
+ function R(t) {
880
+ if (t)
881
+ throw new Error("Proxy has been released and is not useable");
882
+ }
883
+ function $(t) {
884
+ return b(t, {
885
+ type: "RELEASE"
886
+ }).then(() => {
887
+ j(t);
888
+ });
889
+ }
890
+ const k = /* @__PURE__ */ new WeakMap(), x = "FinalizationRegistry" in globalThis && new FinalizationRegistry((t) => {
891
+ const e = (k.get(t) || 0) - 1;
892
+ k.set(t, e), e === 0 && $(t);
893
+ });
894
+ function fe(t, e) {
895
+ const r = (k.get(e) || 0) + 1;
896
+ k.set(e, r), x && x.register(t, e, t);
897
+ }
898
+ function pe(t) {
899
+ x && x.unregister(t);
900
+ }
901
+ function A(t, e = [], r = function() {
902
+ }) {
903
+ let n = !1;
904
+ const s = new Proxy(r, {
905
+ get(a, i) {
906
+ if (R(n), i === ce)
907
+ return () => {
908
+ pe(s), $(t), n = !0;
909
+ };
910
+ if (i === "then") {
911
+ if (e.length === 0)
912
+ return { then: () => s };
913
+ const o = b(t, {
914
+ type: "GET",
915
+ path: e.map((c) => c.toString())
916
+ }).then(P);
917
+ return o.then.bind(o);
918
+ }
919
+ return A(t, [...e, i]);
920
+ },
921
+ set(a, i, o) {
922
+ R(n);
923
+ const [c, l] = T(o);
924
+ return b(t, {
925
+ type: "SET",
926
+ path: [...e, i].map((u) => u.toString()),
927
+ value: c
928
+ }, l).then(P);
929
+ },
930
+ apply(a, i, o) {
931
+ R(n);
932
+ const c = e[e.length - 1];
933
+ if (c === ae)
934
+ return b(t, {
935
+ type: "ENDPOINT"
936
+ }).then(P);
937
+ if (c === "bind")
938
+ return A(t, e.slice(0, -1));
939
+ const [l, u] = U(o);
940
+ return b(t, {
941
+ type: "APPLY",
942
+ path: e.map((p) => p.toString()),
943
+ argumentList: l
944
+ }, u).then(P);
945
+ },
946
+ construct(a, i) {
947
+ R(n);
948
+ const [o, c] = U(i);
949
+ return b(t, {
950
+ type: "CONSTRUCT",
951
+ path: e.map((l) => l.toString()),
952
+ argumentList: o
953
+ }, c).then(P);
954
+ }
955
+ });
956
+ return fe(s, t), s;
957
+ }
958
+ function me(t) {
959
+ return Array.prototype.concat.apply([], t);
960
+ }
961
+ function U(t) {
962
+ const e = t.map(T);
963
+ return [e.map((r) => r[0]), me(e.map((r) => r[1]))];
964
+ }
965
+ const q = /* @__PURE__ */ new WeakMap();
966
+ function ge(t, e) {
967
+ return q.set(t, e), t;
968
+ }
969
+ function B(t) {
970
+ return Object.assign(t, { [D]: !0 });
971
+ }
972
+ function V(t, e = globalThis, r = "*") {
973
+ return {
974
+ postMessage: (n, s) => t.postMessage(n, r, s),
975
+ addEventListener: e.addEventListener.bind(e),
976
+ removeEventListener: e.removeEventListener.bind(e)
977
+ };
978
+ }
979
+ function T(t) {
980
+ for (const [e, r] of _)
981
+ if (r.canHandle(t)) {
982
+ const [n, s] = r.serialize(t);
983
+ return [
984
+ {
985
+ type: "HANDLER",
986
+ name: e,
987
+ value: n
988
+ },
989
+ s
990
+ ];
991
+ }
992
+ return [
993
+ {
994
+ type: "RAW",
995
+ value: t
996
+ },
997
+ q.get(t) || []
998
+ ];
999
+ }
1000
+ function P(t) {
1001
+ switch (t.type) {
1002
+ case "HANDLER":
1003
+ return _.get(t.name).deserialize(t.value);
1004
+ case "RAW":
1005
+ return t.value;
1006
+ }
1007
+ }
1008
+ function b(t, e, r) {
1009
+ return new Promise((n) => {
1010
+ const s = ye();
1011
+ t.addEventListener("message", function a(i) {
1012
+ !i.data || !i.data.id || i.data.id !== s || (t.removeEventListener("message", a), n(i.data));
1013
+ }), t.start && t.start(), t.postMessage(Object.assign({ id: s }, e), r);
1014
+ });
1015
+ }
1016
+ function ye() {
1017
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
1018
+ }
1019
+ function Se(t) {
1020
+ G();
1021
+ const e = t instanceof Worker ? t : V(t);
1022
+ return L(e);
1023
+ }
1024
+ function _e(t, e) {
1025
+ G();
1026
+ let r;
1027
+ const n = new Promise((i) => {
1028
+ r = i;
1029
+ }), s = J(t), a = new Proxy(s, {
1030
+ get: (i, o) => o === "isReady" ? () => n : o in i ? i[o] : e?.[o]
1031
+ });
1032
+ return F(
1033
+ a,
1034
+ typeof window < "u" ? V(self.parent) : void 0
1035
+ ), [r, a];
1036
+ }
1037
+ function G() {
1038
+ _.set("EVENT", {
1039
+ canHandle: (t) => t instanceof CustomEvent,
1040
+ serialize: (t) => [
1041
+ {
1042
+ detail: t.detail
1043
+ },
1044
+ []
1045
+ ],
1046
+ deserialize: (t) => t
1047
+ }), _.set("FUNCTION", {
1048
+ canHandle: (t) => typeof t == "function",
1049
+ serialize(t) {
1050
+ console.debug("[Comlink][Performance] Proxying a function");
1051
+ const { port1: e, port2: r } = new MessageChannel();
1052
+ return F(t, e), [r, [r]];
1053
+ },
1054
+ deserialize(t) {
1055
+ return t.start(), L(t);
1056
+ }
1057
+ });
1058
+ }
1059
+ function J(t) {
1060
+ return new Proxy(t, {
1061
+ get(e, r) {
1062
+ switch (typeof e[r]) {
1063
+ case "function":
1064
+ return (...n) => e[r](...n);
1065
+ case "object":
1066
+ return e[r] === null ? e[r] : J(e[r]);
1067
+ case "undefined":
1068
+ case "number":
1069
+ case "string":
1070
+ return e[r];
1071
+ default:
1072
+ return B(e[r]);
1073
+ }
1074
+ }
1075
+ });
1076
+ }
1077
+ async function we(t = Y) {
1078
+ switch (t) {
1079
+ case "8.2":
1080
+ return await import("php_8_2.js");
1081
+ case "8.1":
1082
+ return await import("php_8_1.js");
1083
+ case "8.0":
1084
+ return await import("php_8_0.js");
1085
+ case "7.4":
1086
+ return await import("php_7_4.js");
1087
+ case "7.3":
1088
+ return await import("php_7_3.js");
1089
+ case "7.2":
1090
+ return await import("php_7_2.js");
1091
+ case "7.1":
1092
+ return await import("php_7_1.js");
1093
+ case "7.0":
1094
+ return await import("php_7_0.js");
1095
+ case "5.6":
1096
+ return await import("php_5_6.js");
1097
+ }
1098
+ throw new Error(`Unsupported PHP version ${t}`);
1099
+ }
1100
+ class H extends m {
1101
+ /**
1102
+ * Creates a new PHP instance.
1103
+ *
1104
+ * Dynamically imports the PHP module, initializes the runtime,
1105
+ * and sets up networking. It's a shorthand for the lower-level
1106
+ * functions like `getPHPLoaderModule`, `loadPHPRuntime`, and
1107
+ * `PHP.initializeRuntime`
1108
+ *
1109
+ * @param phpVersion The PHP Version to load
1110
+ * @param options The options to use when loading PHP
1111
+ * @returns A new PHP instance
1112
+ */
1113
+ static async load(e, r = {}) {
1114
+ return await H.loadSync(e, r).phpReady;
1115
+ }
1116
+ /**
1117
+ * Does what load() does, but synchronously returns
1118
+ * an object with the PHP instance and a promise that
1119
+ * resolves when the PHP instance is ready.
1120
+ *
1121
+ * @see load
1122
+ * @inheritdoc load
1123
+ */
1124
+ static loadSync(e, r = {}) {
1125
+ const n = new H(void 0, r.requestHandler), a = (async () => {
1126
+ const i = await Promise.all([
1127
+ we(e),
1128
+ ...r.dataModules || []
1129
+ ]), [o, ...c] = i;
1130
+ r.downloadMonitor?.setModules(i);
1131
+ const l = await oe(
1132
+ o,
1133
+ {
1134
+ ...r.emscriptenOptions || {},
1135
+ ...r.downloadMonitor?.getEmscriptenOptions() || {}
1136
+ },
1137
+ c
1138
+ );
1139
+ return n.initializeRuntime(l), { dataModules: c };
1140
+ })();
1141
+ return {
1142
+ php: n,
1143
+ phpReady: a.then(() => n),
1144
+ dataModules: a.then((i) => i.dataModules)
1145
+ };
1146
+ }
1147
+ }
1148
+ const d = /* @__PURE__ */ new WeakMap();
1149
+ class ke {
1150
+ /** @inheritDoc */
1151
+ constructor(e, r) {
1152
+ d.set(this, {
1153
+ php: e,
1154
+ monitor: r
1155
+ }), this.absoluteUrl = Promise.resolve(
1156
+ e.requestHandler.server.absoluteUrl
1157
+ ), this.documentRoot = Promise.resolve(
1158
+ e.requestHandler.server.documentRoot
1159
+ );
1160
+ }
1161
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.pathToInternalUrl */
1162
+ async pathToInternalUrl(e) {
1163
+ return d.get(this).php.requestHandler.server.pathToInternalUrl(e);
1164
+ }
1165
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.internalUrlToPath */
1166
+ async internalUrlToPath(e) {
1167
+ return d.get(this).php.requestHandler.server.internalUrlToPath(e);
1168
+ }
1169
+ async onDownloadProgress(e) {
1170
+ d.get(this).monitor?.addEventListener("progress", e);
1171
+ }
1172
+ /** @inheritDoc @php-wasm/web!PHPRequestHandler.request */
1173
+ request(e, r) {
1174
+ return d.get(this).php.request(e, r);
1175
+ }
1176
+ /** @inheritDoc @php-wasm/web!PHP.run */
1177
+ async run(e) {
1178
+ return d.get(this).php.run(e);
1179
+ }
1180
+ /** @inheritDoc @php-wasm/web!PHP.chdir */
1181
+ chdir(e) {
1182
+ return d.get(this).php.chdir(e);
1183
+ }
1184
+ /** @inheritDoc @php-wasm/web!PHP.setPhpIniPath */
1185
+ setPhpIniPath(e) {
1186
+ return d.get(this).php.setPhpIniPath(e);
1187
+ }
1188
+ /** @inheritDoc @php-wasm/web!PHP.setPhpIniEntry */
1189
+ setPhpIniEntry(e, r) {
1190
+ d.get(this).php.setPhpIniEntry(e, r);
1191
+ }
1192
+ /** @inheritDoc @php-wasm/web!PHP.mkdirTree */
1193
+ mkdirTree(e) {
1194
+ d.get(this).php.mkdirTree(e);
1195
+ }
1196
+ /** @inheritDoc @php-wasm/web!PHP.readFileAsText */
1197
+ async readFileAsText(e) {
1198
+ return d.get(this).php.readFileAsText(e);
1199
+ }
1200
+ /** @inheritDoc @php-wasm/web!PHP.readFileAsBuffer */
1201
+ async readFileAsBuffer(e) {
1202
+ return d.get(this).php.readFileAsBuffer(e);
1203
+ }
1204
+ /** @inheritDoc @php-wasm/web!PHP.writeFile */
1205
+ writeFile(e, r) {
1206
+ d.get(this).php.writeFile(e, r);
1207
+ }
1208
+ /** @inheritDoc @php-wasm/web!PHP.unlink */
1209
+ unlink(e) {
1210
+ d.get(this).php.unlink(e);
1211
+ }
1212
+ /** @inheritDoc @php-wasm/web!PHP.listFiles */
1213
+ async listFiles(e) {
1214
+ return d.get(this).php.listFiles(e);
1215
+ }
1216
+ /** @inheritDoc @php-wasm/web!PHP.isDir */
1217
+ async isDir(e) {
1218
+ return d.get(this).php.isDir(e);
1219
+ }
1220
+ /** @inheritDoc @php-wasm/web!PHP.fileExists */
1221
+ async fileExists(e) {
1222
+ return d.get(this).php.fileExists(e);
1223
+ }
1224
+ }
1225
+ function Pe(t, e) {
1226
+ return {
1227
+ type: "response",
1228
+ requestId: t,
1229
+ response: e
1230
+ };
1231
+ }
1232
+ async function xe(t, e, r, n) {
1233
+ const s = navigator.serviceWorker;
1234
+ if (!s)
1235
+ throw new Error("Service workers are not supported in this browser.");
1236
+ const a = await s.getRegistrations();
1237
+ if (a.length > 0) {
1238
+ const i = await be();
1239
+ if (n !== i) {
1240
+ console.debug(
1241
+ `[window] Reloading the currently registered Service Worker (expected version: ${n}, registered version: ${i})`
1242
+ );
1243
+ for (const o of a) {
1244
+ let c = !1;
1245
+ try {
1246
+ await o.update();
1247
+ } catch {
1248
+ c = !0;
1249
+ }
1250
+ const l = o.waiting || o.installing;
1251
+ l && !c && (i !== null ? l.postMessage("skip-waiting") : c = !0), c && (await o.unregister(), window.location.reload());
1252
+ }
1253
+ }
1254
+ } else
1255
+ console.debug(
1256
+ `[window] Creating a Service Worker registration (version: ${n})`
1257
+ ), await s.register(r, {
1258
+ type: "module"
1259
+ });
1260
+ navigator.serviceWorker.addEventListener(
1261
+ "message",
1262
+ async function(o) {
1263
+ if (console.debug("Message from ServiceWorker", o), e && o.data.scope !== e)
1264
+ return;
1265
+ const c = o.data.args || [], l = o.data.method, u = await t[l](...c);
1266
+ o.source.postMessage(Pe(o.data.requestId, u));
1267
+ }
1268
+ ), s.startMessages();
1269
+ }
1270
+ async function be() {
1271
+ try {
1272
+ return (await (await fetch("/version")).json()).version;
1273
+ } catch {
1274
+ return null;
1275
+ }
1276
+ }
1277
+ function Te() {
1278
+ const t = {};
1279
+ return typeof self?.location?.href < "u" && new URL(self.location.href).searchParams.forEach((r, n) => {
1280
+ t[n] = r;
1281
+ }), t;
1282
+ }
1283
+ const Fe = function() {
1284
+ return navigator.userAgent.toLowerCase().indexOf("firefox") > -1 ? "iframe" : "webworker";
1285
+ }();
1286
+ async function Ce(t, e = "webworker", r = {}) {
1287
+ if (t = Ee(t, r), e === "webworker")
1288
+ return new Worker(t, { type: "module" });
1289
+ if (e === "iframe")
1290
+ return (await Re(t)).contentWindow;
1291
+ throw new Error(`Unknown backendName: ${e}`);
1292
+ }
1293
+ function Ee(t, e) {
1294
+ if (!Object.entries(e).length)
1295
+ return t + "";
1296
+ const r = new URL(t);
1297
+ for (const [n, s] of Object.entries(e))
1298
+ r.searchParams.set(n, s);
1299
+ return r.toString();
1300
+ }
1301
+ async function Re(t) {
1302
+ const e = document.createElement("iframe"), r = "/" + t.split("/").slice(-1)[0];
1303
+ return e.src = r, e.style.display = "none", document.body.appendChild(e), await new Promise((n) => {
1304
+ e.addEventListener("load", n);
1305
+ }), e;
1306
+ }
1307
+ export {
1308
+ Y as LatestSupportedPHPVersion,
1309
+ H as PHP,
1310
+ K as PHPBrowser,
1311
+ ke as PHPClient,
1312
+ ee as PHPRequestHandler,
1313
+ W as SupportedPHPVersions,
1314
+ ve as SupportedPHPVersionsList,
1315
+ Se as consumeAPI,
1316
+ _e as exposeAPI,
1317
+ we as getPHPLoaderModule,
1318
+ oe as loadPHPRuntime,
1319
+ Te as parseWorkerStartupOptions,
1320
+ Fe as recommendedWorkerBackend,
1321
+ xe as registerServiceWorker,
1322
+ Ce as spawnPHPWorkerThread
1323
+ };