-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathserver_actions.rs
3083 lines (2784 loc) · 118 KB
/
server_actions.rs
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
cell::RefCell,
collections::{hash_map, BTreeMap},
convert::{TryFrom, TryInto},
mem::{replace, take},
rc::Rc,
};
use hex::encode as hex_encode;
use indoc::formatdoc;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::Deserialize;
use sha1::{Digest, Sha1};
use swc_core::{
atoms::Atom,
common::{
comments::{Comment, CommentKind, Comments},
errors::HANDLER,
source_map::PURE_SP,
util::take::Take,
BytePos, FileName, Mark, Span, SyntaxContext, DUMMY_SP,
},
ecma::{
ast::*,
utils::{private_ident, quote_ident, ExprFactory},
visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith},
},
quote,
};
use turbo_rcstr::RcStr;
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config {
pub is_react_server_layer: bool,
pub is_development: bool,
pub use_cache_enabled: bool,
pub hash_salt: String,
pub cache_kinds: FxHashSet<RcStr>,
}
#[derive(Clone, Debug)]
enum Directive {
UseServer,
UseCache { cache_kind: RcStr },
}
#[derive(Clone, Debug)]
enum DirectiveLocation {
Module,
FunctionBody,
}
#[derive(Clone, Debug)]
enum ThisStatus {
Allowed,
Forbidden { directive: Directive },
}
#[derive(Clone, Debug)]
enum ServerActionsErrorKind {
ExportedSyncFunction {
span: Span,
in_action_file: bool,
},
ForbiddenExpression {
span: Span,
expr: String,
directive: Directive,
},
InlineSyncFunction {
span: Span,
directive: Directive,
},
InlineUseCacheInClassInstanceMethod {
span: Span,
},
InlineUseCacheInClientComponent {
span: Span,
},
InlineUseServerInClassInstanceMethod {
span: Span,
},
InlineUseServerInClientComponent {
span: Span,
},
MisplacedDirective {
span: Span,
directive: String,
location: DirectiveLocation,
},
MisplacedWrappedDirective {
span: Span,
directive: String,
location: DirectiveLocation,
},
MisspelledDirective {
span: Span,
directive: String,
expected_directive: String,
},
MultipleDirectives {
span: Span,
location: DirectiveLocation,
},
UnknownCacheKind {
span: Span,
cache_kind: RcStr,
},
UseCacheWithoutExperimentalFlag {
span: Span,
directive: String,
},
WrappedDirective {
span: Span,
directive: String,
},
}
/// A mapping of hashed action id to the action's exported function name.
// Using BTreeMap to ensure the order of the actions is deterministic.
pub type ActionsMap = BTreeMap<Atom, Atom>;
#[tracing::instrument(level = tracing::Level::TRACE, skip_all)]
pub fn server_actions<C: Comments>(
file_name: &FileName,
config: Config,
comments: C,
use_cache_telemetry_tracker: Rc<RefCell<FxHashMap<String, usize>>>,
) -> impl Pass {
visit_mut_pass(ServerActions {
config,
comments,
file_name: file_name.to_string(),
start_pos: BytePos(0),
file_directive: None,
in_exported_expr: false,
in_default_export_decl: false,
fn_decl_ident: None,
in_callee: false,
has_action: false,
has_cache: false,
this_status: ThisStatus::Allowed,
reference_index: 0,
in_module_level: true,
should_track_names: false,
names: Default::default(),
declared_idents: Default::default(),
exported_idents: Default::default(),
// This flag allows us to rewrite `function foo() {}` to `const foo = createProxy(...)`.
rewrite_fn_decl_to_proxy_decl: None,
rewrite_default_fn_expr_to_proxy_expr: None,
rewrite_expr_to_proxy_expr: None,
annotations: Default::default(),
extra_items: Default::default(),
hoisted_extra_items: Default::default(),
export_actions: Default::default(),
private_ctxt: SyntaxContext::empty().apply_mark(Mark::new()),
arrow_or_fn_expr_ident: None,
exported_local_ids: FxHashSet::default(),
use_cache_telemetry_tracker,
})
}
/// Serializes the Server Actions into a magic comment prefixed by
/// `__next_internal_action_entry_do_not_use__`.
fn generate_server_actions_comment(actions: ActionsMap) -> String {
format!(
" __next_internal_action_entry_do_not_use__ {} ",
serde_json::to_string(&actions).unwrap()
)
}
struct ServerActions<C: Comments> {
#[allow(unused)]
config: Config,
file_name: String,
comments: C,
start_pos: BytePos,
file_directive: Option<Directive>,
in_exported_expr: bool,
in_default_export_decl: bool,
fn_decl_ident: Option<Ident>,
in_callee: bool,
has_action: bool,
has_cache: bool,
this_status: ThisStatus,
reference_index: u32,
in_module_level: bool,
should_track_names: bool,
names: Vec<Name>,
declared_idents: Vec<Ident>,
// This flag allows us to rewrite `function foo() {}` to `const foo = createProxy(...)`.
rewrite_fn_decl_to_proxy_decl: Option<VarDecl>,
rewrite_default_fn_expr_to_proxy_expr: Option<Box<Expr>>,
rewrite_expr_to_proxy_expr: Option<Box<Expr>>,
exported_idents: Vec<(
/* ident */ Ident,
/* name */ Atom,
/* id */ Atom,
)>,
annotations: Vec<Stmt>,
extra_items: Vec<ModuleItem>,
hoisted_extra_items: Vec<ModuleItem>,
export_actions: Vec<(/* name */ Atom, /* id */ Atom)>,
private_ctxt: SyntaxContext,
arrow_or_fn_expr_ident: Option<Ident>,
exported_local_ids: FxHashSet<Id>,
use_cache_telemetry_tracker: Rc<RefCell<FxHashMap<String, usize>>>,
}
impl<C: Comments> ServerActions<C> {
fn generate_server_reference_id(
&self,
export_name: &str,
is_cache: bool,
params: Option<&Vec<Param>>,
) -> Atom {
// Attach a checksum to the action using sha1:
// $$id = special_byte + sha1('hash_salt' + 'file_name' + ':' + 'export_name');
// Currently encoded as hex.
let mut hasher = Sha1::new();
hasher.update(self.config.hash_salt.as_bytes());
hasher.update(self.file_name.as_bytes());
hasher.update(b":");
hasher.update(export_name.as_bytes());
let mut result = hasher.finalize().to_vec();
// Prepend an extra byte to the ID, with the following format:
// 0 000000 0
// ^type ^arg mask ^rest args
//
// The type bit represents if the action is a cache function or not.
// For cache functions, the type bit is set to 1. Otherwise, it's 0.
//
// The arg mask bit is used to determine which arguments are used by
// the function itself, up to 6 arguments. The bit is set to 1 if the
// argument is used, or being spread or destructured (so it can be
// indirectly or partially used). The bit is set to 0 otherwise.
//
// The rest args bit is used to determine if there's a ...rest argument
// in the function signature. If there is, the bit is set to 1.
//
// For example:
//
// async function foo(a, foo, b, bar, ...baz) {
// 'use cache';
// return a + b;
// }
//
// will have it encoded as [1][101011][1]. The first bit is set to 1
// because it's a cache function. The second part has 1010 because the
// only arguments used are `a` and `b`. The subsequent 11 bits are set
// to 1 because there's a ...rest argument starting from the 5th. The
// last bit is set to 1 as well for the same reason.
let type_bit = if is_cache { 1u8 } else { 0u8 };
let mut arg_mask = 0u8;
let mut rest_args = 0u8;
if let Some(params) = params {
// TODO: For the current implementation, we don't track if an
// argument ident is actually referenced in the function body.
// Instead, we go with the easy route and assume defined ones are
// used. This can be improved in the future.
for (i, param) in params.iter().enumerate() {
if let Pat::Rest(_) = param.pat {
// If there's a ...rest argument, we set the rest args bit
// to 1 and set the arg mask to 0b111111.
arg_mask = 0b111111;
rest_args = 0b1;
break;
}
if i < 6 {
arg_mask |= 0b1 << (5 - i);
} else {
// More than 6 arguments, we set the rest args bit to 1.
// This is rare for a Server Action, usually.
rest_args = 0b1;
break;
}
}
} else {
// If we can't determine the arguments (e.g. not staticaly analyzable),
// we assume all arguments are used.
arg_mask = 0b111111;
rest_args = 0b1;
}
result.push((type_bit << 7) | (arg_mask << 1) | rest_args);
result.rotate_right(1);
Atom::from(hex_encode(result))
}
fn gen_action_ident(&mut self) -> Atom {
let id: Atom = format!("$$RSC_SERVER_ACTION_{0}", self.reference_index).into();
self.reference_index += 1;
id
}
fn gen_cache_ident(&mut self) -> Atom {
let id: Atom = format!("$$RSC_SERVER_CACHE_{0}", self.reference_index).into();
self.reference_index += 1;
id
}
fn gen_ref_ident(&mut self) -> Atom {
let id: Atom = format!("$$RSC_SERVER_REF_{0}", self.reference_index).into();
self.reference_index += 1;
id
}
fn create_bound_action_args_array_pat(&mut self, arg_len: usize) -> Pat {
Pat::Array(ArrayPat {
span: DUMMY_SP,
elems: (0..arg_len)
.map(|i| {
Some(Pat::Ident(
Ident::new(
format!("$$ACTION_ARG_{i}").into(),
DUMMY_SP,
self.private_ctxt,
)
.into(),
))
})
.collect(),
optional: false,
type_ann: None,
})
}
// Check if the function or arrow function is an action or cache function,
// and remove any server function directive.
fn get_directive_for_function(
&mut self,
maybe_body: Option<&mut BlockStmt>,
) -> Option<Directive> {
let mut directive: Option<Directive> = None;
// Even if it's a file-level action or cache module, the function body
// might still have directives that override the module-level annotations.
if let Some(body) = maybe_body {
let directive_visitor = &mut DirectiveVisitor {
config: &self.config,
directive: None,
has_file_directive: self.file_directive.is_some(),
is_allowed_position: true,
location: DirectiveLocation::FunctionBody,
use_cache_telemetry_tracker: self.use_cache_telemetry_tracker.clone(),
};
body.stmts.retain(|stmt| {
let has_directive = directive_visitor.visit_stmt(stmt);
!has_directive
});
directive = directive_visitor.directive.clone();
}
// All exported functions inherit the file directive if they don't have their own directive.
if self.in_exported_expr && directive.is_none() && self.file_directive.is_some() {
return self.file_directive.clone();
}
directive
}
fn get_directive_for_module(&mut self, stmts: &mut Vec<ModuleItem>) -> Option<Directive> {
let directive_visitor = &mut DirectiveVisitor {
config: &self.config,
directive: None,
has_file_directive: false,
is_allowed_position: true,
location: DirectiveLocation::Module,
use_cache_telemetry_tracker: self.use_cache_telemetry_tracker.clone(),
};
stmts.retain(|item| {
if let ModuleItem::Stmt(stmt) = item {
let has_directive = directive_visitor.visit_stmt(stmt);
!has_directive
} else {
directive_visitor.is_allowed_position = false;
true
}
});
directive_visitor.directive.clone()
}
fn maybe_hoist_and_create_proxy_for_server_action_arrow_expr(
&mut self,
ids_from_closure: Vec<Name>,
arrow: &mut ArrowExpr,
) -> Box<Expr> {
let mut new_params: Vec<Param> = vec![];
if !ids_from_closure.is_empty() {
// First param is the encrypted closure variables.
new_params.push(Param {
span: DUMMY_SP,
decorators: vec![],
pat: Pat::Ident(IdentName::new("$$ACTION_CLOSURE_BOUND".into(), DUMMY_SP).into()),
});
}
for p in arrow.params.iter() {
new_params.push(Param::from(p.clone()));
}
let action_name = self.gen_action_ident();
let action_ident = Ident::new(action_name.clone(), arrow.span, self.private_ctxt);
let action_id = self.generate_server_reference_id(&action_name, false, Some(&new_params));
self.has_action = true;
self.export_actions
.push((action_name.clone(), action_id.clone()));
let register_action_expr = bind_args_to_ref_expr(
annotate_ident_as_server_reference(action_ident.clone(), action_id.clone(), arrow.span),
ids_from_closure
.iter()
.cloned()
.map(|id| Some(id.as_arg()))
.collect(),
action_id.clone(),
);
if let BlockStmtOrExpr::BlockStmt(block) = &mut *arrow.body {
block.visit_mut_with(&mut ClosureReplacer {
used_ids: &ids_from_closure,
private_ctxt: self.private_ctxt,
});
}
let mut new_body: BlockStmtOrExpr = *arrow.body.clone();
if !ids_from_closure.is_empty() {
// Prepend the decryption declaration to the body.
// var [arg1, arg2, arg3] = await decryptActionBoundArgs(actionId,
// $$ACTION_CLOSURE_BOUND)
let decryption_decl = VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: false,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: self.create_bound_action_args_array_pat(ids_from_closure.len()),
init: Some(Box::new(Expr::Await(AwaitExpr {
span: DUMMY_SP,
arg: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: quote_ident!("decryptActionBoundArgs").as_callee(),
args: vec![
action_id.as_arg(),
quote_ident!("$$ACTION_CLOSURE_BOUND").as_arg(),
],
..Default::default()
})),
}))),
definite: Default::default(),
}],
..Default::default()
};
match &mut new_body {
BlockStmtOrExpr::BlockStmt(body) => {
body.stmts.insert(0, decryption_decl.into());
}
BlockStmtOrExpr::Expr(body_expr) => {
new_body = BlockStmtOrExpr::BlockStmt(BlockStmt {
span: DUMMY_SP,
stmts: vec![
decryption_decl.into(),
Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(body_expr.take()),
}),
],
..Default::default()
});
}
}
}
// Create the action export decl from the arrow function
// export const $$RSC_SERVER_ACTION_0 = async function action($$ACTION_CLOSURE_BOUND) {}
self.hoisted_extra_items
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span: DUMMY_SP,
decl: VarDecl {
kind: VarDeclKind::Const,
span: DUMMY_SP,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: Pat::Ident(action_ident.clone().into()),
definite: false,
init: Some(Box::new(Expr::Fn(FnExpr {
ident: self.arrow_or_fn_expr_ident.clone(),
function: Box::new(Function {
params: new_params,
body: match new_body {
BlockStmtOrExpr::BlockStmt(body) => Some(body),
BlockStmtOrExpr::Expr(expr) => Some(BlockStmt {
span: DUMMY_SP,
stmts: vec![Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(expr),
})],
..Default::default()
}),
},
decorators: vec![],
span: DUMMY_SP,
is_generator: false,
is_async: true,
..Default::default()
}),
}))),
}],
declare: Default::default(),
ctxt: self.private_ctxt,
}
.into(),
})));
Box::new(register_action_expr.clone())
}
fn maybe_hoist_and_create_proxy_for_server_action_function(
&mut self,
ids_from_closure: Vec<Name>,
function: &mut Function,
fn_name: Option<Ident>,
) -> Box<Expr> {
let mut new_params: Vec<Param> = vec![];
if !ids_from_closure.is_empty() {
// First param is the encrypted closure variables.
new_params.push(Param {
span: DUMMY_SP,
decorators: vec![],
pat: Pat::Ident(IdentName::new("$$ACTION_CLOSURE_BOUND".into(), DUMMY_SP).into()),
});
}
new_params.append(&mut function.params);
let action_name: Atom = self.gen_action_ident();
let mut action_ident = Ident::new(action_name.clone(), function.span, self.private_ctxt);
if action_ident.span.lo == self.start_pos {
action_ident.span = Span::dummy_with_cmt();
}
let action_id = self.generate_server_reference_id(&action_name, false, Some(&new_params));
self.has_action = true;
self.export_actions
.push((action_name.clone(), action_id.clone()));
let register_action_expr = bind_args_to_ref_expr(
annotate_ident_as_server_reference(
action_ident.clone(),
action_id.clone(),
function.span,
),
ids_from_closure
.iter()
.cloned()
.map(|id| Some(id.as_arg()))
.collect(),
action_id.clone(),
);
function.body.visit_mut_with(&mut ClosureReplacer {
used_ids: &ids_from_closure,
private_ctxt: self.private_ctxt,
});
let mut new_body: Option<BlockStmt> = function.body.clone();
if !ids_from_closure.is_empty() {
// Prepend the decryption declaration to the body.
// var [arg1, arg2, arg3] = await decryptActionBoundArgs(actionId,
// $$ACTION_CLOSURE_BOUND)
let decryption_decl = VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: self.create_bound_action_args_array_pat(ids_from_closure.len()),
init: Some(Box::new(Expr::Await(AwaitExpr {
span: DUMMY_SP,
arg: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: quote_ident!("decryptActionBoundArgs").as_callee(),
args: vec![
action_id.as_arg(),
quote_ident!("$$ACTION_CLOSURE_BOUND").as_arg(),
],
..Default::default()
})),
}))),
definite: Default::default(),
}],
..Default::default()
};
if let Some(body) = &mut new_body {
body.stmts.insert(0, decryption_decl.into());
} else {
new_body = Some(BlockStmt {
span: DUMMY_SP,
stmts: vec![decryption_decl.into()],
..Default::default()
});
}
}
// Create the action export decl from the function
// export const $$RSC_SERVER_ACTION_0 = async function action($$ACTION_CLOSURE_BOUND) {}
self.hoisted_extra_items
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span: DUMMY_SP,
decl: VarDecl {
kind: VarDeclKind::Const,
span: DUMMY_SP,
decls: vec![VarDeclarator {
span: DUMMY_SP, // TODO: need to map it to the original span?
name: Pat::Ident(action_ident.clone().into()),
definite: false,
init: Some(Box::new(Expr::Fn(FnExpr {
ident: fn_name,
function: Box::new(Function {
params: new_params,
body: new_body,
..function.take()
}),
}))),
}],
declare: Default::default(),
ctxt: self.private_ctxt,
}
.into(),
})));
Box::new(register_action_expr)
}
fn maybe_hoist_and_create_proxy_for_cache_arrow_expr(
&mut self,
ids_from_closure: Vec<Name>,
cache_kind: RcStr,
arrow: &mut ArrowExpr,
) -> Box<Expr> {
let mut new_params: Vec<Param> = vec![];
// Add the collected closure variables as the first parameter to the
// function. They are unencrypted and passed into this function by the
// cache wrapper.
if !ids_from_closure.is_empty() {
new_params.push(Param {
span: DUMMY_SP,
decorators: vec![],
pat: self.create_bound_action_args_array_pat(ids_from_closure.len()),
});
}
for p in arrow.params.iter() {
new_params.push(Param::from(p.clone()));
}
let cache_name: Atom = self.gen_cache_ident();
let cache_ident = private_ident!(Span::dummy_with_cmt(), cache_name.clone());
let export_name: Atom = cache_name;
let reference_id = self.generate_server_reference_id(&export_name, true, Some(&new_params));
self.has_cache = true;
self.export_actions
.push((export_name.clone(), reference_id.clone()));
if let BlockStmtOrExpr::BlockStmt(block) = &mut *arrow.body {
block.visit_mut_with(&mut ClosureReplacer {
used_ids: &ids_from_closure,
private_ctxt: self.private_ctxt,
});
}
// Create the action export decl from the arrow function
// export var cache_ident = async function() {}
self.hoisted_extra_items
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span: DUMMY_SP,
decl: VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: vec![VarDeclarator {
span: arrow.span,
name: Pat::Ident(cache_ident.clone().into()),
init: Some(wrap_cache_expr(
Box::new(Expr::Fn(FnExpr {
ident: None,
function: Box::new(Function {
params: new_params,
body: match *arrow.body.take() {
BlockStmtOrExpr::BlockStmt(body) => Some(body),
BlockStmtOrExpr::Expr(expr) => Some(BlockStmt {
span: DUMMY_SP,
stmts: vec![Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(expr),
})],
..Default::default()
}),
},
decorators: vec![],
span: DUMMY_SP,
is_generator: false,
is_async: true,
..Default::default()
}),
})),
&cache_kind,
&reference_id,
ids_from_closure.len(),
)),
definite: false,
}],
..Default::default()
}
.into(),
})));
if let Some(Ident { sym, .. }) = &self.arrow_or_fn_expr_ident {
assign_name_to_ident(&cache_ident, sym.as_str(), &mut self.hoisted_extra_items);
}
let bound_args: Vec<_> = ids_from_closure
.iter()
.cloned()
.map(|id| Some(id.as_arg()))
.collect();
let register_action_expr = annotate_ident_as_server_reference(
cache_ident.clone(),
reference_id.clone(),
arrow.span,
);
// If there're any bound args from the closure, we need to hoist the
// register action expression to the top-level, and return the bind
// expression inline.
if !bound_args.is_empty() {
let ref_ident = private_ident!(self.gen_ref_ident());
let ref_decl = VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: Pat::Ident(ref_ident.clone().into()),
init: Some(Box::new(register_action_expr.clone())),
definite: false,
}],
..Default::default()
};
// Hoist the register action expression to the top-level.
self.extra_items
.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(ref_decl)))));
Box::new(bind_args_to_ref_expr(
Expr::Ident(ref_ident.clone()),
bound_args,
reference_id.clone(),
))
} else {
Box::new(register_action_expr)
}
}
fn maybe_hoist_and_create_proxy_for_cache_function(
&mut self,
ids_from_closure: Vec<Name>,
fn_name: Option<Ident>,
cache_kind: RcStr,
function: &mut Function,
) -> Box<Expr> {
let mut new_params: Vec<Param> = vec![];
// Add the collected closure variables as the first parameter to the
// function. They are unencrypted and passed into this function by the
// cache wrapper.
if !ids_from_closure.is_empty() {
new_params.push(Param {
span: DUMMY_SP,
decorators: vec![],
pat: self.create_bound_action_args_array_pat(ids_from_closure.len()),
});
}
for p in function.params.iter() {
new_params.push(p.clone());
}
let cache_name: Atom = self.gen_cache_ident();
let cache_ident = private_ident!(Span::dummy_with_cmt(), cache_name.clone());
let reference_id = self.generate_server_reference_id(&cache_name, true, Some(&new_params));
self.has_cache = true;
self.export_actions
.push((cache_name.clone(), reference_id.clone()));
let register_action_expr = annotate_ident_as_server_reference(
cache_ident.clone(),
reference_id.clone(),
function.span,
);
function.body.visit_mut_with(&mut ClosureReplacer {
used_ids: &ids_from_closure,
private_ctxt: self.private_ctxt,
});
// export var cache_ident = async function() {}
self.hoisted_extra_items
.push(ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
span: DUMMY_SP,
decl: VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: vec![VarDeclarator {
span: function.span,
name: Pat::Ident(cache_ident.clone().into()),
init: Some(wrap_cache_expr(
Box::new(Expr::Fn(FnExpr {
ident: fn_name.clone(),
function: Box::new(Function {
params: new_params,
..function.take()
}),
})),
&cache_kind,
&reference_id,
ids_from_closure.len(),
)),
definite: false,
}],
..Default::default()
}
.into(),
})));
if let Some(Ident { sym, .. }) = fn_name {
assign_name_to_ident(&cache_ident, sym.as_str(), &mut self.hoisted_extra_items);
} else if self.in_default_export_decl {
assign_name_to_ident(&cache_ident, "default", &mut self.hoisted_extra_items);
}
let bound_args: Vec<_> = ids_from_closure
.iter()
.cloned()
.map(|id| Some(id.as_arg()))
.collect();
// If there're any bound args from the closure, we need to hoist the
// register action expression to the top-level, and return the bind
// expression inline.
if !bound_args.is_empty() {
let ref_ident = private_ident!(self.gen_ref_ident());
let ref_decl = VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: Pat::Ident(ref_ident.clone().into()),
init: Some(Box::new(register_action_expr.clone())),
definite: false,
}],
..Default::default()
};
// Hoist the register action expression to the top-level.
self.extra_items
.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(ref_decl)))));
Box::new(bind_args_to_ref_expr(
Expr::Ident(ref_ident.clone()),
bound_args,
reference_id.clone(),
))
} else {
Box::new(register_action_expr)
}
}
}
impl<C: Comments> VisitMut for ServerActions<C> {
fn visit_mut_export_decl(&mut self, decl: &mut ExportDecl) {
let old_in_exported_expr = replace(&mut self.in_exported_expr, true);
decl.decl.visit_mut_with(self);
self.in_exported_expr = old_in_exported_expr;
}
fn visit_mut_export_default_decl(&mut self, decl: &mut ExportDefaultDecl) {
let old_in_exported_expr = replace(&mut self.in_exported_expr, true);
let old_in_default_export_decl = replace(&mut self.in_default_export_decl, true);
self.rewrite_default_fn_expr_to_proxy_expr = None;
decl.decl.visit_mut_with(self);
self.in_exported_expr = old_in_exported_expr;
self.in_default_export_decl = old_in_default_export_decl;
}
fn visit_mut_export_default_expr(&mut self, expr: &mut ExportDefaultExpr) {
let old_in_exported_expr = replace(&mut self.in_exported_expr, true);
let old_in_default_export_decl = replace(&mut self.in_default_export_decl, true);
expr.expr.visit_mut_with(self);
self.in_exported_expr = old_in_exported_expr;
self.in_default_export_decl = old_in_default_export_decl;
}
fn visit_mut_fn_expr(&mut self, f: &mut FnExpr) {
let old_this_status = replace(&mut self.this_status, ThisStatus::Allowed);
let old_arrow_or_fn_expr_ident = self.arrow_or_fn_expr_ident.clone();
if let Some(ident) = &f.ident {
self.arrow_or_fn_expr_ident = Some(ident.clone());
}
f.visit_mut_children_with(self);
self.this_status = old_this_status;
self.arrow_or_fn_expr_ident = old_arrow_or_fn_expr_ident;
}
fn visit_mut_function(&mut self, f: &mut Function) {
let directive = self.get_directive_for_function(f.body.as_mut());
let declared_idents_until = self.declared_idents.len();
let old_names = take(&mut self.names);
if let Some(directive) = &directive {
self.this_status = ThisStatus::Forbidden {
directive: directive.clone(),
};
}
// Visit children
{
let old_in_module = replace(&mut self.in_module_level, false);
let should_track_names = directive.is_some() || self.should_track_names;
let old_should_track_names = replace(&mut self.should_track_names, should_track_names);
let old_in_exported_expr = replace(&mut self.in_exported_expr, false);
let old_in_default_export_decl = replace(&mut self.in_default_export_decl, false);
let old_fn_decl_ident = self.fn_decl_ident.take();
f.visit_mut_children_with(self);
self.in_module_level = old_in_module;
self.should_track_names = old_should_track_names;
self.in_exported_expr = old_in_exported_expr;
self.in_default_export_decl = old_in_default_export_decl;
self.fn_decl_ident = old_fn_decl_ident;
}
if let Some(directive) = directive {
if !f.is_async {
emit_error(ServerActionsErrorKind::InlineSyncFunction {
span: f.span,
directive,
});
return;
}
let has_errors = HANDLER.with(|handler| handler.has_errors());
// Don't hoist a function if 1) an error was emitted, or 2) we're in the client layer.
if has_errors || !self.config.is_react_server_layer {
return;
}