File size: 1,878 Bytes
bee6636
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { BareMuxConnection } from "@mercuryworkshop/bare-mux";
import { rewriteUrl } from "../../shared/rewriters/url";
import { ScramjetClient } from "../client";

export default function (client: ScramjetClient, _self: typeof globalThis) {
	client.Proxy("Worker", {
		construct(ctx) {
			ctx.args[0] = rewriteUrl(ctx.args[0], client.meta) + "?dest=worker";

			if (ctx.args[1] && ctx.args[1].type === "module") {
				ctx.args[0] += "&type=module";
			}

			const worker = ctx.call();
			const conn = new BareMuxConnection();

			(async () => {
				const port = await conn.getInnerPort();
				client.natives.call(
					"Worker.prototype.postMessage",
					worker,
					{
						$scramjet$type: "baremuxinit",
						port,
					},
					[port]
				);
			})();
		},
	});

	// sharedworkers can only be constructed from window
	client.Proxy("SharedWorker", {
		construct(ctx) {
			ctx.args[0] = rewriteUrl(ctx.args[0], client.meta) + "?dest=sharedworker";

			if (ctx.args[1] && typeof ctx.args[1] === "string")
				ctx.args[1] = `${client.url.origin}@${ctx.args[1]}`;

			if (ctx.args[1] && typeof ctx.args[1] === "object") {
				if (ctx.args[1].type === "module") {
					ctx.args[0] += "&type=module";
				}

				if (ctx.args[1].name) {
					ctx.args[1].name = `${client.url.origin}@${ctx.args[1].name}`;
				}
			}

			const worker = ctx.call();
			const conn = new BareMuxConnection();

			(async () => {
				const port = await conn.getInnerPort();
				client.natives.call(
					"MessagePort.prototype.postMessage",
					worker.port,
					{
						$scramjet$type: "baremuxinit",
						port,
					},
					[port]
				);
			})();
		},
	});

	client.Proxy("Worklet.prototype.addModule", {
		apply(ctx) {
			if (ctx.args[0])
				ctx.args[0] = rewriteUrl(ctx.args[0], client.meta) + "?dest=worklet";
		},
	});
}