rspack_core 0.100.1

rspack core
Documentation
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use std::{
  borrow::Cow,
  fmt::{self, Debug},
  hash::Hash,
  str::FromStr,
  string::ParseError,
  sync::LazyLock,
};

use regex::Regex;
use rspack_cacheable::cacheable;
use rspack_hash::RspackHash;
pub use rspack_hash::{HashDigest, HashFunction, HashSalt};
use rspack_macros::MergeFrom;
use rspack_paths::Utf8PathBuf;
#[cfg(allocative)]
use rspack_util::allocative;

use super::CleanOptions;
use crate::{Chunk, ChunkGroupByUkey, ChunkKind, Compilation, Filename};

#[derive(Debug)]
pub enum PathInfo {
  Bool(bool),
  String(String),
}

// BE CAREFUL:
// Add more fields to this struct should result in adding new fields to options builder.
// `impl From<OutputOptions> for OutputOptionsBuilder` should be updated.
#[derive(Debug)]
pub struct OutputOptions {
  pub path: Utf8PathBuf,
  pub pathinfo: PathInfo,
  pub clean: CleanOptions,
  pub public_path: PublicPath,
  pub asset_module_filename: Filename,
  pub wasm_loading: WasmLoading,
  pub webassembly_module_filename: Filename,
  pub unique_name: String,
  pub chunk_loading: ChunkLoading,
  pub chunk_loading_global: String,
  pub chunk_load_timeout: u32,
  pub filename: Filename,
  pub chunk_filename: Filename,
  pub cross_origin_loading: CrossOriginLoading,
  pub css_filename: Filename,
  pub css_chunk_filename: Filename,
  pub hot_update_main_filename: Filename,
  pub hot_update_chunk_filename: Filename,
  pub hot_update_global: String,
  pub library: Option<LibraryOptions>,
  pub enabled_library_types: Option<Vec<String>>,
  pub strict_module_error_handling: bool,
  pub global_object: String,
  pub import_function_name: String,
  pub import_meta_name: String,
  pub iife: bool,
  pub module: bool,
  pub trusted_types: Option<TrustedTypes>,
  pub source_map_filename: Filename,
  pub hash_function: HashFunction,
  pub hash_digest: HashDigest,
  pub hash_digest_length: usize,
  pub hash_salt: HashSalt,
  pub async_chunks: bool,
  pub worker_chunk_loading: ChunkLoading,
  pub worker_wasm_loading: WasmLoading,
  pub worker_public_path: String,
  pub script_type: String,
  pub environment: Environment,
  pub compare_before_emit: bool,
}

impl From<&OutputOptions> for RspackHash {
  fn from(value: &OutputOptions) -> Self {
    Self::with_salt(&value.hash_function, &value.hash_salt)
  }
}

#[derive(Debug)]
pub enum OnPolicyCreationFailure {
  Continue,
  Stop,
}

impl From<String> for OnPolicyCreationFailure {
  fn from(value: String) -> Self {
    if value == "continue" {
      Self::Continue
    } else {
      Self::Stop
    }
  }
}

