1use core::fmt;
6use std::fmt::Debug;
7
8use crate::utils::{
9 object::define_subclass,
10 option::Undefined,
11 primordials::{BasePrimordials, Primordial},
12};
13use rquickjs::{
14 atom::PredefinedAtom,
15 class::{
16 impl_::{CloneTrait, CloneWrapper},
17 JsClass, Trace,
18 },
19 function::{Constructor, Opt},
20 object::{Accessor, Property},
21 prelude::{Func, This},
22 qjs, Class, Coerced, Ctx, Error, Exception, FromJs, IntoJs, JsLifetime, Object, Result, Value,
23};
24
25#[derive(JsLifetime)]
26struct ExceptionPrimordials<'js> {
27 constructor_dom_exception: Constructor<'js>,
28 constructor_quota_exceeded_error: Constructor<'js>,
29}
30
31impl<'js> Primordial<'js> for ExceptionPrimordials<'js> {
32 fn new(ctx: &Ctx<'js>) -> Result<Self> {
33 let globals = ctx.globals();
34 Ok(Self {
35 constructor_dom_exception: globals.get(DOMException::NAME)?,
36 constructor_quota_exceeded_error: globals.get("QuotaExceededError")?,
37 })
38 }
39}
40
41#[derive(Trace, JsLifetime, Debug)]
42pub struct DOMException {
43 name: String,
44 message: String,
45 stack: String,
46 code: u8,
47}
48
49impl fmt::Display for DOMException {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.debug_struct("DOMException")
52 .field("name", &self.name())
53 .field("message", &self.message())
54 .field("stack", &self.stack)
55 .finish()
56 }
57}
58
59fn add_constants(obj: &Object<'_>) -> Result<()> {
60 const CONSTANTS: [(&str, u8); 25] = [
61 ("INDEX_SIZE_ERR", 1),
62 ("DOMSTRING_SIZE_ERR", 2),
63 ("HIERARCHY_REQUEST_ERR", 3),
64 ("WRONG_DOCUMENT_ERR", 4),
65 ("INVALID_CHARACTER_ERR", 5),
66 ("NO_DATA_ALLOWED_ERR", 6),
67 ("NO_MODIFICATION_ALLOWED_ERR", 7),
68 ("NOT_FOUND_ERR", 8),
69 ("NOT_SUPPORTED_ERR", 9),
70 ("INUSE_ATTRIBUTE_ERR", 10),
71 ("INVALID_STATE_ERR", 11),
72 ("SYNTAX_ERR", 12),
73 ("INVALID_MODIFICATION_ERR", 13),
74 ("NAMESPACE_ERR", 14),
75 ("INVALID_ACCESS_ERR", 15),
76 ("VALIDATION_ERR", 16),
77 ("TYPE_MISMATCH_ERR", 17),
78 ("SECURITY_ERR", 18),
79 ("NETWORK_ERR", 19),
80 ("ABORT_ERR", 20),
81 ("URL_MISMATCH_ERR", 21),
82 ("QUOTA_EXCEEDED_ERR", 22),
83 ("TIMEOUT_ERR", 23),
84 ("INVALID_NODE_TYPE_ERR", 24),
85 ("DATA_CLONE_ERR", 25),
86 ];
87
88 for (key, value) in CONSTANTS {
89 obj.prop(key, Property::from(value).enumerable())?;
90 }
91
92 Ok(())
93}
94
95impl<'js> JsClass<'js> for DOMException {
96 const NAME: &'static str = "DOMException";
97 type Mutable = rquickjs::class::Writable;
98 fn prototype(ctx: &Ctx<'js>) -> rquickjs::Result<Option<Object<'js>>> {
99 use rquickjs::class::impl_::{MethodImpl, MethodImplementor};
100 let proto = Object::new(ctx.clone())?;
101 let implementor = MethodImpl::<Self>::new();
102 implementor.implement(&proto)?;
103 add_constants(&proto)?;
104
105 Ok(Some(proto))
106 }
107 fn constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>> {
108 use rquickjs::class::impl_::{ConstructorCreate, ConstructorCreator};
109 let implementor = ConstructorCreate::<Self>::new();
110 let constructor = implementor
111 .create_constructor(ctx)?
112 .expect("DOMException must have a constructor");
113 add_constants(&constructor)?;
114
115 Ok(Some(constructor))
116 }
117}
118
119impl<'js> IntoJs<'js> for DOMException {
120 fn into_js(self, ctx: &rquickjs::Ctx<'js>) -> Result<Value<'js>> {
121 let cls = Class::<Self>::instance(ctx.clone(), self)?;
122 IntoJs::into_js(cls, ctx)
123 }
124}
125
126impl<'js> FromJs<'js> for DOMException
127where
128 for<'a> CloneWrapper<'a, Self>: CloneTrait<Self>,
129{
130 fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
131 let value = Class::<Self>::from_js(ctx, value)?;
132 let borrow = value.try_borrow()?;
133 Ok(CloneWrapper(&*borrow).wrap_clone())
134 }
135}
136
137#[rquickjs::methods]
138impl DOMException {
139 #[qjs(constructor)]
140 pub fn new<'js>(
141 ctx: Ctx<'js>,
142 this: This<Value<'js>>,
143 message: Opt<Undefined<Coerced<String>>>,
144 name: Opt<Undefined<Coerced<String>>>,
145 ) -> Result<Self> {
146 if this.0.as_function().is_none() {
149 return Err(Exception::throw_type(
150 &ctx,
151 "Cannot call the DOMException constructor without 'new'",
152 ));
153 }
154
155 let message = match message.0 {
156 Some(Undefined(Some(message))) => message.0,
157 _ => String::new(),
158 };
159
160 let name = match name.0 {
161 Some(Undefined(Some(message))) => DOMExceptionName::from(message.0),
162 _ => DOMExceptionName::Error,
163 };
164
165 Self::new_with_name(&ctx, name, message)
166 }
167
168 #[qjs(skip)]
169 pub fn new_with_name(ctx: &Ctx<'_>, name: DOMExceptionName, message: String) -> Result<Self> {
170 let primordials = BasePrimordials::get(ctx)?;
171
172 let new: Object = primordials
173 .constructor_error
174 .construct((message.clone(),))?;
175
176 Ok(Self {
177 name: name.as_str().to_string(),
178 code: name.code(),
179 message,
180 stack: new.get::<_, String>(PredefinedAtom::Stack)?,
181 })
182 }
183
184 #[qjs(get, enumerable, configurable)]
185 fn message(&self) -> &str {
186 self.message.as_str()
187 }
188
189 #[qjs(get, enumerable, configurable)]
190 pub fn name(&self) -> &str {
191 self.name.as_str()
192 }
193
194 #[qjs(get, enumerable, configurable)]
195 pub fn code(&self) -> u8 {
196 self.code
197 }
198
199 #[qjs(prop, rename = PredefinedAtom::SymbolToStringTag, configurable)]
200 pub fn to_string_tag() -> &'static str {
201 stringify!(DOMException)
202 }
203}
204
205impl<'js> DOMException {
206 fn create(
207 ctx: &Ctx<'js>,
208 name: DOMExceptionName,
209 message: impl Into<String>,
210 ) -> Result<Value<'js>> {
211 let primordials = ExceptionPrimordials::get(ctx)?;
212 let ctor = match name {
213 DOMExceptionName::QuotaExceededError => &primordials.constructor_quota_exceeded_error,
214 _ => &primordials.constructor_dom_exception,
215 };
216 ctor.construct((message.into(), name.as_str()))
217 }
218
219 fn throw_value(ctx: &Ctx<'js>, value: Value<'js>) -> Error {
220 unsafe {
221 let dup = qjs::JS_DupValue(ctx.as_raw().as_ptr(), value.as_raw());
222 qjs::JS_Throw(ctx.as_raw().as_ptr(), dup);
223 }
224 Error::Exception
225 }
226
227 fn create_error(ctx: &Ctx<'js>, name: DOMExceptionName, message: impl Into<String>) -> Error {
228 match Self::create(ctx, name, message) {
229 Ok(value) => Self::throw_value(ctx, value),
230 Err(error) => error,
231 }
232 }
233
234 pub fn not_supported_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
235 Self::create_error(ctx, DOMExceptionName::NotSupportedError, message)
236 }
237
238 pub fn type_mismatch_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
239 Self::create_error(ctx, DOMExceptionName::TypeMismatchError, message)
240 }
241
242 pub fn operation_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
243 Self::create_error(ctx, DOMExceptionName::OperationError, message)
244 }
245
246 pub fn quota_exceeded_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
247 Self::create_error(ctx, DOMExceptionName::QuotaExceededError, message)
248 }
249
250 pub fn data_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
251 Self::create_error(ctx, DOMExceptionName::DataError, message)
252 }
253
254 pub fn invalid_access_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
255 Self::create_error(ctx, DOMExceptionName::InvalidAccessError, message)
256 }
257
258 pub fn syntax_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
259 Self::create_error(ctx, DOMExceptionName::SyntaxError, message)
260 }
261
262 pub fn data_clone_error(ctx: &Ctx<'js>, message: impl Into<String>) -> Error {
263 Self::create_error(ctx, DOMExceptionName::DataCloneError, message)
264 }
265
266 fn define_quota_exceeded_error(ctx: &Ctx<'js>) -> Result<()> {
267 let dom_exception: Constructor = ctx.globals().get(Self::NAME)?;
268 let quota_exceeded_error = define_subclass(
269 ctx,
270 "QuotaExceededError",
271 &dom_exception,
272 |ctx, message: Opt<Undefined<Coerced<String>>>| {
273 let message = match message.0 {
274 Some(Undefined(Some(m))) => m.0,
275 _ => String::new(),
276 };
277 Self::new_with_name(&ctx, DOMExceptionName::QuotaExceededError, message)
278 },
279 )?;
280 let null = Value::new_null(ctx.clone());
281 let proto: Object = quota_exceeded_error.get(PredefinedAtom::Prototype)?;
282 proto.prop(
283 "requested",
284 Property::from(null.clone()).enumerable().configurable(),
285 )?;
286 proto.prop("quota", Property::from(null).enumerable().configurable())?;
287 ctx.globals().prop(
288 "QuotaExceededError",
289 Property::from(quota_exceeded_error)
290 .writable()
291 .configurable(),
292 )
293 }
294}
295
296macro_rules! create_dom_exception {
297 ($name:ident, $($variant:ident),+ $(,)?) => {
298 #[derive(Debug)]
299 pub enum $name {
300 $(
301 $variant,
302 )+
303 Other(String),
304 }
305
306 impl $name {
307 pub fn as_str(&self) -> &str {
308 match self {
309 $(
310 Self::$variant => stringify!($variant),
311 )+
312 Self::Other(value) => value,
313 }
314 }
315 }
316
317 impl From<String> for $name {
318 fn from(value: String) -> Self {
319 match value.as_str() {
320 $(
321 stringify!($variant) => Self::$variant,
322 )+
323 _ => Self::Other(value),
324 }
325 }
326 }
327 };
328}
329
330create_dom_exception!(
332 DOMExceptionName,
333 IndexSizeError,
334 HierarchyRequestError,
335 WrongDocumentError,
336 InvalidCharacterError,
337 NoModificationAllowedError,
338 NotFoundError,
339 NotSupportedError,
340 InUseAttributeError,
341 InvalidStateError,
342 SyntaxError,
343 InvalidModificationError,
344 NamespaceError,
345 InvalidAccessError,
346 TypeMismatchError,
347 SecurityError,
348 NetworkError,
349 AbortError,
350 URLMismatchError,
351 QuotaExceededError,
352 TimeoutError,
353 InvalidNodeTypeError,
354 DataCloneError,
355 EncodingError,
356 NotReadableError,
357 UnknownError,
358 ConstraintError,
359 DataError,
360 TransactionInactiveError,
361 ReadOnlyError,
362 VersionError,
363 OperationError,
364 NotAllowedError,
365 Error,
366);
367
368impl DOMExceptionName {
369 fn code(&self) -> u8 {
370 match self {
371 DOMExceptionName::IndexSizeError => 1,
372 DOMExceptionName::HierarchyRequestError => 3,
373 DOMExceptionName::WrongDocumentError => 4,
374 DOMExceptionName::InvalidCharacterError => 5,
375 DOMExceptionName::NoModificationAllowedError => 7,
376 DOMExceptionName::NotFoundError => 8,
377 DOMExceptionName::NotSupportedError => 9,
378 DOMExceptionName::InUseAttributeError => 10,
379 DOMExceptionName::InvalidStateError => 11,
380 DOMExceptionName::SyntaxError => 12,
381 DOMExceptionName::InvalidModificationError => 13,
382 DOMExceptionName::NamespaceError => 14,
383 DOMExceptionName::InvalidAccessError => 15,
384 DOMExceptionName::TypeMismatchError => 17,
385 DOMExceptionName::SecurityError => 18,
386 DOMExceptionName::NetworkError => 19,
387 DOMExceptionName::AbortError => 20,
388 DOMExceptionName::URLMismatchError => 21,
389 DOMExceptionName::QuotaExceededError => 22,
390 DOMExceptionName::TimeoutError => 23,
391 DOMExceptionName::InvalidNodeTypeError => 24,
392 DOMExceptionName::DataCloneError => 25,
393 _ => 0,
394 }
395 }
396}
397
398pub fn init(ctx: &Ctx<'_>) -> Result<()> {
399 let globals = ctx.globals();
400
401 BasePrimordials::init(ctx)?;
402
403 if let Some(constructor) = Class::<DOMException>::create_constructor(ctx)? {
404 globals.prop(
406 DOMException::NAME,
407 Property::from(constructor).writable().configurable(),
408 )?;
409 }
410
411 let dom_ex_proto = Class::<DOMException>::prototype(ctx)?.unwrap();
412 dom_ex_proto.set_prototype(Some(&BasePrimordials::get(ctx)?.prototype_error))?;
413
414 DOMException::define_quota_exceeded_error(ctx)?;
415 ExceptionPrimordials::init(ctx)?;
416
417 BasePrimordials::get(ctx)?
424 .constructor_error
425 .set("isError", Func::from(is_error))?;
426
427 define_error_stack_accessor(ctx)?;
428
429 Ok(())
430}
431
432fn define_error_stack_accessor<'js>(ctx: &Ctx<'js>) -> Result<()> {
437 let prototype_error = BasePrimordials::get(ctx)?.prototype_error.clone();
438 prototype_error.prop(
439 PredefinedAtom::Stack,
440 Accessor::new(
441 |this: This<Value<'js>>| -> Result<String> {
442 let stack = Class::<DOMException>::from_value(&this.0)
443 .ok()
444 .map(|cls| cls.borrow().stack.clone());
445 Ok(stack.unwrap_or_default())
446 },
447 |ctx: Ctx<'js>, this: This<Value<'js>>, value: Value<'js>| -> Result<()> {
448 let Some(obj) = this.0.as_object() else {
451 return Ok(());
452 };
453 if *obj == BasePrimordials::get(&ctx)?.prototype_error {
454 return Ok(());
455 }
456 obj.prop(
457 PredefinedAtom::Stack,
458 Property::from(value).writable().enumerable().configurable(),
459 )
460 },
461 )
462 .configurable(),
463 )
464}
465
466fn is_error<'js>(ctx: Ctx<'js>, value: Value<'js>) -> Result<bool> {
467 if value.is_error() {
468 return Ok(true);
469 }
470 let Some(obj) = value.as_object() else {
471 return Ok(false);
472 };
473 let dom_exception: Value = ctx.globals().get(DOMException::NAME)?;
474 Ok(obj.is_instance_of(&dom_exception))
475}