@waffle-os/runtime 0.0.152 → 0.0.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/browser/net/helper.ts +114 -19
  2. package/browser/net/ring.ts +18 -6
  3. package/browser/net/runtime.ts +2 -2
  4. package/browser/notification-relay.ts +105 -18
  5. package/browser/notification-wait.ts +45 -4
  6. package/browser/notification-worker.ts +169 -76
  7. package/browser/preview.ts +15 -2
  8. package/browser/run-command.ts +14 -8
  9. package/browser/runtime-terminals.ts +26 -0
  10. package/browser/terminal-output.ts +3 -1
  11. package/core/filesystem.ts +4 -0
  12. package/core/wasi.ts +49 -0
  13. package/dist/browser/net/helper.js +83 -18
  14. package/dist/browser/net/ring.js +6 -5
  15. package/dist/browser/net/runtime.js +2 -2
  16. package/dist/browser/notification-relay.js +78 -15
  17. package/dist/browser/notification-wait.js +37 -5
  18. package/dist/browser/notification-worker.js +146 -67
  19. package/dist/browser/run-command.js +11 -7
  20. package/dist/browser/runtime-terminals.js +16 -0
  21. package/dist/browser/terminal-output.js +2 -2
  22. package/dist/core/wasi.js +40 -0
  23. package/dist/fs/backend.js +7 -0
  24. package/dist/fs/client.js +69 -15
  25. package/dist/fs/dirty-admission.js +15 -8
  26. package/dist/fs/indexeddb.js +288 -96
  27. package/dist/fs/memory.js +106 -20
  28. package/dist/fs/multitab-backend.js +121 -37
  29. package/dist/fs/multitab-protocol.js +1 -0
  30. package/dist/fs/persistent.js +70 -16
  31. package/dist/fs/protocol.js +15 -7
  32. package/dist/fs/publication-attachment.js +9 -7
  33. package/dist/fs/service.js +34 -9
  34. package/dist/fs/shared.js +96 -6
  35. package/dist/proc/command-stdio.js +1 -1
  36. package/dist/proc/start-command.js +4 -0
  37. package/dist/tooling/program/program-transformer.json +1 -1
  38. package/fs/backend.ts +11 -0
  39. package/fs/client.ts +93 -16
  40. package/fs/dirty-admission.ts +22 -7
  41. package/fs/guest-watch.ts +1 -1
  42. package/fs/indexeddb.ts +379 -110
  43. package/fs/memory.ts +120 -19
  44. package/fs/multitab-backend.ts +206 -61
  45. package/fs/multitab-protocol.ts +1 -0
  46. package/fs/persistent.ts +82 -16
  47. package/fs/protocol.ts +26 -7
  48. package/fs/publication-attachment.ts +9 -7
  49. package/fs/service.ts +35 -7
  50. package/fs/shared.ts +106 -8
  51. package/package.json +1 -1
  52. package/proc/command-stdio.ts +1 -1
  53. package/proc/start-command.ts +9 -0
  54. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  55. package/testing/indexeddb-storage-browser.ts +435 -1
  56. package/tooling/program/program-transformer.json +1 -1
