Skip to content

The open alternative to Salesforce, designed for AI.

16.0 KB
Raw Blame
import prettier from '@prettier/sync';
import * as fs from 'fs';
import { globSync } from 'glob';
import path from 'path';
import { type Options } from 'prettier';
import slash from 'slash';
import ts from 'typescript';

// TODO prastoin refactor this file in several one into its dedicated package and make it a TypeScript CLI

const shouldCheck = process.argv.includes('--check');
const writeGeneratedFile = ({
  file,
  content,
}: {
  file: string;
  content: string;
}) => {
  if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === content) {
    return;
  }
  if (shouldCheck) {
    throw new Error(
      `Generated exports are stale: ${file}. Run nx generateBarrels twenty-ui.`,
    );
  }
  fs.writeFileSync(file, content, 'utf8');
};

const INDEX_FILENAME = 'index';
const PACKAGE_JSON_FILENAME = 'package.json';
const NX_PROJECT_CONFIGURATION_FILENAME = 'project.json';
const PACKAGE_PATH = path.resolve('packages/twenty-ui');
const SRC_PATH = path.resolve(`${PACKAGE_PATH}/src`);
const STANDALONE_MODULES = [
  'assets',
  'components/code-editor',
  'icon/provider',
  'styles',
  'testing',
];
const PACKAGE_JSON_PATH = path.join(PACKAGE_PATH, PACKAGE_JSON_FILENAME);
const NX_PROJECT_CONFIGURATION_PATH = path.join(
  PACKAGE_PATH,
  NX_PROJECT_CONFIGURATION_FILENAME,
);

const prettierConfigFile = prettier.resolveConfigFile();
if (prettierConfigFile == null) {
  throw new Error('Prettier config file not found');
}
const prettierConfiguration = prettier.resolveConfig(prettierConfigFile);
const prettierFormat = ({
  content,
  parser,
}: {
  content: string;
  parser: Options['parser'];
}) =>
  prettier.format(content, {
    ...prettierConfiguration,
    parser,
  });
type createTypeScriptFileArgs = {
  path: string;
  content: string;
  filename: string;
};
const createTypeScriptFile = ({
  content,
  path: filePath,
  filename,
}: createTypeScriptFileArgs) => {
  const header = `
/*
 * _____                    _
 *|_   _|_      _____ _ __ | |_ _   _
 *  | | \\ \\ /\\ / / _ \\ '_ \\| __| | | | Auto-generated file
 *  | |  \\ V  V /  __/ | | | |_| |_| | Any edits to this will be overridden
 *  |_|   \\_/\\_/ \\___|_| |_|\\__|\\__, |
 *                              |___/
 */
`;
  const formattedContent = prettierFormat({
    content: `${header}\n${content}\n`,
    parser: 'typescript',
  });
  writeGeneratedFile({
    file: path.join(filePath, `${filename}.ts`),
    content: formattedContent,
  });
};

const getModuleName = (moduleDirectory: string) =>
  slash(path.relative(SRC_PATH, moduleDirectory));

const getSubDirectoryPaths = (directoryPath: string): string[] => {
  return globSync('*/', {
    ignore: [...EXCLUDED_DIRECTORIES],
    cwd: directoryPath,
    nodir: false,
    maxDepth: 1,
  })
    .map((directory) => path.resolve(directoryPath, directory))
    .sort((a, b) => a.localeCompare(b));
};

const partitionFileExportsByType = (declarations: DeclarationOccurrence[]) => {
  return declarations.reduce<{
    typeAndInterfaceDeclarations: DeclarationOccurrence[];
    otherDeclarations: DeclarationOccurrence[];
  }>(
    (acc, { kind, name }) => {
      if (kind === 'type' || kind === 'interface') {
        return {
          ...acc,
          typeAndInterfaceDeclarations: [
            ...acc.typeAndInterfaceDeclarations,
            { kind, name },
          ],
        };
      }

      return {
        ...acc,
        otherDeclarations: [...acc.otherDeclarations, { kind, name }],
      };
    },
    {
      typeAndInterfaceDeclarations: [],
      otherDeclarations: [],
    },
  );
};

