lune_std_net/
lib.rs

1#![allow(clippy::cargo_common_metadata)]
2
3use lune_utils::TableBuilder;
4use mlua::prelude::*;
5
6pub(crate) mod body;
7pub(crate) mod client;
8pub(crate) mod server;
9pub(crate) mod shared;
10pub(crate) mod url;
11
12use self::{
13    client::ws_stream::WsStream,
14    server::config::ServeConfig,
15    shared::{request::Request, response::Response, websocket::Websocket},
16};
17
18pub use self::client::fetch;
19
20const TYPEDEFS: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/types.d.luau"));
21
22/**
23    Returns a string containing type definitions for the `net` standard library.
24*/
25#[must_use]
26pub fn typedefs() -> String {
27    TYPEDEFS.to_string()
28}
29
30/**
31    Creates the `net` standard library module.
32
33    # Errors
34
35    Errors when out of memory.
36*/
37pub fn module(lua: Lua) -> LuaResult<LuaTable> {
38    // No initial rustls setup is necessary, the respective
39    // functions lazily initialize anything there as needed
40    TableBuilder::new(lua)?
41        .with_async_function("request", net_request)?
42        .with_async_function("socket", net_socket)?
43        .with_async_function("serve", net_serve)?
44        .with_function("urlEncode", net_url_encode)?
45        .with_function("urlDecode", net_url_decode)?
46        .build_readonly()
47}
48
49async fn net_request(lua: Lua, req: Request) -> LuaResult<Response> {
50    self::client::send(req, lua).await
51}
52
53async fn net_socket(_: Lua, url: String) -> LuaResult<Websocket<WsStream>> {
54    let url = url.parse().into_lua_err()?;
55    self::client::connect_websocket(url).await
56}
57
58async fn net_serve(lua: Lua, (port, config): (u16, ServeConfig)) -> LuaResult<LuaTable> {
59    self::server::serve(lua.clone(), port, config)
60        .await?
61        .into_lua_table(lua)
62}
63
64fn net_url_encode(
65    lua: &Lua,
66    (lua_string, as_binary): (LuaString, Option<bool>),
67) -> LuaResult<LuaString> {
68    let as_binary = as_binary.unwrap_or_default();
69    let bytes = self::url::encode(lua_string, as_binary)?;
70    lua.create_string(bytes)
71}
72
73fn net_url_decode(
74    lua: &Lua,
75    (lua_string, as_binary): (LuaString, Option<bool>),
76) -> LuaResult<LuaString> {
77    let as_binary = as_binary.unwrap_or_default();
78    let bytes = self::url::decode(lua_string, as_binary)?;
79    lua.create_string(bytes)
80}