rolldown_error 1.2.3

rolldown_error
Documentation
use super::BuildEvent;
use crate::DiagnosticOptions;
use crate::build_diagnostic::diagnostic::Diagnostic;
use arcstr::ArcStr;
use oxc::span::Span;

/// What produced the empty `import.meta` a warning is being raised about.
#[derive(Debug, Clone, Copy)]
pub enum EmptyImportMetaKind {
  /// A bare `import.meta` (or a member access other than `url`) the user wrote.
  Plain,
  /// An `import.meta.url` the user wrote.
  Url,
  /// Generated by expanding an `import.meta.ROLLDOWN_FILE_URL_*` reference into
  /// `new URL(..., import.meta.url).href`. The [`EmptyImportMeta::span`] points at
  /// that original reference (so the code frame shows the exact one),
  /// whose generated `import.meta.url` is what collapses to `{}`.
  RolldownFileUrl,
}

#[derive(Debug)]
pub struct EmptyImportMeta {
  pub filename: String,
  pub source: ArcStr,
  pub span: Span,
  pub format: ArcStr,
  pub kind: EmptyImportMetaKind,
}

impl BuildEvent for EmptyImportMeta {
  fn kind(&self) -> crate::types::event_kind::EventKind {
    crate::types::event_kind::EventKind::EmptyImportMeta
  }

  fn id(&self) -> Option<String> {
    Some(self.filename.clone())
  }

  fn message(&self, _opts: &DiagnosticOptions) -> String {
    format!("`import.meta` may not be a valid syntax with the `{}` output format.", self.format)
  }

  fn on_diagnostic(&self, diagnostic: &mut Diagnostic, opts: &DiagnosticOptions) {
    let filename = opts.stabilize_path(&self.filename);
    let file_id = diagnostic.add_file(filename, self.source.clone());

    diagnostic.title =
      format!("`import.meta` may not be a valid syntax with the `{}` output format.", self.format);

    if matches!(self.kind, EmptyImportMetaKind::RolldownFileUrl) {
      diagnostic.add_label(
        &file_id,
        self.span.start..self.span.end,
        String::from(
          "This file URL reference is rewritten to `new URL(..., import.meta.url).href`, and that generated `import.meta.url` becomes `undefined`.",
        ),
      );
      diagnostic.add_help(String::from("If you want to polyfill `import.meta.url` like Rollup does, check out the Document: https://rolldown.rs/in-depth/non-esm-output-formats#well-known-import-meta-properties"));
      return;
    }

    diagnostic.add_label(
      &file_id,
      self.span.start..self.span.end,
      String::from(
        "This `import.meta` will be replaced with an empty object (`{}`) automatically. If this is desired, you can suppress this warning by adding `transform.define: { 'import.meta': {} }`. If `import.meta` needs to be kept as-is, you need to set the output format to `esm`.",
      ),
    );

    if matches!(self.kind, EmptyImportMetaKind::Url) {
      diagnostic.add_help(String::from("If you want to polyfill `import.meta.url` like Rollup does, check out the Document: https://rolldown.rs/in-depth/non-esm-output-formats#well-known-import-meta-properties"));
    }
  }
}