-
-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathserver-action.ts
More file actions
80 lines (78 loc) · 2.53 KB
/
Copy pathserver-action.ts
File metadata and controls
80 lines (78 loc) · 2.53 KB
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
import type { Literal, Program } from 'estree'
import type MagicString from 'magic-string'
import { transformHoistInlineDirective } from './hoist'
import {
transformWrapExport,
type TransformWrapExportOptions,
} from './wrap-export'
// TODO
// source map for `options.runtime` (registerServerReference) call
// needs to match original position.
export function transformServerActionServer(
input: string,
ast: Program,
options: {
runtime: (value: string, name: string) => string
directive?: string | RegExp
moduleDirective?: Literal
moduleRuntime?: TransformWrapExportOptions['runtime']
inlineRuntime?: Parameters<
typeof transformHoistInlineDirective
>[2]['runtime']
filter?: TransformWrapExportOptions['filter']
rejectNonAsyncFunction?: boolean
rejectNonAsyncModule?: boolean
encode?: (value: string) => string
decode?: (value: string) => string
preserveModuleDirective?: boolean
detectUseServerModule?: boolean
},
):
| {
exportNames: string[]
output: MagicString
}
| {
output: MagicString
names: string[]
} {
const useServerStatement =
options.detectUseServerModule === false
? undefined
: ast.body.find(
(statement) =>
statement.type === 'ExpressionStatement' &&
statement.expression.type === 'Literal' &&
statement.expression.value === 'use server',
)
const moduleDirective =
options.moduleDirective ??
(useServerStatement?.type === 'ExpressionStatement' &&
useServerStatement.expression.type === 'Literal'
? useServerStatement.expression
: undefined)
// TODO: unify (generalize transformHoistInlineDirective to support top-level directive cases)
if (moduleDirective?.type === 'Literal') {
const result = transformWrapExport(input, ast, {
runtime: options.moduleRuntime ?? options.runtime,
filter: options.filter,
rejectNonAsyncFunction:
options.rejectNonAsyncModule ?? options.rejectNonAsyncFunction,
})
if (!options.preserveModuleDirective && options.moduleDirective) {
result.output.overwrite(
moduleDirective.start,
moduleDirective.end,
`/* ${JSON.stringify(moduleDirective.value)} */`,
)
}
return result
}
return transformHoistInlineDirective(input, ast, {
runtime: options.inlineRuntime ?? options.runtime,
directive: options.directive ?? 'use server',
rejectNonAsyncFunction: options.rejectNonAsyncFunction,
encode: options.encode,
decode: options.decode,
})
}