| 281 | } |
| 282 | |
| 283 | export function generate( |
| 284 | ast: RootNode, |
| 285 | options: CodegenOptions & { |
| 286 | onContextCreated?: (context: CodegenContext) => void |
| 287 | } = {}, |
| 288 | ): CodegenResult { |
| 289 | const context = createCodegenContext(ast, options) |
| 290 | if (options.onContextCreated) options.onContextCreated(context) |
| 291 | const { |
| 292 | mode, |
| 293 | push, |
| 294 | prefixIdentifiers, |
| 295 | indent, |
| 296 | deindent, |
| 297 | newline, |
| 298 | scopeId, |
| 299 | ssr, |
| 300 | } = context |
| 301 | |
| 302 | const helpers = Array.from(ast.helpers) |
| 303 | const hasHelpers = helpers.length > 0 |
| 304 | const useWithBlock = !prefixIdentifiers && mode !== 'module' |
| 305 | const genScopeId = !__BROWSER__ && scopeId != null && mode === 'module' |
| 306 | const isSetupInlined = !__BROWSER__ && !!options.inline |
| 307 | |
| 308 | // preambles |
| 309 | // in setup() inline mode, the preamble is generated in a sub context |
| 310 | // and returned separately. |
| 311 | const preambleContext = isSetupInlined |
| 312 | ? createCodegenContext(ast, options) |
| 313 | : context |
| 314 | if (!__BROWSER__ && mode === 'module') { |
| 315 | genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined) |
| 316 | } else { |
| 317 | genFunctionPreamble(ast, preambleContext) |
| 318 | } |
| 319 | // enter render function |
| 320 | const functionName = ssr ? `ssrRender` : `render` |
| 321 | const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'] |
| 322 | if (!__BROWSER__ && options.bindingMetadata && !options.inline) { |
| 323 | // binding optimization args |
| 324 | args.push('$props', '$setup', '$data', '$options') |
| 325 | } |
| 326 | const signature = |
| 327 | !__BROWSER__ && options.isTS |
| 328 | ? args.map(arg => `${arg}: any`).join(',') |
| 329 | : args.join(', ') |
| 330 | |
| 331 | if (isSetupInlined) { |
| 332 | push(`(${signature}) => {`) |
| 333 | } else { |
| 334 | push(`function ${functionName}(${signature}) {`) |
| 335 | } |
| 336 | indent() |
| 337 | |
| 338 | if (useWithBlock) { |
| 339 | push(`with (_ctx) {`) |
| 340 | indent() |