1#![no_std]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5extern crate alloc;
6extern crate self as taba; #[cfg(feature = "std")]
8extern crate std;
9
10mod error;
11mod procedure;
12#[cfg(feature = "rpc")]
13pub mod rpc;
14mod typescript;
15
16use alloc::string::{String, ToString as _};
17use core::fmt::{self, Display, Write};
18
19use serde_core::Serialize;
20#[cfg(feature = "derive")]
21pub use taba_derive::{Input, Output};
22
23pub use crate::{
24 error::Error,
25 procedure::{IntoReply, Never, Once, Procedure, Procedures, Strand},
26 typescript::{Input, Key, Output},
27};
28
29pub type Result<T, E = Error> = core::result::Result<T, E>;
31
32#[doc(hidden)]
34pub mod __private {
35 pub use alloc::string::String;
37
38 #[cfg(feature = "rpc")]
39 pub use crate::rpc::__private as rpc;
40 pub use crate::{procedure::__private as procedure, typescript::__private as typescript};
41}
42
43#[macro_export]
60macro_rules! include_scripts {
61 ($(#[$attribute:meta])* $visibility:vis mod $name:ident $(;)?) => {
62 $(#[$attribute])*
63 $visibility mod $name {
64 ::core::include!(::core::concat!(::core::env!("OUT_DIR"), "/taba/mod.rs"));
65 }
66 };
67}
68
69const BLOCK_SCOPED_GLOBAL: &str = "_taba";
71
72pub fn script<T>(bundle: &str, input: &T) -> Result<String, Error>
76where
77 T: ?Sized + Serialize,
78{
79 let input = Json::serialize(input)?.declare_constant();
80 Ok(block(format_args!("{input}\n{bundle}")).to_string())
81}
82
83fn block(body: impl Display) -> impl Display {
87 fmt::from_fn(move |f| write!(f, "{{\n{body}\n}}"))
88}
89
90struct Json(String);
96
97impl Json {
98 fn serialize<T: ?Sized + Serialize>(input: &T) -> Result<Self, Error> {
99 serde_json::to_string(input).map(Self).map_err(Error)
100 }
101
102 fn declare_constant(self) -> impl Display {
103 fmt::from_fn(move |f| write!(f, "const {BLOCK_SCOPED_GLOBAL} = {};", self.json_parse()))
104 }
105
106 fn json_parse(&self) -> impl Display {
107 fmt::from_fn(move |f| write!(f, "JSON.parse({})", self.string_literal()))
108 }
109
110 fn string_literal(&self) -> impl Display {
116 const BACKSLASH: char = '\\';
117 const SINGLE_QUOTE: char = '\'';
118 fmt::from_fn(move |f| {
119 f.write_char(SINGLE_QUOTE)?;
120
121 let mut last = 0;
122 for (idx, _) in self.0.match_indices([BACKSLASH, SINGLE_QUOTE]) {
123 f.write_str(&self.0[last..idx])?;
124 f.write_char(BACKSLASH)?;
125 last = idx;
126 }
127
128 f.write_str(&self.0[last..])?;
129 f.write_char(SINGLE_QUOTE)
130 })
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 #[test]
137 fn every_json_type() {
138 let input = serde_json::json!({ "input": [null, true, 42, r"it's C:\"] });
139 let bundle = "run(_taba);\n//# sourceMappingURL=run.js.map";
140
141 insta::assert_snapshot!(super::script(bundle, &input).unwrap(), @r#"
142 {
143 const _taba = JSON.parse('{"input":[null,true,42,"it\'s C:\\\\"]}');
144 run(_taba);
145 //# sourceMappingURL=run.js.map
146 }
147 "#);
148 }
149}