1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::string::String as StdString;

use js::{
	class::{Trace, Tracer},
	prelude::*,
	Class, Ctx, Exception, FromJs, Object, Result, Value,
};

use crate::fnc::script::fetch::{classes::Headers, util};

/// Struct containing data from the init argument from the Response constructor.
#[derive(Clone)]
pub struct ResponseInit<'js> {
	// u16 instead of reqwest::StatusCode since javascript allows non valid status codes in some
	// circumstances.
	pub status: u16,
	pub status_text: StdString,
	pub headers: Class<'js, Headers>,
}

impl<'js> Trace<'js> for ResponseInit<'js> {
	fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
		self.headers.trace(tracer);
	}
}

impl<'js> ResponseInit<'js> {
	/// Returns a ResponseInit object with all values as the default value.
	pub fn default(ctx: Ctx<'js>) -> Result<Self> {
		let headers = Class::instance(ctx, Headers::new_empty())?;
		Ok(ResponseInit {
			status: 200,
			status_text: StdString::new(),
			headers,
		})
	}
}

impl<'js> FromJs<'js> for ResponseInit<'js> {
	fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
		let object = Object::from_js(ctx, value)?;

		// Extract status.
		let status =
			if let Some(Coerced(status)) = object.get::<_, Option<Coerced<i32>>>("status")? {
				if !(200..=599).contains(&status) {
					return Err(Exception::throw_range(ctx, "response status code outside range"));
				}
				status as u16
			} else {
				200u16
			};

		// Extract status text.
		let status_text = if let Some(Coerced(string)) =
			object.get::<_, Option<Coerced<StdString>>>("statusText")?
		{
			if !util::is_reason_phrase(string.as_str()) {
				return Err(Exception::throw_type(ctx, "statusText was not a valid reason phrase"));
			}
			string
		} else {
			StdString::new()
		};

		// Extract headers.
		let headers = if let Some(headers) = object.get::<_, Option<Value>>("headers")? {
			let headers = Headers::new_inner(ctx, headers)?;
			Class::instance(ctx.clone(), headers)?
		} else {
			Class::instance(ctx.clone(), Headers::new_empty())?
		};

		Ok(ResponseInit {
			status,
			status_text,
			headers,
		})
	}
}