File size: 25,043 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
609
610
611
612
613
614
615
616
617
618
use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

use pathdiff::diff_paths;
use swc_core::{
    atoms::Atom,
    common::{errors::HANDLER, FileName, Span, DUMMY_SP},
    ecma::{
        ast::{
            op, ArrayLit, ArrowExpr, BinExpr, BlockStmt, BlockStmtOrExpr, Bool, CallExpr, Callee,
            Expr, ExprOrSpread, ExprStmt, Id, Ident, IdentName, ImportDecl, ImportNamedSpecifier,
            ImportSpecifier, KeyValueProp, Lit, ModuleDecl, ModuleItem, ObjectLit, Pass, Prop,
            PropName, PropOrSpread, Stmt, Str, Tpl, UnaryExpr, UnaryOp,
        },
        utils::{private_ident, quote_ident, ExprFactory},
        visit::{fold_pass, Fold, FoldWith, VisitMut, VisitMutWith},
    },
    quote,
};

/// Creates a SWC visitor to transform `next/dynamic` calls to have the
/// corresponding `loadableGenerated` property.
///
/// **NOTE** We do not use `NextDynamicMode::Turbopack` yet. It isn't compatible
/// with current loadable manifest, which causes hydration errors.
pub fn next_dynamic(
    is_development: bool,
    is_server_compiler: bool,
    is_react_server_layer: bool,
    prefer_esm: bool,
    mode: NextDynamicMode,
    filename: Arc<FileName>,
    pages_or_app_dir: Option<PathBuf>,
) -> impl Pass {
    fold_pass(NextDynamicPatcher {
        is_development,
        is_server_compiler,
        is_react_server_layer,
        prefer_esm,
        pages_or_app_dir,
        filename,
        dynamic_bindings: vec![],
        is_next_dynamic_first_arg: false,
        dynamically_imported_specifier: None,
        state: match mode {
            NextDynamicMode::Webpack => NextDynamicPatcherState::Webpack,
            NextDynamicMode::Turbopack {
                dynamic_client_transition_name,
                dynamic_transition_name,
            } => NextDynamicPatcherState::Turbopack {
                dynamic_client_transition_name,
                dynamic_transition_name,
                imports: vec![],
            },
        },
    })
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum NextDynamicMode {
    /// In Webpack mode, each `dynamic()` call will generate a key composed
    /// from:
    /// 1. The current module's path relative to the pages directory;
    /// 2. The relative imported module id.
    ///
    /// This key is of the form:
    /// {currentModulePath} -> {relativeImportedModulePath}
    ///
    /// It corresponds to an entry in the React Loadable Manifest generated by
    /// the React Loadable Webpack plugin.
    Webpack,
    /// In Turbopack mode:
    /// * each dynamic import is amended with a transition to `dynamic_transition_name`
    /// * the ident of the client module (via `dynamic_client_transition_name`) is added to the
    ///   metadata
    Turbopack {
        dynamic_client_transition_name: Atom,
        dynamic_transition_name: Atom,
    },
}

#[derive(Debug)]
struct NextDynamicPatcher {
    is_development: bool,
    is_server_compiler: bool,
    is_react_server_layer: bool,
    prefer_esm: bool,
    pages_or_app_dir: Option<PathBuf>,
    filename: Arc<FileName>,
    dynamic_bindings: Vec<Id>,
    is_next_dynamic_first_arg: bool,
    dynamically_imported_specifier: Option<(Atom, Span)>,
    state: NextDynamicPatcherState,
}

#[derive(Debug, Clone, Eq, PartialEq)]
enum NextDynamicPatcherState {
    Webpack,
    /// In Turbo mode, contains a list of modules that need to be imported with
    /// the given transition under a particular ident.
    #[allow(unused)]
    Turbopack {
        dynamic_client_transition_name: Atom,
        dynamic_transition_name: Atom,
        imports: Vec<TurbopackImport>,
    },
}

#[derive(Debug, Clone, Eq, PartialEq)]
enum TurbopackImport {
    // TODO do we need more variants? server vs client vs dev vs prod?
    Import { id_ident: Ident, specifier: Atom },
}

impl Fold for NextDynamicPatcher {
    fn fold_module_items(&mut self, mut items: Vec<ModuleItem>) -> Vec<ModuleItem> {
        items = items.fold_children_with(self);

        self.maybe_add_dynamically_imported_specifier(&mut items);

        items
    }

    fn fold_import_decl(&mut self, decl: ImportDecl) -> ImportDecl {
        let ImportDecl {
            ref src,
            ref specifiers,
            ..
        } = decl;
        if &src.value == "next/dynamic" {
            for specifier in specifiers {
                if let ImportSpecifier::Default(default_specifier) = specifier {
                    self.dynamic_bindings.push(default_specifier.local.to_id());
                }
            }
        }

        decl
    }

    fn fold_call_expr(&mut self, expr: CallExpr) -> CallExpr {
        if self.is_next_dynamic_first_arg {
            if let Callee::Import(..) = &expr.callee {
                match &*expr.args[0].expr {
                    Expr::Lit(Lit::Str(Str { value, span, .. })) => {
                        self.dynamically_imported_specifier = Some((value.clone(), *span));
                    }
                    Expr::Tpl(Tpl { exprs, quasis, .. }) if exprs.is_empty() => {
                        self.dynamically_imported_specifier =
                            Some((quasis[0].raw.clone(), quasis[0].span));
                    }
                    _ => {}
                }
            }
            return expr.fold_children_with(self);
        }
        let mut expr = expr.fold_children_with(self);
        if let Callee::Expr(i) = &expr.callee {
            if let Expr::Ident(identifier) = &**i {
                if self.dynamic_bindings.contains(&identifier.to_id()) {
                    if expr.args.is_empty() {
                        HANDLER.with(|handler| {
                            handler
                                .struct_span_err(
                                    identifier.span,
                                    "next/dynamic requires at least one argument",
                                )
                                .emit()
                        });
                        return expr;
                    } else if expr.args.len() > 2 {
                        HANDLER.with(|handler| {
                            handler
                                .struct_span_err(
                                    identifier.span,
                                    "next/dynamic only accepts 2 arguments",
                                )
                                .emit()
                        });
                        return expr;
                    }
                    if expr.args.len() == 2 {
                        match &*expr.args[1].expr {
                            Expr::Object(_) => {}
                            _ => {
                                HANDLER.with(|handler| {
                          handler
                              .struct_span_err(
                                  identifier.span,
                                  "next/dynamic options must be an object literal.\nRead more: https://nextjs.org/docs/messages/invalid-dynamic-options-type",
                              )
                              .emit();
                      });
                                return expr;
                            }
                        }
                    }

                    self.is_next_dynamic_first_arg = true;
                    expr.args[0].expr = expr.args[0].expr.clone().fold_with(self);
                    self.is_next_dynamic_first_arg = false;

                    let Some((dynamically_imported_specifier, dynamically_imported_specifier_span)) =
                        self.dynamically_imported_specifier.take()
                    else {
                        return expr;
                    };

                    let project_dir = match self.pages_or_app_dir.as_deref() {
                        Some(pages_or_app) => pages_or_app.parent(),
                        _ => None,
                    };

                    let generated = Box::new(Expr::Object(ObjectLit {
                        span: DUMMY_SP,
                        props: match &mut self.state {
                            NextDynamicPatcherState::Webpack => {
                                // dev client or server:
                                // loadableGenerated: {
                                //   modules:
                                // ["/project/src/file-being-transformed.js -> " +
                                // '../components/hello'] }
                                //
                                // prod client
                                // loadableGenerated: {
                                //   webpack: () => [require.resolveWeak('../components/hello')],
                                if self.is_development || self.is_server_compiler {
                                    module_id_options(quote!(
                                        "$left + $right" as Expr,
                                        left: Expr = format!(
                                            "{} -> ",
                                            rel_filename(project_dir, &self.filename)
                                        )
                                        .into(),
                                        right: Expr = dynamically_imported_specifier.clone().into(),
                                    ))
                                } else {
                                    webpack_options(quote!(
                                        "require.resolveWeak($id)" as Expr,
                                        id: Expr = dynamically_imported_specifier.clone().into()
                                    ))
                                }
                            }

                            NextDynamicPatcherState::Turbopack { imports, .. } => {
                                // loadableGenerated: { modules: [
                                // ".../client.js [app-client] (ecmascript, next/dynamic entry)"
                                // ]}
                                let id_ident =
                                    private_ident!(dynamically_imported_specifier_span, "id");

                                imports.push(TurbopackImport::Import {
                                    id_ident: id_ident.clone(),
                                    specifier: dynamically_imported_specifier.clone(),
                                });

                                module_id_options(Expr::Ident(id_ident))
                            }
                        },
                    }));

                    let mut props =
                        vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
                            key: PropName::Ident(IdentName::new(
                                "loadableGenerated".into(),
                                DUMMY_SP,
                            )),
                            value: generated,
                        })))];

                    let mut has_ssr_false = false;

                    if expr.args.len() == 2 {
                        if let Expr::Object(ObjectLit {
                            props: options_props,
                            ..
                        }) = &*expr.args[1].expr
                        {
                            for prop in options_props.iter() {
                                if let Some(KeyValueProp { key, value }) = match prop {
                                    PropOrSpread::Prop(prop) => match &**prop {
                                        Prop::KeyValue(key_value_prop) => Some(key_value_prop),
                                        _ => None,
                                    },
                                    _ => None,
                                } {
                                    if let Some(IdentName { sym, span: _ }) = match key {
                                        PropName::Ident(ident) => Some(ident),
                                        _ => None,
                                    } {
                                        if sym == "ssr" {
                                            if let Some(Lit::Bool(Bool {
                                                value: false,
                                                span: _,
                                            })) = value.as_lit()
                                            {
                                                has_ssr_false = true
                                            }
                                        }
                                    }
                                }
                            }
                            props.extend(options_props.iter().cloned());
                        }
                    }

                    let should_skip_ssr_compile = has_ssr_false
                        && self.is_server_compiler
                        && !self.is_react_server_layer
                        && self.prefer_esm;

                    match &self.state {
                        NextDynamicPatcherState::Webpack => {
                            // Only use `require.resolveWebpack` to decouple modules for webpack,
                            // turbopack doesn't need this

                            // When it's not preferring to picking up ESM (in the pages router), we
                            // don't need to do it as it doesn't need to enter the non-ssr module.
                            //
                            // Also transforming it to `require.resolveWeak` doesn't work with ESM
                            // imports ( i.e. require.resolveWeak(esm asset)).
                            if should_skip_ssr_compile {
                                // if it's server components SSR layer
                                // Transform 1st argument `expr.args[0]` aka the module loader from:
                                // dynamic(() => import('./client-mod'), { ssr: false }))`
                                // into:
                                // dynamic(async () => {
                                //   require.resolveWeak('./client-mod')
                                // }, { ssr: false }))`

                                let require_resolve_weak_expr = Expr::Call(CallExpr {
                                    span: DUMMY_SP,
                                    callee: quote_ident!("require.resolveWeak").as_callee(),
                                    args: vec![ExprOrSpread {
                                        spread: None,
                                        expr: Box::new(Expr::Lit(Lit::Str(Str {
                                            span: DUMMY_SP,
                                            value: dynamically_imported_specifier.clone(),
                                            raw: None,
                                        }))),
                                    }],
                                    ..Default::default()
                                });

                                let side_effect_free_loader_arg = Expr::Arrow(ArrowExpr {
                                    span: DUMMY_SP,
                                    params: vec![],
                                    body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt {
                                        span: DUMMY_SP,
                                        stmts: vec![Stmt::Expr(ExprStmt {
                                            span: DUMMY_SP,
                                            expr: Box::new(exec_expr_when_resolve_weak_available(
                                                &require_resolve_weak_expr,
                                            )),
                                        })],
                                        ..Default::default()
                                    })),
                                    is_async: true,
                                    is_generator: false,
                                    ..Default::default()
                                });

                                expr.args[0] = side_effect_free_loader_arg.as_arg();
                            }
                        }
                        NextDynamicPatcherState::Turbopack {
                            dynamic_transition_name,
                            ..
                        } => {
                            // When `ssr: false`
                            // if it's server components SSR layer
                            // Transform 1st argument `expr.args[0]` aka the module loader from:
                            // dynamic(() => import('./client-mod'), { ssr: false }))`
                            // into:
                            // dynamic(async () => {}, { ssr: false }))`
                            if should_skip_ssr_compile {
                                let side_effect_free_loader_arg = Expr::Arrow(ArrowExpr {
                                    span: DUMMY_SP,
                                    params: vec![],
                                    body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt {
                                        span: DUMMY_SP,
                                        stmts: vec![],
                                        ..Default::default()
                                    })),
                                    is_async: true,
                                    is_generator: false,
                                    ..Default::default()
                                });

                                expr.args[0] = side_effect_free_loader_arg.as_arg();
                            } else {
                                // Add `{with:{turbopack-transition: ...}}` to the dynamic import
                                let mut visitor = DynamicImportTransitionAdder {
                                    transition_name: dynamic_transition_name,
                                };
                                expr.args[0].visit_mut_with(&mut visitor);
                            }
                        }
                    }

                    let second_arg = ExprOrSpread {
                        spread: None,
                        expr: Box::new(Expr::Object(ObjectLit {
                            span: DUMMY_SP,
                            props,
                        })),
                    };

                    if expr.args.len() == 2 {
                        expr.args[1] = second_arg;
                    } else {
                        expr.args.push(second_arg)
                    }
                }
            }
        }
        expr
    }
}

