@php-wasm/fs-journal 0.5.6 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,74 +1,74 @@
1
- var ne = (r, e, t) => {
2
- if (!e.has(r))
3
- throw TypeError("Cannot " + t);
1
+ var K = (e, t, r) => {
2
+ if (!t.has(e))
3
+ throw TypeError("Cannot " + r);
4
4
  };
5
- var a = (r, e, t) => (ne(r, e, "read from private field"), t ? t.call(r) : e.get(r)), c = (r, e, t) => {
6
- if (e.has(r))
5
+ var a = (e, t, r) => (K(e, t, "read from private field"), r ? r.call(e) : t.get(e)), l = (e, t, r) => {
6
+ if (t.has(e))
7
7
  throw TypeError("Cannot add the same private member more than once");
8
- e instanceof WeakSet ? e.add(r) : e.set(r, t);
9
- }, d = (r, e, t, n) => (ne(r, e, "write to private field"), n ? n.call(r, t) : e.set(r, t), t);
10
- var m = (r, e, t) => (ne(r, e, "access private method"), t);
8
+ t instanceof WeakSet ? t.add(e) : t.set(e, r);
9
+ }, d = (e, t, r, s) => (K(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
+ var f = (e, t, r) => (K(e, t, "access private method"), r);
11
11
  if (typeof File > "u") {
12
- class r extends Blob {
13
- constructor(t, n, s) {
14
- super(t);
15
- let o;
16
- s != null && s.lastModified && (o = /* @__PURE__ */ new Date()), (!o || isNaN(o.getFullYear())) && (o = /* @__PURE__ */ new Date()), this.lastModifiedDate = o, this.lastModified = o.getMilliseconds(), this.name = n || "";
12
+ class e extends Blob {
13
+ constructor(r, s, i) {
14
+ super(r);
15
+ let n;
16
+ i != null && i.lastModified && (n = /* @__PURE__ */ new Date()), (!n || isNaN(n.getFullYear())) && (n = /* @__PURE__ */ new Date()), this.lastModifiedDate = n, this.lastModified = n.getMilliseconds(), this.name = s || "";
17
17
  }
18
18
  }
19
- global.File = r;
19
+ global.File = e;
20
20
  }
21
- function me(r) {
22
- return new Promise(function(e, t) {
23
- r.onload = r.onerror = function(n) {
24
- r.onload = r.onerror = null, n.type === "load" ? e(r.result) : t(new Error("Failed to read the blob/file"));
21
+ function asPromise(e) {
22
+ return new Promise(function(t, r) {
23
+ e.onload = e.onerror = function(s) {
24
+ e.onload = e.onerror = null, s.type === "load" ? t(e.result) : r(new Error("Failed to read the blob/file"));
25
25
  };
26
26
  });
27
27
  }
28
28
  typeof Blob.prototype.arrayBuffer > "u" && (Blob.prototype.arrayBuffer = function() {
29
- const e = new FileReader();
30
- return e.readAsArrayBuffer(this), me(e);
29
+ const t = new FileReader();
30
+ return t.readAsArrayBuffer(this), asPromise(t);
31
31
  });
32
32
  typeof Blob.prototype.text > "u" && (Blob.prototype.text = function() {
33
- const e = new FileReader();
34
- return e.readAsText(this), me(e);
33
+ const t = new FileReader();
34
+ return t.readAsText(this), asPromise(t);
35
35
  });
36
- function $e() {
37
- const r = new Uint8Array([1, 2, 3, 4]), t = new File([r], "test").stream();
36
+ function isByobSupported() {
37
+ const e = new Uint8Array([1, 2, 3, 4]), r = new File([e], "test").stream();
38
38
  try {
39
- return t.getReader({ mode: "byob" }), !0;
39
+ return r.getReader({ mode: "byob" }), !0;
40
40
  } catch {
41
41
  return !1;
42
42
  }
43
43
  }
44
- (typeof Blob.prototype.stream > "u" || !$e()) && (Blob.prototype.stream = function() {
45
- let r = 0;
46
- const e = this;
44
+ (typeof Blob.prototype.stream > "u" || !isByobSupported()) && (Blob.prototype.stream = function() {
45
+ let e = 0;
46
+ const t = this;
47
47
  return new ReadableStream({
48
48
  type: "bytes",
49
49
  // 0.5 MB seems like a reasonable chunk size, let's adjust
50
50
  // this if needed.
51
51
  autoAllocateChunkSize: 512 * 1024,
52
- async pull(t) {
53
- const n = t.byobRequest.view, o = await e.slice(r, r + n.byteLength).arrayBuffer(), i = new Uint8Array(o);
54
- new Uint8Array(n.buffer).set(i);
55
- const u = i.byteLength;
56
- t.byobRequest.respond(u), r += u, r >= e.size && t.close();
52
+ async pull(r) {
53
+ const s = r.byobRequest.view, n = await t.slice(e, e + s.byteLength).arrayBuffer(), o = new Uint8Array(n);
54
+ new Uint8Array(s.buffer).set(o);
55
+ const c = o.byteLength;
56
+ r.byobRequest.respond(c), e += c, e >= t.size && r.close();
57
57
  }
58
58
  });
59
59
  });
60
60
  if (typeof CustomEvent > "u") {
61
- class r extends Event {
62
- constructor(t, n = {}) {
63
- super(t, n), this.detail = n.detail;
61
+ class e extends Event {
62
+ constructor(r, s = {}) {
63
+ super(r, s), this.detail = s.detail;
64
64
  }
65
65
  initCustomEvent() {
66
66
  }
67
67
  }
68
- globalThis.CustomEvent = r;
68
+ globalThis.CustomEvent = e;
69
69
  }
70
- const ae = Symbol("error"), le = Symbol("message");
71
- class oe extends Event {
70
+ const kError = Symbol("error"), kMessage = Symbol("message");
71
+ class ErrorEvent2 extends Event {
72
72
  /**
73
73
  * Create a new `ErrorEvent`.
74
74
  *
@@ -76,93 +76,93 @@ class oe extends Event {
76
76
  * @param options A dictionary object that allows for setting
77
77
  * attributes via object members of the same name.
78
78
  */
79
- constructor(e, t = {}) {
80
- super(e), this[ae] = t.error === void 0 ? null : t.error, this[le] = t.message === void 0 ? "" : t.message;
79
+ constructor(t, r = {}) {
80
+ super(t), this[kError] = r.error === void 0 ? null : r.error, this[kMessage] = r.message === void 0 ? "" : r.message;
81
81
  }
82
82
  get error() {
83
- return this[ae];
83
+ return this[kError];
84
84
  }
85
85
  get message() {
86
- return this[le];
86
+ return this[kMessage];
87
87
  }
88
88
  }
89
- Object.defineProperty(oe.prototype, "error", { enumerable: !0 });
90
- Object.defineProperty(oe.prototype, "message", { enumerable: !0 });
91
- const Ie = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : oe;
92
- function Ne(r) {
93
- return r instanceof Error ? "exitCode" in r && (r == null ? void 0 : r.exitCode) === 0 || (r == null ? void 0 : r.name) === "ExitStatus" && "status" in r && r.status === 0 : !1;
89
+ Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: !0 });
90
+ Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: !0 });
91
+ const ErrorEvent = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : ErrorEvent2;
92
+ function isExitCodeZero(e) {
93
+ 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;
94
94
  }
95
- class Me extends EventTarget {
95
+ class UnhandledRejectionsTarget extends EventTarget {
96
96
  constructor() {
97
97
  super(...arguments), this.listenersCount = 0;
98
98
  }
99
- addEventListener(e, t) {
100
- ++this.listenersCount, super.addEventListener(e, t);
99
+ addEventListener(t, r) {
100
+ ++this.listenersCount, super.addEventListener(t, r);
101
101
  }
102
- removeEventListener(e, t) {
103
- --this.listenersCount, super.removeEventListener(e, t);
102
+ removeEventListener(t, r) {
103
+ --this.listenersCount, super.removeEventListener(t, r);
104
104
  }
105
105
  hasListeners() {
106
106
  return this.listenersCount > 0;
107
107
  }
108
108
  }
109
- function Le(r) {
110
- r.asm = {
111
- ...r.asm
109
+ function improveWASMErrorReporting(e) {
110
+ e.asm = {
111
+ ...e.asm
112
112
  };
113
- const e = new Me();
114
- for (const t in r.asm)
115
- if (typeof r.asm[t] == "function") {
116
- const n = r.asm[t];
117
- r.asm[t] = function(...s) {
118
- var o;
113
+ const t = new UnhandledRejectionsTarget();
114
+ for (const r in e.asm)
115
+ if (typeof e.asm[r] == "function") {
116
+ const s = e.asm[r];
117
+ e.asm[r] = function(...i) {
118
+ var n;
119
119
  try {
120
- return n(...s);
121
- } catch (i) {
122
- if (!(i instanceof Error))
123
- throw i;
124
- const u = Be(
125
- i,
126
- (o = r.lastAsyncifyStackSource) == null ? void 0 : o.stack
120
+ return s(...i);
121
+ } catch (o) {
122
+ if (!(o instanceof Error))
123
+ throw o;
124
+ const c = clarifyErrorMessage(
125
+ o,
126
+ (n = e.lastAsyncifyStackSource) == null ? void 0 : n.stack
127
127
  );
128
- if (r.lastAsyncifyStackSource && (i.cause = r.lastAsyncifyStackSource), e.hasListeners()) {
129
- e.dispatchEvent(
130
- new Ie("error", {
131
- error: i,
132
- message: u
128
+ if (e.lastAsyncifyStackSource && (o.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
129
+ t.dispatchEvent(
130
+ new ErrorEvent("error", {
131
+ error: o,
132
+ message: c
133
133
  })
134
134
  );
135
135
  return;
136
136
  }
137
- throw Ne(i) || qe(u), i;
137
+ throw isExitCodeZero(o) || showCriticalErrorBox(c), o;
138
138
  }
139
139
  };
140
140
  }
141
- return e;
141
+ return t;
142
142
  }
143
- let se = [];
144
- function Ue() {
145
- return se;
143
+ let functionsMaybeMissingFromAsyncify = [];
144
+ function getFunctionsMaybeMissingFromAsyncify() {
145
+ return functionsMaybeMissingFromAsyncify;
146
146
  }
147
- function Be(r, e) {
148
- if (r.message === "unreachable") {
149
- let t = We;
150
- e || (t += `
147
+ function clarifyErrorMessage(e, t) {
148
+ if (e.message === "unreachable") {
149
+ let r = UNREACHABLE_ERROR;
150
+ t || (r += `
151
151
 
152
152
  This stack trace is lacking. For a better one initialize
153
153
  the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
154
154
 
155
- `), se = je(
156
- e || r.stack || ""
155
+ `), functionsMaybeMissingFromAsyncify = extractPHPFunctionsFromStack(
156
+ t || e.stack || ""
157
157
  );
158
- for (const n of se)
159
- t += ` * ${n}
158
+ for (const s of functionsMaybeMissingFromAsyncify)
159
+ r += ` * ${s}
160
160
  `;
161
- return t;
161
+ return r;
162
162
  }
163
- return r.message;
163
+ return e.message;
164
164
  }
165
- const We = `
165
+ const UNREACHABLE_ERROR = `
166
166
  "unreachable" WASM instruction executed.
167
167
 
168
168
  The typical reason is a PHP function missing from the ASYNCIFY_ONLY
@@ -186,39 +186,39 @@ the Dockerfile, you'll need to trigger this error again with long stack
186
186
  traces enabled. In node.js, you can do it using the --stack-trace-limit=100
187
187
  CLI option:
188
188
 
189
- `, ce = "\x1B[41m", De = "\x1B[1m", ue = "\x1B[0m", he = "\x1B[K";
190
- let de = !1;
191
- function qe(r) {
192
- if (!de && (de = !0, !(r != null && r.trim().startsWith("Program terminated with exit")))) {
193
- console.log(`${ce}
194
- ${he}
195
- ${De} WASM ERROR${ue}${ce}`);
196
- for (const e of r.split(`
189
+ `, redBg = "\x1B[41m", bold = "\x1B[1m", reset = "\x1B[0m", eol = "\x1B[K";
190
+ let logged = !1;
191
+ function showCriticalErrorBox(e) {
192
+ if (!logged && (logged = !0, !(e != null && e.trim().startsWith("Program terminated with exit")))) {
193
+ console.log(`${redBg}
194
+ ${eol}
195
+ ${bold} WASM ERROR${reset}${redBg}`);
196
+ for (const t of e.split(`
197
197
  `))
198
- console.log(`${he} ${e} `);
199
- console.log(`${ue}`);
198
+ console.log(`${eol} ${t} `);
199
+ console.log(`${reset}`);
200
200
  }
201
201
  }
202
- function je(r) {
202
+ function extractPHPFunctionsFromStack(e) {
203
203
  try {
204
- const e = r.split(`
205
- `).slice(1).map((t) => {
206
- const n = t.trim().substring(3).split(" ");
204
+ const t = e.split(`
205
+ `).slice(1).map((r) => {
206
+ const s = r.trim().substring(3).split(" ");
207
207
  return {
208
- fn: n.length >= 2 ? n[0] : "<unknown>",
209
- isWasm: t.includes("wasm://")
208
+ fn: s.length >= 2 ? s[0] : "<unknown>",
209
+ isWasm: r.includes("wasm://")
210
210
  };
211
211
  }).filter(
212
- ({ fn: t, isWasm: n }) => n && !t.startsWith("dynCall_") && !t.startsWith("invoke_")
213
- ).map(({ fn: t }) => t);
214
- return Array.from(new Set(e));
212
+ ({ fn: r, isWasm: s }) => s && !r.startsWith("dynCall_") && !r.startsWith("invoke_")
213
+ ).map(({ fn: r }) => r);
214
+ return Array.from(new Set(t));
215
215
  } catch {
216
216
  return [];
217
217
  }
218
218
  }
219
- class ie {
220
- constructor({ concurrency: e }) {
221
- this._running = 0, this.concurrency = e, this.queue = [];
219
+ class Semaphore {
220
+ constructor({ concurrency: t }) {
221
+ this._running = 0, this.concurrency = t, this.queue = [];
222
222
  }
223
223
  get running() {
224
224
  return this._running;
@@ -226,79 +226,134 @@ class ie {
226
226
  async acquire() {
227
227
  for (; ; )
228
228
  if (this._running >= this.concurrency)
229
- await new Promise((e) => this.queue.push(e));
229
+ await new Promise((t) => this.queue.push(t));
230
230
  else {
231
231
  this._running++;
232
- let e = !1;
232
+ let t = !1;
233
233
  return () => {
234
- e || (e = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
234
+ t || (t = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
235
235
  };
236
236
  }
237
237
  }
238
- async run(e) {
239
- const t = await this.acquire();
238
+ async run(t) {
239
+ const r = await this.acquire();
240
240
  try {
241
- return await e();
241
+ return await t();
242
242
  } finally {
243
- t();
243
+ r();
244
244
  }
245
245
  }
246
246
  }
247
- function B(...r) {
248
- let e = r.join("/");
249
- const t = e[0] === "/", n = e.substring(e.length - 1) === "/";
250
- return e = ye(e), !e && !t && (e = "."), e && n && (e += "/"), e;
247
+ function joinPaths(...e) {
248
+ let t = e.join("/");
249
+ const r = t[0] === "/", s = t.substring(t.length - 1) === "/";
250
+ return t = normalizePath$1(t), !t && !r && (t = "."), t && s && (t += "/"), t;
251
251
  }
252
- function ze(r) {
253
- if (r === "/")
252
+ function basename(e) {
253
+ if (e === "/")
254
254
  return "/";
255
- r = ye(r);
256
- const e = r.lastIndexOf("/");
257
- return e === -1 ? r : r.substr(e + 1);
255
+ e = normalizePath$1(e);
256
+ const t = e.lastIndexOf("/");
257
+ return t === -1 ? e : e.substr(t + 1);
258
258
  }
259
- function ye(r) {
260
- const e = r[0] === "/";
261
- return r = Ge(
262
- r.split("/").filter((t) => !!t),
263
- !e
264
- ).join("/"), (e ? "/" : "") + r.replace(/\/$/, "");
259
+ function normalizePath$1(e) {
260
+ const t = e[0] === "/";
261
+ return e = normalizePathsArray(
262
+ e.split("/").filter((r) => !!r),
263
+ !t
264
+ ).join("/"), (t ? "/" : "") + e.replace(/\/$/, "");
265
265
  }
266
- function Ge(r, e) {
267
- let t = 0;
268
- for (let n = r.length - 1; n >= 0; n--) {
269
- const s = r[n];
270
- s === "." ? r.splice(n, 1) : s === ".." ? (r.splice(n, 1), t++) : t && (r.splice(n, 1), t--);
271
- }
272
- if (e)
273
- for (; t; t--)
274
- r.unshift("..");
275
- return r;
266
+ function normalizePathsArray(e, t) {
267
+ let r = 0;
268
+ for (let s = e.length - 1; s >= 0; s--) {
269
+ const i = e[s];
270
+ i === "." ? e.splice(s, 1) : i === ".." ? (e.splice(s, 1), r++) : r && (e.splice(s, 1), r--);
271
+ }
272
+ if (t)
273
+ for (; r; r--)
274
+ e.unshift("..");
275
+ return e;
276
+ }
277
+ function createSpawnHandler(e) {
278
+ return function(t) {
279
+ const r = new ChildProcess(), s = new ProcessApi(r);
280
+ return setTimeout(async () => {
281
+ await e(t, s), r.emit("spawn", !0);
282
+ }), r;
283
+ };
284
+ }
285
+ class EventEmitter {
286
+ constructor() {
287
+ this.listeners = {};
288
+ }
289
+ emit(t, r) {
290
+ this.listeners[t] && this.listeners[t].forEach(function(s) {
291
+ s(r);
292
+ });
293
+ }
294
+ on(t, r) {
295
+ this.listeners[t] || (this.listeners[t] = []), this.listeners[t].push(r);
296
+ }
297
+ }
298
+ class ProcessApi extends EventEmitter {
299
+ constructor(t) {
300
+ super(), this.childProcess = t, this.exited = !1, this.stdinData = [], t.on("stdin", (r) => {
301
+ this.stdinData ? this.stdinData.push(r.slice()) : this.emit("stdin", r);
302
+ });
303
+ }
304
+ stdout(t) {
305
+ typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stdout.emit("data", t);
306
+ }
307
+ stderr(t) {
308
+ typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stderr.emit("data", t);
309
+ }
310
+ exit(t) {
311
+ this.exited || (this.exited = !0, this.childProcess.emit("exit", t));
312
+ }
313
+ flushStdin() {
314
+ if (this.stdinData)
315
+ for (let t = 0; t < this.stdinData.length; t++)
316
+ this.emit("stdin", this.stdinData[t]);
317
+ this.stdinData = null;
318
+ }
319
+ }
320
+ let lastPid = 9743;
321
+ class ChildProcess extends EventEmitter {
322
+ constructor(t = lastPid++) {
323
+ super(), this.pid = t, this.stdout = new EventEmitter(), this.stderr = new EventEmitter();
324
+ const r = this;
325
+ this.stdin = {
326
+ write: (s) => {
327
+ r.emit("stdin", s);
328
+ }
329
+ };
330
+ }
276
331
  }
277
332
  ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symbol.asyncIterator] = async function* () {
278
- const r = this.getReader();
333
+ const e = this.getReader();
279
334
  try {
280
335
  for (; ; ) {
281
- const { done: e, value: t } = await r.read();
282
- if (e)
336
+ const { done: t, value: r } = await e.read();
337
+ if (t)
283
338
  return;
284
- yield t;
339
+ yield r;
285
340
  }
286
341
  } finally {
287
- r.releaseLock();
342
+ e.releaseLock();
288
343
  }
289
344
  }, ReadableStream.prototype.iterate = // @ts-ignore
290
345
  ReadableStream.prototype[Symbol.asyncIterator]);
291
- class A {
292
- constructor(e, t, n, s = "", o = 0) {
293
- this.httpStatusCode = e, this.headers = t, this.bytes = n, this.exitCode = o, this.errors = s;
294
- }
295
- static fromRawData(e) {
296
- return new A(
297
- e.httpStatusCode,
298
- e.headers,
299
- e.bytes,
300
- e.errors,
301
- e.exitCode
346
+ class PHPResponse {
347
+ constructor(t, r, s, i = "", n = 0) {
348
+ this.httpStatusCode = t, this.headers = r, this.bytes = s, this.exitCode = n, this.errors = i;
349
+ }
350
+ static fromRawData(t) {
351
+ return new PHPResponse(
352
+ t.httpStatusCode,
353
+ t.headers,
354
+ t.bytes,
355
+ t.errors,
356
+ t.exitCode
302
357
  );
303
358
  }
304
359
  toRawData() {
@@ -323,19 +378,19 @@ class A {
323
378
  return new TextDecoder().decode(this.bytes);
324
379
  }
325
380
  }
326
- var S, H;
327
- class Je {
381
+ var b, T;
382
+ class PHPBrowser {
328
383
  /**
329
384
  * @param server - The PHP server to browse.
330
385
  * @param config - The browser configuration.
331
386
  */
332
- constructor(e, t = {}) {
333
- c(this, S, void 0);
334
- c(this, H, void 0);
335
- this.requestHandler = e, d(this, S, {}), d(this, H, {
387
+ constructor(t, r = {}) {
388
+ l(this, b, void 0);
389
+ l(this, T, void 0);
390
+ this.requestHandler = t, d(this, b, {}), d(this, T, {
336
391
  handleRedirects: !1,
337
392
  maxRedirects: 4,
338
- ...t
393
+ ...r
339
394
  });
340
395
  }
341
396
  /**
@@ -352,37 +407,37 @@ class Je {
352
407
  * @param redirects - Internal. The number of redirects handled so far.
353
408
  * @returns PHPRequestHandler response.
354
409
  */
355
- async request(e, t = 0) {
356
- const n = await this.requestHandler.request({
357
- ...e,
410
+ async request(t, r = 0) {
411
+ const s = await this.requestHandler.request({
412
+ ...t,
358
413
  headers: {
359
- ...e.headers,
414
+ ...t.headers,
360
415
  cookie: this.serializeCookies()
361
416
  }
362
417
  });
363
- if (n.headers["set-cookie"] && this.setCookies(n.headers["set-cookie"]), a(this, H).handleRedirects && n.headers.location && t < a(this, H).maxRedirects) {
364
- const s = new URL(
365
- n.headers.location[0],
418
+ if (s.headers["set-cookie"] && this.setCookies(s.headers["set-cookie"]), a(this, T).handleRedirects && s.headers.location && r < a(this, T).maxRedirects) {
419
+ const i = new URL(
420
+ s.headers.location[0],
366
421
  this.requestHandler.absoluteUrl
367
422
  );
368
423
  return this.request(
369
424
  {
370
- url: s.toString(),
425
+ url: i.toString(),
371
426
  method: "GET",
372
427
  headers: {}
373
428
  },
374
- t + 1
429
+ r + 1
375
430
  );
376
431
  }
377
- return n;
432
+ return s;
378
433
  }
379
434
  /** @inheritDoc */
380
- pathToInternalUrl(e) {
381
- return this.requestHandler.pathToInternalUrl(e);
435
+ pathToInternalUrl(t) {
436
+ return this.requestHandler.pathToInternalUrl(t);
382
437
  }
383
438
  /** @inheritDoc */
384
- internalUrlToPath(e) {
385
- return this.requestHandler.internalUrlToPath(e);
439
+ internalUrlToPath(t) {
440
+ return this.requestHandler.internalUrlToPath(t);
386
441
  }
387
442
  /** @inheritDoc */
388
443
  get absoluteUrl() {
@@ -392,49 +447,49 @@ class Je {
392
447
  get documentRoot() {
393
448
  return this.requestHandler.documentRoot;
394
449
  }
395
- setCookies(e) {
396
- for (const t of e)
450
+ setCookies(t) {
451
+ for (const r of t)
397
452
  try {
398
- if (!t.includes("="))
453
+ if (!r.includes("="))
399
454
  continue;
400
- const n = t.indexOf("="), s = t.substring(0, n), o = t.substring(n + 1).split(";")[0];
401
- a(this, S)[s] = o;
402
- } catch (n) {
403
- console.error(n);
455
+ const s = r.indexOf("="), i = r.substring(0, s), n = r.substring(s + 1).split(";")[0];
456
+ a(this, b)[i] = n;
457
+ } catch (s) {
458
+ console.error(s);
404
459
  }
405
460
  }
406
461
  serializeCookies() {
407
- const e = [];
408
- for (const t in a(this, S))
409
- e.push(`${t}=${a(this, S)[t]}`);
410
- return e.join("; ");
462
+ const t = [];
463
+ for (const r in a(this, b))
464
+ t.push(`${r}=${a(this, b)[r]}`);
465
+ return t.join("; ");
411
466
  }
412
467
  }
413
- S = new WeakMap(), H = new WeakMap();
414
- const Ye = "http://example.com";
415
- function fe(r) {
416
- return r.toString().substring(r.origin.length);
468
+ b = new WeakMap(), T = new WeakMap();
469
+ const DEFAULT_BASE_URL = "http://example.com";
470
+ function toRelativeUrl(e) {
471
+ return e.toString().substring(e.origin.length);
417
472
  }
418
- function pe(r, e) {
419
- return !e || !r.startsWith(e) ? r : r.substring(e.length);
473
+ function removePathPrefix(e, t) {
474
+ return !t || !e.startsWith(t) ? e : e.substring(t.length);
420
475
  }
421
- function Ve(r, e) {
422
- return !e || r.startsWith(e) ? r : e + r;
476
+ function ensurePathPrefix(e, t) {
477
+ return !t || e.startsWith(t) ? e : t + e;
423
478
  }
424
- var g, O, L, x, $, w, I, N, D, ge, q, we, j, be;
425
- class Ke {
479
+ var E, F, N, R, x, m, k, C, M, Z, B, Q, L, X;
480
+ class PHPRequestHandler {
426
481
  /**
427
482
  * @param php - The PHP instance.
428
483
  * @param config - Request Handler configuration.
429
484
  */
430
- constructor(e, t = {}) {
485
+ constructor(t, r = {}) {
431
486
  /**
432
487
  * Serves a static file from the PHP filesystem.
433
488
  *
434
489
  * @param fsPath - Absolute path of the static file to serve.
435
490
  * @returns The response.
436
491
  */
437
- c(this, D);
492
+ l(this, M);
438
493
  /**
439
494
  * Runs the requested PHP file with all the request and $_SERVER
440
495
  * superglobals populated.
@@ -442,7 +497,7 @@ class Ke {
442
497
  * @param request - The request.
443
498
  * @returns The response.
444
499
  */
445
- c(this, q);
500
+ l(this, B);
446
501
  /**
447
502
  * Resolve the requested path to the filesystem path of the requested PHP file.
448
503
  *
@@ -452,68 +507,68 @@ class Ke {
452
507
  * @throws {Error} If the requested path doesn't exist.
453
508
  * @returns The resolved filesystem path.
454
509
  */
455
- c(this, j);
456
- c(this, g, void 0);
457
- c(this, O, void 0);
458
- c(this, L, void 0);
459
- c(this, x, void 0);
460
- c(this, $, void 0);
461
- c(this, w, void 0);
462
- c(this, I, void 0);
463
- c(this, N, void 0);
464
- d(this, N, new ie({ concurrency: 1 }));
510
+ l(this, L);
511
+ l(this, E, void 0);
512
+ l(this, F, void 0);
513
+ l(this, N, void 0);
514
+ l(this, R, void 0);
515
+ l(this, x, void 0);
516
+ l(this, m, void 0);
517
+ l(this, k, void 0);
518
+ l(this, C, void 0);
519
+ d(this, C, new Semaphore({ concurrency: 1 }));
465
520
  const {
466
- documentRoot: n = "/www/",
467
- absoluteUrl: s = typeof location == "object" ? location == null ? void 0 : location.href : ""
468
- } = t;
469
- this.php = e, d(this, g, n);
470
- const o = new URL(s);
471
- d(this, L, o.hostname), d(this, x, o.port ? Number(o.port) : o.protocol === "https:" ? 443 : 80), d(this, O, (o.protocol || "").replace(":", ""));
472
- const i = a(this, x) !== 443 && a(this, x) !== 80;
473
- d(this, $, [
474
- a(this, L),
475
- i ? `:${a(this, x)}` : ""
476
- ].join("")), d(this, w, o.pathname.replace(/\/+$/, "")), d(this, I, [
477
- `${a(this, O)}://`,
478
- a(this, $),
479
- a(this, w)
521
+ documentRoot: s = "/www/",
522
+ absoluteUrl: i = typeof location == "object" ? location == null ? void 0 : location.href : ""
523
+ } = r;
524
+ this.php = t, d(this, E, s);
525
+ const n = new URL(i);
526
+ d(this, N, n.hostname), d(this, R, n.port ? Number(n.port) : n.protocol === "https:" ? 443 : 80), d(this, F, (n.protocol || "").replace(":", ""));
527
+ const o = a(this, R) !== 443 && a(this, R) !== 80;
528
+ d(this, x, [
529
+ a(this, N),
530
+ o ? `:${a(this, R)}` : ""
531
+ ].join("")), d(this, m, n.pathname.replace(/\/+$/, "")), d(this, k, [
532
+ `${a(this, F)}://`,
533
+ a(this, x),
534
+ a(this, m)
480
535
  ].join(""));
481
536
  }
482
537
  /** @inheritDoc */
483
- pathToInternalUrl(e) {
484
- return `${this.absoluteUrl}${e}`;
538
+ pathToInternalUrl(t) {
539
+ return `${this.absoluteUrl}${t}`;
485
540
  }
486
541
  /** @inheritDoc */
487
- internalUrlToPath(e) {
488
- const t = new URL(e);
489
- return t.pathname.startsWith(a(this, w)) && (t.pathname = t.pathname.slice(a(this, w).length)), fe(t);
542
+ internalUrlToPath(t) {
543
+ const r = new URL(t);
544
+ return r.pathname.startsWith(a(this, m)) && (r.pathname = r.pathname.slice(a(this, m).length)), toRelativeUrl(r);
490
545
  }
491
546
  get isRequestRunning() {
492
- return a(this, N).running > 0;
547
+ return a(this, C).running > 0;
493
548
  }
494
549
  /** @inheritDoc */
495
550
  get absoluteUrl() {
496
- return a(this, I);
551
+ return a(this, k);
497
552
  }
498
553
  /** @inheritDoc */
499
554
  get documentRoot() {
500
- return a(this, g);
555
+ return a(this, E);
501
556
  }
502
557
  /** @inheritDoc */
503
- async request(e) {
504
- const t = e.url.startsWith("http://") || e.url.startsWith("https://"), n = new URL(
505
- e.url,
506
- t ? void 0 : Ye
507
- ), s = pe(
508
- n.pathname,
509
- a(this, w)
510
- ), o = `${a(this, g)}${s}`;
511
- return Xe(o) ? await m(this, q, we).call(this, e, n) : m(this, D, ge).call(this, o);
558
+ async request(t) {
559
+ const r = t.url.startsWith("http://") || t.url.startsWith("https://"), s = new URL(
560
+ t.url,
561
+ r ? void 0 : DEFAULT_BASE_URL
562
+ ), i = removePathPrefix(
563
+ s.pathname,
564
+ a(this, m)
565
+ ), n = `${a(this, E)}${i}`;
566
+ return seemsLikeAPHPRequestHandlerPath(n) ? await f(this, B, Q).call(this, t, s) : f(this, M, Z).call(this, n);
512
567
  }
513
568
  }
514
- g = new WeakMap(), O = new WeakMap(), L = new WeakMap(), x = new WeakMap(), $ = new WeakMap(), w = new WeakMap(), I = new WeakMap(), N = new WeakMap(), D = new WeakSet(), ge = function(e) {
515
- if (!this.php.fileExists(e))
516
- return new A(
569
+ E = new WeakMap(), F = new WeakMap(), N = new WeakMap(), R = new WeakMap(), x = new WeakMap(), m = new WeakMap(), k = new WeakMap(), C = new WeakMap(), M = new WeakSet(), Z = function(t) {
570
+ if (!this.php.fileExists(t))
571
+ return new PHPResponse(
517
572
  404,
518
573
  // Let the service worker know that no static file was found
519
574
  // and that it's okay to issue a real fetch() to the server.
@@ -522,104 +577,110 @@ g = new WeakMap(), O = new WeakMap(), L = new WeakMap(), x = new WeakMap(), $ =
522
577
  },
523
578
  new TextEncoder().encode("404 File not found")
524
579
  );
525
- const t = this.php.readFileAsBuffer(e);
526
- return new A(
580
+ const r = this.php.readFileAsBuffer(t);
581
+ return new PHPResponse(
527
582
  200,
528
583
  {
529
- "content-length": [`${t.byteLength}`],
584
+ "content-length": [`${r.byteLength}`],
530
585
  // @TODO: Infer the content-type from the arrayBuffer instead of the file path.
531
586
  // The code below won't return the correct mime-type if the extension
532
587
  // was tampered with.
533
- "content-type": [Qe(e)],
588
+ "content-type": [inferMimeType(t)],
534
589
  "accept-ranges": ["bytes"],
535
590
  "cache-control": ["public, max-age=0"]
536
591
  },
537
- t
592
+ r
538
593
  );
539
- }, q = new WeakSet(), we = async function(e, t) {
540
- var s;
541
- const n = await a(this, N).acquire();
594
+ }, B = new WeakSet(), Q = async function(t, r) {
595
+ var i, n;
596
+ const s = await a(this, C).acquire();
542
597
  try {
543
- this.php.addServerGlobalEntry("DOCUMENT_ROOT", a(this, g)), this.php.addServerGlobalEntry(
598
+ this.php.addServerGlobalEntry("REMOTE_ADDR", "127.0.0.1"), this.php.addServerGlobalEntry("DOCUMENT_ROOT", a(this, E)), this.php.addServerGlobalEntry(
544
599
  "HTTPS",
545
- a(this, I).startsWith("https://") ? "on" : ""
600
+ a(this, k).startsWith("https://") ? "on" : ""
546
601
  );
547
602
  let o = "GET";
548
- const i = {
549
- host: a(this, $),
550
- ...He(e.headers || {})
551
- }, u = [];
552
- if (e.files && Object.keys(e.files).length) {
603
+ const c = {
604
+ host: a(this, x),
605
+ ...normalizeHeaders(t.headers || {})
606
+ }, h = [];
607
+ if (t.files && Object.keys(t.files).length) {
553
608
  o = "POST";
554
- for (const p in e.files) {
555
- const R = e.files[p];
556
- u.push({
557
- key: p,
558
- name: R.name,
559
- type: R.type,
560
- data: new Uint8Array(await R.arrayBuffer())
609
+ for (const _ in t.files) {
610
+ const v = t.files[_];
611
+ h.push({
612
+ key: _,
613
+ name: v.name,
614
+ type: v.type,
615
+ data: new Uint8Array(await v.arrayBuffer())
561
616
  });
562
617
  }
563
- (s = i["content-type"]) != null && s.startsWith("multipart/form-data") && (e.formData = Ze(
564
- e.body || ""
565
- ), i["content-type"] = "application/x-www-form-urlencoded", delete e.body);
618
+ (i = c["content-type"]) != null && i.startsWith("multipart/form-data") && (t.formData = parseMultipartFormDataString(
619
+ t.body || ""
620
+ ), c["content-type"] = "application/x-www-form-urlencoded", delete t.body);
566
621
  }
567
- let h;
568
- e.formData !== void 0 ? (o = "POST", i["content-type"] = i["content-type"] || "application/x-www-form-urlencoded", h = new URLSearchParams(
569
- e.formData
570
- ).toString()) : h = e.body;
571
- let f;
622
+ let p;
623
+ t.formData !== void 0 ? (o = "POST", c["content-type"] = c["content-type"] || "application/x-www-form-urlencoded", p = new URLSearchParams(
624
+ t.formData
625
+ ).toString()) : p = t.body;
626
+ let u;
572
627
  try {
573
- f = m(this, j, be).call(this, t.pathname);
628
+ let _ = r.pathname;
629
+ if ((n = t.headers) != null && n["x-rewrite-url"])
630
+ try {
631
+ _ = new URL(
632
+ t.headers["x-rewrite-url"]
633
+ ).pathname;
634
+ } catch {
635
+ }
636
+ u = f(this, L, X).call(this, _);
574
637
  } catch {
575
- return new A(
638
+ return new PHPResponse(
576
639
  404,
577
640
  {},
578
641
  new TextEncoder().encode("404 File not found")
579
642
  );
580
643
  }
581
644
  return await this.php.run({
582
- relativeUri: Ve(
583
- fe(t),
584
- a(this, w)
645
+ relativeUri: ensurePathPrefix(
646
+ toRelativeUrl(r),
647
+ a(this, m)
585
648
  ),
586
- protocol: a(this, O),
587
- method: e.method || o,
588
- body: h,
589
- fileInfos: u,
590
- scriptPath: f,
591
- headers: i
649
+ protocol: a(this, F),
650
+ method: t.method || o,
651
+ body: p,
652
+ fileInfos: h,
653
+ scriptPath: u,
654
+ headers: c
592
655
  });
593
656
  } finally {
594
- n();
595
- }
596
- }, j = new WeakSet(), be = function(e) {
597
- let t = pe(e, a(this, w));
598
- t.includes(".php") ? t = t.split(".php")[0] + ".php" : (t.endsWith("/") || (t += "/"), t.endsWith("index.php") || (t += "index.php"));
599
- const n = `${a(this, g)}${t}`;
600
- if (this.php.fileExists(n))
601
- return n;
602
- if (!this.php.fileExists(`${a(this, g)}/index.php`))
603
- throw new Error(`File not found: ${n}`);
604
- return `${a(this, g)}/index.php`;
657
+ s();
658
+ }
659
+ }, L = new WeakSet(), X = function(t) {
660
+ let r = removePathPrefix(t, a(this, m));
661
+ r.includes(".php") ? r = r.split(".php")[0] + ".php" : (r.endsWith("/") || (r += "/"), r.endsWith("index.php") || (r += "index.php"));
662
+ const s = `${a(this, E)}${r}`;
663
+ if (this.php.fileExists(s))
664
+ return s;
665
+ throw new Error(`File not found: ${s}`);
605
666
  };
606
- function Ze(r) {
607
- const e = {}, t = r.match(/--(.*)\r\n/);
608
- if (!t)
609
- return e;
610
- const n = t[1], s = r.split(`--${n}`);
611
- return s.shift(), s.pop(), s.forEach((o) => {
612
- const i = o.indexOf(`\r
667
+ function parseMultipartFormDataString(e) {
668
+ const t = {}, r = e.match(/--(.*)\r\n/);
669
+ if (!r)
670
+ return t;
671
+ const s = r[1], i = e.split(`--${s}`);
672
+ return i.shift(), i.pop(), i.forEach((n) => {
673
+ const o = n.indexOf(`\r
613
674
  \r
614
- `), u = o.substring(0, i).trim(), h = o.substring(i + 4).trim(), f = u.match(/name="([^"]+)"/);
615
- if (f) {
616
- const p = f[1];
617
- e[p] = h;
675
+ `), c = n.substring(0, o).trim(), h = n.substring(o + 4).trim(), p = c.match(/name="([^"]+)"/);
676
+ if (p) {
677
+ const u = p[1];
678
+ t[u] = h;
618
679
  }
619
- }), e;
680
+ }), t;
620
681
  }
621
- function Qe(r) {
622
- switch (r.split(".").pop()) {
682
+ function inferMimeType(e) {
683
+ switch (e.split(".").pop()) {
623
684
  case "css":
624
685
  return "text/css";
625
686
  case "js":
@@ -658,16 +719,16 @@ function Qe(r) {
658
719
  return "application-octet-stream";
659
720
  }
660
721
  }
661
- function Xe(r) {
662
- return et(r) || tt(r);
722
+ function seemsLikeAPHPRequestHandlerPath(e) {
723
+ return seemsLikeAPHPFile(e) || seemsLikeADirectoryRoot(e);
663
724
  }
664
- function et(r) {
665
- return r.endsWith(".php") || r.includes(".php/");
725
+ function seemsLikeAPHPFile(e) {
726
+ return e.endsWith(".php") || e.includes(".php/");
666
727
  }
667
- function tt(r) {
668
- return !r.split("/").pop().includes(".");
728
+ function seemsLikeADirectoryRoot(e) {
729
+ return !e.split("/").pop().includes(".");
669
730
  }
670
- const W = {
731
+ const FileErrorCodes = {
671
732
  0: "No error occurred. System call completed successfully.",
672
733
  1: "Argument list too long.",
673
734
  2: "Permission denied.",
@@ -746,46 +807,46 @@ const W = {
746
807
  75: "Cross-device link.",
747
808
  76: "Extension: Capabilities insufficient."
748
809
  };
749
- function rt(r) {
750
- const e = typeof r == "object" ? r == null ? void 0 : r.errno : null;
751
- if (e in W)
752
- return W[e];
810
+ function getEmscriptenFsError(e) {
811
+ const t = typeof e == "object" ? e == null ? void 0 : e.errno : null;
812
+ if (t in FileErrorCodes)
813
+ return FileErrorCodes[t];
753
814
  }
754
- function b(r = "") {
755
- return function(t, n, s) {
756
- const o = s.value;
757
- s.value = function(...i) {
815
+ function rethrowFileSystemError(e = "") {
816
+ return function(r, s, i) {
817
+ const n = i.value;
818
+ i.value = function(...o) {
758
819
  try {
759
- return o.apply(this, i);
760
- } catch (u) {
761
- const h = typeof u == "object" ? u == null ? void 0 : u.errno : null;
762
- if (h in W) {
763
- const f = W[h], p = typeof i[0] == "string" ? i[0] : null, R = p !== null ? r.replaceAll("{path}", p) : r;
764
- throw new Error(`${R}: ${f}`, {
765
- cause: u
820
+ return n.apply(this, o);
821
+ } catch (c) {
822
+ const h = typeof c == "object" ? c == null ? void 0 : c.errno : null;
823
+ if (h in FileErrorCodes) {
824
+ const p = FileErrorCodes[h], u = typeof o[0] == "string" ? o[0] : null, _ = u !== null ? e.replaceAll("{path}", u) : e;
825
+ throw new Error(`${_}: ${p}`, {
826
+ cause: c
766
827
  });
767
828
  }
768
- throw u;
829
+ throw c;
769
830
  }
770
831
  };
771
832
  };
772
833
  }
773
- const nt = /* @__PURE__ */ new Map();
774
- function st(r) {
775
- return nt.get(r);
834
+ const loadedRuntimes = /* @__PURE__ */ new Map();
835
+ function getLoadedRuntime(e) {
836
+ return loadedRuntimes.get(e);
776
837
  }
777
838
  (function() {
778
- var r;
779
- return typeof process < "u" && ((r = process.release) == null ? void 0 : r.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope ? "WORKER" : "NODE";
839
+ var e;
840
+ 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";
780
841
  })();
781
- var ot = Object.defineProperty, it = Object.getOwnPropertyDescriptor, E = (r, e, t, n) => {
782
- for (var s = n > 1 ? void 0 : n ? it(e, t) : e, o = r.length - 1, i; o >= 0; o--)
783
- (i = r[o]) && (s = (n ? i(e, t, s) : i(s)) || s);
784
- return n && s && ot(e, t, s), s;
842
+ var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, r, s) => {
843
+ for (var i = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, n = e.length - 1, o; n >= 0; n--)
844
+ (o = e[n]) && (i = (s ? o(t, r, i) : o(i)) || i);
845
+ return s && i && __defProp(t, r, i), i;
785
846
  };
786
- const y = "string", C = "number", l = Symbol("__private__dont__use");
787
- var k, T, F, _, v, M, U, z, Ee, G, Pe, J, Re, Y, ve, V, Te, K, _e, Z, Se, Q, xe, X, ke, ee, Fe, te, Ce, re, Ae;
788
- class P {
847
+ const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
848
+ var S, H, A, y, g, P, w, I, O, ee, U, te, D, re, $, se, W, ne, q, ie, j, oe, z, ae, G, le, J, ce, Y, ue, V, de;
849
+ class BasePHP {
789
850
  /**
790
851
  * Initializes a PHP runtime.
791
852
  *
@@ -794,15 +855,15 @@ class P {
794
855
  * @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
795
856
  */
796
857
  constructor(e, t) {
797
- c(this, z);
798
- c(this, G);
799
- c(this, J);
800
- c(this, Y);
801
- c(this, V);
802
- c(this, K);
803
- c(this, Z);
804
- c(this, Q);
805
- c(this, X);
858
+ l(this, O);
859
+ l(this, U);
860
+ l(this, D);
861
+ l(this, $);
862
+ l(this, W);
863
+ l(this, q);
864
+ l(this, j);
865
+ l(this, z);
866
+ l(this, G);
806
867
  /**
807
868
  * Adds file information to $_FILES superglobal in PHP.
808
869
  *
@@ -812,40 +873,41 @@ class P {
812
873
  *
813
874
  * @param fileInfo - File details
814
875
  */
815
- c(this, ee);
816
- c(this, te);
817
- c(this, re);
818
- c(this, k, void 0);
819
- c(this, T, void 0);
820
- c(this, F, void 0);
821
- c(this, _, void 0);
822
- c(this, v, void 0);
823
- c(this, M, void 0);
824
- c(this, U, void 0);
825
- d(this, k, []), d(this, T, !1), d(this, F, null), d(this, _, {}), d(this, v, /* @__PURE__ */ new Map()), d(this, M, []), d(this, U, new ie({ concurrency: 1 })), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new Je(
826
- new Ke(this, t)
876
+ l(this, J);
877
+ l(this, Y);
878
+ l(this, V);
879
+ l(this, S, void 0);
880
+ l(this, H, void 0);
881
+ l(this, A, void 0);
882
+ l(this, y, void 0);
883
+ l(this, g, void 0);
884
+ l(this, P, void 0);
885
+ l(this, w, void 0);
886
+ l(this, I, void 0);
887
+ d(this, S, []), d(this, y, !1), d(this, g, null), d(this, P, {}), d(this, w, /* @__PURE__ */ new Map()), d(this, I, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e), t && (this.requestHandler = new PHPBrowser(
888
+ new PHPRequestHandler(this, t)
827
889
  ));
828
890
  }
829
891
  addEventListener(e, t) {
830
- a(this, v).has(e) || a(this, v).set(e, /* @__PURE__ */ new Set()), a(this, v).get(e).add(t);
892
+ a(this, w).has(e) || a(this, w).set(e, /* @__PURE__ */ new Set()), a(this, w).get(e).add(t);
831
893
  }
832
894
  removeEventListener(e, t) {
833
- var n;
834
- (n = a(this, v).get(e)) == null || n.delete(t);
895
+ var r;
896
+ (r = a(this, w).get(e)) == null || r.delete(t);
835
897
  }
836
898
  dispatchEvent(e) {
837
- const t = a(this, v).get(e.type);
899
+ const t = a(this, w).get(e.type);
838
900
  if (t)
839
- for (const n of t)
840
- n(e);
901
+ for (const r of t)
902
+ r(e);
841
903
  }
842
904
  /** @inheritDoc */
843
905
  async onMessage(e) {
844
- a(this, M).push(e);
906
+ a(this, I).push(e);
845
907
  }
846
908
  /** @inheritDoc */
847
- async setSpawnHandler(e) {
848
- this[l].spawnProcess = e;
909
+ async setSpawnHandler(handler) {
910
+ typeof handler == "string" && (handler = createSpawnHandler(eval(handler))), this[__private__dont__use].spawnProcess = handler;
849
911
  }
850
912
  /** @inheritDoc */
851
913
  get absoluteUrl() {
@@ -866,25 +928,40 @@ class P {
866
928
  );
867
929
  }
868
930
  initializeRuntime(e) {
869
- if (this[l])
931
+ if (this[__private__dont__use])
870
932
  throw new Error("PHP runtime already initialized.");
871
- const t = st(e);
933
+ const t = getLoadedRuntime(e);
872
934
  if (!t)
873
935
  throw new Error("Invalid PHP runtime id.");
874
- this[l] = t, t.onMessage = async (n) => {
875
- for (const s of a(this, M)) {
876
- const o = await s(n);
877
- if (o)
878
- return o;
936
+ this[__private__dont__use] = t, t.onMessage = async (r) => {
937
+ for (const s of a(this, I)) {
938
+ const i = await s(r);
939
+ if (i)
940
+ return i;
879
941
  }
880
942
  return "";
881
- }, d(this, F, Le(t));
943
+ }, d(this, g, improveWASMErrorReporting(t)), this.dispatchEvent({
944
+ type: "runtime.initialized"
945
+ });
946
+ }
947
+ /** @inheritDoc */
948
+ async setSapiName(e) {
949
+ if (this[__private__dont__use].ccall(
950
+ "wasm_set_sapi_name",
951
+ NUMBER,
952
+ [STRING],
953
+ [e]
954
+ ) !== 0)
955
+ throw new Error(
956
+ "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
957
+ );
958
+ d(this, A, e);
882
959
  }
883
960
  /** @inheritDoc */
884
961
  setPhpIniPath(e) {
885
- if (a(this, T))
962
+ if (a(this, y))
886
963
  throw new Error("Cannot set PHP ini path after calling run().");
887
- this[l].ccall(
964
+ d(this, H, e), this[__private__dont__use].ccall(
888
965
  "wasm_set_phpini_path",
889
966
  null,
890
967
  ["string"],
@@ -893,13 +970,13 @@ class P {
893
970
  }
894
971
  /** @inheritDoc */
895
972
  setPhpIniEntry(e, t) {
896
- if (a(this, T))
973
+ if (a(this, y))
897
974
  throw new Error("Cannot set PHP ini entries after calling run().");
898
- a(this, k).push([e, t]);
975
+ a(this, S).push([e, t]);
899
976
  }
900
977
  /** @inheritDoc */
901
978
  chdir(e) {
902
- this[l].FS.chdir(e);
979
+ this[__private__dont__use].FS.chdir(e);
903
980
  }
904
981
  /** @inheritDoc */
905
982
  async request(e, t) {
@@ -909,27 +986,45 @@ class P {
909
986
  }
910
987
  /** @inheritDoc */
911
988
  async run(e) {
912
- const t = await a(this, U).acquire();
989
+ const t = await this.semaphore.acquire();
990
+ let r;
913
991
  try {
914
- a(this, T) || (m(this, z, Ee).call(this), d(this, T, !0)), m(this, Q, xe).call(this, e.scriptPath || ""), m(this, J, Re).call(this, e.relativeUri || ""), m(this, V, Te).call(this, e.method || "GET");
915
- const n = He(e.headers || {}), s = n.host || "example.com:443";
916
- if (m(this, Y, ve).call(this, s, e.protocol || "http"), m(this, K, _e).call(this, n), e.body && m(this, Z, Se).call(this, e.body), e.fileInfos)
992
+ a(this, y) || (f(this, O, ee).call(this), d(this, y, !0)), f(this, z, ae).call(this, e.scriptPath || ""), f(this, D, re).call(this, e.relativeUri || ""), f(this, W, ne).call(this, e.method || "GET");
993
+ const s = normalizeHeaders(e.headers || {}), i = s.host || "example.com:443";
994
+ if (f(this, $, se).call(this, i, e.protocol || "http"), f(this, q, ie).call(this, s), e.body && (r = f(this, j, oe).call(this, e.body)), e.fileInfos)
917
995
  for (const o of e.fileInfos)
918
- m(this, ee, Fe).call(this, o);
919
- return e.code && m(this, te, Ce).call(this, " ?>" + e.code), m(this, X, ke).call(this), await m(this, re, Ae).call(this);
996
+ f(this, J, ce).call(this, o);
997
+ typeof e.code == "string" && f(this, Y, ue).call(this, " ?>" + e.code), f(this, G, le).call(this);
998
+ const n = await f(this, V, de).call(this);
999
+ if (e.throwOnError && n.exitCode !== 0) {
1000
+ const o = {
1001
+ stdout: n.text,
1002
+ stderr: n.errors
1003
+ };
1004
+ console.warn("PHP.run() output was:", o);
1005
+ const c = new Error(
1006
+ `PHP.run() failed with exit code ${n.exitCode} and the following output`
1007
+ );
1008
+ throw c.output = o, c;
1009
+ }
1010
+ return n;
920
1011
  } finally {
921
- t(), this.dispatchEvent({
922
- type: "request.end"
923
- });
1012
+ try {
1013
+ r && this[__private__dont__use].free(r);
1014
+ } finally {
1015
+ t(), this.dispatchEvent({
1016
+ type: "request.end"
1017
+ });
1018
+ }
924
1019
  }
925
1020
  }
926
1021
  addServerGlobalEntry(e, t) {
927
- a(this, _)[e] = t;
1022
+ a(this, P)[e] = t;
928
1023
  }
929
1024
  defineConstant(e, t) {
930
- let n = {};
1025
+ let r = {};
931
1026
  try {
932
- n = JSON.parse(
1027
+ r = JSON.parse(
933
1028
  this.fileExists("/tmp/consts.json") && this.readFileAsText("/tmp/consts.json") || "{}"
934
1029
  );
935
1030
  } catch {
@@ -937,13 +1032,13 @@ class P {
937
1032
  this.writeFile(
938
1033
  "/tmp/consts.json",
939
1034
  JSON.stringify({
940
- ...n,
1035
+ ...r,
941
1036
  [e]: t
942
1037
  })
943
1038
  );
944
1039
  }
945
1040
  mkdir(e) {
946
- this[l].FS.mkdirTree(e);
1041
+ this[__private__dont__use].FS.mkdirTree(e);
947
1042
  }
948
1043
  mkdirTree(e) {
949
1044
  this.mkdir(e);
@@ -952,67 +1047,91 @@ class P {
952
1047
  return new TextDecoder().decode(this.readFileAsBuffer(e));
953
1048
  }
954
1049
  readFileAsBuffer(e) {
955
- return this[l].FS.readFile(e);
1050
+ return this[__private__dont__use].FS.readFile(e);
956
1051
  }
957
1052
  writeFile(e, t) {
958
- this[l].FS.writeFile(e, t);
1053
+ this[__private__dont__use].FS.writeFile(e, t);
959
1054
  }
960
1055
  unlink(e) {
961
- this[l].FS.unlink(e);
1056
+ this[__private__dont__use].FS.unlink(e);
962
1057
  }
963
1058
  /** @inheritDoc */
964
1059
  mv(e, t) {
965
1060
  try {
966
- this[l].FS.rename(e, t);
967
- } catch (n) {
968
- const s = rt(n);
1061
+ this[__private__dont__use].FS.rename(e, t);
1062
+ } catch (r) {
1063
+ const s = getEmscriptenFsError(r);
969
1064
  throw s ? new Error(
970
1065
  `Could not move ${e} to ${t}: ${s}`,
971
1066
  {
972
- cause: n
1067
+ cause: r
973
1068
  }
974
- ) : n;
1069
+ ) : r;
975
1070
  }
976
1071
  }
977
1072
  rmdir(e, t = { recursive: !0 }) {
978
- t != null && t.recursive && this.listFiles(e).forEach((n) => {
979
- const s = `${e}/${n}`;
1073
+ t != null && t.recursive && this.listFiles(e).forEach((r) => {
1074
+ const s = `${e}/${r}`;
980
1075
  this.isDir(s) ? this.rmdir(s, t) : this.unlink(s);
981
- }), this[l].FS.rmdir(e);
1076
+ }), this[__private__dont__use].FS.rmdir(e);
982
1077
  }
983
1078
  listFiles(e, t = { prependPath: !1 }) {
984
1079
  if (!this.fileExists(e))
985
1080
  return [];
986
1081
  try {
987
- const n = this[l].FS.readdir(e).filter(
1082
+ const r = this[__private__dont__use].FS.readdir(e).filter(
988
1083
  (s) => s !== "." && s !== ".."
989
1084
  );
990
1085
  if (t.prependPath) {
991
1086
  const s = e.replace(/\/$/, "");
992
- return n.map((o) => `${s}/${o}`);
1087
+ return r.map((i) => `${s}/${i}`);
993
1088
  }
994
- return n;
995
- } catch (n) {
996
- return console.error(n, { path: e }), [];
1089
+ return r;
1090
+ } catch (r) {
1091
+ return console.error(r, { path: e }), [];
997
1092
  }
998
1093
  }
999
1094
  isDir(e) {
1000
- return this.fileExists(e) ? this[l].FS.isDir(
1001
- this[l].FS.lookupPath(e).node.mode
1095
+ return this.fileExists(e) ? this[__private__dont__use].FS.isDir(
1096
+ this[__private__dont__use].FS.lookupPath(e).node.mode
1002
1097
  ) : !1;
1003
1098
  }
1004
1099
  fileExists(e) {
1005
1100
  try {
1006
- return this[l].FS.lookupPath(e), !0;
1101
+ return this[__private__dont__use].FS.lookupPath(e), !0;
1007
1102
  } catch {
1008
1103
  return !1;
1009
1104
  }
1010
1105
  }
1106
+ /**
1107
+ * Hot-swaps the PHP runtime for a new one without
1108
+ * interrupting the operations of this PHP instance.
1109
+ *
1110
+ * @param runtime
1111
+ */
1112
+ hotSwapPHPRuntime(e) {
1113
+ const t = this[__private__dont__use].FS;
1114
+ try {
1115
+ this.exit();
1116
+ } catch {
1117
+ }
1118
+ if (this.initializeRuntime(e), a(this, H) && this.setPhpIniPath(a(this, H)), a(this, A) && this.setSapiName(a(this, A)), this.requestHandler) {
1119
+ const r = this.documentRoot;
1120
+ recreateMemFS(this[__private__dont__use].FS, t, r);
1121
+ }
1122
+ }
1011
1123
  exit(e = 0) {
1012
- return this[l]._exit(e);
1124
+ this.dispatchEvent({
1125
+ type: "runtime.beforedestroy"
1126
+ });
1127
+ try {
1128
+ this[__private__dont__use]._exit(e);
1129
+ } catch {
1130
+ }
1131
+ d(this, y, !1), d(this, g, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1013
1132
  }
1014
1133
  }
1015
- k = new WeakMap(), T = new WeakMap(), F = new WeakMap(), _ = new WeakMap(), v = new WeakMap(), M = new WeakMap(), U = new WeakMap(), z = new WeakSet(), Ee = function() {
1134
+ S = new WeakMap(), H = new WeakMap(), A = new WeakMap(), y = new WeakMap(), g = new WeakMap(), P = new WeakMap(), w = new WeakMap(), I = new WeakMap(), O = new WeakSet(), ee = function() {
1016
1135
  if (this.setPhpIniEntry("auto_prepend_file", "/tmp/consts.php"), this.fileExists("/tmp/consts.php") || this.writeFile(
1017
1136
  "/tmp/consts.php",
1018
1137
  `<?php
@@ -1024,422 +1143,461 @@ k = new WeakMap(), T = new WeakMap(), F = new WeakMap(), _ = new WeakMap(), v =
1024
1143
  }
1025
1144
  }
1026
1145
  }`
1027
- ), a(this, k).length > 0) {
1028
- const e = a(this, k).map(([t, n]) => `${t}=${n}`).join(`
1146
+ ), a(this, S).length > 0) {
1147
+ const e = a(this, S).map(([t, r]) => `${t}=${r}`).join(`
1029
1148
  `) + `
1030
1149
 
1031
1150
  `;
1032
- this[l].ccall(
1151
+ this[__private__dont__use].ccall(
1033
1152
  "wasm_set_phpini_entries",
1034
1153
  null,
1035
- [y],
1154
+ [STRING],
1036
1155
  [e]
1037
1156
  );
1038
1157
  }
1039
- this[l].ccall("php_wasm_init", null, [], []);
1040
- }, G = new WeakSet(), Pe = function() {
1158
+ this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1159
+ }, U = new WeakSet(), te = function() {
1041
1160
  const e = "/tmp/headers.json";
1042
1161
  if (!this.fileExists(e))
1043
1162
  throw new Error(
1044
1163
  "SAPI Error: Could not find response headers file."
1045
1164
  );
1046
- const t = JSON.parse(this.readFileAsText(e)), n = {};
1165
+ const t = JSON.parse(this.readFileAsText(e)), r = {};
1047
1166
  for (const s of t.headers) {
1048
1167
  if (!s.includes(": "))
1049
1168
  continue;
1050
- const o = s.indexOf(": "), i = s.substring(0, o).toLowerCase(), u = s.substring(o + 2);
1051
- i in n || (n[i] = []), n[i].push(u);
1169
+ const i = s.indexOf(": "), n = s.substring(0, i).toLowerCase(), o = s.substring(i + 2);
1170
+ n in r || (r[n] = []), r[n].push(o);
1052
1171
  }
1053
1172
  return {
1054
- headers: n,
1173
+ headers: r,
1055
1174
  httpStatusCode: t.status
1056
1175
  };
1057
- }, J = new WeakSet(), Re = function(e) {
1058
- if (this[l].ccall(
1176
+ }, D = new WeakSet(), re = function(e) {
1177
+ if (this[__private__dont__use].ccall(
1059
1178
  "wasm_set_request_uri",
1060
1179
  null,
1061
- [y],
1180
+ [STRING],
1062
1181
  [e]
1063
1182
  ), e.includes("?")) {
1064
1183
  const t = e.substring(e.indexOf("?") + 1);
1065
- this[l].ccall(
1184
+ this[__private__dont__use].ccall(
1066
1185
  "wasm_set_query_string",
1067
1186
  null,
1068
- [y],
1187
+ [STRING],
1069
1188
  [t]
1070
1189
  );
1071
1190
  }
1072
- }, Y = new WeakSet(), ve = function(e, t) {
1073
- this[l].ccall(
1191
+ }, $ = new WeakSet(), se = function(e, t) {
1192
+ this[__private__dont__use].ccall(
1074
1193
  "wasm_set_request_host",
1075
1194
  null,
1076
- [y],
1195
+ [STRING],
1077
1196
  [e]
1078
1197
  );
1079
- let n;
1198
+ let r;
1080
1199
  try {
1081
- n = parseInt(new URL(e).port, 10);
1200
+ r = parseInt(new URL(e).port, 10);
1082
1201
  } catch {
1083
1202
  }
1084
- (!n || isNaN(n) || n === 80) && (n = t === "https" ? 443 : 80), this[l].ccall(
1203
+ (!r || isNaN(r) || r === 80) && (r = t === "https" ? 443 : 80), this[__private__dont__use].ccall(
1085
1204
  "wasm_set_request_port",
1086
1205
  null,
1087
- [C],
1088
- [n]
1089
- ), (t === "https" || !t && n === 443) && this.addServerGlobalEntry("HTTPS", "on");
1090
- }, V = new WeakSet(), Te = function(e) {
1091
- this[l].ccall(
1206
+ [NUMBER],
1207
+ [r]
1208
+ ), (t === "https" || !t && r === 443) && this.addServerGlobalEntry("HTTPS", "on");
1209
+ }, W = new WeakSet(), ne = function(e) {
1210
+ this[__private__dont__use].ccall(
1092
1211
  "wasm_set_request_method",
1093
1212
  null,
1094
- [y],
1213
+ [STRING],
1095
1214
  [e]
1096
1215
  );
1097
- }, K = new WeakSet(), _e = function(e) {
1098
- e.cookie && this[l].ccall(
1216
+ }, q = new WeakSet(), ie = function(e) {
1217
+ e.cookie && this[__private__dont__use].ccall(
1099
1218
  "wasm_set_cookies",
1100
1219
  null,
1101
- [y],
1220
+ [STRING],
1102
1221
  [e.cookie]
1103
- ), e["content-type"] && this[l].ccall(
1222
+ ), e["content-type"] && this[__private__dont__use].ccall(
1104
1223
  "wasm_set_content_type",
1105
1224
  null,
1106
- [y],
1225
+ [STRING],
1107
1226
  [e["content-type"]]
1108
- ), e["content-length"] && this[l].ccall(
1227
+ ), e["content-length"] && this[__private__dont__use].ccall(
1109
1228
  "wasm_set_content_length",
1110
1229
  null,
1111
- [C],
1230
+ [NUMBER],
1112
1231
  [parseInt(e["content-length"], 10)]
1113
1232
  );
1114
1233
  for (const t in e) {
1115
- let n = "HTTP_";
1116
- ["content-type", "content-length"].includes(t.toLowerCase()) && (n = ""), this.addServerGlobalEntry(
1117
- `${n}${t.toUpperCase().replace(/-/g, "_")}`,
1234
+ let r = "HTTP_";
1235
+ ["content-type", "content-length"].includes(t.toLowerCase()) && (r = ""), this.addServerGlobalEntry(
1236
+ `${r}${t.toUpperCase().replace(/-/g, "_")}`,
1118
1237
  e[t]
1119
1238
  );
1120
1239
  }
1121
- }, Z = new WeakSet(), Se = function(e) {
1122
- this[l].ccall(
1240
+ }, j = new WeakSet(), oe = function(e) {
1241
+ const t = this[__private__dont__use].lengthBytesUTF8(e), r = this[__private__dont__use].malloc(t + 1);
1242
+ if (!r)
1243
+ throw new Error("Could not allocate memory for the request body.");
1244
+ return this[__private__dont__use].stringToUTF8(
1245
+ e,
1246
+ r,
1247
+ t + 1
1248
+ ), this[__private__dont__use].ccall(
1123
1249
  "wasm_set_request_body",
1124
1250
  null,
1125
- [y],
1126
- [e]
1127
- ), this[l].ccall(
1251
+ [NUMBER],
1252
+ [r]
1253
+ ), this[__private__dont__use].ccall(
1128
1254
  "wasm_set_content_length",
1129
1255
  null,
1130
- [C],
1256
+ [NUMBER],
1131
1257
  [new TextEncoder().encode(e).length]
1132
- );
1133
- }, Q = new WeakSet(), xe = function(e) {
1134
- this[l].ccall(
1258
+ ), r;
1259
+ }, z = new WeakSet(), ae = function(e) {
1260
+ this[__private__dont__use].ccall(
1135
1261
  "wasm_set_path_translated",
1136
1262
  null,
1137
- [y],
1263
+ [STRING],
1138
1264
  [e]
1139
1265
  );
1140
- }, X = new WeakSet(), ke = function() {
1141
- for (const e in a(this, _))
1142
- this[l].ccall(
1266
+ }, G = new WeakSet(), le = function() {
1267
+ for (const e in a(this, P))
1268
+ this[__private__dont__use].ccall(
1143
1269
  "wasm_add_SERVER_entry",
1144
1270
  null,
1145
- [y, y],
1146
- [e, a(this, _)[e]]
1271
+ [STRING, STRING],
1272
+ [e, a(this, P)[e]]
1147
1273
  );
1148
- }, ee = new WeakSet(), Fe = function(e) {
1149
- const { key: t, name: n, type: s, data: o } = e, i = `/tmp/${Math.random().toFixed(20)}`;
1150
- this.writeFile(i, o);
1151
- const u = 0;
1152
- this[l].ccall(
1274
+ }, J = new WeakSet(), ce = function(e) {
1275
+ const { key: t, name: r, type: s, data: i } = e, n = `/tmp/${Math.random().toFixed(20)}`;
1276
+ this.writeFile(n, i);
1277
+ const o = 0;
1278
+ this[__private__dont__use].ccall(
1153
1279
  "wasm_add_uploaded_file",
1154
1280
  null,
1155
- [y, y, y, y, C, C],
1156
- [t, n, s, i, u, o.byteLength]
1281
+ [STRING, STRING, STRING, STRING, NUMBER, NUMBER],
1282
+ [t, r, s, n, o, i.byteLength]
1157
1283
  );
1158
- }, te = new WeakSet(), Ce = function(e) {
1159
- this[l].ccall(
1284
+ }, Y = new WeakSet(), ue = function(e) {
1285
+ this[__private__dont__use].ccall(
1160
1286
  "wasm_set_php_code",
1161
1287
  null,
1162
- [y],
1288
+ [STRING],
1163
1289
  [e]
1164
1290
  );
1165
- }, re = new WeakSet(), Ae = async function() {
1166
- var o;
1291
+ }, V = new WeakSet(), de = async function() {
1292
+ var i;
1167
1293
  let e, t;
1168
1294
  try {
1169
- e = await new Promise((i, u) => {
1170
- var f;
1295
+ e = await new Promise((n, o) => {
1296
+ var h;
1171
1297
  t = (p) => {
1172
- const R = new Error("Rethrown");
1173
- R.cause = p.error, R.betterMessage = p.message, u(R);
1174
- }, (f = a(this, F)) == null || f.addEventListener(
1298
+ const u = new Error("Rethrown");
1299
+ u.cause = p.error, u.betterMessage = p.message, o(u);
1300
+ }, (h = a(this, g)) == null || h.addEventListener(
1175
1301
  "error",
1176
1302
  t
1177
1303
  );
1178
- const h = this[l].ccall(
1304
+ const c = this[__private__dont__use].ccall(
1179
1305
  "wasm_sapi_handle_request",
1180
- C,
1306
+ NUMBER,
1181
1307
  [],
1182
1308
  [],
1183
1309
  { async: !0 }
1184
1310
  );
1185
- return h instanceof Promise ? h.then(i, u) : i(h);
1311
+ return c instanceof Promise ? c.then(n, o) : n(c);
1186
1312
  });
1187
- } catch (i) {
1313
+ } catch (n) {
1188
1314
  for (const p in this)
1189
1315
  typeof this[p] == "function" && (this[p] = () => {
1190
1316
  throw new Error(
1191
1317
  "PHP runtime has crashed – see the earlier error for details."
1192
1318
  );
1193
1319
  });
1194
- this.functionsMaybeMissingFromAsyncify = Ue();
1195
- const u = i, h = "betterMessage" in u ? u.betterMessage : u.message, f = new Error(h);
1196
- throw f.cause = u, f;
1320
+ this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1321
+ const o = n, c = "betterMessage" in o ? o.betterMessage : o.message, h = new Error(c);
1322
+ throw h.cause = o, h;
1197
1323
  } finally {
1198
- (o = a(this, F)) == null || o.removeEventListener("error", t), d(this, _, {});
1324
+ (i = a(this, g)) == null || i.removeEventListener("error", t), d(this, P, {});
1199
1325
  }
1200
- const { headers: n, httpStatusCode: s } = m(this, G, Pe).call(this);
1201
- return new A(
1326
+ const { headers: r, httpStatusCode: s } = f(this, U, te).call(this);
1327
+ return new PHPResponse(
1202
1328
  s,
1203
- n,
1329
+ r,
1204
1330
  this.readFileAsBuffer("/tmp/stdout"),
1205
1331
  this.readFileAsText("/tmp/stderr"),
1206
1332
  e
1207
1333
  );
1208
1334
  };
1209
- E([
1210
- b('Could not create directory "{path}"')
1211
- ], P.prototype, "mkdir", 1);
1212
- E([
1213
- b('Could not create directory "{path}"')
1214
- ], P.prototype, "mkdirTree", 1);
1215
- E([
1216
- b('Could not read "{path}"')
1217
- ], P.prototype, "readFileAsText", 1);
1218
- E([
1219
- b('Could not read "{path}"')
1220
- ], P.prototype, "readFileAsBuffer", 1);
1221
- E([
1222
- b('Could not write to "{path}"')
1223
- ], P.prototype, "writeFile", 1);
1224
- E([
1225
- b('Could not unlink "{path}"')
1226
- ], P.prototype, "unlink", 1);
1227
- E([
1228
- b('Could not remove directory "{path}"')
1229
- ], P.prototype, "rmdir", 1);
1230
- E([
1231
- b('Could not list files in "{path}"')
1232
- ], P.prototype, "listFiles", 1);
1233
- E([
1234
- b('Could not stat "{path}"')
1235
- ], P.prototype, "isDir", 1);
1236
- E([
1237
- b('Could not stat "{path}"')
1238
- ], P.prototype, "fileExists", 1);
1239
- function He(r) {
1240
- const e = {};
1241
- for (const t in r)
1242
- e[t.toLowerCase()] = r[t];
1243
- return e;
1335
+ __decorateClass([
1336
+ rethrowFileSystemError('Could not create directory "{path}"')
1337
+ ], BasePHP.prototype, "mkdir", 1);
1338
+ __decorateClass([
1339
+ rethrowFileSystemError('Could not create directory "{path}"')
1340
+ ], BasePHP.prototype, "mkdirTree", 1);
1341
+ __decorateClass([
1342
+ rethrowFileSystemError('Could not read "{path}"')
1343
+ ], BasePHP.prototype, "readFileAsText", 1);
1344
+ __decorateClass([
1345
+ rethrowFileSystemError('Could not read "{path}"')
1346
+ ], BasePHP.prototype, "readFileAsBuffer", 1);
1347
+ __decorateClass([
1348
+ rethrowFileSystemError('Could not write to "{path}"')
1349
+ ], BasePHP.prototype, "writeFile", 1);
1350
+ __decorateClass([
1351
+ rethrowFileSystemError('Could not unlink "{path}"')
1352
+ ], BasePHP.prototype, "unlink", 1);
1353
+ __decorateClass([
1354
+ rethrowFileSystemError('Could not remove directory "{path}"')
1355
+ ], BasePHP.prototype, "rmdir", 1);
1356
+ __decorateClass([
1357
+ rethrowFileSystemError('Could not list files in "{path}"')
1358
+ ], BasePHP.prototype, "listFiles", 1);
1359
+ __decorateClass([
1360
+ rethrowFileSystemError('Could not stat "{path}"')
1361
+ ], BasePHP.prototype, "isDir", 1);
1362
+ __decorateClass([
1363
+ rethrowFileSystemError('Could not stat "{path}"')
1364
+ ], BasePHP.prototype, "fileExists", 1);
1365
+ function normalizeHeaders(e) {
1366
+ const t = {};
1367
+ for (const r in e)
1368
+ t[r.toLowerCase()] = e[r];
1369
+ return t;
1370
+ }
1371
+ function recreateMemFS(e, t, r) {
1372
+ let s;
1373
+ try {
1374
+ s = t.lookupPath(r);
1375
+ } catch {
1376
+ return;
1377
+ }
1378
+ if (!("contents" in s.node))
1379
+ return;
1380
+ try {
1381
+ e = e.lookupPath(r);
1382
+ return;
1383
+ } catch {
1384
+ }
1385
+ if (!t.isDir(s.node.mode)) {
1386
+ e.writeFile(r, t.readFile(r));
1387
+ return;
1388
+ }
1389
+ e.mkdirTree(r);
1390
+ const i = t.readdir(r).filter((n) => n !== "." && n !== "..");
1391
+ for (const n of i)
1392
+ recreateMemFS(e, t, joinPaths(r, n));
1244
1393
  }
1245
- function pt(r, e, t = () => {
1394
+ function journalFSEvents(e, t, r = () => {
1246
1395
  }) {
1247
- e = lt(e);
1248
- const n = r[l].FS, s = at(n, (h) => {
1249
- if (h.path.startsWith(e))
1250
- t(h);
1251
- else if (h.operation === "RENAME" && h.toPath.startsWith(e))
1252
- for (const f of Oe(
1253
- r,
1254
- h.path,
1255
- h.toPath
1256
- ))
1257
- t(f);
1258
- }), o = {};
1259
- for (const [h] of Object.entries(s))
1260
- o[h] = n[h];
1261
- function i() {
1262
- for (const [h, f] of Object.entries(s))
1263
- n[h] = function(...p) {
1264
- return f(...p), o[h].apply(this, p);
1265
- };
1396
+ function s() {
1397
+ t = normalizePath(t);
1398
+ const n = e[__private__dont__use].FS, o = createFSHooks(n, (u) => {
1399
+ if (u.path.startsWith(t))
1400
+ r(u);
1401
+ else if (u.operation === "RENAME" && u.toPath.startsWith(t))
1402
+ for (const _ of recordExistingPath(
1403
+ e,
1404
+ u.path,
1405
+ u.toPath
1406
+ ))
1407
+ r(_);
1408
+ }), c = {};
1409
+ for (const [u] of Object.entries(o))
1410
+ c[u] = n[u];
1411
+ function h() {
1412
+ for (const [u, _] of Object.entries(o))
1413
+ n[u] = function(...v) {
1414
+ return _(...v), c[u].apply(this, v);
1415
+ };
1416
+ }
1417
+ function p() {
1418
+ for (const [u, _] of Object.entries(c))
1419
+ e[__private__dont__use].FS[u] = _;
1420
+ }
1421
+ e[__private__dont__use].journal = {
1422
+ bind: h,
1423
+ unbind: p
1424
+ }, h();
1266
1425
  }
1267
- function u() {
1268
- for (const [h, f] of Object.entries(o))
1269
- r[l].FS[h] = f;
1426
+ e.addEventListener("runtime.initialized", s), e[__private__dont__use] && s();
1427
+ function i() {
1428
+ e[__private__dont__use].journal.unbind(), delete e[__private__dont__use].journal;
1270
1429
  }
1271
- return r[l].journal = {
1272
- bind: i,
1273
- unbind: u
1274
- }, i(), u;
1430
+ return e.addEventListener("runtime.beforedestroy", i), function() {
1431
+ return e.removeEventListener("runtime.initialized", s), e.removeEventListener("runtime.beforedestroy", i), e[__private__dont__use].journal.unbind();
1432
+ };
1275
1433
  }
1276
- const at = (r, e = () => {
1434
+ const createFSHooks = (e, t = () => {
1277
1435
  }) => ({
1278
- write(t) {
1279
- e({
1436
+ write(r) {
1437
+ t({
1280
1438
  operation: "WRITE",
1281
- path: t.path,
1439
+ path: r.path,
1282
1440
  nodeType: "file"
1283
1441
  });
1284
1442
  },
1285
- truncate(t) {
1286
- let n;
1287
- typeof t == "string" ? n = r.lookupPath(t, {
1443
+ truncate(r) {
1444
+ let s;
1445
+ typeof r == "string" ? s = e.lookupPath(r, {
1288
1446
  follow: !0
1289
- }).node : n = t, e({
1447
+ }).node : s = r, t({
1290
1448
  operation: "WRITE",
1291
- path: r.getPath(n),
1449
+ path: e.getPath(s),
1292
1450
  nodeType: "file"
1293
1451
  });
1294
1452
  },
1295
- unlink(t) {
1296
- e({
1453
+ unlink(r) {
1454
+ t({
1297
1455
  operation: "DELETE",
1298
- path: t,
1456
+ path: r,
1299
1457
  nodeType: "file"
1300
1458
  });
1301
1459
  },
1302
- mknod(t, n) {
1303
- r.isFile(n) && e({
1460
+ mknod(r, s) {
1461
+ e.isFile(s) && t({
1304
1462
  operation: "CREATE",
1305
- path: t,
1463
+ path: r,
1306
1464
  nodeType: "file"
1307
1465
  });
1308
1466
  },
1309
- mkdir(t) {
1310
- e({
1467
+ mkdir(r) {
1468
+ t({
1311
1469
  operation: "CREATE",
1312
- path: t,
1470
+ path: r,
1313
1471
  nodeType: "directory"
1314
1472
  });
1315
1473
  },
1316
- rmdir(t) {
1317
- e({
1474
+ rmdir(r) {
1475
+ t({
1318
1476
  operation: "DELETE",
1319
- path: t,
1477
+ path: r,
1320
1478
  nodeType: "directory"
1321
1479
  });
1322
1480
  },
1323
- rename(t, n) {
1481
+ rename(r, s) {
1324
1482
  try {
1325
- const s = r.lookupPath(t, {
1483
+ const i = e.lookupPath(r, {
1326
1484
  follow: !0
1327
- }), o = r.lookupPath(n, {
1485
+ }), n = e.lookupPath(s, {
1328
1486
  parent: !0
1329
1487
  }).path;
1330
- e({
1488
+ t({
1331
1489
  operation: "RENAME",
1332
- nodeType: r.isDir(s.node.mode) ? "directory" : "file",
1333
- path: s.path,
1334
- toPath: B(o, ze(n))
1490
+ nodeType: e.isDir(i.node.mode) ? "directory" : "file",
1491
+ path: i.path,
1492
+ toPath: joinPaths(n, basename(s))
1335
1493
  });
1336
1494
  } catch {
1337
1495
  }
1338
1496
  }
1339
1497
  });
1340
- function mt(r, e) {
1341
- r[l].journal.unbind();
1498
+ function replayFSJournal(e, t) {
1499
+ e[__private__dont__use].journal.unbind();
1342
1500
  try {
1343
- for (const t of e)
1344
- t.operation === "CREATE" ? t.nodeType === "file" ? r.writeFile(t.path, " ") : r.mkdir(t.path) : t.operation === "DELETE" ? t.nodeType === "file" ? r.unlink(t.path) : r.rmdir(t.path) : t.operation === "WRITE" ? r.writeFile(t.path, t.data) : t.operation === "RENAME" && r.mv(t.path, t.toPath);
1501
+ for (const r of t)
1502
+ r.operation === "CREATE" ? r.nodeType === "file" ? e.writeFile(r.path, " ") : e.mkdir(r.path) : r.operation === "DELETE" ? r.nodeType === "file" ? e.unlink(r.path) : e.rmdir(r.path) : r.operation === "WRITE" ? e.writeFile(r.path, r.data) : r.operation === "RENAME" && e.mv(r.path, r.toPath);
1345
1503
  } finally {
1346
- r[l].journal.bind();
1504
+ e[__private__dont__use].journal.bind();
1347
1505
  }
1348
1506
  }
1349
- function* Oe(r, e, t) {
1350
- if (r.isDir(e)) {
1507
+ function* recordExistingPath(e, t, r) {
1508
+ if (e.isDir(t)) {
1351
1509
  yield {
1352
1510
  operation: "CREATE",
1353
- path: t,
1511
+ path: r,
1354
1512
  nodeType: "directory"
1355
1513
  };
1356
- for (const n of r.listFiles(e))
1357
- yield* Oe(
1358
- r,
1359
- B(e, n),
1360
- B(t, n)
1514
+ for (const s of e.listFiles(t))
1515
+ yield* recordExistingPath(
1516
+ e,
1517
+ joinPaths(t, s),
1518
+ joinPaths(r, s)
1361
1519
  );
1362
1520
  } else
1363
1521
  yield {
1364
1522
  operation: "CREATE",
1365
- path: t,
1523
+ path: r,
1366
1524
  nodeType: "file"
1367
1525
  }, yield {
1368
1526
  operation: "WRITE",
1369
1527
  nodeType: "file",
1370
- path: t
1528
+ path: r
1371
1529
  };
1372
1530
  }
1373
- function lt(r) {
1374
- return r.replace(/\/$/, "").replace(/\/\/+/g, "/");
1531
+ function normalizePath(e) {
1532
+ return e.replace(/\/$/, "").replace(/\/\/+/g, "/");
1375
1533
  }
1376
- function ct(r) {
1377
- const e = {};
1378
- for (let t = r.length - 1; t >= 0; t--) {
1379
- for (let n = t - 1; n >= 0; n--) {
1380
- const s = ut(r[t], r[n]);
1381
- if (s === "none")
1534
+ function normalizeFilesystemOperations(e) {
1535
+ const t = {};
1536
+ for (let r = e.length - 1; r >= 0; r--) {
1537
+ for (let s = r - 1; s >= 0; s--) {
1538
+ const i = checkRelationship(e[r], e[s]);
1539
+ if (i === "none")
1382
1540
  continue;
1383
- const o = r[t], i = r[n];
1384
- if (o.operation === "RENAME" && i.operation === "RENAME") {
1541
+ const n = e[r], o = e[s];
1542
+ if (n.operation === "RENAME" && o.operation === "RENAME") {
1385
1543
  console.warn(
1386
1544
  "[FS Journal] Normalizing a double rename is not yet supported:",
1387
1545
  {
1388
- current: o,
1389
- last: i
1546
+ current: n,
1547
+ last: o
1390
1548
  }
1391
1549
  );
1392
1550
  continue;
1393
1551
  }
1394
- (i.operation === "CREATE" || i.operation === "WRITE") && (o.operation === "RENAME" ? s === "same_node" ? (e[n] = [], e[t] = [
1552
+ (o.operation === "CREATE" || o.operation === "WRITE") && (n.operation === "RENAME" ? i === "same_node" ? (t[s] = [], t[r] = [
1395
1553
  {
1396
- ...i,
1397
- path: o.toPath
1554
+ ...o,
1555
+ path: n.toPath
1398
1556
  },
1399
- ...e[t] || []
1400
- ]) : s === "descendant" && (e[n] = [], e[t] = [
1557
+ ...t[r] || []
1558
+ ]) : i === "descendant" && (t[s] = [], t[r] = [
1401
1559
  {
1402
- ...i,
1403
- path: B(
1404
- o.toPath,
1405
- i.path.substring(o.path.length)
1560
+ ...o,
1561
+ path: joinPaths(
1562
+ n.toPath,
1563
+ o.path.substring(n.path.length)
1406
1564
  )
1407
1565
  },
1408
- ...e[t] || []
1409
- ]) : o.operation === "WRITE" && s === "same_node" ? e[n] = [] : o.operation === "DELETE" && s === "same_node" && (e[n] = [], e[t] = []));
1566
+ ...t[r] || []
1567
+ ]) : n.operation === "WRITE" && i === "same_node" ? t[s] = [] : n.operation === "DELETE" && i === "same_node" && (t[s] = [], t[r] = []));
1410
1568
  }
1411
- if (Object.entries(e).length > 0) {
1412
- const n = r.flatMap((s, o) => o in e ? e[o] : [s]);
1413
- return ct(n);
1569
+ if (Object.entries(t).length > 0) {
1570
+ const s = e.flatMap((i, n) => n in t ? t[n] : [i]);
1571
+ return normalizeFilesystemOperations(s);
1414
1572
  }
1415
1573
  }
1416
- return r;
1574
+ return e;
1417
1575
  }
1418
- function ut(r, e) {
1419
- const t = r.path, n = r.operation !== "WRITE" && r.nodeType === "directory", s = e.operation !== "WRITE" && e.nodeType === "directory", o = e.operation === "RENAME" ? e.toPath : e.path;
1420
- return o === t ? "same_node" : s && t.startsWith(o + "/") ? "ancestor" : n && o.startsWith(t + "/") ? "descendant" : "none";
1576
+ function checkRelationship(e, t) {
1577
+ const r = e.path, s = e.operation !== "WRITE" && e.nodeType === "directory", i = t.operation !== "WRITE" && t.nodeType === "directory", n = t.operation === "RENAME" ? t.toPath : t.path;
1578
+ return n === r ? "same_node" : i && r.startsWith(n + "/") ? "ancestor" : s && n.startsWith(r + "/") ? "descendant" : "none";
1421
1579
  }
1422
- async function yt(r, e) {
1423
- const n = e.filter(
1424
- (s) => s.operation === "WRITE"
1425
- ).map((s) => dt(r, s));
1426
- return await Promise.all(n), e;
1580
+ async function hydrateUpdateFileOps(e, t) {
1581
+ const s = t.filter(
1582
+ (i) => i.operation === "WRITE"
1583
+ ).map((i) => hydrateOp(e, i));
1584
+ return await Promise.all(s), t;
1427
1585
  }
1428
- const ht = new ie({ concurrency: 15 });
1429
- async function dt(r, e) {
1430
- const t = await ht.acquire();
1586
+ const hydrateLock = new Semaphore({ concurrency: 15 });
1587
+ async function hydrateOp(e, t) {
1588
+ const r = await hydrateLock.acquire();
1431
1589
  try {
1432
- e.data = await r.readFileAsBuffer(e.path);
1433
- } catch (n) {
1590
+ t.data = await e.readFileAsBuffer(t.path);
1591
+ } catch (s) {
1434
1592
  console.warn(
1435
- `Journal failed to hydrate a file on flush: the path ${e.path} no longer exists`
1436
- ), console.error(n);
1593
+ `Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`
1594
+ ), console.error(s);
1437
1595
  }
1438
- t();
1596
+ r();
1439
1597
  }
1440
1598
  export {
1441
- yt as hydrateUpdateFileOps,
1442
- pt as journalFSEvents,
1443
- ct as normalizeFilesystemOperations,
1444
- mt as replayFSJournal
1599
+ hydrateUpdateFileOps,
1600
+ journalFSEvents,
1601
+ normalizeFilesystemOperations,
1602
+ replayFSJournal
1445
1603
  };