diff --git a/src/runtime/_internal/utils.ts b/src/runtime/_internal/utils.ts index b2897f48..66dcf7a1 100644 --- a/src/runtime/_internal/utils.ts +++ b/src/runtime/_internal/utils.ts @@ -28,3 +28,11 @@ export function notImplemented(name: string) { throw new Error(`[unenv] ${name} is not implemented yet!`); }; } + +export function notImplementedClass(name: string) { + return class { + constructor() { + throw new Error(`[unenv] ${name} is not implemented yet!`); + } + } +} diff --git a/src/runtime/node/net/index.ts b/src/runtime/node/net/index.ts index c166e428..41889cb0 100644 --- a/src/runtime/node/net/index.ts +++ b/src/runtime/node/net/index.ts @@ -1,23 +1,47 @@ // https://nodejs.org/api/net.html import type net from "node:net"; -import { notImplemented } from "../../_internal/utils"; -import * as socket from "./socket"; +import { notImplemented, notImplementedClass } from "../../_internal/utils"; +import { Socket, SocketAddress } from "./socket"; -export * from "./socket"; +export { Socket, SocketAddress } from "./socket"; export const createServer = notImplemented( "net.createServer", ) as typeof net.createServer; +export const Server = notImplementedClass("net.Server") as typeof net.Server; + +export const BlockList = notImplementedClass("net.BlockList") as typeof net.BlockList; + export const connect = notImplemented("net.connect") as typeof net.connect; export const createConnection = notImplemented( "net.createConnection", ) as typeof net.createConnection; -export default { - ...socket, +const IPV4Regex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/; +export const isIPv4: typeof net.isIPv4 = ((host: string) => IPV4Regex.test(host)); + +const IPV6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/; +export const isIPv6: typeof net.isIPv6 = ((host: string) => IPV6Regex.test(host)); + +export const isIP: typeof net.isIP = (host: string) => { + if (isIPv4(host)) return 4; + if (isIPv6(host)) return 6; + return 0; +} + +export const exports: typeof net = { + Socket: Socket as any, // TODO + Server, + BlockList, + SocketAddress, createServer, connect, createConnection, + isIPv4, + isIPv6, + isIP, }; + +export default exports; diff --git a/src/runtime/node/net/socket.ts b/src/runtime/node/net/socket.ts index 5b325c53..4e3095fd 100644 --- a/src/runtime/node/net/socket.ts +++ b/src/runtime/node/net/socket.ts @@ -88,3 +88,16 @@ export class Socket extends Duplex implements net.Socket { return this; } } + +export class SocketAddress implements net.SocketAddress { + address: string; + family: 'ipv4' | 'ipv6'; + port: number; + flowlabel: number; + constructor(options: net.SocketAddress) { + this.address = options.address; + this.family = options.family ; + this.port = options.port; + this.flowlabel = options.flowlabel; + } +}