struct DynamicImportTransitionAdder<'a> {
    transition_name: &'a str,
}
// Add `{with:{turbopack-transition: <self.transition_name>}}` to any dynamic imports
impl VisitMut for DynamicImportTransitionAdder<'_> {
    fn visit_mut_call_expr(&mut self, expr: &mut CallExpr) {
        if let Callee::Import(..) = &expr.callee {
            let options = ExprOrSpread {
                expr: Box::new(
                    ObjectLit {
                        span: DUMMY_SP,
                        props: vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
                            key: PropName::Ident(IdentName::new("with".into(), DUMMY_SP)),
                            value: with_transition(self.transition_name).into(),
                        })))],
                    }
                    .into(),
                ),
                spread: None,
            };

            match expr.args.get_mut(1) {
                Some(arg) => *arg = options,
                None => expr.args.push(options),
            }
        } else {
            expr.visit_mut_children_with(self);
        }
    }
}

fn module_id_options(module_id: Expr) -> Vec<PropOrSpread> {
    vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
        key: PropName::Ident(IdentName::new("modules".into(), DUMMY_SP)),
        value: Box::new(Expr::Array(ArrayLit {
            elems: vec![Some(ExprOrSpread {
                expr: Box::new(module_id),
                spread: None,
            })],
            span: DUMMY_SP,
        })),
    })))]
}