const generateModuleIndexFiles = (exportByBarrel: ExportByBarrel[]) => {
  return exportByBarrel.map<createTypeScriptFileArgs>(
    ({ barrel: { moduleDirectory }, allFileExports }) => {
      const childModuleDirectories = exportByBarrel
        .map(({ barrel }) => barrel.moduleDirectory)
        .filter((directory) => path.dirname(directory) === moduleDirectory);
      const fileExports = allFileExports
        .filter(
          ({ file }) =>
            !childModuleDirectories.some((directory) =>
              file.startsWith(`${directory}${path.sep}`),
            ),
        )
        .sort((a, b) => a.file.localeCompare(b.file))
        .map(({ exports, file }) => {
          const { otherDeclarations, typeAndInterfaceDeclarations } =
            partitionFileExportsByType(exports);

          const fileWithoutExtension = path.parse(file).name;
          const pathToImport = slash(
            path.relative(
              moduleDirectory,
              path.join(path.dirname(file), fileWithoutExtension),
            ),
          );
          const mapDeclarationNameAndJoin = (
            declarations: DeclarationOccurrence[],
          ) => declarations.map(({ name }) => name).join(', ');

          const typeExport =
            typeAndInterfaceDeclarations.length > 0
              ? `export type { ${mapDeclarationNameAndJoin(typeAndInterfaceDeclarations)} } from "./${pathToImport}"`
              : '';
          const othersExport =
            otherDeclarations.length > 0
              ? `export { ${mapDeclarationNameAndJoin(otherDeclarations)} } from "./${pathToImport}"`
              : '';

          return [typeExport, othersExport]
            .filter((el) => el !== '')
            .join('\n');
        })
        .join('\n');
      const childModuleExports = childModuleDirectories
        .filter(
          (directory) => !STANDALONE_MODULES.includes(getModuleName(directory)),
        )
        .map((directory) => `export * from './${path.basename(directory)}';`);
      const content = [fileExports, ...childModuleExports]
        .filter((entry) => entry !== '')
        .join('\n');

      return {
        // A placeholder barrel for an empty module must still be a valid module
        // so `export * from './x'` re-exports (e.g. in individual-entry.ts) resolve.
        content: content === '' ? 'export {};' : content,
        path: moduleDirectory,
        filename: INDEX_FILENAME,
      };
    },
  );
};

type JsonUpdate = Record<string, any>;
type WriteInJsonFileArgs = {
  content: JsonUpdate;
  file: string;
};
const updateJsonFile = ({ content, file }: WriteInJsonFileArgs) => {
  const updatedJsonFile = JSON.stringify(content);
  const formattedContent = prettier.format(updatedJsonFile, {
    ...prettierConfiguration,
    filepath: file,
  });
  writeGeneratedFile({ file, content: formattedContent });
};

const writeInPackageJson = (update: JsonUpdate) => {
  const rawJsonFile = fs.readFileSync(PACKAGE_JSON_PATH, 'utf-8');
  const initialJsonFile = JSON.parse(rawJsonFile);

  updateJsonFile({
    file: PACKAGE_JSON_PATH,
    content: {
      ...initialJsonFile,
      ...update,
    },
  });
};

const updateNxProjectConfigurationBuildOutputs = (outputs: JsonUpdate) => {
  const rawJsonFile = fs.readFileSync(NX_PROJECT_CONFIGURATION_PATH, 'utf-8');
  const initialJsonFile = JSON.parse(rawJsonFile);

  updateJsonFile({
    file: NX_PROJECT_CONFIGURATION_PATH,
    content: {
      ...initialJsonFile,
      targets: {
        ...initialJsonFile.targets,
        build: {
          ...initialJsonFile.targets.build,
          outputs,
        },
      },
    },
  });
};

type ExportOccurrence = {
  types: string;
  import: string;
  require: string;
};
type ExportsConfig = Record<string, ExportOccurrence | string>;

const generateModulePackageExports = (moduleDirectories: string[]) => {
  return moduleDirectories.reduce<ExportsConfig>(
    (acc, moduleDirectory) => {
      const moduleName = getModuleName(moduleDirectory);
      if (moduleName === undefined) {
        throw new Error(
          `Should never occur, moduleName is undefined ${moduleDirectory}`,
        );
      }

      return {
        ...acc,
        [`./${moduleName}`]: {
          types: `./dist/${moduleName}/index.d.ts`,
          import: `./dist/${moduleName}.mjs`,
          require: `./dist/${moduleName}.cjs`,
        },
      };
    },
    {
      './style.css': './dist/style.css',
      './theme-light.css': './dist/theme-light.css',
      './theme-dark.css': './dist/theme-dark.css',
    },
  );
};

