rspack_core/
runtime_module.rs1use std::fmt::Debug;
2
3use async_trait::async_trait;
4use rspack_cacheable::cacheable;
5use rspack_collections::Identifier;
6
7use crate::{ChunkUkey, Compilation, Module};
8
9#[async_trait]
10pub trait RuntimeModule: Module + CustomSourceRuntimeModule {
11 fn name(&self) -> Identifier;
12 fn attach(&mut self, _chunk: ChunkUkey) {}
13 fn stage(&self) -> RuntimeModuleStage {
14 RuntimeModuleStage::Normal
15 }
16 fn full_hash(&self) -> bool {
17 false
18 }
19 fn dependent_hash(&self) -> bool {
20 false
21 }
22 fn should_isolate(&self) -> bool {
24 true
25 }
26 fn template(&self) -> Vec<(String, String)> {
27 vec![]
28 }
29 async fn generate(&self, compilation: &Compilation) -> rspack_error::Result<String>;
30 async fn generate_with_custom(&self, compilation: &Compilation) -> rspack_error::Result<String> {
31 if let Some(custom_source) = self.get_custom_source() {
32 Ok(custom_source)
33 } else {
34 self.generate(compilation).await
35 }
36 }
37}
38
39#[async_trait]
40pub trait CustomSourceRuntimeModule {
41 fn set_custom_source(&mut self, source: String);
42 fn get_custom_source(&self) -> Option<String>;
43 fn get_constructor_name(&self) -> String;
44}
45
46pub type BoxRuntimeModule = Box<dyn RuntimeModule>;
47
48#[cacheable]
49#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub enum RuntimeModuleStage {
51 #[default]
52 Normal, Basic, Attach, Trigger, }
57
58impl From<u32> for RuntimeModuleStage {
59 fn from(stage: u32) -> Self {
60 match stage {
61 0 => RuntimeModuleStage::Normal,
62 5 => RuntimeModuleStage::Basic,
63 10 => RuntimeModuleStage::Attach,
64 20 => RuntimeModuleStage::Trigger,
65 _ => RuntimeModuleStage::Normal,
66 }
67 }
68}
69
70impl From<RuntimeModuleStage> for u32 {
71 fn from(value: RuntimeModuleStage) -> Self {
72 match value {
73 RuntimeModuleStage::Normal => 0,
74 RuntimeModuleStage::Basic => 5,
75 RuntimeModuleStage::Attach => 10,
76 RuntimeModuleStage::Trigger => 20,
77 }
78 }
79}
80
81pub trait RuntimeModuleExt {
82 fn boxed(self) -> Box<dyn RuntimeModule>;
83}
84
85impl<T: RuntimeModule + 'static> RuntimeModuleExt for T {
86 fn boxed(self) -> Box<dyn RuntimeModule> {
87 Box::new(self)
88 }
89}