1use std::borrow::Cow;
27use std::collections::HashSet;
28use std::pin::Pin;
29
30use futures_util::future::join_all;
31use futures_util::stream::{FuturesUnordered, Stream, StreamExt};
32
33use crate::class_names::{map_class_list, map_raw_html};
34use crate::css_split::{self, Pieces};
35use crate::escape::{escape_attr, escape_raw_text, escape_text, is_safe_url, is_url_attr, is_valid_attr_name};
36use crate::node::{AttrValue, BoxNodeFuture, Element, Node, View};
37use crate::style::Stylesheet;
38
39pub const STREAMING_RUNTIME: &str = "function $nr(i){var t=document.getElementById(\"nr-t\"+i),b=document.getElementById(\"nr-b\"+i);if(t&&b){b.replaceWith(t.content);t.remove()}}";
41
42type PendingBoundary = Pin<Box<dyn std::future::Future<Output = (u32, Node)> + Send>>;
43
44#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
47pub struct RenderFlags {
48 pub links: bool,
51 pub islands: bool,
53 pub streamed: bool,
55 pub ui: bool,
58}
59
60struct Writer {
61 out: String,
62 styles_seen: HashSet<&'static str>,
63 styles_known: HashSet<String>,
65 hoisted: Option<Vec<&'static Stylesheet>>,
67 split: bool,
69 split_sheets: Vec<(&'static Stylesheet, Pieces)>,
71 classes: HashSet<String>,
73 scripts: HashSet<String>,
75 flags: RenderFlags,
76 streaming: bool,
77 next_id: u32,
78 pending: Vec<(u32, BoxNodeFuture)>,
79}
80
81impl Writer {
82 fn new(streaming: bool, hoist: bool) -> Self {
83 Writer {
84 out: String::with_capacity(4096),
85 styles_seen: HashSet::new(),
86 styles_known: HashSet::new(),
87 hoisted: hoist.then(Vec::new),
88 split: false,
89 split_sheets: Vec::new(),
90 classes: HashSet::new(),
91 scripts: HashSet::new(),
92 flags: RenderFlags::default(),
93 streaming,
94 next_id: 0,
95 pending: Vec::new(),
96 }
97 }
98
99 fn style(&mut self, sheet: &'static Stylesheet) {
100 let sheet = crate::style::resolve(sheet);
101 if self.split && sheet.per_class.is_some() {
102 if !self.split_sheets.iter().any(|(s, _)| std::ptr::eq(*s, sheet)) {
103 let known = css_split::split(sheet).known(sheet, &self.styles_known);
104 self.split_sheets.push((sheet, known));
105 }
106 return;
107 }
108 if !self.styles_seen.insert(sheet.id) || self.styles_known.contains(sheet.id) {
109 return;
110 }
111 match &mut self.hoisted {
112 Some(list) => list.push(sheet),
113 None => write_style(&mut self.out, sheet),
114 }
115 }
116
117 fn node(&mut self, node: Node, raw_text: bool) {
118 match node {
119 Node::Empty => {}
120 Node::Text(t) => {
121 if raw_text {
122 self.out.push_str(&escape_raw_text(&t));
123 } else {
124 self.out.push_str(&escape_text(&t));
125 }
126 }
127 Node::Raw(r) => {
128 let html = map_raw_html(&r);
129 if self.split {
130 collect_raw_classes(&html, &mut self.classes);
131 }
132 self.out.push_str(&html);
133 }
134 Node::Fragment(children) => {
135 for c in children {
136 self.node(c, raw_text);
137 }
138 }
139 Node::Style(sheet) => self.style(sheet),
140 Node::Element(el) => self.element(*el),
141 Node::Suspense(s) => {
142 if self.streaming {
143 self.next_id += 1;
144 let id = self.next_id;
145 self.flags.streamed = true;
146 self.out.push_str(&format!("<nr-b id=\"nr-b{id}\">"));
147 self.node(s.fallback, false);
148 self.out.push_str("</nr-b>");
149 self.pending.push((id, s.content));
150 } else {
151 self.node(s.fallback, raw_text);
153 }
154 }
155 }
156 }
157
158 fn element(&mut self, el: Element) {
159 for a in &el.attrs {
160 for sheet in &a.sheets {
161 self.style(sheet);
162 }
163 }
164 let tag = el.tag;
165 self.out.push('<');
166 self.out.push_str(&tag);
167 for a in &el.attrs {
168 let Some(value) = &a.value else { continue };
169 if !is_valid_attr_name(&a.name) {
170 continue;
171 }
172 if !a.trusted && a.name.len() > 2 && a.name[..2].eq_ignore_ascii_case("on") {
173 continue;
175 }
176 match value {
177 AttrValue::Bool(true) => {
178 self.out.push(' ');
179 self.out.push_str(&attr_name(&a.name));
180 }
181 AttrValue::Bool(false) => {}
182 AttrValue::Text(t) => {
183 let t = match a.name.as_ref() {
184 "class" | "data-nr-active" | "data-nr-active-prefix" => {
185 let mapped = map_class_list(t);
186 if self.split {
187 self.classes.extend(mapped.split_ascii_whitespace().map(str::to_owned));
188 }
189 mapped
190 }
191 _ => Cow::Borrowed(t.as_ref()),
192 };
193 if a.name == "class" && t.is_empty() {
194 continue;
196 }
197 let safe = if is_url_attr(&a.name) && !is_safe_url(&t) { "#" } else { t.as_ref() };
198 let name = attr_name(&a.name);
199 if self.split {
200 if let Some(class) = name.strip_prefix("data-nr-class-") {
201 self.classes.insert(class.to_owned());
202 }
203 if (tag == "nr-island" && a.name == "data-module") || (tag == "script" && a.name == "src") {
204 self.scripts.insert(script_key(&t));
205 }
206 }
207 self.out.push(' ');
208 self.out.push_str(&name);
209 self.out.push_str("=\"");
210 self.out.push_str(&escape_attr(safe));
211 self.out.push('"');
212 }
213 }
214 if a.name == "data-nr-ui" {
218 self.flags.ui = true;
219 }
220 if a.name == "data-nr-link"
221 || a.name == "data-nr-action"
222 || (tag == "a" && a.name == "href" && is_internal_href(value))
223 {
224 self.flags.links = true;
225 }
226 }
227 self.out.push('>');
228 if tag == "nr-island" {
229 self.flags.islands = true;
230 }
231 if el.void {
232 return;
233 }
234 let raw = tag.eq_ignore_ascii_case("script") || tag.eq_ignore_ascii_case("style");
235 for c in el.children {
236 self.node(c, raw);
237 }
238 self.out.push_str("</");
239 self.out.push_str(&tag);
240 self.out.push('>');
241 }
242}
243
244impl Writer {
245 fn split_styles(&mut self) -> String {
248 let mut out = String::new();
249 for (sheet, sent) in &mut self.split_sheets {
250 let split = css_split::split(sheet);
251 let scripts = &self.scripts;
252 let scoped = sheet.scripts.iter().filter(|(k, _)| scripts.contains(*k)).flat_map(|(_, c)| c.iter());
253 let keep: Vec<&str> = sheet
254 .per_class
255 .unwrap_or_default()
256 .iter()
257 .chain(scoped)
258 .map(|c| crate::class_names::short_class_name(c).unwrap_or(c))
259 .collect();
260 let classes = &self.classes;
261 let used = |c: &str| classes.contains(c) || keep.contains(&c);
262 let pieces = split.delta(&used, sent);
263 out.push_str(&split.style(sheet, &pieces));
264 split.record(sent, &pieces);
265 }
266 out
267 }
268}
269
270pub fn script_key(url: &str) -> String {
274 let path = url.split(['?', '#']).next().unwrap_or(url);
275 let path = path.strip_prefix("/_next-rust/").or_else(|| path.strip_prefix('/')).unwrap_or(path);
276 let (dir, file) = path.rsplit_once('/').map_or(("", path), |(d, f)| (d, f));
277 let parts: Vec<&str> = file.split('.').collect();
278 let mut name: Vec<&str> = Vec::with_capacity(parts.len());
279 for (i, part) in parts.iter().enumerate() {
280 let fingerprint =
281 i > 0 && i + 1 < parts.len() && part.len() == 16 && part.bytes().all(|b| b.is_ascii_hexdigit());
282 if !fingerprint {
283 name.push(part);
284 }
285 }
286 let file = name.join(".");
287 if dir.is_empty() { file } else { format!("{dir}/{file}") }
288}
289
290fn collect_raw_classes(html: &str, into: &mut HashSet<String>) {
292 let lower = html.to_ascii_lowercase();
293 let mut from = 0;
294 while let Some(at) = lower[from..].find("class=") {
295 let start = from + at + "class=".len();
296 from = start;
297 let Some(q @ (b'"' | b'\'')) = html.as_bytes().get(start).copied() else { continue };
298 let Some(len) = html[start + 1..].find(q as char) else { break };
299 into.extend(html[start + 1..start + 1 + len].split_ascii_whitespace().map(str::to_owned));
300 from = start + 1 + len;
301 }
302}
303
304fn attr_name(name: &str) -> Cow<'_, str> {
307 match name.strip_prefix("data-nr-class-").and_then(crate::class_names::short_class_name) {
308 Some(short) => Cow::Owned(format!("data-nr-class-{short}")),
309 None => Cow::Borrowed(name),
310 }
311}
312
313fn write_style(out: &mut String, sheet: &Stylesheet) {
314 out.push_str("<style data-nr-css=\"");
315 out.push_str(sheet.id);
316 out.push_str("\">");
317 out.push_str(&escape_raw_text(sheet.css));
318 out.push_str("</style>");
319}
320
321pub fn render_static(view: impl View) -> String {
323 let mut w = Writer::new(false, false);
324 w.node(view.into_node(), false);
325 w.out
326}
327
328pub fn resolve(node: Node) -> Pin<Box<dyn std::future::Future<Output = Node> + Send>> {
330 Box::pin(async move {
331 match node {
332 Node::Suspense(s) => resolve(s.content.await).await,
333 Node::Fragment(children) => Node::Fragment(join_all(children.into_iter().map(resolve)).await),
334 Node::Element(mut el) => {
335 let children = std::mem::take(&mut el.children);
336 el.children = join_all(children.into_iter().map(resolve)).await;
337 Node::Element(el)
338 }
339 other => other,
340 }
341 })
342}
343
344pub async fn render_to_string(view: impl View) -> String {
346 let node = resolve(view.into_node()).await;
347 render_static(node)
348}
349
350pub struct DocumentParts {
352 pub lang: String,
353 pub html_attributes: Vec<(String, String)>,
356 pub head: String,
358 pub head_extra: String,
360 pub body: Node,
361 pub nonce: Option<String>,
363 pub tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
366 pub known_styles: Vec<String>,
368 pub generator: Option<String>,
371}
372
373impl DocumentParts {
374 pub fn new(body: impl View) -> Self {
375 DocumentParts {
376 lang: "en".into(),
377 html_attributes: Vec::new(),
378 head: String::new(),
379 head_extra: String::new(),
380 body: body.into_node(),
381 nonce: None,
382 tail: Box::new(|_| String::new()),
383 known_styles: Vec::new(),
384 generator: None,
385 }
386 }
387}
388
389fn nonce_attr(nonce: &Option<String>) -> String {
390 nonce.as_ref().map(|n| format!(" nonce=\"{}\"", escape_attr(n))).unwrap_or_default()
391}
392
393fn open_document(parts: &DocumentParts, w: &mut Writer, body: &str) -> String {
394 let mut s = String::with_capacity(body.len() + parts.head.len() + 256);
395 let lang = parts.html_attributes.iter().find(|(name, _)| name == "lang").map_or(&parts.lang, |(_, v)| v);
396 s.push_str("<!DOCTYPE html><html lang=\"");
397 s.push_str(&escape_attr(lang));
398 s.push('"');
399 for (name, value) in &parts.html_attributes {
400 let name = name.as_str();
401 if name == "lang" || !is_valid_attr_name(name) || (name.len() > 2 && name[..2].eq_ignore_ascii_case("on")) {
402 continue;
403 }
404 let value = if name == "class" {
405 let mapped = map_class_list(value);
407 w.classes.extend(mapped.split_ascii_whitespace().map(str::to_owned));
408 mapped
409 } else {
410 Cow::Borrowed(value.as_str())
411 };
412 let value = if is_url_attr(name) && !is_safe_url(&value) { "#" } else { value.as_ref() };
413 s.push(' ');
414 s.push_str(&attr_name(name));
415 s.push_str("=\"");
416 s.push_str(&escape_attr(value));
417 s.push('"');
418 }
419 s.push_str("><head>");
420 if let Some(generator) = &parts.generator {
421 s.push_str("<meta name=\"generator\" content=\"");
422 s.push_str(&escape_attr(generator));
423 s.push_str("\">");
424 }
425 s.push_str(&parts.head);
426 s.push_str(&w.split_styles());
428 if let Some(sheets) = w.hoisted.take() {
429 for sheet in sheets {
430 write_style(&mut s, sheet);
431 }
432 }
433 if !w.pending.is_empty() {
434 s.push_str("<style>nr-b,nr-island{display:contents}</style>");
435 s.push_str(&format!("<script{}>{STREAMING_RUNTIME}</script>", nonce_attr(&parts.nonce)));
436 } else if w.flags.islands {
437 s.push_str("<style>nr-island{display:contents}</style>");
438 }
439 s.push_str(&parts.head_extra);
440 s.push_str("</head><body>");
441 s.push_str(body);
442 s
443}
444
445pub fn stream_document(parts: DocumentParts, streaming: bool) -> impl Stream<Item = String> + Send {
451 enum State {
452 Start(DocumentParts, bool),
453 Streaming {
454 pending: FuturesUnordered<PendingBoundary>,
455 w: Writer,
456 nonce: Option<String>,
457 tail: Box<dyn FnOnce(RenderFlags) -> String + Send>,
458 },
459 Done,
460 }
461
462 futures_util::stream::unfold(State::Start(parts, streaming), |state| async move {
463 match state {
464 State::Done => None,
465 State::Start(mut parts, streaming) => {
466 let body = std::mem::take(&mut parts.body);
467 let body = if streaming { body } else { resolve(body).await };
468 let mut w = Writer::new(streaming, true);
469 w.split = true;
470 w.styles_known = std::mem::take(&mut parts.known_styles).into_iter().collect();
471 w.node(body, false);
472 let body_html = std::mem::take(&mut w.out);
473 let mut chunk = open_document(&parts, &mut w, &body_html);
474 if w.pending.is_empty() {
475 chunk.push_str(&(parts.tail)(w.flags));
476 chunk.push_str("</body></html>");
477 return Some((chunk, State::Done));
478 }
479 let pending = FuturesUnordered::new();
480 for (id, fut) in w.pending.drain(..) {
481 pending.push(Box::pin(async move { (id, fut.await) })
482 as Pin<Box<dyn std::future::Future<Output = _> + Send>>);
483 }
484 w.hoisted = None;
487 Some((chunk, State::Streaming { pending, w, nonce: parts.nonce, tail: parts.tail }))
488 }
489 State::Streaming { mut pending, mut w, nonce, tail } => match pending.next().await {
490 Some((id, node)) => {
491 w.out.clear();
492 w.out.push_str(&format!("<template id=\"nr-t{id}\">"));
493 w.node(node, false);
494 w.out.push_str(&format!("</template><script{}>$nr({id})</script>", nonce_attr(&nonce)));
495 let styles = w.split_styles();
497 w.out.insert_str(0, &styles);
498 for (nid, fut) in w.pending.drain(..) {
499 pending.push(Box::pin(async move { (nid, fut.await) }));
500 }
501 let chunk = std::mem::take(&mut w.out);
502 Some((chunk, State::Streaming { pending, w, nonce, tail }))
503 }
504 None => {
505 let mut chunk = tail(w.flags);
506 chunk.push_str("</body></html>");
507 Some((chunk, State::Done))
508 }
509 },
510 }
511 })
512}
513
514fn is_internal_href(value: &AttrValue) -> bool {
517 matches!(value, AttrValue::Text(href) if href.starts_with('/') && !href.starts_with("//"))
518}