@php-wasm/fs-journal 0.7.19 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,155 +1,230 @@
1
- var D = (e, t, r) => {
2
- if (!t.has(e))
3
- throw TypeError("Cannot " + r);
4
- };
5
- var h = (e, t, r) => (D(e, t, "read from private field"), r ? r.call(e) : t.get(e)), u = (e, t, r) => {
6
- if (t.has(e))
7
- throw TypeError("Cannot add the same private member more than once");
8
- t instanceof WeakSet ? t.add(e) : t.set(e, r);
9
- }, f = (e, t, r, s) => (D(e, t, "write to private field"), s ? s.call(e, r) : t.set(e, r), r);
10
- var p = (e, t, r) => (D(e, t, "access private method"), r);
11
- const currentJsRuntime = function() {
12
- var e;
13
- return typeof process < "u" && ((e = process.release) == null ? void 0 : e.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : (
1
+ const C = function() {
2
+ var r;
3
+ return typeof process < "u" && ((r = process.release) == null ? void 0 : r.name) === "node" ? "NODE" : typeof window < "u" ? "WEB" : (
14
4
  // @ts-ignore
15
5
  typeof WorkerGlobalScope < "u" && // @ts-ignore
16
6
  self instanceof WorkerGlobalScope ? "WORKER" : "NODE"
17
7
  );
18
8
  }();
19
- if (currentJsRuntime === "NODE") {
20
- let e = function(r) {
21
- return new Promise(function(s, i) {
22
- r.onload = r.onerror = function(n) {
23
- r.onload = r.onerror = null, n.type === "load" ? s(r.result) : i(new Error("Failed to read the blob/file"));
9
+ if (C === "NODE") {
10
+ let r = function(t) {
11
+ return new Promise(function(o, n) {
12
+ t.onload = t.onerror = function(i) {
13
+ t.onload = t.onerror = null, i.type === "load" ? o(t.result) : n(new Error("Failed to read the blob/file"));
24
14
  };
25
15
  });
26
- }, t = function() {
27
- const r = new Uint8Array([1, 2, 3, 4]), i = new File([r], "test").stream();
16
+ }, e = function() {
17
+ const t = new Uint8Array([1, 2, 3, 4]), n = new File([t], "test").stream();
28
18
  try {
29
- return i.getReader({ mode: "byob" }), !0;
19
+ return n.getReader({ mode: "byob" }), !0;
30
20
  } catch {
31
21
  return !1;
32
22
  }
33
23
  };
34
24
  if (typeof File > "u") {
35
- class r extends Blob {
36
- constructor(i, n, o) {
37
- super(i);
25
+ class t extends Blob {
26
+ constructor(n, i, s) {
27
+ super(n);
38
28
  let a;
39
- o != null && o.lastModified && (a = /* @__PURE__ */ new Date()), (!a || isNaN(a.getFullYear())) && (a = /* @__PURE__ */ new Date()), this.lastModifiedDate = a, this.lastModified = a.getMilliseconds(), this.name = n || "";
29
+ s != null && s.lastModified && (a = /* @__PURE__ */ new Date()), (!a || isNaN(a.getFullYear())) && (a = /* @__PURE__ */ new Date()), this.lastModifiedDate = a, this.lastModified = a.getMilliseconds(), this.name = i || "";
40
30
  }
41
31
  }
42
- global.File = r;
32
+ global.File = t;
43
33
  }
44
34
  typeof Blob.prototype.arrayBuffer > "u" && (Blob.prototype.arrayBuffer = function() {
45
- const s = new FileReader();
46
- return s.readAsArrayBuffer(this), e(s);
35
+ const o = new FileReader();
36
+ return o.readAsArrayBuffer(this), r(o);
47
37
  }), typeof Blob.prototype.text > "u" && (Blob.prototype.text = function() {
48
- const s = new FileReader();
49
- return s.readAsText(this), e(s);
50
- }), (typeof Blob.prototype.stream > "u" || !t()) && (Blob.prototype.stream = function() {
51
- let r = 0;
52
- const s = this;
38
+ const o = new FileReader();
39
+ return o.readAsText(this), r(o);
40
+ }), (typeof Blob.prototype.stream > "u" || !e()) && (Blob.prototype.stream = function() {
41
+ let t = 0;
42
+ const o = this;
53
43
  return new ReadableStream({
54
44
  type: "bytes",
55
45
  // 0.5 MB seems like a reasonable chunk size, let's adjust
56
46
  // this if needed.
57
47
  autoAllocateChunkSize: 512 * 1024,
58
- async pull(i) {
59
- const n = i.byobRequest.view, a = await s.slice(
60
- r,
61
- r + n.byteLength
62
- ).arrayBuffer(), l = new Uint8Array(a);
63
- new Uint8Array(n.buffer).set(l);
64
- const c = l.byteLength;
65
- i.byobRequest.respond(c), r += c, r >= s.size && i.close();
48
+ async pull(n) {
49
+ const i = n.byobRequest.view, a = await o.slice(
50
+ t,
51
+ t + i.byteLength
52
+ ).arrayBuffer(), m = new Uint8Array(a);
53
+ new Uint8Array(i.buffer).set(m);
54
+ const h = m.byteLength;
55
+ n.byobRequest.respond(h), t += h, t >= o.size && n.close();
66
56
  }
67
57
  });
68
58
  });
69
59
  }
70
- if (currentJsRuntime === "NODE" && typeof CustomEvent > "u") {
71
- class e extends Event {
72
- constructor(r, s = {}) {
73
- super(r, s), this.detail = s.detail;
60
+ if (C === "NODE" && typeof CustomEvent > "u") {
61
+ class r extends Event {
62
+ constructor(t, o = {}) {
63
+ super(t, o), this.detail = o.detail;
74
64
  }
75
65
  initCustomEvent() {
76
66
  }
77
67
  }
78
- globalThis.CustomEvent = e;
79
- }
80
- const kError = Symbol("error"), kMessage = Symbol("message");
81
- class ErrorEvent2 extends Event {
82
- /**
83
- * Create a new `ErrorEvent`.
84
- *
85
- * @param type The name of the event
86
- * @param options A dictionary object that allows for setting
87
- * attributes via object members of the same name.
88
- */
89
- constructor(t, r = {}) {
90
- super(t), this[kError] = r.error === void 0 ? null : r.error, this[kMessage] = r.message === void 0 ? "" : r.message;
91
- }
92
- get error() {
93
- return this[kError];
94
- }
95
- get message() {
96
- return this[kMessage];
97
- }
68
+ globalThis.CustomEvent = r;
98
69
  }
99
- Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: !0 });
100
- Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: !0 });
101
- const ErrorEvent = typeof globalThis.ErrorEvent == "function" ? globalThis.ErrorEvent : ErrorEvent2;
102
- function isExitCodeZero(e) {
103
- 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;
70
+ const E = {
71
+ 0: "No error occurred. System call completed successfully.",
72
+ 1: "Argument list too long.",
73
+ 2: "Permission denied.",
74
+ 3: "Address in use.",
75
+ 4: "Address not available.",
76
+ 5: "Address family not supported.",
77
+ 6: "Resource unavailable, or operation would block.",
78
+ 7: "Connection already in progress.",
79
+ 8: "Bad file descriptor.",
80
+ 9: "Bad message.",
81
+ 10: "Device or resource busy.",
82
+ 11: "Operation canceled.",
83
+ 12: "No child processes.",
84
+ 13: "Connection aborted.",
85
+ 14: "Connection refused.",
86
+ 15: "Connection reset.",
87
+ 16: "Resource deadlock would occur.",
88
+ 17: "Destination address required.",
89
+ 18: "Mathematics argument out of domain of function.",
90
+ 19: "Reserved.",
91
+ 20: "File exists.",
92
+ 21: "Bad address.",
93
+ 22: "File too large.",
94
+ 23: "Host is unreachable.",
95
+ 24: "Identifier removed.",
96
+ 25: "Illegal byte sequence.",
97
+ 26: "Operation in progress.",
98
+ 27: "Interrupted function.",
99
+ 28: "Invalid argument.",
100
+ 29: "I/O error.",
101
+ 30: "Socket is connected.",
102
+ 31: "There is a directory under that path.",
103
+ 32: "Too many levels of symbolic links.",
104
+ 33: "File descriptor value too large.",
105
+ 34: "Too many links.",
106
+ 35: "Message too large.",
107
+ 36: "Reserved.",
108
+ 37: "Filename too long.",
109
+ 38: "Network is down.",
110
+ 39: "Connection aborted by network.",
111
+ 40: "Network unreachable.",
112
+ 41: "Too many files open in system.",
113
+ 42: "No buffer space available.",
114
+ 43: "No such device.",
115
+ 44: "There is no such file or directory OR the parent directory does not exist.",
116
+ 45: "Executable file format error.",
117
+ 46: "No locks available.",
118
+ 47: "Reserved.",
119
+ 48: "Not enough space.",
120
+ 49: "No message of the desired type.",
121
+ 50: "Protocol not available.",
122
+ 51: "No space left on device.",
123
+ 52: "Function not supported.",
124
+ 53: "The socket is not connected.",
125
+ 54: "Not a directory or a symbolic link to a directory.",
126
+ 55: "Directory not empty.",
127
+ 56: "State not recoverable.",
128
+ 57: "Not a socket.",
129
+ 58: "Not supported, or operation not supported on socket.",
130
+ 59: "Inappropriate I/O control operation.",
131
+ 60: "No such device or address.",
132
+ 61: "Value too large to be stored in data type.",
133
+ 62: "Previous owner died.",
134
+ 63: "Operation not permitted.",
135
+ 64: "Broken pipe.",
136
+ 65: "Protocol error.",
137
+ 66: "Protocol not supported.",
138
+ 67: "Protocol wrong type for socket.",
139
+ 68: "Result too large.",
140
+ 69: "Read-only file system.",
141
+ 70: "Invalid seek.",
142
+ 71: "No such process.",
143
+ 72: "Reserved.",
144
+ 73: "Connection timed out.",
145
+ 74: "Text file busy.",
146
+ 75: "Cross-device link.",
147
+ 76: "Extension: Capabilities insufficient."
148
+ };
149
+ function O(r) {
150
+ const e = typeof r == "object" ? r == null ? void 0 : r.errno : null;
151
+ if (e in E)
152
+ return E[e];
153
+ }
154
+ function u(r = "") {
155
+ return function(t, o, n) {
156
+ const i = n.value;
157
+ n.value = function(...s) {
158
+ try {
159
+ return i.apply(this, s);
160
+ } catch (a) {
161
+ const m = typeof a == "object" ? a == null ? void 0 : a.errno : null;
162
+ if (m in E) {
163
+ const h = E[m], l = typeof s[1] == "string" ? s[1] : null, y = l !== null ? r.replaceAll("{path}", l) : r;
164
+ throw new Error(`${y}: ${h}`, {
165
+ cause: a
166
+ });
167
+ }
168
+ throw a;
169
+ }
170
+ };
171
+ };
104
172
  }
105
- const logToConsole = (e, ...t) => {
106
- switch (e.severity) {
173
+ const x = "playground-log", R = (r, ...e) => {
174
+ b.dispatchEvent(
175
+ new CustomEvent(x, {
176
+ detail: {
177
+ log: r,
178
+ args: e
179
+ }
180
+ })
181
+ );
182
+ }, I = (r, ...e) => {
183
+ switch (typeof r.message == "string" ? r.message = w(r.message) : r.message.message && typeof r.message.message == "string" && (r.message.message = w(r.message.message)), r.severity) {
107
184
  case "Debug":
108
- console.debug(e.message, ...t);
185
+ console.debug(r.message, ...e);
109
186
  break;
110
187
  case "Info":
111
- console.info(e.message, ...t);
188
+ console.info(r.message, ...e);
112
189
  break;
113
190
  case "Warn":
114
- console.warn(e.message, ...t);
191
+ console.warn(r.message, ...e);
115
192
  break;
116
193
  case "Error":
117
- console.error(e.message, ...t);
194
+ console.error(r.message, ...e);
118
195
  break;
119
196
  case "Fatal":
120
- console.error(e.message, ...t);
197
+ console.error(r.message, ...e);
121
198
  break;
122
199
  default:
123
- console.log(e.message, ...t);
124
- }
125
- }, prepareLogMessage = (e, ...t) => [
126
- typeof e == "object" ? JSON.stringify(e) : e,
127
- ...t.map((r) => JSON.stringify(r))
128
- ].join(" "), logs = [], addToLogArray = (e) => {
129
- logs.push(e);
130
- }, logToMemory = (e) => {
131
- if (e.raw === !0)
132
- addToLogArray(e.message);
200
+ console.log(r.message, ...e);
201
+ }
202
+ }, B = (r) => r instanceof Error ? [r.message, r.stack].join(`
203
+ `) : JSON.stringify(r, null, 2), N = [], A = (r) => {
204
+ N.push(r);
205
+ }, v = (r) => {
206
+ if (r.raw === !0)
207
+ A(r.message);
133
208
  else {
134
- const t = formatLogEntry(
135
- typeof e.message == "object" ? prepareLogMessage(e.message) : e.message,
136
- e.severity ?? "Info",
137
- e.prefix ?? "JavaScript"
209
+ const e = W(
210
+ typeof r.message == "object" ? B(r.message) : r.message,
211
+ r.severity ?? "Info",
212
+ r.prefix ?? "JavaScript"
138
213
  );
139
- addToLogArray(t);
214
+ A(e);
140
215
  }
141
216
  };
142
- class Logger extends EventTarget {
217
+ class P extends EventTarget {
143
218
  // constructor
144
- constructor(t = []) {
145
- super(), this.handlers = t, this.fatalErrorEvent = "playground-fatal-error";
219
+ constructor(e = []) {
220
+ super(), this.handlers = e, this.fatalErrorEvent = "playground-fatal-error";
146
221
  }
147
222
  /**
148
223
  * Get all logs.
149
224
  * @returns string[]
150
225
  */
151
226
  getLogs() {
152
- return this.handlers.includes(logToMemory) ? [...logs] : (this.error(`Logs aren't stored because the logToMemory handler isn't registered.
227
+ return this.handlers.includes(v) ? [...N] : (this.error(`Logs aren't stored because the logToMemory handler isn't registered.
153
228
  If you're using a custom logger instance, make sure to register logToMemory handler.
154
229
  `), []);
155
230
  }
@@ -161,9 +236,9 @@ class Logger extends EventTarget {
161
236
  * @param raw boolean
162
237
  * @param args any
163
238
  */
164
- logMessage(t, ...r) {
165
- for (const s of this.handlers)
166
- s(t, ...r);
239
+ logMessage(e, ...t) {
240
+ for (const o of this.handlers)
241
+ o(e, ...t);
167
242
  }
168
243
  /**
169
244
  * Log message
@@ -171,15 +246,15 @@ class Logger extends EventTarget {
171
246
  * @param message any
172
247
  * @param args any
173
248
  */
174
- log(t, ...r) {
249
+ log(e, ...t) {
175
250
  this.logMessage(
176
251
  {
177
- message: t,
252
+ message: e,
178
253
  severity: void 0,
179
254
  prefix: "JavaScript",
180
255
  raw: !1
181
256
  },
182
- ...r
257
+ ...t
183
258
  );
184
259
  }
185
260
  /**
@@ -188,15 +263,15 @@ class Logger extends EventTarget {
188
263
  * @param message any
189
264
  * @param args any
190
265
  */
191
- debug(t, ...r) {
266
+ debug(e, ...t) {
192
267
  this.logMessage(
193
268
  {
194
- message: t,
269
+ message: e,
195
270
  severity: "Debug",
196
271
  prefix: "JavaScript",
197
272
  raw: !1
198
273
  },
199
- ...r
274
+ ...t
200
275
  );
201
276
  }
202
277
  /**
@@ -205,15 +280,15 @@ class Logger extends EventTarget {
205
280
  * @param message any
206
281
  * @param args any
207
282
  */
208
- info(t, ...r) {
283
+ info(e, ...t) {
209
284
  this.logMessage(
210
285
  {
211
- message: t,
286
+ message: e,
212
287
  severity: "Info",
213
288
  prefix: "JavaScript",
214
289
  raw: !1
215
290
  },
216
- ...r
291
+ ...t
217
292
  );
218
293
  }
219
294
  /**
@@ -222,15 +297,15 @@ class Logger extends EventTarget {
222
297
  * @param message any
223
298
  * @param args any
224
299
  */
225
- warn(t, ...r) {
300
+ warn(e, ...t) {
226
301
  this.logMessage(
227
302
  {
228
- message: t,
303
+ message: e,
229
304
  severity: "Warn",
230
305
  prefix: "JavaScript",
231
306
  raw: !1
232
307
  },
233
- ...r
308
+ ...t
234
309
  );
235
310
  }
236
311
  /**
@@ -239,172 +314,54 @@ class Logger extends EventTarget {
239
314
  * @param message any
240
315
  * @param args any
241
316
  */
242
- error(t, ...r) {
317
+ error(e, ...t) {
243
318
  this.logMessage(
244
319
  {
245
- message: t,
320
+ message: e,
246
321
  severity: "Error",
247
322
  prefix: "JavaScript",
248
323
  raw: !1
249
324
  },
250
- ...r
325
+ ...t
251
326
  );
252
327
  }
253
328
  }
254
- const logger = new Logger([logToMemory, logToConsole]), formatLogEntry = (e, t, r) => {
255
- const s = /* @__PURE__ */ new Date(), i = new Intl.DateTimeFormat("en-GB", {
329
+ const M = () => {
330
+ try {
331
+ if (process.env.NODE_ENV === "test")
332
+ return [v, R];
333
+ } catch {
334
+ }
335
+ return [v, I, R];
336
+ }, b = new P(M()), w = (r) => r.replace(/\t/g, ""), W = (r, e, t) => {
337
+ const o = /* @__PURE__ */ new Date(), n = new Intl.DateTimeFormat("en-GB", {
256
338
  year: "numeric",
257
339
  month: "short",
258
340
  day: "2-digit",
259
341
  timeZone: "UTC"
260
- }).format(s).replace(/ /g, "-"), n = new Intl.DateTimeFormat("en-GB", {
342
+ }).format(o).replace(/ /g, "-"), i = new Intl.DateTimeFormat("en-GB", {
261
343
  hour: "2-digit",
262
344
  minute: "2-digit",
263
345
  second: "2-digit",
264
346
  hour12: !1,
265
347
  timeZone: "UTC",
266
348
  timeZoneName: "short"
267
- }).format(s);
268
- return `[${i + " " + n}] ${r} ${t}: ${e}`;
269
- };
270
- class UnhandledRejectionsTarget extends EventTarget {
271
- constructor() {
272
- super(...arguments), this.listenersCount = 0;
273
- }
274
- addEventListener(t, r) {
275
- ++this.listenersCount, super.addEventListener(t, r);
276
- }
277
- removeEventListener(t, r) {
278
- --this.listenersCount, super.removeEventListener(t, r);
279
- }
280
- hasListeners() {
281
- return this.listenersCount > 0;
282
- }
283
- }
284
- function improveWASMErrorReporting(e) {
285
- e.asm = {
286
- ...e.asm
287
- };
288
- const t = new UnhandledRejectionsTarget();
289
- for (const r in e.asm)
290
- if (typeof e.asm[r] == "function") {
291
- const s = e.asm[r];
292
- e.asm[r] = function(...i) {
293
- var n;
294
- try {
295
- return s(...i);
296
- } catch (o) {
297
- if (!(o instanceof Error))
298
- throw o;
299
- const a = clarifyErrorMessage(
300
- o,
301
- (n = e.lastAsyncifyStackSource) == null ? void 0 : n.stack
302
- );
303
- if (e.lastAsyncifyStackSource && (o.cause = e.lastAsyncifyStackSource), t.hasListeners()) {
304
- t.dispatchEvent(
305
- new ErrorEvent("error", {
306
- error: o,
307
- message: a
308
- })
309
- );
310
- return;
311
- }
312
- throw isExitCodeZero(o) || showCriticalErrorBox(a), o;
313
- }
314
- };
315
- }
316
- return t;
317
- }
318
- let functionsMaybeMissingFromAsyncify = [];
319
- function getFunctionsMaybeMissingFromAsyncify() {
320
- return functionsMaybeMissingFromAsyncify;
321
- }
322
- function clarifyErrorMessage(e, t) {
323
- if (e.message === "unreachable") {
324
- let r = UNREACHABLE_ERROR;
325
- t || (r += `
326
-
327
- This stack trace is lacking. For a better one initialize
328
- the PHP runtime with { debug: true }, e.g. PHPNode.load('8.1', { debug: true }).
329
-
330
- `), functionsMaybeMissingFromAsyncify = extractPHPFunctionsFromStack(
331
- t || e.stack || ""
332
- );
333
- for (const s of functionsMaybeMissingFromAsyncify)
334
- r += ` * ${s}
335
- `;
336
- return r;
337
- }
338
- return e.message;
339
- }
340
- const UNREACHABLE_ERROR = `
341
- "unreachable" WASM instruction executed.
342
-
343
- The typical reason is a PHP function missing from the ASYNCIFY_ONLY
344
- list when building PHP.wasm.
345
-
346
- You will need to file a new issue in the WordPress Playground repository
347
- and paste this error message there:
348
-
349
- https://github.com/WordPress/wordpress-playground/issues/new
350
-
351
- If you're a core developer, the typical fix is to:
352
-
353
- * Isolate a minimal reproduction of the error
354
- * Add a reproduction of the error to php-asyncify.spec.ts in the WordPress Playground repository
355
- * Run 'npm run fix-asyncify'
356
- * Commit the changes, push to the repo, release updated NPM packages
357
-
358
- Below is a list of all the PHP functions found in the stack trace to
359
- help with the minimal reproduction. If they're all already listed in
360
- the Dockerfile, you'll need to trigger this error again with long stack
361
- traces enabled. In node.js, you can do it using the --stack-trace-limit=100
362
- CLI option:
363
-
364
- `, redBg = "\x1B[41m", bold = "\x1B[1m", reset = "\x1B[0m", eol = "\x1B[K";
365
- let logged = !1;
366
- function showCriticalErrorBox(e) {
367
- if (!logged && (logged = !0, !(e != null && e.trim().startsWith("Program terminated with exit")))) {
368
- logger.log(`${redBg}
369
- ${eol}
370
- ${bold} WASM ERROR${reset}${redBg}`);
371
- for (const t of e.split(`
372
- `))
373
- logger.log(`${eol} ${t} `);
374
- logger.log(`${reset}`);
375
- }
376
- }
377
- function extractPHPFunctionsFromStack(e) {
378
- try {
379
- const t = e.split(`
380
- `).slice(1).map((r) => {
381
- const s = r.trim().substring(3).split(" ");
382
- return {
383
- fn: s.length >= 2 ? s[0] : "<unknown>",
384
- isWasm: r.includes("wasm://")
385
- };
386
- }).filter(
387
- ({ fn: r, isWasm: s }) => s && !r.startsWith("dynCall_") && !r.startsWith("invoke_")
388
- ).map(({ fn: r }) => r);
389
- return Array.from(new Set(t));
390
- } catch {
391
- return [];
392
- }
393
- }
394
- const SleepFinished = Symbol("SleepFinished");
395
- function sleep(e) {
396
- return new Promise((t) => {
397
- setTimeout(() => t(SleepFinished), e);
349
+ }).format(o), s = n + " " + i;
350
+ return r = w(r), `[${s}] ${t} ${e}: ${r}`;
351
+ }, D = Symbol("SleepFinished");
352
+ function L(r) {
353
+ return new Promise((e) => {
354
+ setTimeout(() => e(D), r);
398
355
  });
399
356
  }
400
- class AcquireTimeoutError extends Error {
357
+ class S extends Error {
401
358
  constructor() {
402
359
  super("Acquiring lock timed out");
403
360
  }
404
361
  }
405
- class Semaphore {
406
- constructor({ concurrency: t, timeout: r }) {
407
- this._running = 0, this.concurrency = t, this.timeout = r, this.queue = [];
362
+ class $ {
363
+ constructor({ concurrency: e, timeout: t }) {
364
+ this._running = 0, this.concurrency = e, this.timeout = t, this.queue = [];
408
365
  }
409
366
  get remaining() {
410
367
  return this.concurrency - this.running;
@@ -415,1113 +372,416 @@ class Semaphore {
415
372
  async acquire() {
416
373
  for (; ; )
417
374
  if (this._running >= this.concurrency) {
418
- const t = new Promise((r) => {
419
- this.queue.push(r);
375
+ const e = new Promise((t) => {
376
+ this.queue.push(t);
420
377
  });
421
- this.timeout !== void 0 ? await Promise.race([t, sleep(this.timeout)]).then(
422
- (r) => {
423
- if (r === SleepFinished)
424
- throw new AcquireTimeoutError();
378
+ this.timeout !== void 0 ? await Promise.race([e, L(this.timeout)]).then(
379
+ (t) => {
380
+ if (t === D)
381
+ throw new S();
425
382
  }
426
- ) : await t;
383
+ ) : await e;
427
384
  } else {
428
385
  this._running++;
429
- let t = !1;
386
+ let e = !1;
430
387
  return () => {
431
- t || (t = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
388
+ e || (e = !0, this._running--, this.queue.length > 0 && this.queue.shift()());
432
389
  };
433
390
  }
434
391
  }
435
- async run(t) {
436
- const r = await this.acquire();
392
+ async run(e) {
393
+ const t = await this.acquire();
437
394
  try {
438
- return await t();
395
+ return await e();
439
396
  } finally {
440
- r();
397
+ t();
441
398
  }
442
399
  }
443
400
  }
444
- function joinPaths(...e) {
445
- let t = e.join("/");
446
- const r = t[0] === "/", s = t.substring(t.length - 1) === "/";
447
- return t = normalizePath$1(t), !t && !r && (t = "."), t && s && (t += "/"), t;
401
+ function g(...r) {
402
+ let e = r.join("/");
403
+ const t = e[0] === "/", o = e.substring(e.length - 1) === "/";
404
+ return e = T(e), !e && !t && (e = "."), e && o && (e += "/"), e;
448
405
  }
449
- function basename(e) {
450
- if (e === "/")
406
+ function _(r) {
407
+ if (r === "/")
451
408
  return "/";
452
- e = normalizePath$1(e);
453
- const t = e.lastIndexOf("/");
454
- return t === -1 ? e : e.substr(t + 1);
455
- }
456
- function normalizePath$1(e) {
457
- const t = e[0] === "/";
458
- return e = normalizePathsArray(
459
- e.split("/").filter((r) => !!r),
460
- !t
461
- ).join("/"), (t ? "/" : "") + e.replace(/\/$/, "");
462
- }
463
- function normalizePathsArray(e, t) {
464
- let r = 0;
465
- for (let s = e.length - 1; s >= 0; s--) {
466
- const i = e[s];
467
- i === "." ? e.splice(s, 1) : i === ".." ? (e.splice(s, 1), r++) : r && (e.splice(s, 1), r--);
468
- }
469
- if (t)
470
- for (; r; r--)
471
- e.unshift("..");
472
- return e;
409
+ r = T(r);
410
+ const e = r.lastIndexOf("/");
411
+ return e === -1 ? "" : e === 0 ? "/" : r.substr(0, e);
473
412
  }
474
- function splitShellCommand(e) {
475
- let s = 0, i = "";
476
- const n = [];
477
- let o = "";
478
- for (let a = 0; a < e.length; a++) {
479
- const l = e[a];
480
- l === "\\" ? ((e[a + 1] === '"' || e[a + 1] === "'") && a++, o += e[a]) : s === 0 ? l === '"' || l === "'" ? (s = 1, i = l) : l.match(/\s/) ? (o.trim().length && n.push(o.trim()), o = l) : n.length && !o ? o = n.pop() + l : o += l : s === 1 && (l === i ? (s = 0, i = "") : o += l);
481
- }
482
- return o && n.push(o.trim()), n;
483
- }
484
- function createSpawnHandler(e) {
485
- return function(t, r = [], s = {}) {
486
- const i = new ChildProcess(), n = new ProcessApi(i);
487
- return setTimeout(async () => {
488
- let o = [];
489
- if (r.length)
490
- o = [t, ...r];
491
- else if (typeof t == "string")
492
- o = splitShellCommand(t);
493
- else if (Array.isArray(t))
494
- o = t;
495
- else
496
- throw new Error("Invalid command ", t);
497
- try {
498
- await e(o, n, s);
499
- } catch (a) {
500
- i.emit("error", a), typeof a == "object" && a !== null && "message" in a && typeof a.message == "string" && n.stderr(a.message), n.exit(1);
501
- }
502
- i.emit("spawn", !0);
503
- }), i;
504
- };
505
- }
506
- class EventEmitter {
507
- constructor() {
508
- this.listeners = {};
509
- }
510
- emit(t, r) {
511
- this.listeners[t] && this.listeners[t].forEach(function(s) {
512
- s(r);
513
- });
514
- }
515
- on(t, r) {
516
- this.listeners[t] || (this.listeners[t] = []), this.listeners[t].push(r);
517
- }
518
- }
519
- class ProcessApi extends EventEmitter {
520
- constructor(t) {
521
- super(), this.childProcess = t, this.exited = !1, this.stdinData = [], t.on("stdin", (r) => {
522
- this.stdinData ? this.stdinData.push(r.slice()) : this.emit("stdin", r);
523
- });
524
- }
525
- stdout(t) {
526
- typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stdout.emit("data", t);
527
- }
528
- stdoutEnd() {
529
- this.childProcess.stdout.emit("end", {});
530
- }
531
- stderr(t) {
532
- typeof t == "string" && (t = new TextEncoder().encode(t)), this.childProcess.stderr.emit("data", t);
533
- }
534
- stderrEnd() {
535
- this.childProcess.stderr.emit("end", {});
536
- }
537
- exit(t) {
538
- this.exited || (this.exited = !0, this.childProcess.emit("exit", t));
539
- }
540
- flushStdin() {
541
- if (this.stdinData)
542
- for (let t = 0; t < this.stdinData.length; t++)
543
- this.emit("stdin", this.stdinData[t]);
544
- this.stdinData = null;
545
- }
546
- }
547
- let lastPid = 9743;
548
- class ChildProcess extends EventEmitter {
549
- constructor(t = lastPid++) {
550
- super(), this.pid = t, this.stdout = new EventEmitter(), this.stderr = new EventEmitter();
551
- const r = this;
552
- this.stdin = {
553
- write: (s) => {
554
- r.emit("stdin", s);
555
- }
556
- };
557
- }
558
- }
559
- ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symbol.asyncIterator] = async function* () {
560
- const e = this.getReader();
561
- try {
562
- for (; ; ) {
563
- const { done: t, value: r } = await e.read();
564
- if (t)
565
- return;
566
- yield r;
567
- }
568
- } finally {
569
- e.releaseLock();
570
- }
571
- }, ReadableStream.prototype.iterate = // @ts-ignore
572
- ReadableStream.prototype[Symbol.asyncIterator]);
573
- const responseTexts = {
574
- 500: "Internal Server Error",
575
- 502: "Bad Gateway",
576
- 404: "Not Found",
577
- 403: "Forbidden",
578
- 401: "Unauthorized",
579
- 400: "Bad Request",
580
- 301: "Moved Permanently",
581
- 302: "Found",
582
- 307: "Temporary Redirect",
583
- 308: "Permanent Redirect",
584
- 204: "No Content",
585
- 201: "Created",
586
- 200: "OK"
413
+ function q(r) {
414
+ if (r === "/")
415
+ return "/";
416
+ r = T(r);
417
+ const e = r.lastIndexOf("/");
418
+ return e === -1 ? r : r.substr(e + 1);
419
+ }
420
+ function T(r) {
421
+ const e = r[0] === "/";
422
+ return r = j(
423
+ r.split("/").filter((t) => !!t),
424
+ !e
425
+ ).join("/"), (e ? "/" : "") + r.replace(/\/$/, "");
426
+ }
427
+ function j(r, e) {
428
+ let t = 0;
429
+ for (let o = r.length - 1; o >= 0; o--) {
430
+ const n = r[o];
431
+ n === "." ? r.splice(o, 1) : n === ".." ? (r.splice(o, 1), t++) : t && (r.splice(o, 1), t--);
432
+ }
433
+ if (e)
434
+ for (; t; t--)
435
+ r.unshift("..");
436
+ return r;
437
+ }
438
+ var J = Object.defineProperty, z = Object.getOwnPropertyDescriptor, d = (r, e, t, o) => {
439
+ for (var n = o > 1 ? void 0 : o ? z(e, t) : e, i = r.length - 1, s; i >= 0; i--)
440
+ (s = r[i]) && (n = (o ? s(e, t, n) : s(n)) || n);
441
+ return o && n && J(e, t, n), n;
587
442
  };
588
- class PHPResponse {
589
- constructor(t, r, s, i = "", n = 0) {
590
- this.httpStatusCode = t, this.headers = r, this.bytes = s, this.exitCode = n, this.errors = i;
591
- }
592
- static forHttpCode(t, r = "") {
593
- return new PHPResponse(
594
- t,
595
- {},
596
- new TextEncoder().encode(
597
- r || responseTexts[t] || ""
598
- )
599
- );
443
+ const f = class c {
444
+ static readFileAsText(e, t) {
445
+ return new TextDecoder().decode(c.readFileAsBuffer(e, t));
600
446
  }
601
- static fromRawData(t) {
602
- return new PHPResponse(
603
- t.httpStatusCode,
604
- t.headers,
605
- t.bytes,
606
- t.errors,
607
- t.exitCode
608
- );
447
+ static readFileAsBuffer(e, t) {
448
+ return e.readFile(t);
609
449
  }
610
- toRawData() {
611
- return {
612
- headers: this.headers,
613
- bytes: this.bytes,
614
- errors: this.errors,
615
- exitCode: this.exitCode,
616
- httpStatusCode: this.httpStatusCode
617
- };
450
+ static writeFile(e, t, o) {
451
+ e.writeFile(t, o);
618
452
  }
619
- /**
620
- * Response body as JSON.
621
- */
622
- get json() {
623
- return JSON.parse(this.text);
453
+ static unlink(e, t) {
454
+ e.unlink(t);
624
455
  }
625
456
  /**
626
- * Response body as text.
627
- */
628
- get text() {
629
- return new TextDecoder().decode(this.bytes);
630
- }
631
- }
632
- const FileErrorCodes = {
633
- 0: "No error occurred. System call completed successfully.",
634
- 1: "Argument list too long.",
635
- 2: "Permission denied.",
636
- 3: "Address in use.",
637
- 4: "Address not available.",
638
- 5: "Address family not supported.",
639
- 6: "Resource unavailable, or operation would block.",
640
- 7: "Connection already in progress.",
641
- 8: "Bad file descriptor.",
642
- 9: "Bad message.",
643
- 10: "Device or resource busy.",
644
- 11: "Operation canceled.",
645
- 12: "No child processes.",
646
- 13: "Connection aborted.",
647
- 14: "Connection refused.",
648
- 15: "Connection reset.",
649
- 16: "Resource deadlock would occur.",
650
- 17: "Destination address required.",
651
- 18: "Mathematics argument out of domain of function.",
652
- 19: "Reserved.",
653
- 20: "File exists.",
654
- 21: "Bad address.",
655
- 22: "File too large.",
656
- 23: "Host is unreachable.",
657
- 24: "Identifier removed.",
658
- 25: "Illegal byte sequence.",
659
- 26: "Operation in progress.",
660
- 27: "Interrupted function.",
661
- 28: "Invalid argument.",
662
- 29: "I/O error.",
663
- 30: "Socket is connected.",
664
- 31: "There is a directory under that path.",
665
- 32: "Too many levels of symbolic links.",
666
- 33: "File descriptor value too large.",
667
- 34: "Too many links.",
668
- 35: "Message too large.",
669
- 36: "Reserved.",
670
- 37: "Filename too long.",
671
- 38: "Network is down.",
672
- 39: "Connection aborted by network.",
673
- 40: "Network unreachable.",
674
- 41: "Too many files open in system.",
675
- 42: "No buffer space available.",
676
- 43: "No such device.",
677
- 44: "There is no such file or directory OR the parent directory does not exist.",
678
- 45: "Executable file format error.",
679
- 46: "No locks available.",
680
- 47: "Reserved.",
681
- 48: "Not enough space.",
682
- 49: "No message of the desired type.",
683
- 50: "Protocol not available.",
684
- 51: "No space left on device.",
685
- 52: "Function not supported.",
686
- 53: "The socket is not connected.",
687
- 54: "Not a directory or a symbolic link to a directory.",
688
- 55: "Directory not empty.",
689
- 56: "State not recoverable.",
690
- 57: "Not a socket.",
691
- 58: "Not supported, or operation not supported on socket.",
692
- 59: "Inappropriate I/O control operation.",
693
- 60: "No such device or address.",
694
- 61: "Value too large to be stored in data type.",
695
- 62: "Previous owner died.",
696
- 63: "Operation not permitted.",
697
- 64: "Broken pipe.",
698
- 65: "Protocol error.",
699
- 66: "Protocol not supported.",
700
- 67: "Protocol wrong type for socket.",
701
- 68: "Result too large.",
702
- 69: "Read-only file system.",
703
- 70: "Invalid seek.",
704
- 71: "No such process.",
705
- 72: "Reserved.",
706
- 73: "Connection timed out.",
707
- 74: "Text file busy.",
708
- 75: "Cross-device link.",
709
- 76: "Extension: Capabilities insufficient."
710
- };
711
- function getEmscriptenFsError(e) {
712
- const t = typeof e == "object" ? e == null ? void 0 : e.errno : null;
713
- if (t in FileErrorCodes)
714
- return FileErrorCodes[t];
715
- }
716
- function rethrowFileSystemError(e = "") {
717
- return function(r, s, i) {
718
- const n = i.value;
719
- i.value = function(...o) {
720
- try {
721
- return n.apply(this, o);
722
- } catch (a) {
723
- const l = typeof a == "object" ? a == null ? void 0 : a.errno : null;
724
- if (l in FileErrorCodes) {
725
- const c = FileErrorCodes[l], d = typeof o[0] == "string" ? o[0] : null, g = d !== null ? e.replaceAll("{path}", d) : e;
726
- throw new Error(`${g}: ${c}`, {
727
- cause: a
728
- });
729
- }
730
- throw a;
731
- }
732
- };
733
- };
734
- }
735
- const loadedRuntimes = /* @__PURE__ */ new Map();
736
- function getLoadedRuntime(e) {
737
- return loadedRuntimes.get(e);
738
- }
739
- (function() {
740
- var e;
741
- 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";
742
- })();
743
- var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = (e, t, r, s) => {
744
- for (var i = s > 1 ? void 0 : s ? __getOwnPropDesc(t, r) : t, n = e.length - 1, o; n >= 0; n--)
745
- (o = e[n]) && (i = (s ? o(t, r, i) : o(i)) || i);
746
- return s && i && __defProp(t, r, i), i;
747
- };
748
- const STRING = "string", NUMBER = "number", __private__dont__use = Symbol("__private__dont__use");
749
- class PHPExecutionFailureError extends Error {
750
- constructor(t, r, s) {
751
- super(t), this.response = r, this.source = s;
752
- }
753
- }
754
- var E, w, v, _, y, m, P, b, $, S, U, R, q, T, W, F, z, C, j, x, G, k, J, I, Q, N, V, A, Y, M, Z, O, K, H, X, B, ee;
755
- class BasePHP {
756
- /**
757
- * Initializes a PHP runtime.
457
+ * Moves a file or directory in the PHP filesystem to a
458
+ * new location.
758
459
  *
759
- * @internal
760
- * @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
761
- * @param requestHandlerOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
762
- */
763
- constructor(e) {
764
- /**
765
- * Prepares the $_SERVER entries for the PHP runtime.
766
- *
767
- * @param defaults Default entries to include in $_SERVER.
768
- * @param headers HTTP headers to include in $_SERVER (as HTTP_ prefixed entries).
769
- * @param port HTTP port, used to determine infer $_SERVER['HTTPS'] value if none
770
- * was provided.
771
- * @returns Computed $_SERVER entries.
772
- */
773
- u(this, b);
774
- u(this, S);
775
- u(this, R);
776
- u(this, T);
777
- u(this, F);
778
- u(this, C);
779
- u(this, x);
780
- u(this, k);
781
- u(this, I);
782
- u(this, N);
783
- u(this, A);
784
- u(this, M);
785
- u(this, O);
786
- u(this, H);
787
- u(this, B);
788
- u(this, E, void 0);
789
- u(this, w, void 0);
790
- u(this, v, void 0);
791
- u(this, _, void 0);
792
- u(this, y, void 0);
793
- u(this, m, void 0);
794
- u(this, P, void 0);
795
- f(this, E, []), f(this, _, !1), f(this, y, null), f(this, m, /* @__PURE__ */ new Map()), f(this, P, []), this.semaphore = new Semaphore({ concurrency: 1 }), e !== void 0 && this.initializeRuntime(e);
796
- }
797
- addEventListener(e, t) {
798
- h(this, m).has(e) || h(this, m).set(e, /* @__PURE__ */ new Set()), h(this, m).get(e).add(t);
799
- }
800
- removeEventListener(e, t) {
801
- var r;
802
- (r = h(this, m).get(e)) == null || r.delete(t);
803
- }
804
- dispatchEvent(e) {
805
- const t = h(this, m).get(e.type);
806
- if (t)
807
- for (const r of t)
808
- r(e);
809
- }
810
- /** @inheritDoc */
811
- async onMessage(e) {
812
- h(this, P).push(e);
813
- }
814
- /** @inheritDoc */
815
- async setSpawnHandler(handler) {
816
- typeof handler == "string" && (handler = createSpawnHandler(eval(handler))), this[__private__dont__use].spawnProcess = handler;
817
- }
818
- /** @inheritDoc */
819
- get absoluteUrl() {
820
- return this.requestHandler.absoluteUrl;
821
- }
822
- /** @inheritDoc */
823
- get documentRoot() {
824
- return this.requestHandler.documentRoot;
825
- }
826
- /** @inheritDoc */
827
- pathToInternalUrl(e) {
828
- return this.requestHandler.pathToInternalUrl(e);
829
- }
830
- /** @inheritDoc */
831
- internalUrlToPath(e) {
832
- return this.requestHandler.internalUrlToPath(e);
833
- }
834
- initializeRuntime(e) {
835
- if (this[__private__dont__use])
836
- throw new Error("PHP runtime already initialized.");
837
- const t = getLoadedRuntime(e);
838
- if (!t)
839
- throw new Error("Invalid PHP runtime id.");
840
- this[__private__dont__use] = t, t.onMessage = async (r) => {
841
- for (const s of h(this, P)) {
842
- const i = await s(r);
843
- if (i)
844
- return i;
845
- }
846
- return "";
847
- }, f(this, y, improveWASMErrorReporting(t)), this.dispatchEvent({
848
- type: "runtime.initialized"
849
- });
850
- }
851
- /** @inheritDoc */
852
- async setSapiName(e) {
853
- if (this[__private__dont__use].ccall(
854
- "wasm_set_sapi_name",
855
- NUMBER,
856
- [STRING],
857
- [e]
858
- ) !== 0)
859
- throw new Error(
860
- "Could not set SAPI name. This can only be done before the PHP WASM module is initialized.Did you already dispatch any requests?"
861
- );
862
- f(this, v, e);
863
- }
864
- /** @inheritDoc */
865
- setPhpIniPath(e) {
866
- if (h(this, _))
867
- throw new Error("Cannot set PHP ini path after calling run().");
868
- f(this, w, e), this[__private__dont__use].ccall(
869
- "wasm_set_phpini_path",
870
- null,
871
- ["string"],
872
- [e]
873
- );
874
- }
875
- /** @inheritDoc */
876
- setPhpIniEntry(e, t) {
877
- if (h(this, _))
878
- throw new Error("Cannot set PHP ini entries after calling run().");
879
- h(this, E).push([e, t]);
880
- }
881
- /** @inheritDoc */
882
- chdir(e) {
883
- this[__private__dont__use].FS.chdir(e);
884
- }
885
- /**
886
- * Do not use. Use new PHPRequestHandler() instead.
887
- * @deprecated
460
+ * @param oldPath The path to rename.
461
+ * @param newPath The new path.
888
462
  */
889
- async request(e) {
890
- if (logger.warn(
891
- "PHP.request() is deprecated. Please use new PHPRequestHandler() instead."
892
- ), !this.requestHandler)
893
- throw new Error("No request handler available.");
894
- return this.requestHandler.request(e);
895
- }
896
- /** @inheritDoc */
897
- async run(e) {
898
- const t = await this.semaphore.acquire();
899
- let r;
900
- try {
901
- if (h(this, _) || (p(this, S, U).call(this), f(this, _, !0)), e.scriptPath && !this.fileExists(e.scriptPath))
902
- throw new Error(
903
- `The script path "${e.scriptPath}" does not exist.`
904
- );
905
- p(this, A, Y).call(this, e.scriptPath || ""), p(this, T, W).call(this, e.relativeUri || ""), p(this, k, J).call(this, e.method || "GET");
906
- const s = normalizeHeaders(e.headers || {}), i = s.host || "example.com:443", n = p(this, x, G).call(this, i, e.protocol || "http");
907
- p(this, F, z).call(this, i), p(this, C, j).call(this, n), p(this, I, Q).call(this, s), e.body && (r = p(this, N, V).call(this, e.body)), typeof e.code == "string" && p(this, H, X).call(this, " ?>" + e.code);
908
- const o = p(this, b, $).call(this, e.$_SERVER, s, n);
909
- for (const c in o)
910
- p(this, M, Z).call(this, c, o[c]);
911
- const a = e.env || {};
912
- for (const c in a)
913
- p(this, O, K).call(this, c, a[c]);
914
- const l = await p(this, B, ee).call(this);
915
- if (l.exitCode !== 0) {
916
- logger.warn("PHP.run() output was:", l.text);
917
- const c = new PHPExecutionFailureError(
918
- `PHP.run() failed with exit code ${l.exitCode} and the following output: ` + l.errors,
919
- l,
920
- "request"
921
- );
922
- throw logger.error(c), c;
923
- }
924
- return l;
925
- } catch (s) {
926
- throw this.dispatchEvent({
927
- type: "request.error",
928
- error: s,
929
- // Distinguish between PHP request and PHP-wasm errors
930
- source: s.source ?? "php-wasm"
931
- }), s;
932
- } finally {
933
- try {
934
- r && this[__private__dont__use].free(r);
935
- } finally {
936
- t(), this.dispatchEvent({
937
- type: "request.end"
938
- });
939
- }
940
- }
941
- }
942
- defineConstant(e, t) {
943
- let r = {};
463
+ static mv(e, t, o) {
944
464
  try {
945
- r = JSON.parse(
946
- this.fileExists("/internal/consts.json") && this.readFileAsText("/internal/consts.json") || "{}"
947
- );
948
- } catch {
949
- }
950
- this.writeFile(
951
- "/internal/consts.json",
952
- JSON.stringify({
953
- ...r,
954
- [e]: t
955
- })
956
- );
957
- }
958
- mkdir(e) {
959
- this[__private__dont__use].FS.mkdirTree(e);
960
- }
961
- mkdirTree(e) {
962
- this.mkdir(e);
963
- }
964
- readFileAsText(e) {
965
- return new TextDecoder().decode(this.readFileAsBuffer(e));
966
- }
967
- readFileAsBuffer(e) {
968
- return this[__private__dont__use].FS.readFile(e);
969
- }
970
- writeFile(e, t) {
971
- this[__private__dont__use].FS.writeFile(e, t);
972
- }
973
- unlink(e) {
974
- this[__private__dont__use].FS.unlink(e);
975
- }
976
- /** @inheritDoc */
977
- mv(e, t) {
978
- try {
979
- this[__private__dont__use].FS.rename(e, t);
980
- } catch (r) {
981
- const s = getEmscriptenFsError(r);
982
- throw s ? new Error(
983
- `Could not move ${e} to ${t}: ${s}`,
465
+ const n = e.lookupPath(t).node.mount, i = c.fileExists(e, o) ? e.lookupPath(o).node.mount : e.lookupPath(_(o)).node.mount;
466
+ n.mountpoint !== i.mountpoint ? (c.copyRecursive(e, t, o), c.rmdir(e, t, { recursive: !0 })) : e.rename(t, o);
467
+ } catch (n) {
468
+ const i = O(n);
469
+ throw i ? new Error(
470
+ `Could not move ${t} to ${o}: ${i}`,
984
471
  {
985
- cause: r
472
+ cause: n
986
473
  }
987
- ) : r;
474
+ ) : n;
988
475
  }
989
476
  }
990
- rmdir(e, t = { recursive: !0 }) {
991
- t != null && t.recursive && this.listFiles(e).forEach((r) => {
992
- const s = `${e}/${r}`;
993
- this.isDir(s) ? this.rmdir(s, t) : this.unlink(s);
994
- }), this[__private__dont__use].FS.rmdir(e);
477
+ static rmdir(e, t, o = { recursive: !0 }) {
478
+ o != null && o.recursive && c.listFiles(e, t).forEach((n) => {
479
+ const i = `${t}/${n}`;
480
+ c.isDir(e, i) ? c.rmdir(e, i, o) : c.unlink(e, i);
481
+ }), e.rmdir(t);
995
482
  }
996
- listFiles(e, t = { prependPath: !1 }) {
997
- if (!this.fileExists(e))
483
+ static listFiles(e, t, o = { prependPath: !1 }) {
484
+ if (!c.fileExists(e, t))
998
485
  return [];
999
486
  try {
1000
- const r = this[__private__dont__use].FS.readdir(e).filter(
1001
- (s) => s !== "." && s !== ".."
487
+ const n = e.readdir(t).filter(
488
+ (i) => i !== "." && i !== ".."
1002
489
  );
1003
- if (t.prependPath) {
1004
- const s = e.replace(/\/$/, "");
1005
- return r.map((i) => `${s}/${i}`);
490
+ if (o.prependPath) {
491
+ const i = t.replace(/\/$/, "");
492
+ return n.map((s) => `${i}/${s}`);
1006
493
  }
1007
- return r;
1008
- } catch (r) {
1009
- return logger.error(r, { path: e }), [];
494
+ return n;
495
+ } catch (n) {
496
+ return b.error(n, { path: t }), [];
1010
497
  }
1011
498
  }
1012
- isDir(e) {
1013
- return this.fileExists(e) ? this[__private__dont__use].FS.isDir(
1014
- this[__private__dont__use].FS.lookupPath(e).node.mode
1015
- ) : !1;
499
+ static isDir(e, t) {
500
+ return c.fileExists(e, t) ? e.isDir(e.lookupPath(t).node.mode) : !1;
1016
501
  }
1017
- fileExists(e) {
502
+ static fileExists(e, t) {
1018
503
  try {
1019
- return this[__private__dont__use].FS.lookupPath(e), !0;
504
+ return e.lookupPath(t), !0;
1020
505
  } catch {
1021
506
  return !1;
1022
507
  }
1023
508
  }
1024
- /**
1025
- * Hot-swaps the PHP runtime for a new one without
1026
- * interrupting the operations of this PHP instance.
1027
- *
1028
- * @param runtime
1029
- * @param cwd. Internal, the VFS path to recreate in the new runtime.
1030
- * This arg is temporary and will be removed once BasePHP
1031
- * is fully decoupled from the request handler and
1032
- * accepts a constructor-level cwd argument.
1033
- */
1034
- hotSwapPHPRuntime(e, t) {
1035
- const r = this[__private__dont__use].FS;
1036
- try {
1037
- this.exit();
1038
- } catch {
1039
- }
1040
- this.initializeRuntime(e), h(this, w) && this.setPhpIniPath(h(this, w)), h(this, v) && this.setSapiName(h(this, v)), t && copyFS(r, this[__private__dont__use].FS, t);
509
+ static mkdir(e, t) {
510
+ e.mkdirTree(t);
1041
511
  }
1042
- exit(e = 0) {
1043
- this.dispatchEvent({
1044
- type: "runtime.beforedestroy"
1045
- });
1046
- try {
1047
- this[__private__dont__use]._exit(e);
1048
- } catch {
1049
- }
1050
- f(this, _, !1), f(this, y, null), delete this[__private__dont__use].onMessage, delete this[__private__dont__use];
1051
- }
1052
- [Symbol.dispose]() {
1053
- h(this, _) && this.exit(0);
1054
- }
1055
- }
1056
- E = new WeakMap(), w = new WeakMap(), v = new WeakMap(), _ = new WeakMap(), y = new WeakMap(), m = new WeakMap(), P = new WeakMap(), b = new WeakSet(), $ = function(e, t, r) {
1057
- const s = {
1058
- ...e || {}
1059
- };
1060
- s.HTTPS = s.HTTPS || r === 443 ? "on" : "off";
1061
- for (const i in t) {
1062
- let n = "HTTP_";
1063
- ["content-type", "content-length"].includes(i.toLowerCase()) && (n = ""), s[`${n}${i.toUpperCase().replace(/-/g, "_")}`] = t[i];
1064
- }
1065
- return s;
1066
- }, S = new WeakSet(), U = function() {
1067
- if (this.setPhpIniEntry("auto_prepend_file", "/internal/consts.php"), this.fileExists("/internal/consts.php") || this.writeFile(
1068
- "/internal/consts.php",
1069
- `<?php
1070
- if(file_exists('/internal/consts.json')) {
1071
- $consts = json_decode(file_get_contents('/internal/consts.json'), true);
1072
- foreach ($consts as $const => $value) {
1073
- if (!defined($const) && is_scalar($value)) {
1074
- define($const, $value);
1075
- }
1076
- }
1077
- }`
1078
- ), h(this, E).length > 0) {
1079
- const e = h(this, E).map(([t, r]) => `${t}=${r}`).join(`
1080
- `) + `
1081
-
1082
- `;
1083
- this[__private__dont__use].ccall(
1084
- "wasm_set_phpini_entries",
1085
- null,
1086
- [STRING],
1087
- [e]
1088
- );
1089
- }
1090
- this[__private__dont__use].ccall("php_wasm_init", null, [], []);
1091
- }, R = new WeakSet(), q = function() {
1092
- const e = "/internal/headers.json";
1093
- if (!this.fileExists(e))
1094
- throw new Error(
1095
- "SAPI Error: Could not find response headers file."
1096
- );
1097
- const t = JSON.parse(this.readFileAsText(e)), r = {};
1098
- for (const s of t.headers) {
1099
- if (!s.includes(": "))
1100
- continue;
1101
- const i = s.indexOf(": "), n = s.substring(0, i).toLowerCase(), o = s.substring(i + 2);
1102
- n in r || (r[n] = []), r[n].push(o);
1103
- }
1104
- return {
1105
- headers: r,
1106
- httpStatusCode: t.status
1107
- };
1108
- }, T = new WeakSet(), W = function(e) {
1109
- if (this[__private__dont__use].ccall(
1110
- "wasm_set_request_uri",
1111
- null,
1112
- [STRING],
1113
- [e]
1114
- ), e.includes("?")) {
1115
- const t = e.substring(e.indexOf("?") + 1);
1116
- this[__private__dont__use].ccall(
1117
- "wasm_set_query_string",
1118
- null,
1119
- [STRING],
1120
- [t]
1121
- );
1122
- }
1123
- }, F = new WeakSet(), z = function(e) {
1124
- this[__private__dont__use].ccall(
1125
- "wasm_set_request_host",
1126
- null,
1127
- [STRING],
1128
- [e]
1129
- );
1130
- }, C = new WeakSet(), j = function(e) {
1131
- this[__private__dont__use].ccall(
1132
- "wasm_set_request_port",
1133
- null,
1134
- [NUMBER],
1135
- [e]
1136
- );
1137
- }, x = new WeakSet(), G = function(e, t) {
1138
- let r;
1139
- try {
1140
- r = parseInt(new URL(e).port, 10);
1141
- } catch {
1142
- }
1143
- return (!r || isNaN(r) || r === 80) && (r = t === "https" ? 443 : 80), r;
1144
- }, k = new WeakSet(), J = function(e) {
1145
- this[__private__dont__use].ccall(
1146
- "wasm_set_request_method",
1147
- null,
1148
- [STRING],
1149
- [e]
1150
- );
1151
- }, I = new WeakSet(), Q = function(e) {
1152
- e.cookie && this[__private__dont__use].ccall(
1153
- "wasm_set_cookies",
1154
- null,
1155
- [STRING],
1156
- [e.cookie]
1157
- ), e["content-type"] && this[__private__dont__use].ccall(
1158
- "wasm_set_content_type",
1159
- null,
1160
- [STRING],
1161
- [e["content-type"]]
1162
- ), e["content-length"] && this[__private__dont__use].ccall(
1163
- "wasm_set_content_length",
1164
- null,
1165
- [NUMBER],
1166
- [parseInt(e["content-length"], 10)]
1167
- );
1168
- }, N = new WeakSet(), V = function(e) {
1169
- let t, r;
1170
- typeof e == "string" ? (logger.warn(
1171
- "Passing a string as the request body is deprecated. Please use a Uint8Array instead. See https://github.com/WordPress/wordpress-playground/issues/997 for more details"
1172
- ), r = this[__private__dont__use].lengthBytesUTF8(e), t = r + 1) : (r = e.byteLength, t = e.byteLength);
1173
- const s = this[__private__dont__use].malloc(t);
1174
- if (!s)
1175
- throw new Error("Could not allocate memory for the request body.");
1176
- return typeof e == "string" ? this[__private__dont__use].stringToUTF8(
1177
- e,
1178
- s,
1179
- t + 1
1180
- ) : this[__private__dont__use].HEAPU8.set(e, s), this[__private__dont__use].ccall(
1181
- "wasm_set_request_body",
1182
- null,
1183
- [NUMBER],
1184
- [s]
1185
- ), this[__private__dont__use].ccall(
1186
- "wasm_set_content_length",
1187
- null,
1188
- [NUMBER],
1189
- [r]
1190
- ), s;
1191
- }, A = new WeakSet(), Y = function(e) {
1192
- this[__private__dont__use].ccall(
1193
- "wasm_set_path_translated",
1194
- null,
1195
- [STRING],
1196
- [e]
1197
- );
1198
- }, M = new WeakSet(), Z = function(e, t) {
1199
- this[__private__dont__use].ccall(
1200
- "wasm_add_SERVER_entry",
1201
- null,
1202
- [STRING, STRING],
1203
- [e, t]
1204
- );
1205
- }, O = new WeakSet(), K = function(e, t) {
1206
- this[__private__dont__use].ccall(
1207
- "wasm_add_ENV_entry",
1208
- null,
1209
- [STRING, STRING],
1210
- [e, t]
1211
- );
1212
- }, H = new WeakSet(), X = function(e) {
1213
- this[__private__dont__use].ccall(
1214
- "wasm_set_php_code",
1215
- null,
1216
- [STRING],
1217
- [e]
1218
- );
1219
- }, B = new WeakSet(), ee = async function() {
1220
- var i;
1221
- let e, t;
1222
- try {
1223
- e = await new Promise((n, o) => {
1224
- var l;
1225
- t = (c) => {
1226
- logger.error(c), logger.error(c.error);
1227
- const d = new Error("Rethrown");
1228
- d.cause = c.error, d.betterMessage = c.message, o(d);
1229
- }, (l = h(this, y)) == null || l.addEventListener(
1230
- "error",
1231
- t
1232
- );
1233
- const a = this[__private__dont__use].ccall(
1234
- "wasm_sapi_handle_request",
1235
- NUMBER,
1236
- [],
1237
- [],
1238
- { async: !0 }
512
+ static copyRecursive(e, t, o) {
513
+ const n = e.lookupPath(t).node;
514
+ if (e.isDir(n.mode)) {
515
+ e.mkdirTree(o);
516
+ const i = e.readdir(t).filter(
517
+ (s) => s !== "." && s !== ".."
1239
518
  );
1240
- return a instanceof Promise ? a.then(n, o) : n(a);
1241
- });
1242
- } catch (n) {
1243
- for (const c in this)
1244
- typeof this[c] == "function" && (this[c] = () => {
1245
- throw new Error(
1246
- "PHP runtime has crashed – see the earlier error for details."
519
+ for (const s of i)
520
+ c.copyRecursive(
521
+ e,
522
+ g(t, s),
523
+ g(o, s)
1247
524
  );
1248
- });
1249
- this.functionsMaybeMissingFromAsyncify = getFunctionsMaybeMissingFromAsyncify();
1250
- const o = n, a = "betterMessage" in o ? o.betterMessage : o.message, l = new Error(a);
1251
- throw l.cause = o, logger.error(l), l;
1252
- } finally {
1253
- (i = h(this, y)) == null || i.removeEventListener("error", t);
525
+ } else
526
+ e.writeFile(o, e.readFile(t));
1254
527
  }
1255
- const { headers: r, httpStatusCode: s } = p(this, R, q).call(this);
1256
- return new PHPResponse(
1257
- e === 0 ? s : 500,
1258
- r,
1259
- this.readFileAsBuffer("/internal/stdout"),
1260
- this.readFileAsText("/internal/stderr"),
1261
- e
1262
- );
1263
528
  };
1264
- __decorateClass([
1265
- rethrowFileSystemError('Could not create directory "{path}"')
1266
- ], BasePHP.prototype, "mkdir", 1);
1267
- __decorateClass([
1268
- rethrowFileSystemError('Could not create directory "{path}"')
1269
- ], BasePHP.prototype, "mkdirTree", 1);
1270
- __decorateClass([
1271
- rethrowFileSystemError('Could not read "{path}"')
1272
- ], BasePHP.prototype, "readFileAsText", 1);
1273
- __decorateClass([
1274
- rethrowFileSystemError('Could not read "{path}"')
1275
- ], BasePHP.prototype, "readFileAsBuffer", 1);
1276
- __decorateClass([
1277
- rethrowFileSystemError('Could not write to "{path}"')
1278
- ], BasePHP.prototype, "writeFile", 1);
1279
- __decorateClass([
1280
- rethrowFileSystemError('Could not unlink "{path}"')
1281
- ], BasePHP.prototype, "unlink", 1);
1282
- __decorateClass([
1283
- rethrowFileSystemError('Could not remove directory "{path}"')
1284
- ], BasePHP.prototype, "rmdir", 1);
1285
- __decorateClass([
1286
- rethrowFileSystemError('Could not list files in "{path}"')
1287
- ], BasePHP.prototype, "listFiles", 1);
1288
- __decorateClass([
1289
- rethrowFileSystemError('Could not stat "{path}"')
1290
- ], BasePHP.prototype, "isDir", 1);
1291
- __decorateClass([
1292
- rethrowFileSystemError('Could not stat "{path}"')
1293
- ], BasePHP.prototype, "fileExists", 1);
1294
- function normalizeHeaders(e) {
1295
- const t = {};
1296
- for (const r in e)
1297
- t[r.toLowerCase()] = e[r];
1298
- return t;
1299
- }
1300
- function copyFS(e, t, r) {
1301
- let s;
529
+ d([
530
+ u('Could not read "{path}"')
531
+ ], f, "readFileAsText", 1);
532
+ d([
533
+ u('Could not read "{path}"')
534
+ ], f, "readFileAsBuffer", 1);
535
+ d([
536
+ u('Could not write to "{path}"')
537
+ ], f, "writeFile", 1);
538
+ d([
539
+ u('Could not unlink "{path}"')
540
+ ], f, "unlink", 1);
541
+ d([
542
+ u('Could not remove directory "{path}"')
543
+ ], f, "rmdir", 1);
544
+ d([
545
+ u('Could not list files in "{path}"')
546
+ ], f, "listFiles", 1);
547
+ d([
548
+ u('Could not stat "{path}"')
549
+ ], f, "isDir", 1);
550
+ d([
551
+ u('Could not stat "{path}"')
552
+ ], f, "fileExists", 1);
553
+ d([
554
+ u('Could not create directory "{path}"')
555
+ ], f, "mkdir", 1);
556
+ d([
557
+ u('Could not copy files from "{path}"')
558
+ ], f, "copyRecursive", 1);
559
+ (function() {
560
+ var r;
561
+ 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";
562
+ })();
563
+ const p = Symbol("__private__dont__use");
564
+ ReadableStream.prototype[Symbol.asyncIterator] || (ReadableStream.prototype[Symbol.asyncIterator] = async function* () {
565
+ const r = this.getReader();
1302
566
  try {
1303
- s = e.lookupPath(r);
1304
- } catch {
1305
- return;
1306
- }
1307
- if (!("contents" in s.node))
1308
- return;
1309
- if (!e.isDir(s.node.mode)) {
1310
- t.writeFile(r, e.readFile(r));
1311
- return;
567
+ for (; ; ) {
568
+ const { done: e, value: t } = await r.read();
569
+ if (e)
570
+ return;
571
+ yield t;
572
+ }
573
+ } finally {
574
+ r.releaseLock();
1312
575
  }
1313
- t.mkdirTree(r);
1314
- const i = e.readdir(r).filter((n) => n !== "." && n !== "..");
1315
- for (const n of i)
1316
- copyFS(e, t, joinPaths(r, n));
1317
- }
1318
- function journalFSEvents(e, t, r = () => {
576
+ }, ReadableStream.prototype.iterate = // @ts-ignore
577
+ ReadableStream.prototype[Symbol.asyncIterator]);
578
+ function Y(r, e, t = () => {
1319
579
  }) {
1320
- function s() {
1321
- t = normalizePath(t);
1322
- const n = e[__private__dont__use].FS, o = createFSHooks(n, (d) => {
1323
- if (d.path.startsWith(t))
1324
- r(d);
1325
- else if (d.operation === "RENAME" && d.toPath.startsWith(t))
1326
- for (const g of recordExistingPath(
1327
- e,
1328
- d.path,
1329
- d.toPath
580
+ function o() {
581
+ e = H(e);
582
+ const i = r[p].FS, s = G(i, (l) => {
583
+ if (l.path.startsWith(e))
584
+ t(l);
585
+ else if (l.operation === "RENAME" && l.toPath.startsWith(e))
586
+ for (const y of F(
587
+ r,
588
+ l.path,
589
+ l.toPath
1330
590
  ))
1331
- r(g);
591
+ t(y);
1332
592
  }), a = {};
1333
- for (const [d] of Object.entries(o))
1334
- a[d] = n[d];
1335
- function l() {
1336
- for (const [d, g] of Object.entries(o))
1337
- n[d] = function(...L) {
1338
- return g(...L), a[d].apply(this, L);
593
+ for (const [l] of Object.entries(s))
594
+ a[l] = i[l];
595
+ function m() {
596
+ for (const [l, y] of Object.entries(s))
597
+ i[l] = function(...k) {
598
+ return y(...k), a[l].apply(this, k);
1339
599
  };
1340
600
  }
1341
- function c() {
1342
- for (const [d, g] of Object.entries(a))
1343
- e[__private__dont__use].FS[d] = g;
601
+ function h() {
602
+ for (const [l, y] of Object.entries(a))
603
+ r[p].FS[l] = y;
1344
604
  }
1345
- e[__private__dont__use].journal = {
1346
- bind: l,
1347
- unbind: c
1348
- }, l();
605
+ r[p].journal = {
606
+ bind: m,
607
+ unbind: h
608
+ }, m();
1349
609
  }
1350
- e.addEventListener("runtime.initialized", s), e[__private__dont__use] && s();
1351
- function i() {
1352
- e[__private__dont__use].journal.unbind(), delete e[__private__dont__use].journal;
610
+ r.addEventListener("runtime.initialized", o), r[p] && o();
611
+ function n() {
612
+ r[p].journal.unbind(), delete r[p].journal;
1353
613
  }
1354
- return e.addEventListener("runtime.beforedestroy", i), function() {
1355
- return e.removeEventListener("runtime.initialized", s), e.removeEventListener("runtime.beforedestroy", i), e[__private__dont__use].journal.unbind();
614
+ return r.addEventListener("runtime.beforedestroy", n), function() {
615
+ return r.removeEventListener("runtime.initialized", o), r.removeEventListener("runtime.beforedestroy", n), r[p].journal.unbind();
1356
616
  };
1357
617
  }
1358
- const createFSHooks = (e, t = () => {
618
+ const G = (r, e = () => {
1359
619
  }) => ({
1360
- write(r) {
1361
- t({
620
+ write(t) {
621
+ e({
1362
622
  operation: "WRITE",
1363
- path: r.path,
623
+ path: t.path,
1364
624
  nodeType: "file"
1365
625
  });
1366
626
  },
1367
- truncate(r) {
1368
- let s;
1369
- typeof r == "string" ? s = e.lookupPath(r, {
627
+ truncate(t) {
628
+ let o;
629
+ typeof t == "string" ? o = r.lookupPath(t, {
1370
630
  follow: !0
1371
- }).node : s = r, t({
631
+ }).node : o = t, e({
1372
632
  operation: "WRITE",
1373
- path: e.getPath(s),
633
+ path: r.getPath(o),
1374
634
  nodeType: "file"
1375
635
  });
1376
636
  },
1377
- unlink(r) {
1378
- t({
637
+ unlink(t) {
638
+ e({
1379
639
  operation: "DELETE",
1380
- path: r,
640
+ path: t,
1381
641
  nodeType: "file"
1382
642
  });
1383
643
  },
1384
- mknod(r, s) {
1385
- e.isFile(s) && t({
644
+ mknod(t, o) {
645
+ r.isFile(o) && e({
1386
646
  operation: "CREATE",
1387
- path: r,
647
+ path: t,
1388
648
  nodeType: "file"
1389
649
  });
1390
650
  },
1391
- mkdir(r) {
1392
- t({
651
+ mkdir(t) {
652
+ e({
1393
653
  operation: "CREATE",
1394
- path: r,
654
+ path: t,
1395
655
  nodeType: "directory"
1396
656
  });
1397
657
  },
1398
- rmdir(r) {
1399
- t({
658
+ rmdir(t) {
659
+ e({
1400
660
  operation: "DELETE",
1401
- path: r,
661
+ path: t,
1402
662
  nodeType: "directory"
1403
663
  });
1404
664
  },
1405
- rename(r, s) {
665
+ rename(t, o) {
1406
666
  try {
1407
- const i = e.lookupPath(r, {
667
+ const n = r.lookupPath(t, {
1408
668
  follow: !0
1409
- }), n = e.lookupPath(s, {
669
+ }), i = r.lookupPath(o, {
1410
670
  parent: !0
1411
671
  }).path;
1412
- t({
672
+ e({
1413
673
  operation: "RENAME",
1414
- nodeType: e.isDir(i.node.mode) ? "directory" : "file",
1415
- path: i.path,
1416
- toPath: joinPaths(n, basename(s))
674
+ nodeType: r.isDir(n.node.mode) ? "directory" : "file",
675
+ path: n.path,
676
+ toPath: g(i, q(o))
1417
677
  });
1418
678
  } catch {
1419
679
  }
1420
680
  }
1421
681
  });
1422
- function replayFSJournal(e, t) {
1423
- e[__private__dont__use].journal.unbind();
682
+ function Q(r, e) {
683
+ r[p].journal.unbind();
1424
684
  try {
1425
- for (const r of t)
1426
- 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);
685
+ for (const t of e)
686
+ 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);
1427
687
  } finally {
1428
- e[__private__dont__use].journal.bind();
688
+ r[p].journal.bind();
1429
689
  }
1430
690
  }
1431
- function* recordExistingPath(e, t, r) {
1432
- if (e.isDir(t)) {
691
+ function* F(r, e, t) {
692
+ if (r.isDir(e)) {
1433
693
  yield {
1434
694
  operation: "CREATE",
1435
- path: r,
695
+ path: t,
1436
696
  nodeType: "directory"
1437
697
  };
1438
- for (const s of e.listFiles(t))
1439
- yield* recordExistingPath(
1440
- e,
1441
- joinPaths(t, s),
1442
- joinPaths(r, s)
698
+ for (const o of r.listFiles(e))
699
+ yield* F(
700
+ r,
701
+ g(e, o),
702
+ g(t, o)
1443
703
  );
1444
704
  } else
1445
705
  yield {
1446
706
  operation: "CREATE",
1447
- path: r,
707
+ path: t,
1448
708
  nodeType: "file"
1449
709
  }, yield {
1450
710
  operation: "WRITE",
1451
711
  nodeType: "file",
1452
- path: r
712
+ path: t
1453
713
  };
1454
714
  }
1455
- function normalizePath(e) {
1456
- return e.replace(/\/$/, "").replace(/\/\/+/g, "/");
715
+ function H(r) {
716
+ return r.replace(/\/$/, "").replace(/\/\/+/g, "/");
1457
717
  }
1458
- function normalizeFilesystemOperations(e) {
1459
- const t = {};
1460
- for (let r = e.length - 1; r >= 0; r--) {
1461
- for (let s = r - 1; s >= 0; s--) {
1462
- const i = checkRelationship(e[r], e[s]);
1463
- if (i === "none")
718
+ function U(r) {
719
+ const e = {};
720
+ for (let t = r.length - 1; t >= 0; t--) {
721
+ for (let o = t - 1; o >= 0; o--) {
722
+ const n = Z(r[t], r[o]);
723
+ if (n === "none")
1464
724
  continue;
1465
- const n = e[r], o = e[s];
1466
- if (n.operation === "RENAME" && o.operation === "RENAME") {
1467
- logger.warn(
725
+ const i = r[t], s = r[o];
726
+ if (i.operation === "RENAME" && s.operation === "RENAME") {
727
+ b.warn(
1468
728
  "[FS Journal] Normalizing a double rename is not yet supported:",
1469
729
  {
1470
- current: n,
1471
- last: o
730
+ current: i,
731
+ last: s
1472
732
  }
1473
733
  );
1474
734
  continue;
1475
735
  }
1476
- (o.operation === "CREATE" || o.operation === "WRITE") && (n.operation === "RENAME" ? i === "same_node" ? (t[s] = [], t[r] = [
736
+ (s.operation === "CREATE" || s.operation === "WRITE") && (i.operation === "RENAME" ? n === "same_node" ? (e[o] = [], e[t] = [
1477
737
  {
1478
- ...o,
1479
- path: n.toPath
738
+ ...s,
739
+ path: i.toPath
1480
740
  },
1481
- ...t[r] || []
1482
- ]) : i === "descendant" && (t[s] = [], t[r] = [
741
+ ...e[t] || []
742
+ ]) : n === "descendant" && (e[o] = [], e[t] = [
1483
743
  {
1484
- ...o,
1485
- path: joinPaths(
1486
- n.toPath,
1487
- o.path.substring(n.path.length)
744
+ ...s,
745
+ path: g(
746
+ i.toPath,
747
+ s.path.substring(i.path.length)
1488
748
  )
1489
749
  },
1490
- ...t[r] || []
1491
- ]) : n.operation === "WRITE" && i === "same_node" ? t[s] = [] : n.operation === "DELETE" && i === "same_node" && (t[s] = [], t[r] = []));
750
+ ...e[t] || []
751
+ ]) : i.operation === "WRITE" && n === "same_node" ? e[o] = [] : i.operation === "DELETE" && n === "same_node" && (e[o] = [], e[t] = []));
1492
752
  }
1493
- if (Object.entries(t).length > 0) {
1494
- const s = e.flatMap((i, n) => n in t ? t[n] : [i]);
1495
- return normalizeFilesystemOperations(s);
753
+ if (Object.entries(e).length > 0) {
754
+ const o = r.flatMap((n, i) => i in e ? e[i] : [n]);
755
+ return U(o);
1496
756
  }
1497
757
  }
1498
- return e;
758
+ return r;
1499
759
  }
1500
- function checkRelationship(e, t) {
1501
- 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;
1502
- return n === r ? "same_node" : i && r.startsWith(n + "/") ? "ancestor" : s && n.startsWith(r + "/") ? "descendant" : "none";
760
+ function Z(r, e) {
761
+ const t = r.path, o = r.operation !== "WRITE" && r.nodeType === "directory", n = e.operation !== "WRITE" && e.nodeType === "directory", i = e.operation === "RENAME" ? e.toPath : e.path;
762
+ return i === t ? "same_node" : n && t.startsWith(i + "/") ? "ancestor" : o && i.startsWith(t + "/") ? "descendant" : "none";
1503
763
  }
1504
- async function hydrateUpdateFileOps(e, t) {
1505
- const s = t.filter(
1506
- (i) => i.operation === "WRITE"
1507
- ).map((i) => hydrateOp(e, i));
1508
- return await Promise.all(s), t;
764
+ async function X(r, e) {
765
+ const o = e.filter(
766
+ (n) => n.operation === "WRITE"
767
+ ).map((n) => V(r, n));
768
+ return await Promise.all(o), e;
1509
769
  }
1510
- const hydrateLock = new Semaphore({ concurrency: 15 });
1511
- async function hydrateOp(e, t) {
1512
- const r = await hydrateLock.acquire();
770
+ const K = new $({ concurrency: 15 });
771
+ async function V(r, e) {
772
+ const t = await K.acquire();
1513
773
  try {
1514
- t.data = await e.readFileAsBuffer(t.path);
1515
- } catch (s) {
1516
- logger.warn(
1517
- `Journal failed to hydrate a file on flush: the path ${t.path} no longer exists`
1518
- ), logger.error(s);
774
+ e.data = await r.readFileAsBuffer(e.path);
775
+ } catch (o) {
776
+ b.warn(
777
+ `Journal failed to hydrate a file on flush: the path ${e.path} no longer exists`
778
+ ), b.error(o);
1519
779
  }
1520
- r();
780
+ t();
1521
781
  }
1522
782
  export {
1523
- hydrateUpdateFileOps,
1524
- journalFSEvents,
1525
- normalizeFilesystemOperations,
1526
- replayFSJournal
783
+ X as hydrateUpdateFileOps,
784
+ Y as journalFSEvents,
785
+ U as normalizeFilesystemOperations,
786
+ Q as replayFSJournal
1527
787
  };