#[derive(Debug)]
pub struct TrustedTypes {
  pub policy_name: Option<String>,
  pub on_policy_creation_failure: OnPolicyCreationFailure,
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChunkLoading {
  Enable(ChunkLoadingType),
  Disable,
}

impl From<ChunkLoading> for String {
  fn from(value: ChunkLoading) -> Self {
    match value {
      ChunkLoading::Enable(ty) => ty.into(),
      ChunkLoading::Disable => "false".to_string(),
    }
  }
}

impl ChunkLoading {
  pub fn as_str(&self) -> &str {
    match self {
      ChunkLoading::Enable(ty) => ty.as_str(),
      ChunkLoading::Disable => "false",
    }
  }
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChunkLoadingType {
  Jsonp,
  ImportScripts,
  Require,
  AsyncNode,
  Import,
  Custom(String),
}

impl From<&str> for ChunkLoadingType {
  fn from(value: &str) -> Self {
    match value {
      "jsonp" => Self::Jsonp,
      "import-scripts" => Self::ImportScripts,
      "require" => Self::Require,
      "async-node" => Self::AsyncNode,
      "import" => Self::Import,
      _ => Self::Custom(value.to_string()),
    }
  }
}

impl From<ChunkLoadingType> for String {
  fn from(value: ChunkLoadingType) -> Self {
    value.as_str().to_string()
  }
}

impl ChunkLoadingType {
  pub fn as_str(&self) -> &str {
    match self {
      ChunkLoadingType::Jsonp => "jsonp",
      ChunkLoadingType::ImportScripts => "import-scripts",
      ChunkLoadingType::Require => "require",
      ChunkLoadingType::AsyncNode => "async-node",
      ChunkLoadingType::Import => "import",
      ChunkLoadingType::Custom(value) => value.as_str(),
    }
  }
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum WasmLoading {
  Enable(WasmLoadingType),
  Disable,
}

impl From<&str> for WasmLoading {
  fn from(value: &str) -> Self {
    match value {
      "false" => Self::Disable,
      v => Self::Enable(v.into()),
    }
  }
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum WasmLoadingType {
  Fetch,
  AsyncNode,
  Universal,
}

impl From<&str> for WasmLoadingType {
  fn from(value: &str) -> Self {
    match value {
      "fetch" => Self::Fetch,
      "async-node" => Self::AsyncNode,
      "universal" => Self::Universal,
      _ => unreachable!(
        "invalid wasm loading type: {value}, expect one of [fetch, async-node, universal]",
      ),
    }
  }
}

#[derive(Debug, Clone)]
#[cfg_attr(allocative, derive(allocative::Allocative))]
pub enum CrossOriginLoading {
  Disable,
  Enable(String),
}

impl fmt::Display for CrossOriginLoading {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      CrossOriginLoading::Disable => write!(f, ""),
      CrossOriginLoading::Enable(value) => write!(f, "{value}"),
    }
  }
}

#[derive(Default, Clone, Copy, Debug)]
pub struct PathData<'a> {
  pub filename: Option<&'a str>,
  pub chunk_name: Option<&'a str>,
  pub chunk_hash: Option<&'a str>,
  pub chunk_id: Option<&'a str>,
  pub module_id: Option<&'a str>,
  pub hash: Option<&'a str>,
  pub content_hash: Option<&'a str>,
  pub runtime: Option<&'a str>,
  pub url: Option<&'a str>,
  pub id: Option<&'a str>,
}

static MATCH_ID_REGEX: LazyLock<Regex> =
  LazyLock::new(|| Regex::new(r#"^"\s\+*\s*(.*)\s*\+\s*"$"#).expect("invalid Regex"));
static PREPARE_ID_REGEX: LazyLock<Regex> =
  LazyLock::new(|| Regex::new(r"(^[.-]|[^a-zA-Z0-9_-])+").expect("invalid Regex"));

impl<'a> PathData<'a> {
  pub fn prepare_id(v: &str) -> Cow<'_, str> {
    if let Some(caps) = MATCH_ID_REGEX.captures(v) {
      Cow::Owned(format!(
        "\" + ({} + \"\").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, \"_\") + \"",
        caps.get(1).expect("capture group should exist").as_str()
      ))
    } else {
      PREPARE_ID_REGEX.replace_all(v, "_")
    }
  }

  pub fn filename(mut self, v: &'a str) -> Self {
    self.filename = Some(v);
    self
  }

  pub fn chunk_hash(mut self, v: &'a str) -> Self {
    self.chunk_hash = Some(v);
    self
  }

  pub fn chunk_hash_optional(mut self, v: Option<&'a str>) -> Self {
    self.chunk_hash = v;
    self
  }

  pub fn chunk_name(mut self, v: &'a str) -> Self {
    self.chunk_name = Some(v);
    self
  }

  pub fn chunk_name_optional(mut self, v: Option<&'a str>) -> Self {
    self.chunk_name = v;
    self
  }

  pub fn chunk_id(mut self, v: &'a str) -> Self {
    self.chunk_id = Some(v);
    self
  }

  pub fn chunk_id_optional(mut self, v: Option<&'a str>) -> Self {
    self.chunk_id = v;
    self
  }

  pub fn module_id_optional(mut self, v: Option<&'a str>) -> Self {
    self.module_id = v;
    self
  }

  pub fn hash(mut self, v: &'a str) -> Self {
    self.hash = Some(v);
    self
  }

  pub fn hash_optional(mut self, v: Option<&'a str>) -> Self {
    self.hash = v;
    self
  }

  pub fn content_hash(mut self, v: &'a str) -> Self {
    self.content_hash = Some(v);
    self
  }

  pub fn content_hash_optional(mut self, v: Option<&'a str>) -> Self {
    self.content_hash = v;
    self
  }

  pub fn runtime(mut self, v: &'a str) -> Self {
    self.runtime = Some(v);
    self
  }

  pub fn url(mut self, v: &'a str) -> Self {
    self.url = Some(v);
    self
  }

  pub fn id(mut self, id: &'a str) -> Self {
    self.id = Some(id);
    self
  }
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, MergeFrom)]
pub enum PublicPath {
  Filename(Filename),
  Auto,
}

//https://github.com/webpack/webpack/blob/001cab14692eb9a833c6b56709edbab547e291a1/lib/util/identifier.js#L378
pub fn get_undo_path(filename: &str, output_path: String, enforce_relative: bool) -> String {
  let mut depth: i32 = -1;
  let mut append = String::new();
  let mut p = output_path;
  if p.ends_with('/') || p.ends_with('\\') {
    p.pop();
  }
  for part in filename.split(&['/', '\\']) {
    if part == ".." {
      if depth > -1 {
        depth -= 1
      } else {
        let pos = match (p.rfind('/'), p.rfind('\\')) {
          (None, None) => {
            p.push('/');
            return p;
          }
          (None, Some(j)) => j,
          (Some(i), None) => i,
          (Some(i), Some(j)) => usize::max(i, j),
        };
        append = format!("{}/{append}", &p[pos + 1..]);
        p = p[0..pos].to_string();
      }
    } else if part != "." {
      depth += 1;
    }
  }

  if depth > 0 {
    format!("{}{append}", "../".repeat(depth as usize))
  } else if enforce_relative {
    format!("./{append}")
  } else {
    append
  }
}

#[test]
fn test_get_undo_path() {
  assert_eq!(get_undo_path("a", "/a/b/c".to_string(), true), "./");
  assert_eq!(
    get_undo_path("static/js/a.js", "/a/b/c".to_string(), false),
    "../../"
  );
}

impl PublicPath {
  pub async fn render(&self, compilation: &Compilation, filename: &str) -> String {
    match self {
      Self::Filename(f) => {
        Self::ensure_ends_with_slash(Self::render_filename(compilation, f).await)
      }
      Self::Auto => Self::render_auto_public_path(compilation, filename),
    }
  }

