Skip to content

Commit

Permalink
add client disallowed transform (#8336)
Browse files Browse the repository at this point in the history
### Description

needed for next.js to disallow "use client" on middleware and
instrumentation

### Testing Instructions

<!--
  Give a quick description of steps to test your changes.
-->
  • Loading branch information
sokra committed Jun 5, 2024
1 parent 9c28c62 commit fb3a61a
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use anyhow::Result;
use async_trait::async_trait;
use swc_core::ecma::{ast::Program, transforms::base::resolver, visit::VisitMutWith};
use turbopack_ecmascript::{CustomTransformer, TransformContext};

use super::{is_client_module, server_to_client_proxy::create_error_proxy_module};

#[derive(Debug)]
pub struct ClientDisallowedDirectiveTransformer {
error_proxy_module: String,
}

impl ClientDisallowedDirectiveTransformer {
pub fn new(error_proxy_module: String) -> Self {
Self { error_proxy_module }
}
}

#[async_trait]
impl CustomTransformer for ClientDisallowedDirectiveTransformer {
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
if is_client_module(program) {
*program = create_error_proxy_module(&self.error_proxy_module);
program.visit_mut_with(&mut resolver(
ctx.unresolved_mark,
ctx.top_level_mark,
false,
));
}

Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use swc_core::ecma::ast::{Lit, Program};

pub mod client;
pub mod client_disallowed;
pub mod server;
mod server_to_client_proxy;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use swc_core::{
common::DUMMY_SP,
ecma::{
ast::{
ImportDecl, ImportSpecifier, ImportStarAsSpecifier, Module, ModuleDecl, ModuleItem,
Program,
ImportDecl, ImportDefaultSpecifier, ImportSpecifier, ImportStarAsSpecifier, Module,
ModuleDecl, ModuleItem, Program,
},
utils::private_ident,
},
Expand Down Expand Up @@ -41,3 +41,28 @@ pub fn create_proxy_module(transition_name: &str, target_import: &str) -> Progra
span: DUMMY_SP,
})
}

pub fn create_error_proxy_module(error_proxy_module: &str) -> Program {
let ident = private_ident!("errorProxy");
Program::Module(Module {
body: vec![
ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
specifiers: vec![ImportSpecifier::Default(ImportDefaultSpecifier {
local: ident.clone(),
span: DUMMY_SP,
})],
src: Box::new(error_proxy_module.into()),
type_only: false,
with: Some(with_clause(&[(TURBOPACK_HELPER.as_str(), "true")])),
span: DUMMY_SP,
phase: Default::default(),
})),
ModuleItem::Stmt(quote!(
"__turbopack_export_namespace__($proxy);" as Stmt,
proxy = ident,
)),
],
shebang: None,
span: DUMMY_SP,
})
}

0 comments on commit fb3a61a

Please sign in to comment.