Diffinery

homeflare/celldpublic

celld/crates/celld/js/node_net.js
64 lines · 2.3 KBRaw History
1// node:net for celld (Homeflare patch).
2//
3// The address helpers only: isIP, isIPv4 and isIPv6. They're what libraries
4// in Workers reach for, usually to check a URL's host before fetching it
5// (Fedify's public-URL check, for one). Sockets and servers aren't here;
6// calling one throws with the member's name, as the generic stub did.
7//
8// The patterns are Node's own (lib/internal/net.js, MIT), so the answers
9// match Node and workerd for the same input, zone IDs included.
10//
11// Injected lazily, so an isolate that never imports node:net pays nothing.
12(() => {
13 "use strict";
14
15 const v4Seg = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])";
16 const v4Str = `(?:${v4Seg}\\.){3}${v4Seg}`;
17 const IPv4Reg = new RegExp(`^${v4Str}$`);
18
19 const v6Seg = "(?:[0-9a-fA-F]{1,4})";
20 const IPv6Reg = new RegExp(
21 "^(?:" +
22 `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
23 `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
24 `(?:${v6Seg}:){5}(?::${v4Str}|(?::${v6Seg}){1,2}|:)|` +
25 `(?:${v6Seg}:){4}(?:(?::${v6Seg}){0,1}:${v4Str}|(?::${v6Seg}){1,3}|:)|` +
26 `(?:${v6Seg}:){3}(?:(?::${v6Seg}){0,2}:${v4Str}|(?::${v6Seg}){1,4}|:)|` +
27 `(?:${v6Seg}:){2}(?:(?::${v6Seg}){0,3}:${v4Str}|(?::${v6Seg}){1,5}|:)|` +
28 `(?:${v6Seg}:){1}(?:(?::${v6Seg}){0,4}:${v4Str}|(?::${v6Seg}){1,6}|:)|` +
29 `(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
30 ")(?:%[0-9a-zA-Z-.:]{1,})?$",
31 );
32
33 // Node stringifies its argument, so isIP(null) is 0 rather than a throw.
34 const isIPv4 = (input) => IPv4Reg.test(`${input}`);
35 const isIPv6 = (input) => IPv6Reg.test(`${input}`);
36 const isIP = (input) => {
37 if (isIPv4(input)) return 4;
38 if (isIPv6(input)) return 6;
39 return 0;
40 };
41
42 const notImplemented = (name) => {
43 const fn = function () {
44 throw new Error(`node:net.${name} is not implemented in celld`);
45 };
46 Object.defineProperty(fn, "name", { value: name });
47 return fn;
48 };
49
50 const net = {
51 isIP,
52 isIPv4,
53 isIPv6,
54 BlockList: notImplemented("BlockList"),
55 connect: notImplemented("connect"),
56 createConnection: notImplemented("createConnection"),
57 createServer: notImplemented("createServer"),
58 Server: notImplemented("Server"),
59 Socket: notImplemented("Socket"),
60 SocketAddress: notImplemented("SocketAddress"),
61 Stream: notImplemented("Stream"),
62 };
63 __celld.__netModule = net;
64})();