  pub async fn render_filename(compilation: &Compilation, template: &Filename) -> String {
    let path_data = PathData::default().hash(compilation.get_hash().unwrap_or("XXXX"));
    template
      .render(path_data, None)
      .await
      .expect("failed to render public path")
  }

  pub fn ensure_ends_with_slash(public_path: String) -> String {
    if !public_path.is_empty() && !public_path.ends_with('/') {
      public_path + "/"
    } else {
      public_path
    }
  }

  pub fn render_auto_public_path(compilation: &Compilation, filename: &str) -> String {
    let public_path = get_undo_path(filename, compilation.options.output.path.to_string(), false);
    Self::ensure_ends_with_slash(public_path)
  }
}

impl Default for PublicPath {
  fn default() -> Self {
    Self::from_str("/").expect("'/' should be a valid public path")
  }
}

impl FromStr for PublicPath {
  type Err = ParseError;
  fn from_str(s: &str) -> Result<Self, Self::Err> {
    if s.eq("auto") {
      Ok(Self::Auto)
    } else {
      Ok(Self::Filename(Filename::from(s)))
    }
  }
}

impl From<String> for PublicPath {
  fn from(value: String) -> Self {
    if value == "auto" {
      Self::Auto
    } else {
      Self::Filename(value.into())
    }
  }
}

pub fn get_css_chunk_filename_template<'filename>(
  chunk: &'filename Chunk,
  output_options: &'filename OutputOptions,
  chunk_group_by_ukey: &ChunkGroupByUkey,
) -> &'filename Filename {
  // Align with https://github.com/webpack/webpack/blob/8241da7f1e75c5581ba535d127fa66aeb9eb2ac8/lib/css/CssModulesPlugin.js#L444
  if let Some(css_filename_template) = chunk.css_filename_template() {
    css_filename_template
  } else if chunk.can_be_initial(chunk_group_by_ukey) {
    &output_options.css_filename
  } else {
    &output_options.css_chunk_filename
  }
}