fn webpack_options(module_id: Expr) -> Vec<PropOrSpread> {
    vec![PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
        key: PropName::Ident(IdentName::new("webpack".into(), DUMMY_SP)),
        value: Box::new(Expr::Arrow(ArrowExpr {
            params: vec![],
            body: Box::new(BlockStmtOrExpr::Expr(Box::new(Expr::Array(ArrayLit {
                elems: vec![Some(ExprOrSpread {
                    expr: Box::new(module_id),
                    spread: None,
                })],
                span: DUMMY_SP,
            })))),
            is_async: false,
            is_generator: false,
            span: DUMMY_SP,
            ..Default::default()
        })),
    })))]
}

impl NextDynamicPatcher {
    fn maybe_add_dynamically_imported_specifier(&mut self, items: &mut Vec<ModuleItem>) {
        let NextDynamicPatcherState::Turbopack {
            dynamic_client_transition_name,
            imports,
            ..
        } = &mut self.state
        else {
            return;
        };

        let mut new_items = Vec::with_capacity(imports.len());

        for import in std::mem::take(imports) {
            match import {
                TurbopackImport::Import {
                    id_ident,
                    specifier,
                } => {
                    // Turbopack will automatically transform the imported `__turbopack_module_id__`
                    // identifier into the imported module's id.
                    new_items.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
                        span: DUMMY_SP,
                        specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
                            span: DUMMY_SP,
                            local: id_ident,
                            imported: Some(
                                Ident::new(
                                    "__turbopack_module_id__".into(),
                                    DUMMY_SP,
                                    Default::default(),
                                )
                                .into(),
                            ),
                            is_type_only: false,
                        })],
                        src: Box::new(specifier.into()),
                        type_only: false,
                        with: Some(with_transition_chunking_type(
                            dynamic_client_transition_name,
                            "none",
                        )),
                        phase: Default::default(),
                    })));
                }
            }
        }

        new_items.append(items);

        std::mem::swap(&mut new_items, items)
    }
}

