export function transpile()

in packages/codegen-ui-react/lib/react-studio-template-renderer-helper.ts [61:125]


export function transpile(
  code: string,
  renderConfig: ReactRenderConfig,
): { componentText: string; declaration?: string } {
  const { target, module, script, renderTypeDeclarations } = renderConfig;
  if (script === ScriptKind.JS || script === ScriptKind.JSX) {
    const transpiledCode = transpileModule(code, {
      compilerOptions: {
        target,
        module,
        jsx: script === ScriptKind.JS ? ts.JsxEmit.React : ts.JsxEmit.Preserve,
        esModuleInterop: true,
      },
    }).outputText;

    const componentText = prettier.format(transpiledCode, { parser: 'typescript', plugins: [parserTypescript] });

    /*
     * createProgram is less performant than traspileModule and should only be used when necessary.
     * createProgram is used here becuase transpileModule cannot produce type declarations.
     * We execute in a virtual filesystem to ensure we have no dependencies on platform fs in this stage.
     */
    if (renderTypeDeclarations) {
      if (target && !new Set(supportedTranspilationTargets).has(target)) {
        throw new InvalidInputError(
          `ScriptTarget ${target} not supported with type declarations enabled, expected one of ${JSON.stringify(
            supportedTranspilationTargets,
          )}`,
        );
      }

      const compilerOptions = {
        target,
        module,
        declaration: true,
        emitDeclarationOnly: true,
        skipLibCheck: true,
      };

      const fsMap = createDefaultMapFromNodeModules(compilerOptions, ts);
      fsMap.set('index.tsx', code);

      const host = createVirtualCompilerHost(createSystem(fsMap), compilerOptions, ts);
      createProgram({
        rootNames: [...fsMap.keys()],
        options: compilerOptions,
        host: host.compilerHost,
      }).emit();

      const declaration = fsMap.get('index.d.ts');

      if (!declaration) {
        throw new InternalError('Component declaration file not generated');
      }

      return { componentText, declaration };
    }

    return {
      componentText,
    };
  }

  return { componentText: prettier.format(code, { parser: 'typescript', plugins: [parserTypescript] }) };
}