const computePackageJsonFilesAndExportsConfig = (
  moduleDirectories: string[],
) => {
  const entrypoints = moduleDirectories.map(getModuleName);
  const exports = {
    '.': {
      types: './dist/index.d.ts',
      import: './dist/index.mjs',
      require: './dist/index.cjs',
    },
    ...generateModulePackageExports(moduleDirectories),
  } satisfies ExportsConfig;

  const typesVersionsEntries = entrypoints.reduce<Record<string, string[]>>(
    (acc, moduleName) => ({
      ...acc,
      [`${moduleName}`]: [`dist/${moduleName}/index.d.ts`],
    }),
    {},
  );

  return {
    exports,
    typesVersions: { '*': typesVersionsEntries },
    files: [
      'dist',
      'LICENSE',
      '!dist/individual',
      '!dist/individual/**',
      '!dist/**/*.map',
    ],
  };
};

const computeProjectNxBuildOutputsPath = () => {
  return ['{projectRoot}/dist'];
};

const EXCLUDED_EXTENSIONS = [
  '**/*.test.ts',
  '**/*.test.tsx',
  '**/*.spec.ts',
  '**/*.spec.tsx',
  '**/*.stories.ts',
  '**/*.stories.tsx',
] as const;
const EXCLUDED_DIRECTORIES = [
  '**/__tests__/**',
  '**/__mocks__/**',
  '**/__stories__/**',
  '**/internal/**',
  '**/internals/**',
  '**/parts/**',
] as const;
function getTypeScriptFiles(
  directoryPath: string,
  includeIndex: boolean = false,
): string[] {
  const pattern = slash(path.join(directoryPath, '**', '*.{ts,tsx}'));
  const files = globSync(pattern, {
    cwd: SRC_PATH,
    nodir: true,
    ignore: [...EXCLUDED_EXTENSIONS, ...EXCLUDED_DIRECTORIES],
  });

  return files.filter(
    (file) =>
      !file.endsWith('.d.ts') &&
      (includeIndex ? true : !file.endsWith('index.ts')),
  );
}

const getKind = (
  node: ts.VariableStatement,
): Extract<ExportKind, 'const' | 'let' | 'var'> => {
  const isConst = (node.declarationList.flags & ts.NodeFlags.Const) !== 0;
  if (isConst) {
    return 'const';
  }

  const isLet = (node.declarationList.flags & ts.NodeFlags.Let) !== 0;
  if (isLet) {
    return 'let';
  }

  return 'var';
};

function extractExportsFromSourceFile(sourceFile: ts.SourceFile) {
  const exports: DeclarationOccurrence[] = [];

  function visit(node: ts.Node) {
    if (!ts.canHaveModifiers(node)) {
      return ts.forEachChild(node, visit);
    }
    const modifiers = ts.getModifiers(node);
    const isExport = modifiers?.some(
      (mod) => mod.kind === ts.SyntaxKind.ExportKeyword,
    );

    if (!isExport && !ts.isExportDeclaration(node)) {
      return ts.forEachChild(node, visit);
    }

    switch (true) {
      case ts.isTypeAliasDeclaration(node):
        exports.push({
          kind: 'type',
          name: node.name.text,
        });
        break;

      case ts.isInterfaceDeclaration(node):
        exports.push({
          kind: 'interface',
          name: node.name.text,
        });
        break;

      case ts.isEnumDeclaration(node):
        exports.push({
          kind: 'enum',
          name: node.name.text,
        });
        break;

      case ts.isFunctionDeclaration(node) && node.name !== undefined:
        exports.push({
          kind: 'function',
          name: node.name.text,
        });
        break;

      case ts.isVariableStatement(node):
        node.declarationList.declarations.forEach((decl) => {
          const kind = getKind(node);

          if (ts.isIdentifier(decl.name)) {
            exports.push({
              kind,
              name: decl.name.text,
            });
          } else if (ts.isObjectBindingPattern(decl.name)) {
            decl.name.elements.forEach((element) => {
              if (
                !ts.isBindingElement(element) ||
                !ts.isIdentifier(element.name)
              ) {
                return;
              }

              exports.push({
                kind,
                name: element.name.text,
              });
            });
          }
        });
        break;

      case ts.isClassDeclaration(node) && node.name !== undefined:
        exports.push({
          kind: 'class',
          name: node.name.text,
        });
        break;
      case ts.isExportDeclaration(node):
        if (node.exportClause && ts.isNamedExports(node.exportClause)) {
          node.exportClause.elements.forEach((element) => {
            const exportName = element.name.text;

            // Check both the declaration and the individual specifier for type-only exports
            const isTypeExport = node.isTypeOnly || element.isTypeOnly;
            if (isTypeExport) {
              exports.push({
                kind: 'type',
                name: exportName,
              });
              return;
            }

            exports.push({
              kind: 'const',
              name: exportName,
            });
          });
        }
        break;
    }
    return ts.forEachChild(node, visit);
  }

  visit(sourceFile);
  return exports;
}

