| 531 | } |
| 532 | |
| 533 | pub(crate) fn clone(&self, ctx: Ctx<'js>) -> Result<Self> { |
| 534 | let body = self.body.read().unwrap(); |
| 535 | let cloned_body = match &*body { |
| 536 | BodyVariant::Incoming(incoming, content_encoding) => { |
| 537 | // Cannot clone if body has been consumed |
| 538 | if incoming.read().unwrap().is_none() { |
| 539 | return Err(Exception::throw_type( |
| 540 | &ctx, |
| 541 | "Cannot clone response after body has been used", |
| 542 | )); |
| 543 | } |
| 544 | |
| 545 | // Convert to stream first, then tee |
| 546 | let stream_val = |
| 547 | create_body_stream(&ctx, incoming.clone(), content_encoding.clone())?; |
| 548 | let stream = Class::<ReadableStream>::from_value(&stream_val)?; |
| 549 | let (branch1, branch2) = |
| 550 | llrt_stream_web::tee_readable_stream(ctx.clone(), stream.clone())?; |
| 551 | |
| 552 | // Update self to use branch1 |
| 553 | drop(body); |
| 554 | let mut body_write = self.body.write().unwrap(); |
| 555 | *body_write = BodyVariant::Provided(Some(branch1.into_value())); |
| 556 | *self.body_stream.write().unwrap() = None; |
| 557 | |
| 558 | return Ok(Self { |
| 559 | body: RwLock::new(BodyVariant::Provided(Some(branch2.into_value()))), |
| 560 | body_stream: RwLock::new(None), |
| 561 | body_consumed: AtomicBool::new(false), |
| 562 | method: self.method.clone(), |
| 563 | url: self.url.clone(), |
| 564 | start: self.start, |
| 565 | status: self.status, |
| 566 | status_text: self.status_text.clone(), |
| 567 | redirected: self.redirected, |
| 568 | headers: Class::<Headers>::instance(ctx, self.headers.borrow().clone())?, |
| 569 | abort_receiver: self.abort_receiver.clone(), |
| 570 | }); |
| 571 | }, |
| 572 | BodyVariant::Provided(provided) => { |
| 573 | let Some(provided) = provided else { |
| 574 | return Err(Exception::throw_type( |
| 575 | &ctx, |
| 576 | "Cannot clone response after body has been used", |
| 577 | )); |
| 578 | }; |
| 579 | // For ReadableStream bodies, use tee() to create two branches |
| 580 | if let Some(stream) = provided |
| 581 | .as_object() |
| 582 | .and_then(Class::<ReadableStream>::from_object) |
| 583 | { |
| 584 | let (branch1, branch2) = |
| 585 | llrt_stream_web::tee_readable_stream(ctx.clone(), stream.clone())?; |
| 586 | |
| 587 | // Update original body to use branch1 |
| 588 | drop(body); |
| 589 | let mut body_write = self.body.write().unwrap(); |
| 590 | *body_write = BodyVariant::Provided(Some(branch1.into_value())); |