pub fn get_js_chunk_filename_template(
  chunk: &Chunk,
  output_options: &OutputOptions,
  chunk_group_by_ukey: &ChunkGroupByUkey,
) -> Filename {
  // Align with https://github.com/webpack/webpack/blob/8241da7f1e75c5581ba535d127fa66aeb9eb2ac8/lib/javascript/JavascriptModulesPlugin.js#L480
  if let Some(filename_template) = chunk.filename_template() {
    filename_template.clone()
  } else if matches!(chunk.kind(), ChunkKind::HotUpdate) {
    output_options.hot_update_chunk_filename.clone()
  } else if chunk.can_be_initial(chunk_group_by_ukey) {
    output_options.filename.clone()
  } else {
    output_options.chunk_filename.clone()
  }
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct LibraryOptions {
  pub name: Option<LibraryName>,
  pub export: Option<LibraryExport>,
  // webpack type
  pub library_type: LibraryType,
  pub umd_named_define: Option<bool>,
  pub auxiliary_comment: Option<LibraryAuxiliaryComment>,
  pub amd_container: Option<String>,
}

pub type LibraryType = String;

pub type LibraryExport = Vec<String>;

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct LibraryAuxiliaryComment {
  pub root: Option<String>,
  pub commonjs: Option<String>,
  pub commonjs2: Option<String>,
  pub amd: Option<String>,
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum LibraryName {
  NonUmdObject(LibraryNonUmdObject),
  UmdObject(LibraryCustomUmdObject),
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum LibraryNonUmdObject {
  Array(Vec<String>),
  String(String),
}

#[cacheable]
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct LibraryCustomUmdObject {
  pub amd: Option<String>,
  pub commonjs: Option<String>,
  pub root: Option<Vec<String>>,
}

#[derive(Debug, Default, Copy, Clone)]
pub struct Environment {
  pub r#const: bool,
  pub method_shorthand: bool,
  pub arrow_function: bool,
  pub node_prefix_for_core_modules: bool,
  pub async_function: bool,
  pub big_int_literal: bool,
  pub destructuring: bool,
  pub document: bool,
  pub dynamic_import: bool,
  pub for_of: bool,
  pub global_this: bool,
  pub module: bool,
  pub optional_chaining: bool,
  pub template_literal: bool,
  pub dynamic_import_in_worker: bool,
  pub import_meta_dirname_and_filename: bool,
}

impl Environment {
  pub fn supports_const(&self) -> bool {
    self.r#const
  }

  pub fn supports_method_shorthand(&self) -> bool {
    self.method_shorthand
  }

  pub fn supports_arrow_function(&self) -> bool {
    self.arrow_function
  }

  pub fn supports_node_prefix_for_core_modules(&self) -> bool {
    self.node_prefix_for_core_modules
  }

  pub fn supports_import_meta_dirname_and_filename(&self) -> bool {
    self.import_meta_dirname_and_filename
  }

  pub fn supports_async_function(&self) -> bool {
    self.async_function
  }

  pub fn supports_big_int_literal(&self) -> bool {
    self.big_int_literal
  }

  pub fn supports_destructuring(&self) -> bool {
    self.destructuring
  }

  pub fn supports_document(&self) -> bool {
    self.document
  }

  pub fn supports_dynamic_import(&self) -> bool {
    self.dynamic_import
  }

  pub fn supports_dynamic_import_in_worker(&self) -> bool {
    self.dynamic_import_in_worker
  }

  pub fn supports_for_of(&self) -> bool {
    self.for_of
  }

  pub fn supports_global_this(&self) -> bool {
    self.global_this
  }

  pub fn supports_module(&self) -> bool {
    self.module
  }

  pub fn supports_optional_chaining(&self) -> bool {
    self.optional_chaining
  }

  pub fn supports_template_literal(&self) -> bool {
    self.template_literal
  }
}