type ExportKind =
  | 'type'
  | 'interface'
  | 'enum'
  | 'function'
  | 'const'
  | 'let'
  | 'var'
  | 'class';
type DeclarationOccurrence = { kind: ExportKind; name: string };
type FileExports = Array<{
  file: string;
  exports: DeclarationOccurrence[];
}>;

function findAllExports(directoryPath: string): FileExports {
  const results: FileExports = [];

  const files = getTypeScriptFiles(directoryPath);

  for (const file of files) {
    const sourceFile = ts.createSourceFile(
      file,
      fs.readFileSync(file, 'utf8'),
      ts.ScriptTarget.Latest,
      true,
    );

    const exports = extractExportsFromSourceFile(sourceFile);
    if (exports.length > 0) {
      results.push({
        file,
        exports,
      });
    }
  }

  return results;
}

type ExportByBarrel = {
  barrel: {
    moduleName: string;
    moduleDirectory: string;
  };
  allFileExports: FileExports;
};
const retrieveExportsByBarrel = (barrelDirectories: string[]) => {
  return barrelDirectories.map<ExportByBarrel>((moduleDirectory) => {
    const moduleExportsPerFile = findAllExports(moduleDirectory);
    const moduleName = getModuleName(moduleDirectory);
    if (!moduleName) {
      throw new Error(
        `Should never occur moduleName not found ${moduleDirectory}`,
      );
    }

    return {
      barrel: {
        moduleName,
        moduleDirectory,
      },
      allFileExports: moduleExportsPerFile,
    };
  });
};

const INDIVIDUAL_ENTRY_FILENAME = 'individual-entry';

const getRootBarrelModuleNames = (moduleDirectories: string[]) =>
  moduleDirectories
    .map(getModuleName)
    .filter((moduleName) => !STANDALONE_MODULES.includes(moduleName));

const generateRootBarrel = (
  moduleDirectories: string[],
): createTypeScriptFileArgs => {
  const content = [
    "import './styles/base/reset.scss';",
    '',
    ...getRootBarrelModuleNames(moduleDirectories).map(
      (moduleName) => `export * from './${moduleName}';`,
    ),
  ].join('\n');

  return { path: SRC_PATH, content, filename: INDEX_FILENAME };
};

const generateIndividualEntry = (
  moduleDirectories: string[],
): createTypeScriptFileArgs => {
  const content = getRootBarrelModuleNames(moduleDirectories)
    .map((moduleName) => `export * from './${moduleName}';`)
    .join('\n');

  return { path: SRC_PATH, content, filename: INDIVIDUAL_ENTRY_FILENAME };
};

const main = () => {
  const moduleDirectories = getSubDirectoryPaths(SRC_PATH);
  const barrelDirectories = [
    ...new Set([
      ...moduleDirectories,
      ...getSubDirectoryPaths(path.join(SRC_PATH, 'primitives')),
      ...getSubDirectoryPaths(path.join(SRC_PATH, 'components')),
      ...STANDALONE_MODULES.map((moduleName) =>
        path.join(SRC_PATH, moduleName),
      ),
    ]),
  ].sort((first, second) => first.localeCompare(second));
  const exportsByBarrel = retrieveExportsByBarrel(barrelDirectories);
  const moduleIndexFiles = generateModuleIndexFiles(exportsByBarrel);
  const packageJsonConfig =
    computePackageJsonFilesAndExportsConfig(barrelDirectories);
  const nxBuildOutputsPath = computeProjectNxBuildOutputsPath();

  updateNxProjectConfigurationBuildOutputs(nxBuildOutputsPath);
  writeInPackageJson(packageJsonConfig);
  moduleIndexFiles.forEach(createTypeScriptFile);
  createTypeScriptFile(generateRootBarrel(moduleDirectories));
  createTypeScriptFile(generateIndividualEntry(moduleDirectories));
};
main();