@php-wasm/fs-journal 0.5.6 → 0.6.1

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