fn exec_expr_when_resolve_weak_available(expr: &Expr) -> Expr {
    let undefined_str_literal = Expr::Lit(Lit::Str(Str {
        span: DUMMY_SP,
        value: "undefined".into(),
        raw: None,
    }));

    let typeof_expr = Expr::Unary(UnaryExpr {
        span: DUMMY_SP,
        op: UnaryOp::TypeOf, // 'typeof' operator
        arg: Box::new(Expr::Ident(Ident {
            sym: quote_ident!("require.resolveWeak").sym,
            ..Default::default()
        })),
    });

    // typeof require.resolveWeak !== 'undefined' && <expression>
    Expr::Bin(BinExpr {
        span: DUMMY_SP,
        left: Box::new(Expr::Bin(BinExpr {
            span: DUMMY_SP,
            op: op!("!=="),
            left: Box::new(typeof_expr),
            right: Box::new(undefined_str_literal),
        })),
        op: op!("&&"),
        right: Box::new(expr.clone()),
    })
}

fn rel_filename(base: Option<&Path>, file: &FileName) -> String {
    let base = match base {
        Some(v) => v,
        None => return file.to_string(),
    };

    let file = match file {
        FileName::Real(v) => v,
        _ => {
            return file.to_string();
        }
    };

    let rel_path = diff_paths(file, base);

    let rel_path = match rel_path {
        Some(v) => v,
        None => return file.display().to_string(),
    };

    rel_path.display().to_string()
}

fn with_transition(transition_name: &str) -> ObjectLit {
    with_clause(&[("turbopack-transition", transition_name)])
}

fn with_transition_chunking_type(transition_name: &str, chunking_type: &str) -> Box<ObjectLit> {
    Box::new(with_clause(&[
        ("turbopack-transition", transition_name),
        ("turbopack-chunking-type", chunking_type),
    ]))
}

fn with_clause<'a>(entries: impl IntoIterator<Item = &'a (&'a str, &'a str)>) -> ObjectLit {
    ObjectLit {
        span: DUMMY_SP,
        props: entries.into_iter().map(|(k, v)| with_prop(k, v)).collect(),
    }
}

fn with_prop(key: &str, value: &str) -> PropOrSpread {
    PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
        key: PropName::Str(key.into()),
        value: Box::new(Expr::Lit(value.into())),
    })))
}