├── .gitignore ├── impl ├── LICENSE-MIT ├── LICENSE-APACHE ├── Cargo.toml └── src │ └── lib.rs ├── tests ├── mixed.rs └── keygen.js ├── Cargo.toml ├── LICENSE-MIT ├── src ├── private.rs └── lib.rs ├── README.md ├── Cargo.lock └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /impl/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /impl/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /tests/mixed.rs: -------------------------------------------------------------------------------- 1 | use serialize_to_javascript::Template; 2 | 3 | #[derive(Template)] 4 | pub struct Foo<'a> { 5 | foo1: &'a str, 6 | foo2: usize, 7 | #[raw] 8 | foo3: &'static str, 9 | } 10 | -------------------------------------------------------------------------------- /tests/keygen.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @type {string} 3 | */ 4 | const keygenKey = __TEMPLATE_key__ 5 | 6 | /** 7 | * @type {number} 8 | */ 9 | const keygenLength = __TEMPLATE_length__ 10 | 11 | __RAW_optional_script__ 12 | 13 | // app logic, we are ensuring the length is equal to the expected one for some reason 14 | if (keygenKey.length === keygenLength) { 15 | console.log("okay!") 16 | } else { 17 | console.error("oh no!") 18 | } -------------------------------------------------------------------------------- /impl/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serialize-to-javascript-impl" 3 | version = "0.1.2" 4 | authors = ["Chip Reed "] 5 | description = "Implementation detail of `serialize-to-javascript`" 6 | license = "MIT OR Apache-2.0" 7 | edition = "2021" 8 | rust-version = "1.56" 9 | repository = "https://github.com/chippers/serialize-to-javascript" 10 | documentation = "https://docs.rs/serialize-to-javascript-impl" 11 | 12 | [lib] 13 | proc-macro = true 14 | 15 | [dependencies] 16 | proc-macro2 = "1.0" 17 | quote = "1.0" 18 | syn = "2" 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["impl"] 3 | 4 | [package] 5 | name = "serialize-to-javascript" 6 | version = "0.1.2" 7 | authors = ["Chip Reed "] 8 | description = "Serialize a serde::Serialize item to a JavaScript literal template using serde_json" 9 | license = "MIT OR Apache-2.0" 10 | edition = "2021" 11 | rust-version = "1.56" 12 | repository = "https://github.com/chippers/serialize-to-javascript" 13 | documentation = "https://docs.rs/serialize-to-javascript" 14 | 15 | [dependencies] 16 | serialize-to-javascript-impl = { version = "=0.1.2", path = "impl" } 17 | serde = { version = "1.0", features = ["derive"] } 18 | serde_json = { version = "1.0", features = ["raw_value"] } 19 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Chip Reed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/private.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | 3 | use serde_json::value::RawValue; 4 | 5 | use crate::{Options, Serialized}; 6 | 7 | pub use serde::Serialize; 8 | 9 | /// Prevent (hidden, not impossible) implementation of crate traits outside this crate. 10 | pub trait Sealed {} 11 | 12 | /// A [`Serialize`] value that has yet to be serialized. 13 | pub struct NotYetSerialized<'a, T: Serialize>(pub &'a T); 14 | 15 | impl<'a, T: Serialize> From<&'a T> for NotYetSerialized<'a, T> { 16 | fn from(input: &'a T) -> Self { 17 | Self(input) 18 | } 19 | } 20 | 21 | /// A [`Serialize`] value that has been serialized exactly once. 22 | pub struct SerializedOnce(Box); 23 | 24 | impl<'a, T: Serialize> TryFrom> for SerializedOnce { 25 | type Error = serde_json::Error; 26 | 27 | fn try_from(value: NotYetSerialized<'_, T>) -> Result { 28 | serde_json::to_string(value.0) 29 | .and_then(RawValue::from_string) 30 | .map(Self) 31 | } 32 | } 33 | 34 | impl SerializedOnce { 35 | /// Transform the serialized data into a valid JavaScript string. 36 | pub fn into_javascript_string_literal(self, options: &Options) -> Serialized { 37 | Serialized::new(&self.0, options) 38 | } 39 | } 40 | 41 | impl Serialized { 42 | /// Create [`Serialized`] from an existing [`String`] without serializing anything. 43 | /// 44 | /// # Safety 45 | /// 46 | /// This performs **NO** serialization of the input, even though [`Serialized`] implies the 47 | /// content has been serialized. 48 | /// 49 | /// This is intended for use from [`serialize_to_javascript_impl`] to put content from 50 | /// templates (which have multiple items that are serialized) into a single [`Serialized`] item 51 | /// after properly performing serialization. Think of this like [`String::get_utf8_unchecked`]. 52 | #[doc(hidden)] 53 | pub unsafe fn from_string_unchecked(string: String) -> Self { 54 | Self(string) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Serialize to JavaScript 2 | ============= 3 | 4 | This library provides serialization from `serde::Serialize` into JavaScript utilizing `serde_json`. It also provides 5 | a very simple templating mechanism along with derive macros to automatically derive them for suitable types. 6 | 7 | ```toml 8 | [dependencies] 9 | serialize-to-javascript = "0.1" 10 | ``` 11 | 12 | --- 13 | 14 | ## Examples 15 | 16 | ### Serialization 17 | ```rust 18 | use serialize_to_javascript::{Options, Serialized}; 19 | 20 | fn main() -> serialize_to_javascript::Result<()> { 21 | let raw_value = serde_json::value::to_raw_value("foo'bar")?; 22 | let serialized = Serialized::new(&raw_value, &Options::default()); 23 | assert_eq!(serialized.into_string(), "JSON.parse('\"foo\\'bar\"')"); 24 | Ok(()) 25 | } 26 | ``` 27 | 28 | ### Templating 29 | 30 | `main.rs`: 31 | ```rust 32 | use serialize_to_javascript::{default_template, DefaultTemplate, Options, Serialized, Template}; 33 | 34 | #[derive(Template)] 35 | #[default_template("keygen.js")] 36 | struct Keygen<'a> { 37 | key: &'a str, 38 | length: usize, 39 | 40 | #[raw] 41 | optional_script: &'static str, 42 | } 43 | 44 | fn main() -> serialize_to_javascript::Result<()> { 45 | let keygen = Keygen { 46 | key: "asdf", 47 | length: 4, 48 | optional_script: "console.log('hello, from my optional script')", 49 | }; 50 | 51 | let _output: Serialized = keygen.render_default(&Options::default())?; 52 | 53 | Ok(()) 54 | } 55 | ``` 56 | 57 | `keygen.js`: 58 | ```javascript 59 | const keygenKey = __TEMPLATE_key__ 60 | const keygenLength = __TEMPLATE_length__ 61 | 62 | __RAW_optional_script__ 63 | 64 | // app logic, we are ensuring the length is equal to the expected one for some reason 65 | if (keygenKey.length === keygenLength) { 66 | console.log("okay!") 67 | } else { 68 | console.error("oh no!") 69 | } 70 | ``` 71 | 72 | --- 73 | 74 | ### License 75 | 76 | Licensed under either of [Apache License 2.0](LICENSE-APACHE), Version or [MIT license](LICENSE-MIT) at your option. 77 | 78 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, 79 | as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 80 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "itoa" 7 | version = "1.0.11" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" 10 | 11 | [[package]] 12 | name = "memchr" 13 | version = "2.7.4" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 16 | 17 | [[package]] 18 | name = "proc-macro2" 19 | version = "1.0.86" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" 22 | dependencies = [ 23 | "unicode-ident", 24 | ] 25 | 26 | [[package]] 27 | name = "quote" 28 | version = "1.0.36" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" 31 | dependencies = [ 32 | "proc-macro2", 33 | ] 34 | 35 | [[package]] 36 | name = "ryu" 37 | version = "1.0.18" 38 | source = "registry+https://github.com/rust-lang/crates.io-index" 39 | checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" 40 | 41 | [[package]] 42 | name = "serde" 43 | version = "1.0.204" 44 | source = "registry+https://github.com/rust-lang/crates.io-index" 45 | checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" 46 | dependencies = [ 47 | "serde_derive", 48 | ] 49 | 50 | [[package]] 51 | name = "serde_derive" 52 | version = "1.0.204" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" 55 | dependencies = [ 56 | "proc-macro2", 57 | "quote", 58 | "syn", 59 | ] 60 | 61 | [[package]] 62 | name = "serde_json" 63 | version = "1.0.122" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da" 66 | dependencies = [ 67 | "itoa", 68 | "memchr", 69 | "ryu", 70 | "serde", 71 | ] 72 | 73 | [[package]] 74 | name = "serialize-to-javascript" 75 | version = "0.1.2" 76 | dependencies = [ 77 | "serde", 78 | "serde_json", 79 | "serialize-to-javascript-impl", 80 | ] 81 | 82 | [[package]] 83 | name = "serialize-to-javascript-impl" 84 | version = "0.1.2" 85 | dependencies = [ 86 | "proc-macro2", 87 | "quote", 88 | "syn", 89 | ] 90 | 91 | [[package]] 92 | name = "syn" 93 | version = "2.0.72" 94 | source = "registry+https://github.com/rust-lang/crates.io-index" 95 | checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" 96 | dependencies = [ 97 | "proc-macro2", 98 | "quote", 99 | "unicode-ident", 100 | ] 101 | 102 | [[package]] 103 | name = "unicode-ident" 104 | version = "1.0.12" 105 | source = "registry+https://github.com/rust-lang/crates.io-index" 106 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" 107 | -------------------------------------------------------------------------------- /impl/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate proc_macro; 2 | 3 | use proc_macro::TokenStream; 4 | 5 | use proc_macro2::TokenStream as TokenStream2; 6 | use quote::{quote, TokenStreamExt}; 7 | use syn::{parse_macro_input, spanned::Spanned}; 8 | 9 | /// Checks if the passed type implements the passed trait. 10 | fn trait_check<'l, L>(lifetimes: L, type_: syn::Type, trait_: TokenStream2) -> TokenStream2 11 | where 12 | L: Iterator, 13 | { 14 | quote!( 15 | const _: fn() = || { 16 | fn declare_lifetime<#(#lifetimes),*>() { 17 | fn assert_impl_all() {} 18 | assert_impl_all::<#type_>(); 19 | } 20 | }; 21 | ) 22 | } 23 | 24 | /// Automatically derive `Template` from a struct with valid input fields. 25 | /// 26 | /// ```no_run,no_compile 27 | /// #[derive(Template)] 28 | /// struct MyTemplate { 29 | /// serializable_field: usize, 30 | /// 31 | /// #[raw] 32 | /// raw_field: &'static str 33 | /// } 34 | /// ``` 35 | #[proc_macro_derive(Template, attributes(raw))] 36 | pub fn derive_template(item: TokenStream) -> TokenStream { 37 | let item = parse_macro_input!(item as syn::DeriveInput); 38 | let item_span = item.span(); 39 | let name = item.ident; 40 | match item.data { 41 | syn::Data::Struct(data) => { 42 | let (impl_generics, ty_generics, _) = item.generics.split_for_impl(); 43 | let mut replacements = TokenStream2::new(); 44 | for field in data.fields { 45 | match field.ident { 46 | Some(ident) => { 47 | let templated_field_name; 48 | let lifetimes = item.generics.lifetimes(); 49 | 50 | // we expect self, template, and options bindings to exist 51 | let data = if field.attrs.iter().any(|attr| attr.path().is_ident("raw")) { 52 | templated_field_name = format!("__RAW_{}__", ident); 53 | let trait_check = trait_check(lifetimes,field.ty, quote!(::std::fmt::Display)); 54 | quote!( 55 | #trait_check 56 | let data: String = self.#ident.to_string(); 57 | ) 58 | } else { 59 | templated_field_name = format!("__TEMPLATE_{}__", ident); 60 | let trait_check = trait_check(lifetimes, field.ty, quote!(::serialize_to_javascript::private::Serialize)); 61 | quote!( 62 | #trait_check 63 | 64 | use ::std::convert::TryInto; 65 | use ::serialize_to_javascript::{ 66 | private::{NotYetSerialized, SerializedOnce}, 67 | Serialized 68 | }; 69 | 70 | let data: SerializedOnce = NotYetSerialized(&self.#ident).try_into()?; 71 | let data: Serialized = data.into_javascript_string_literal(options); 72 | let data: String = data.into_string(); 73 | ) 74 | }; 75 | 76 | replacements.append_all(quote!( 77 | let template = { 78 | #data 79 | template.replace( 80 | #templated_field_name, 81 | &data 82 | ) 83 | }; 84 | )); 85 | } 86 | None => { 87 | return syn::Error::new( 88 | field.span(), 89 | "Template fields must all have names", 90 | ) 91 | .to_compile_error() 92 | .into(); 93 | } 94 | } 95 | } 96 | quote!( 97 | impl #impl_generics ::serialize_to_javascript::private::Sealed for #name #ty_generics {} 98 | impl #impl_generics ::serialize_to_javascript::Template for #name #ty_generics { 99 | fn render(&self, template: &str, options: &::serialize_to_javascript::Options) -> ::serialize_to_javascript::Result<::serialize_to_javascript::Serialized> { 100 | #replacements 101 | Ok(unsafe { 102 | ::serialize_to_javascript::Serialized::from_string_unchecked(template.into()) 103 | }) 104 | } 105 | } 106 | ) 107 | } 108 | _ => { 109 | return syn::Error::new( 110 | item_span, 111 | "`Template` currently only supports data structs", 112 | ) 113 | .to_compile_error() 114 | .into(); 115 | } 116 | } 117 | .into() 118 | } 119 | 120 | /// Automatically derive `DefaultTemplate` for a `Template` from the passed path. 121 | /// 122 | /// ```no_run,no_compile 123 | /// #[default_template("path/to/my_javascript_file.js")] 124 | /// ``` 125 | #[proc_macro_attribute] 126 | pub fn default_template(attr: TokenStream, item: TokenStream) -> TokenStream { 127 | let path = parse_macro_input!(attr as syn::LitStr); 128 | let item = parse_macro_input!(item as syn::DeriveInput); 129 | let name = item.ident.clone(); 130 | let (impl_generics, ty_generics, _) = item.generics.split_for_impl(); 131 | quote!( 132 | #item 133 | impl #impl_generics ::serialize_to_javascript::DefaultTemplate for #name #ty_generics { 134 | const RAW_TEMPLATE: &'static str = include_str!(#path); 135 | } 136 | ) 137 | .into() 138 | } 139 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Serialize [`serde::Serialize`] values to JavaScript using [`serde_json`]. 2 | //! 3 | //! # Serialization 4 | //! 5 | //! The [`Serialized`] item can help you create a valid JavaScript value out of a 6 | //! [`serde_json::value::RawValue`], along with some helpful options. It implements [`fmt::Display`] 7 | //! for direct use, but you can also manually remove it from the [new-type] with 8 | //! [`Serialized::into_string()`]. 9 | //! 10 | //! ```rust 11 | //! use serialize_to_javascript::{Options, Serialized}; 12 | //! 13 | //! fn main() -> serialize_to_javascript::Result<()> { 14 | //! let raw_value = serde_json::value::to_raw_value("foo'bar")?; 15 | //! let serialized = Serialized::new(&raw_value, &Options::default()); 16 | //! assert_eq!(serialized.into_string(), "JSON.parse('\"foo\\'bar\"')"); 17 | //! Ok(()) 18 | //! } 19 | //! ``` 20 | //! 21 | //! # Templating 22 | //! 23 | //! Because of the very common case of wanting to include your JavaScript values into existing 24 | //! JavaScript code, this crate also provides some templating features. [`Template`] helps you map 25 | //! struct fields into template values, while [`DefaultTemplate`] lets you attach it to a specific 26 | //! JavaScript file. See their documentation for more details on how to create and use them. 27 | //! 28 | //! Templated names that are replaced inside templates are `__TEMPLATE_my_field__` where `my_field` 29 | //! is a field on a struct implementing [`Template`]. Raw (`#[raw]` field annotation) value template 30 | //! names use `__RAW_my_field__`. Raw values are inserted directly **without ANY** serialization 31 | //! whatsoever, so being extra careful where it is used is highly recommended. 32 | //! 33 | //! ```rust 34 | //! use serialize_to_javascript::{default_template, DefaultTemplate, Options, Serialized, Template}; 35 | //! 36 | //! #[derive(Template)] 37 | //! #[default_template("../tests/keygen.js")] 38 | //! struct Keygen<'a> { 39 | //! key: &'a str, 40 | //! length: usize, 41 | //! 42 | //! #[raw] 43 | //! optional_script: &'static str, 44 | //! } 45 | //! 46 | //! fn main() -> serialize_to_javascript::Result<()> { 47 | //! let keygen = Keygen { 48 | //! key: "asdf", 49 | //! length: 4, 50 | //! optional_script: "console.log('hello, from my optional script')", 51 | //! }; 52 | //! 53 | //! let output: Serialized = keygen.render_default(&Options::default())?; 54 | //! 55 | //! Ok(()) 56 | //! } 57 | //! ``` 58 | //! 59 | //! [new-type]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#using-the-newtype-pattern-for-type-safety-and-abstraction 60 | 61 | pub use serde_json::{value::RawValue, Error, Result}; 62 | pub use serialize_to_javascript_impl::{default_template, Template}; 63 | 64 | use std::fmt; 65 | 66 | #[doc(hidden)] 67 | pub mod private; 68 | 69 | /// JavaScript code (in the form of a function parameter) for the JSON.parse() reviver. 70 | const FREEZE_REVIVER: &str = ",(_,v)=>Object.freeze(v)"; 71 | 72 | /// Serialized JavaScript output. 73 | #[derive(Debug, Clone)] 74 | pub struct Serialized(String); 75 | 76 | impl fmt::Display for Serialized { 77 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 78 | self.0.fmt(f) 79 | } 80 | } 81 | 82 | impl Serialized { 83 | /// Create a new [`Serialized`] from the inputs. 84 | #[inline(always)] 85 | pub fn new(json: &RawValue, options: &Options) -> Self { 86 | escape_json_parse(json, options) 87 | } 88 | 89 | /// Get the inner [`String`] out. 90 | #[inline(always)] 91 | pub fn into_string(self) -> String { 92 | self.0 93 | } 94 | } 95 | 96 | /// Optional settings to pass to the templating system. 97 | #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)] 98 | pub struct Options { 99 | /// If the parsed JSON will be frozen with [`Object.freeze()`]. 100 | /// 101 | /// [`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze 102 | #[allow(dead_code)] 103 | pub freeze: bool, 104 | 105 | /// _Extra_ amount of bytes to allocate to the String buffer during serialization. 106 | /// 107 | /// Note: This is not the total buffer size, but the extra buffer size created. By default the 108 | /// buffer size will already be enough to not need to allocate more than once for input that 109 | /// does not need escaping. Therefore, this extra buffer is more of "how many bytes of escaped 110 | /// characters do I want to prepare for?" 111 | pub buf: usize, 112 | } 113 | 114 | /// A struct that contains [`serde::Serialize`] data to insert into a template. 115 | /// 116 | /// Create this automatically with a `#[derive(Template)]` attribute. All fields not marked `#[raw]` 117 | /// will be compile-time checked that they implement [`serde::Serialize`]. 118 | /// 119 | /// Due to the nature of templating variables, [tuple structs] are not allowed as their fields 120 | /// have no names. [Unit structs] have no fields and are a valid target of this trait. 121 | /// 122 | /// Template variables are generated as `__TEMPLATE_my_field__` where the serialized value of the 123 | /// `my_field` field replaces all instances of the template variable. 124 | /// 125 | /// # Raw Values 126 | /// 127 | /// If you have raw values you would like to inject into the template that is not serializable 128 | /// through JSON, such as a string of JavaScript code, then you can mark a field with `#[raw]` to 129 | /// make it embedded directly. **Absolutely NO serialization occurs**, the field is just turned into 130 | /// a string using [`Display`]. As such, fields that are marked `#[raw]` _only_ require [`Display`]. 131 | /// 132 | /// Raw values use `__RAW_my_field__` as the template variable. 133 | /// 134 | /// --- 135 | /// 136 | /// This trait is sealed. 137 | /// 138 | /// [tuple structs]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types 139 | /// [`Display`]: std::fmt::Display 140 | pub trait Template: self::private::Sealed { 141 | /// Render the serialized template data into the passed template. 142 | fn render(&self, template: &str, options: &Options) -> Result; 143 | } 144 | 145 | /// A [`Template`] with an attached default template. 146 | /// 147 | /// Create this automatically with `#[default_template("myfile.js")` on your [`Template`] struct. 148 | pub trait DefaultTemplate: Template { 149 | /// The raw static string with the templates contents. 150 | /// 151 | /// When using `#[default_template("myfile.js")]` it will be generated as 152 | /// `include_str!("myfile.js")`. 153 | const RAW_TEMPLATE: &'static str; 154 | 155 | /// Render the serialized template data into the default template. 156 | /// 157 | /// If this method is implemented manually, it still needs to use [`Template::render`] to be 158 | /// serialized correctly. 159 | fn render_default(&self, options: &Options) -> Result { 160 | self.render(Self::RAW_TEMPLATE, options) 161 | } 162 | } 163 | 164 | /// Estimated the minimum capacity needed for the serialized string based on inputs. 165 | /// 166 | /// This size will include the size of the wrapping JavaScript (`JSON.parse()` and a potential 167 | /// reviver function based on options) and the user supplied `buf_size` from the passed [`Options`]. 168 | /// It currently estimates the minimum size of the passed JSON by assuming it does not need escaping 169 | /// and taking the length of the `&str`. 170 | fn estimated_capacity(json: &RawValue, options: &Options) -> usize { 171 | // 14 chars in JSON.parse('') 172 | let mut buf = 14; 173 | 174 | // we know it's at least going to contain the length of the json 175 | buf += json.get().len(); 176 | 177 | // add in user defined extra buffer size 178 | buf += options.buf; 179 | 180 | // freezing code expands the output size due to the embedded reviver code 181 | if options.freeze { 182 | buf += FREEZE_REVIVER.len(); 183 | } 184 | 185 | buf 186 | } 187 | 188 | /// Transforms & escapes a JSON String to `JSON.parse('{json}')` 189 | /// 190 | /// Single quotes chosen because double quotes are already used in JSON. With single quotes, we only 191 | /// need to escape strings that include backslashes or single quotes. If we used double quotes, then 192 | /// there would be no cases that a string doesn't need escaping. 193 | /// 194 | /// # Safety 195 | /// 196 | /// The ability to safely escape JSON into a JSON.parse('{json}') relies entirely on 2 things. 197 | /// 198 | /// 1. `serde_json`'s ability to correctly escape and format JSON into a [`String`]. 199 | /// 2. JavaScript engines not accepting anything except another unescaped, literal single quote 200 | /// character to end a string that was opened with it. 201 | /// 202 | /// # Allocations 203 | /// 204 | /// A new [`String`] will always be allocated. If `buf_size` is set to `0`, then it will by default 205 | /// allocate to the return value of [`estimated_capacity()`]. 206 | fn escape_json_parse(json: &RawValue, options: &Options) -> Serialized { 207 | let capacity = estimated_capacity(json, options); 208 | let json = json.get(); 209 | 210 | let mut buf = String::with_capacity(capacity); 211 | buf.push_str("JSON.parse('"); 212 | 213 | // insert a backslash before any backslash or single quote characters to escape them 214 | let mut last = 0; 215 | for (idx, _) in json.match_indices(|c| c == '\\' || c == '\'') { 216 | buf.push_str(&json[last..idx]); 217 | buf.push('\\'); 218 | last = idx; 219 | } 220 | 221 | // finish appending the trailing json characters that don't need escaping 222 | buf.push_str(&json[last..]); 223 | 224 | // close out the escaped JavaScript string 225 | buf.push('\''); 226 | 227 | // custom reviver to freeze all parsed items 228 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter 229 | if options.freeze { 230 | buf.push_str(FREEZE_REVIVER); 231 | } 232 | 233 | // finish the JSON.parse() call 234 | buf.push(')'); 235 | 236 | Serialized(buf) 237 | } 238 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------