@@ -34,10 +34,10 @@ export class RingWriter extends RingBase {
34
34
  headerView = new DataView(this.header.buffer);
35
35
  queue = Promise.resolve();
36
36
  disposed = false;
37
- write(handle, kind, payload = new Uint8Array) {
37
+ write(handle, kind, payload = new Uint8Array, dropped) {
38
38
  if (payload.length > MAX_RECORD)
39
39
  return Promise.reject(new RangeError(`ring record too large: ${payload.length}`));
40
- this.queue = this.queue.then(() => this.append(handle, kind, payload));
40
+ this.queue = this.queue.then(() => this.append(handle, kind, payload, dropped));
41
41
  return this.queue;
42
42
  }
43
43
  dispose() {
@@ -45,11 +45,12 @@ export class RingWriter extends RingBase {
45
45
  Atomics.add(this.cells, SPACE, 1);
46
46
  Atomics.notify(this.cells, SPACE);
47
47
  }
48
- async append(handle, kind, payload) {
48
+ async append(handle, kind, payload, dropped) {
49
49
  const size = align4(RECORD_HEADER + payload.length);
50
- while (!this.disposed && CAPACITY - this.used() < size)
50
+ const skip = () => this.disposed || dropped?.() === true;
51
+ while (!skip() && CAPACITY - this.used() < size)
51
52
  await this.waitForSpace(size);
52
- if (this.disposed)
53
+ if (skip())
53
54
  return;
54
55
  this.headerView.setInt32(0, handle, true);
55
56
  this.headerView.setInt32(4, kind, true);
@@ -97,9 +97,9 @@ function project(helper, assertLive, release) {
97
97
  live();
98
98
  return helper.listenerFor(port);
99
99
  },
100
- request(port, request, sink) {
100
+ request(port, request, sink, options) {
101
101
  live();
102
- return helper.request(port, request, sink);
102
+ return helper.request(port, request, sink, options);
103
103
  },
104
104
  connect(port, sink) {
105
105
  live();
@@ -1,17 +1,90 @@
1
1
  import { allocateSharedControl } from "../memory/control.js";
2
+
3
+ class SharedRelay {
4
+ url;
5
+ registry;
6
+ worker;
7
+ members = new Map;
8
+ drops = new Map;
9
+ nextId = 1;
10
+ constructor(url, registry) {
11
+ this.url = url;
12
+ this.registry = registry;
13
+ this.worker = new Worker(url, { type: "module" });
14
+ this.worker.onerror = () => {
15
+ for (const dispose of Array.from(this.members.values()))
16
+ dispose().catch(() => {});
17
+ };
18
+ this.worker.onmessage = ({ data }) => {
19
+ const id = data?.id;
20
+ if (data?.type === "dropped")
21
+ return this.acknowledge(id);
22
+ this.members.get(id)?.().catch(() => {});
23
+ };
24
+ }
25
+ add(port, state, dispose) {
26
+ const id = this.nextId++;
27
+ this.worker.postMessage({ id, port, state }, [port]);
28
+ this.members.set(id, dispose);
29
+ return id;
30
+ }
31
+ remove(id) {
32
+ const known = this.members.delete(id);
33
+ if (!this.members.size)
34
+ return this.stop();
35
+ if (!known)
36
+ return Promise.resolve();
37
+ const dropped = Promise.withResolvers();
38
+ this.drops.set(id, dropped);
39
+ try {
40
+ this.worker.postMessage({ drop: id });
41
+ } catch {
42
+ this.acknowledge(id);
43
+ }
44
+ return dropped.promise;
45
+ }
46
+ acknowledge(id) {
47
+ const dropped = this.drops.get(id);
48
+ this.drops.delete(id);
49
+ dropped?.resolve();
50
+ }
51
+ stop() {
52
+ if (this.registry.get(this.url) === this)
53
+ this.registry.delete(this.url);
54
+ let stopped;
55
+ try {
56
+ stopped = Promise.resolve(this.worker.terminate());
57
+ } catch (error) {
58
+ stopped = Promise.reject(error);
59
+ }
60
+ for (const [id, dropped] of Array.from(this.drops)) {
61
+ this.drops.delete(id);
62
+ stopped.then(dropped.resolve, dropped.reject);
63
+ }
64
+ return stopped;
65
+ }
66
+ }
67
+ const relays = new Map;
68
+ function relayFor(url) {
69
+ let relay = relays.get(url);
70
+ if (!relay)
71
+ relays.set(url, relay = new SharedRelay(url, relays));
72
+ return relay;
73
+ }
2
74
  export function createNotificationBridge(workerUrl) {
3
75
  const channel = new MessageChannel;
4
76
  let state;
5
- let worker;
77
+ let relay;
6
78
  try {
7
- state = new Int32Array(allocateSharedControl(8));
8
- worker = new Worker(workerUrl, { type: "module" });
79
+ state = new Int32Array(allocateSharedControl(12));
80
+ relay = relayFor(workerUrl);
9
81
  } catch (error) {
10
82
  channel.port1.close();
11
83
  channel.port2.close();
12
84
  throw error;
13
85
  }
14
86
  let disposed = false;
87
+ let id = 0;
15
88
  let finish;
16
89
  let fail;
17
90
  const closed = new Promise((resolve, reject) => {
@@ -26,21 +99,11 @@ export function createNotificationBridge(workerUrl) {
26
99
  Atomics.add(state, 0, 1);
27
100
  Atomics.notify(state, 0);
28
101
  channel.port2.close();
29
- try {
30
- Promise.resolve(worker.terminate()).then(finish, fail);
31
- } catch (error) {
32
- fail(error);
33
- }
102
+ relay.remove(id).then(finish, fail);
34
103
  return closed;
35
104
  };
36
- worker.onerror = () => {
37
- dispose().catch(() => {});
38
- };
39
- worker.onmessage = () => {
40
- dispose().catch(() => {});
41
- };
42
105
  try {
43
- worker.postMessage({ port: channel.port1, state }, [channel.port1]);
106
+ id = relay.add(channel.port1, state, dispose);
44
107
  } catch (error) {
45
108
  channel.port1.close();
46
109
  dispose().catch(() => {});
@@ -107,6 +107,16 @@ export class NotificationWaitScope {
107
107
  }
108
108
  waitSet(filesystem, network, process, sources, initialCoverage) {
109
109
  let covered = initialCoverage;
110
+ const active = this.connection.state;
111
+ let nextPark = 1;
112
+ const park = (observed) => {
113
+ const values = parkValues(observed, network !== undefined, process !== undefined);
114
+ const id = nextPark;
115
+ nextPark = nextPark === 2147483647 ? 1 : nextPark + 1;
116
+ atomicsStore(active, 2, id);
117
+ this.send({ type: "park", id, values });
118
+ };
119
+ const retire = () => atomicsStore(active, 2, 0);
110
120
  const disposed = () => this.status === "closed" || atomicsLoad(this.connection.state, 1) !== 0;
111
121
  const sample = () => ({
112
122
  sequence: atomicsLoad(this.wake, 0),
@@ -123,16 +133,28 @@ export class NotificationWaitScope {
123
133
  },
124
134
  sample,
125
135
  wait: (observed, deadline) => {
136
+ const settled = (result) => disposed() ? "closed" : result;
126
137
  if (disposed())
127
138
  return "closed";
128
- const current = sample();
129
- if (changed(observed, current))
130
- return "not-equal";
139
+ if (changed(observed, sample()))
140
+ return settled("not-equal");
131
141
  const remaining = deadline === 1 / 0 ? 1 / 0 : maximum(0, deadline - now());
132
142
  if (remaining === 0)
133
- return "timed-out";
143
+ return settled("timed-out");
144
+ try {
145
+ park(observed);
146
+ } catch {
147
+ retire();
148
+ this.cleanupStep(() => this.dispose());
149
+ return "closed";
150
+ }
151
+ if (changed(observed, sample())) {
152
+ retire();
153
+ return settled("not-equal");
154
+ }
134
155
  const result = atomicsWait(this.wake, 0, observed.sequence, covered ? remaining : minimum(remaining, 10));
135
- return disposed() ? "closed" : result;
156
+ retire();
157
+ return settled(result);
136
158
  },
137
159
  setProcessSubscriptions(subscriptions) {
138
160
  covered = sources.process?.registerPoll(subscriptions, "shared").covered ?? subscriptions.length === 0;
@@ -174,6 +196,16 @@ export class NotificationWaitScope {
174
196
  }
175
197
  }
176
198
  }
199
+ function parkValues(sample, network, process) {
200
+ const filesystem = sample.filesystem;
201
+ if (network && process)
202
+ return [filesystem, sample.network, sample.process];
203
+ if (network)
204
+ return [filesystem, sample.network];
205
+ if (process)
206
+ return [filesystem, sample.process];
207
+ return [filesystem];
208
+ }
177
209
  function changed(before, after) {
178
210
  return before.sequence !== after.sequence || before.filesystem !== after.filesystem || before.network !== after.network || before.process !== after.process;
179
211
  }
@@ -2,82 +2,161 @@ import {
2
2
  createNotificationWaiters,
3
3
  notificationBlockingWait
4
4
  } from "./notification-blocking-wait.js";
5
- const waiters = createNotificationWaiters(import.meta.url);
6
- const waitForWord = waiters.wait;
7
- const observers = [];
8
- const pendingWaits = [];
9
- function publish(state) {
10
- if (Atomics.load(state, 1))
11
- return;
12
- Atomics.add(state, 0, 1);
13
- Atomics.notify(state, 0);
14
- }
15
- function clearRoot(roots, slot) {
16
- if (slot < roots.length)
17
- roots[slot] = undefined;
18
- }
19
- async function observe(word, state, slot) {
20
- let seen = Atomics.load(word.cells, word.index);
21
- while (!Atomics.load(state, 1)) {
22
- const waiting = waitForWord(word.cells, word.index, seen);
23
- if (!waiting.async) {
24
- seen = Atomics.load(word.cells, word.index);
25
- publish(state);
26
- continue;
27
- }
28
- pendingWaits[slot] = waiting.value;
29
- try {
30
- await waiting.value;
31
- } finally {
32
- clearRoot(pendingWaits, slot);
33
- }
34
- seen = Atomics.load(word.cells, word.index);
35
- publish(state);
36
- }
37
- }
38
- async function observeSafely(word, state, reply, slot) {
39
- try {
40
- await observe(word, state, slot);
41
- } catch (error) {
42
- reply({ type: "error", message: String(error) });
43
- globalThis.postMessage("failed");
44
- } finally {
45
- clearRoot(observers, slot);
5
+ const MAX_WORDS = 3;
6
+
7
+ class RelayConnection {
8
+ id;
9
+ port;
10
+ state;
11
+ words;
12
+ parked;
13
+ outstanding = [];
14
+ pendingWaits = [];
15
+ waiters = createNotificationWaiters(import.meta.url);
16
+ closed = false;
17
+ failed = false;
18
+ constructor(id, port, state) {
19
+ this.id = id;
20
+ this.port = port;
21
+ this.state = state;
22
+ port.onmessage = ({ data }) => {
23
+ try {
24
+ this.receive(data);
25
+ } catch (error) {
26
+ this.fail(error);
27
+ }
28
+ };
29
+ port.start();
46
30
  }
47
- }
48
- function arm(words, state, reply) {
49
- for (let slot = 0;slot < words.length; slot++)
50
- observers[slot] = observeSafely(words[slot], state, reply, slot);
51
- reply({ type: "armed" });
52
- }
53
- function connect({ port, state }) {
54
- let armed = false;
55
- const reply = (value) => port.postMessage(value);
56
- port.onmessage = ({ data }) => {
57
- if (data.type === "dispose") {
58
- waiters.dispose();
59
- observers.length = 0;
60
- pendingWaits.length = 0;
61
- port.close();
62
- globalThis.postMessage("disposed");
31
+ receive(data) {
32
+ if (this.closed || this.failed)
63
33
  return;
64
- }
65
- if (armed || Atomics.load(state, 1))
34
+ if (!data || typeof data !== "object")
35
+ throw new TypeError("malformed notification request");
36
+ if (data.type === "dispose")
37
+ return this.dispose(true);
38
+ if (Atomics.load(this.state, 1))
66
39
  return;
67
- armed = true;
40
+ if (data.type === "park")
41
+ return this.park(data);
42
+ if (data.type !== "arm" || this.words)
43
+ throw new TypeError("unexpected notification request");
68
44
  try {
69
- arm(data.words, state, reply);
45
+ this.arm(data.words);
70
46
  } catch (error) {
71
- reply({ type: "error", message: String(error) });
47
+ this.reply({ type: "error", message: String(error) });
72
48
  }
73
- };
74
- port.start();
49
+ }
50
+ arm(words) {
51
+ if (words.length > MAX_WORDS)
52
+ throw new RangeError("too many notification words");
53
+ for (const word of words)
54
+ Atomics.load(word.cells, word.index);
55
+ this.words = words;
56
+ this.reply({ type: "armed" });
57
+ }
58
+ park({ id, values }) {
59
+ const words = this.words;
60
+ if (!words)
61
+ throw new TypeError("notification park before arm");
62
+ if (typeof id !== "number" || (id | 0) !== id || id <= 0 || !validValues(values, words.length))
63
+ throw new TypeError("malformed notification park");
64
+ this.parked = { id, values };
65
+ if (this.moved(this.parked))
66
+ return this.publish();
67
+ for (let slot = 0;slot < words.length; slot++)
68
+ this.watch(slot);
69
+ }
70
+ moved(parked) {
71
+ const words = this.words;
72
+ for (let slot = 0;slot < words.length; slot++)
73
+ if (Atomics.load(words[slot].cells, words[slot].index) !== parked.values[slot])
74
+ return true;
75
+ return false;
76
+ }
77
+ watch(slot) {
78
+ const parked = this.parked;
79
+ if (!parked || this.outstanding[slot] !== undefined)
80
+ return;
81
+ const word = this.words[slot];
82
+ const seen = parked.values[slot];
83
+ const waiting = this.waiters.wait(word.cells, word.index, seen);
84
+ if (!waiting.async)
85
+ return this.publish();
86
+ this.outstanding[slot] = seen;
87
+ this.pendingWaits[slot] = waiting.value;
88
+ waiting.value.then(() => this.settle(slot, seen), (error) => this.fail(error));
89
+ }
90
+ settle(slot, seen) {
91
+ if (this.closed)
92
+ return;
93
+ this.outstanding[slot] = undefined;
94
+ this.pendingWaits[slot] = undefined;
95
+ const parked = this.parked;
96
+ if (!parked)
97
+ return;
98
+ const word = this.words[slot];
99
+ if (seen === parked.values[slot] || Atomics.load(word.cells, word.index) !== parked.values[slot])
100
+ return this.publish();
101
+ this.watch(slot);
102
+ }
103
+ publish() {
104
+ const parked = this.parked;
105
+ this.parked = undefined;
106
+ if (Atomics.load(this.state, 1))
107
+ return;
108
+ if (Atomics.compareExchange(this.state, 2, parked.id, 0) !== parked.id)
109
+ return;
110
+ Atomics.add(this.state, 0, 1);
111
+ Atomics.notify(this.state, 0);
112
+ }
113
+ reply(value) {
114
+ this.port.postMessage(value);
115
+ }
116
+ fail(error) {
117
+ if (this.closed || this.failed)
118
+ return;
119
+ this.failed = true;
120
+ this.parked = undefined;
121
+ this.reply({ type: "error", message: String(error) });
122
+ notice(this.id, "failed");
123
+ }
124
+ dispose(fromGuest = true) {
125
+ if (this.closed)
126
+ return;
127
+ this.closed = true;
128
+ this.parked = undefined;
129
+ this.waiters.dispose();
130
+ this.outstanding.length = 0;
131
+ this.pendingWaits.length = 0;
132
+ this.port.close();
133
+ connections.delete(this.id);
134
+ if (fromGuest)
135
+ notice(this.id, "disposed");
136
+ }
75
137
  }
138
+ function validValues(values, length) {
139
+ if (!Array.isArray(values) || values.length !== length)
140
+ return false;
141
+ for (let index = 0;index < length; index++) {
142
+ const value = values[index];
143
+ if (typeof value !== "number" || (value | 0) !== value)
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ function notice(id, type) {
149
+ globalThis.postMessage({ id, type });
150
+ }
151
+ const connections = new Map;
76
152
  globalThis.onmessage = ({
77
153
  data
78
154
  }) => {
79
155
  if ("type" in data)
80
- notificationBlockingWait(data);
81
- else
82
- connect(data);
156
+ return notificationBlockingWait(data);
157
+ if ("drop" in data) {
158
+ connections.get(data.drop)?.dispose(false);
159
+ return notice(data.drop, "dropped");
160
+ }
161
+ connections.set(data.id, new RelayConnection(data.id, data.port, data.state));
83
162
  };
@@ -13,7 +13,7 @@ import {
13
13
  WorkerProcessClient,
14
14
  workerProcessState
15
15
  } from "../proc/worker-client.js";
16
- import { createRuntimeTerminalCodec } from "./runtime-terminals.js";
16
+ import { createRuntimeTerminalCodec, hostPipeDestination } from "./runtime-terminals.js";
17
17
  import { CommandInput } from "./command-input.js";
18
18
  import { yieldTask } from "./yield-task.js";
19
19
  const READ = 1n << 1n;
@@ -318,14 +318,18 @@ class Command {
318
318
  for (const fd of [0, 1, 2]) {
319
319
  if (fd === 0 && stdin !== undefined || fd === 1 && this.options.stdout === "closed" || fd === 2 && this.options.stderr === "closed")
320
320
  continue;
321
- this.descriptors.openAt(fd, {
322
- kind: "terminal",
323
- read: () => 0,
324
- write: () => 0,
325
- readiness: () => ({ readable: fd === 0, writable: fd !== 0, hangup: fd === 0 })
326
- }, (fd === 0 ? READ : WRITE) | POLL | FD_FILESTAT_GET, 0n);
321
+ this.descriptors.openAt(fd, this.hostStdio(fd), (fd === 0 ? READ : WRITE) | POLL | FD_FILESTAT_GET, 0n);
327
322
  }
328
323
  }
324
+ hostStdio(fd) {
325
+ const stream = {
326
+ kind: this.options.terminal ? "terminal" : "pipe",
327
+ read: () => 0,
328
+ write: () => 0,
329
+ readiness: () => ({ readable: fd === 0, writable: fd !== 0, hangup: fd === 0 })
330
+ };
331
+ return this.options.terminal ? stream : hostPipeDestination(fd, stream);
332
+ }
329
333
  deliver(fd, bytes) {
330
334
  if (this.outputBatch === 0) {
331
335
  this.outputTask ??= yieldTask().then(() => {
@@ -5,7 +5,15 @@ import { ProcessError } from "../proc/types.js";
5
5
  import { WeakMapConstructor, weakMapGet, weakMapHas, weakMapSet } from "../proc/intrinsics.js";
6
6
  import { hostTerminalStream } from "./terminal-output.js";
7
7
  const targets = new WeakMapConstructor;
8
+ const pipeDestinations = new WeakMapConstructor;
8
9
  const NOSYS = 52;
10
+ export function hostPipeDestination(target, stream) {
11
+ if (stream.kind !== "pipe")
12
+ throw new TypeError("host pipe destination must be a pipe");
13
+ weakMapSet(targets, stream, target);
14
+ weakMapSet(pipeDestinations, stream, true);
15
+ return stream;
16
+ }
9
17
  function nullDeviceToken(value) {
10
18
  if (typeof value !== "object" || value === null || !("kind" in value) || value.kind !== "null-device")
11
19
  return;
@@ -19,6 +27,8 @@ function terminalToken(value) {
19
27
  return;
20
28
  if (!("target" in value) || value.target !== 0 && value.target !== 1 && value.target !== 2)
21
29
  throw new TypeError("invalid browser terminal target");
30
+ if ("pipe" in value && value.pipe !== true)
31
+ throw new TypeError("invalid browser terminal kind");
22
32
  return value;
23
33
  }
24
34
  function resolveTerminal(options, target) {
@@ -52,6 +62,8 @@ export function createRuntimeTerminalCodec(options) {
52
62
  return options.fallback.export(descriptor, pid);
53
63
  if (target === undefined)
54
64
  throw new ProcessError(NOSYS, "terminal has no transferable browser destination");
65
+ if (weakMapHas(pipeDestinations, resource))
66
+ return { kind: "web-terminal", target, pipe: true };
55
67
  return { kind: "web-terminal", target };
56
68
  },
57
69
  import(value, pid) {
@@ -61,6 +73,10 @@ export function createRuntimeTerminalCodec(options) {
61
73
  const token = terminalToken(value);
62
74
  if (!token)
63
75
  return options.fallback.import(value, pid);
76
+ if (token.pipe) {
77
+ const stream = hostTerminalStream(token.target, options.output, options.checkActive, "pipe");
78
+ return new OpenDescription(hostPipeDestination(token.target, stream));
79
+ }
64
80
  const resolved = resolveTerminal(options, token.target);
65
81
  if (resolved !== undefined) {
66
82
  const remember = (stream) => {
@@ -386,7 +386,7 @@ export function deliveredTerminalOutput(deliver) {
386
386
  writable: () => true
387
387
  };
388
388
  }
389
- export function hostTerminalStream(target, output, checkActive) {
389
+ export function hostTerminalStream(target, output, checkActive, kind = "terminal") {
390
390
  const destination = target === 2 ? 2 : 1;
391
391
  const read = () => {
392
392
  checkActive?.();
@@ -401,7 +401,7 @@ export function hostTerminalStream(target, output, checkActive) {
401
401
  return blocking && output.write ? output.write(destination, chunks) : output.tryWrite(destination, chunks);
402
402
  };
403
403
  return {
404
- kind: "terminal",
404
+ kind,
405
405
  read,
406
406
  tryRead: read,
407
407
  write: (chunks) => send(true, chunks),
package/dist/core/wasi.js CHANGED
@@ -118,6 +118,14 @@ function followsFinal(final, path) {
118
118
  function lookupFlags(flags) {
119
119
  return flags & 1 ? "follow" : "nofollow";
120
120
  }
121
+ function guestPathname(bytes, ptr, len) {
122
+ try {
123
+ const path = decodeBytes(bytes, ptr, len, fatalDecoder);
124
+ return path.includes("\x00") ? undefined : path;
125
+ } catch {
126
+ return;
127
+ }
128
+ }
121
129
  function writeUtf8Prefix(target, output) {
122
130
  if (output.length === 0)
123
131
  return 0;
@@ -338,6 +346,7 @@ export class Wasi {
338
346
  const impl = this.functions();
339
347
  const filesystem = {
340
348
  path_permissions_get: this.pathPermissions.bind(this),
349
+ path_realpath: this.pathRealpath.bind(this),
341
350
  watch_open: this.watchOpen.bind(this),
342
351
  watch_ready: () => this.watches?.ready() ? 1 : 0,
343
352
  watch_read: this.watchRead.bind(this),
@@ -533,6 +542,37 @@ export class Wasi {
533
542
  this.view().setUint32(out, result.length, true);
534
543
  return SUCCESS;
535
544
  }
545
+ pathRealpath(fd, ptr, len, buf, capacity, used) {
546
+ ptr >>>= 0;
547
+ len >>>= 0;
548
+ buf >>>= 0;
549
+ capacity >>>= 0;
550
+ used >>>= 0;
551
+ const bytes = this.bytes();
552
+ if (ptr + len > bytes.length || buf + capacity > bytes.length || used + 4 > bytes.length)
553
+ return EFAULT;
554
+ if (capacity > 0 && buf < used + 4 && used < buf + capacity)
555
+ return EINVAL;
556
+ const path = guestPathname(bytes, ptr, len);
557
+ if (path === undefined)
558
+ return EINVAL;
559
+ const entry = this.descriptors.get(fd >>> 0);
560
+ if (!entry)
561
+ return EBADF;
562
+ if (entry.resource.kind !== "directory")
563
+ return ENOTDIR;
564
+ if (!(entry.rightsBase & RIGHT_PATH_FILESTAT_GET))
565
+ return ENOTCAPABLE;
566
+ const real = this.opts.fs.realpath(entry.resource.handle, path, this.rooted);
567
+ if (typeof real === "number")
568
+ return real;
569
+ const encoded = encoder.encode(real);
570
+ this.view().setUint32(used, encoded.length, true);
571
+ if (encoded.length > capacity)
572
+ return ENOBUFS;
573
+ this.memory.range(buf, encoded.length).set(encoded);
574
+ return SUCCESS;
575
+ }
536
576
  pathPermissions(fd, ptr, len, flags, out) {
537
577
  if (flags !== 0)
538
578
  return ENOTSUP;
@@ -16,6 +16,9 @@ function sameTimes(left, right) {
16
16
 
17
17
  export class MemoryBackend {
18
18
  watchOwner;
19
+ unlinkGeneration() {
20
+ return this.shared.unlinkGeneration();
21
+ }
19
22
  installWatchObserver(observer) {
20
23
  if (this.watchOwner.observer && this.watchOwner.observer !== observer)
21
24
  throw new Error("filesystem root already has a watch owner");
@@ -96,6 +99,7 @@ export class MemoryBackend {
96
99
  this.shared = new SharedFilesystemState(buffer, maxBytes, undefined, segments, undefined, publication);
97
100
  if (this.sharedPhase !== "imported")
98
101
  this.shared.identities.copyFrom(previous.identities);
102
+ this.shared.continueUnlinks(previous);
99
103
  this.sharedPhase = "attached";
100
104
  }
101
105
  readMetadata(node, revoked) {
@@ -266,6 +270,9 @@ export class MemoryBackend {
266
270
  case "resolve":
267
271
  this.check(a, "directory");
268
272
  return this.fs.resolve(a, b, c === true, args[3] === true);
273
+ case "realpath":
274
+ this.check(a, "directory");
275
+ return this.fs.realpath(a, b, c === true);
269
276
  case "readlink":
270
277
  this.check(a);
271
278
  return this.fs.readlink(a);