<commit_before>import fs from 'fs'
import pMap from 'p-map'
import path from 'path'
import {
  GeneratorOptions,
  GeneratorConfig,
  EngineType,
} from '@prisma/generator-helper'
import chalk from 'chalk'
import {
  BinaryDownloadConfiguration,
  DownloadOptions,
} from '@prisma/fetch-engine/dist/download'
import { download } from '@prisma/fetch-engine'
import { getPlatform, Platform } from '@prisma/get-platform'
import { printGeneratorConfig, fixPlatforms } from '@prisma/engine-core'

import { getConfig, getDMMF } from './engineCommands'
import { unique } from './unique'
import { pick } from './pick'
import { Generator } from './Generator'
import { resolveOutput } from './resolveOutput'
import {
  predefinedGeneratorResolvers,
  GeneratorPaths,
} from './predefinedGeneratorResolvers'
import { flatMap } from './utils/flatMap'
import { missingModelMessage } from './utils/missingGeneratorMessage'

const defaultEngineVersion = eval(`require('../package.json').prisma.version`)

export type ProviderAliases = { [alias: string]: GeneratorPaths }

export type GetGeneratorOptions = {
  schemaPath: string
  providerAliases?: ProviderAliases
  cliVersion?: string
  version?: string
  printDownloadProgress?: boolean
  baseDir?: string // useful in tests to resolve the base dir from which `output` is resolved
  overrideGenerators?: GeneratorConfig[]
  skipDownload?: boolean
}

/**
 * Makes sure that all generators have the binaries they deserve and returns a
 * `Generator` class per generator defined in the schema.prisma file.
 * In other words, this is basically a generator factory function.
 * @param schemaPath Path to schema.prisma
 * @param aliases Aliases like `prisma-client-js` -> `node_modules/@prisma/client/generator-build/index.js`
 */
export async function getGenerators({
  schemaPath,
  providerAliases: aliases, // do you get the pun?
  version,
  cliVersion,
  printDownloadProgress,
  baseDir = path.dirname(schemaPath),
  overrideGenerators,
  skipDownload,
}: GetGeneratorOptions): Promise<Generator[]> {
  if (!schemaPath) {
    throw new Error(
      `schemaPath for getGenerators got invalid value ${schemaPath}`,
    )
  }

  if (!fs.existsSync(schemaPath)) {
    throw new Error(`${schemaPath} does not exist`)
  }
  const platform = await getPlatform()

  let prismaPath: string | undefined = undefined

  // overwrite query engine if the version is provided
  if (version) {
    const downloadParams: DownloadOptions = {
      binaries: {
        'query-engine': eval(`require('path').join(__dirname, '..')`),
      },
      binaryTargets: [platform],
      showProgress: false,
      version,
      skipDownload,
    }

    const binaryPathsWithEngineType = await download(downloadParams)
    prismaPath = binaryPathsWithEngineType['query-engine']![platform]
  }

  const datamodel = fs.readFileSync(schemaPath, 'utf-8')
  const dmmf = await getDMMF({
    datamodel,
    datamodelPath: schemaPath,
    prismaPath,
  })

  if (dmmf.datamodel.models.length === 0) {
    throw new Error(missingModelMessage)
  }

  const config = await getConfig({
    datamodel,
    datamodelPath: schemaPath,
    prismaPath,
    ignoreEnvVarErrors: true,
  })

  const generatorConfigs = overrideGenerators || config.generators

  await validateGenerators(generatorConfigs)

  const runningGenerators: Generator[] = []
  try {
    // 1. Get all generators
    const generators = await pMap(
      generatorConfigs,
      async (generator, index) => {
        let generatorPath = generator.provider
        let paths: GeneratorPaths | undefined

        // as of now mostly used by studio
        if (aliases && aliases[generator.provider]) {
          generatorPath = aliases[generator.provider].generatorPath
          paths = aliases[generator.provider]
          if (!fs.existsSync(generatorPath)) {
            throw new Error(
              `Could not find generator executable ${
                aliases[generator.provider].generatorPath
              } for generator ${generator.provider}`,
            )
          }
        } else if (predefinedGeneratorResolvers[generator.provider]) {
          paths = await predefinedGeneratorResolvers[generator.provider](
            baseDir,
            cliVersion,
          )
          generatorPath = paths.generatorPath
        }

        const generatorInstance = new Generator(generatorPath)

        await generatorInstance.init()<commit_msg>fix(sdk): generator path<commit_after>import fs from 'fs'
import pMap from 'p-map'
import path from 'path'
import {
  GeneratorOptions,
  GeneratorConfig,
  EngineType,
} from '@prisma/generator-helper'
import chalk from 'chalk'
import {
  BinaryDownloadConfiguration,
  DownloadOptions,
} from '@prisma/fetch-engine/dist/download'
import { download } from '@prisma/fetch-engine'
import { getPlatform, Platform } from '@prisma/get-platform'
import { printGeneratorConfig, fixPlatforms } from '@prisma/engine-core'

import { getConfig, getDMMF } from './engineCommands'
import { unique } from './unique'
import { pick } from './pick'
import { Generator } from './Generator'
import { resolveOutput } from './resolveOutput'
import {
  predefinedGeneratorResolvers,
  GeneratorPaths,
} from './predefinedGeneratorResolvers'
import { flatMap } from './utils/flatMap'
import { missingModelMessage } from './utils/missingGeneratorMessage'

const defaultEngineVersion = eval(`require('../package.json').prisma.version`)

export type ProviderAliases = { [alias: string]: GeneratorPaths }

export type GetGeneratorOptions = {
  schemaPath: string
  providerAliases?: ProviderAliases
  cliVersion?: string
  version?: string
  printDownloadProgress?: boolean
  baseDir?: string // useful in tests to resolve the base dir from which `output` is resolved
  overrideGenerators?: GeneratorConfig[]
  skipDownload?: boolean
}

/**
 * Makes sure that all generators have the binaries they deserve and returns a
 * `Generator` class per generator defined in the schema.prisma file.
 * In other words, this is basically a generator factory function.
 * @param schemaPath Path to schema.prisma
 * @param aliases Aliases like `prisma-client-js` -> `node_modules/@prisma/client/generator-build/index.js`
 */
export async function getGenerators({
  schemaPath,
  providerAliases: aliases, // do you get the pun?
  version,
  cliVersion,
  printDownloadProgress,
  baseDir = path.dirname(schemaPath),
  overrideGenerators,
  skipDownload,
}: GetGeneratorOptions): Promise<Generator[]> {
  if (!schemaPath) {
    throw new Error(
      `schemaPath for getGenerators got invalid value ${schemaPath}`,
    )
  }

  if (!fs.existsSync(schemaPath)) {
    throw new Error(`${schemaPath} does not exist`)
  }
  const platform = await getPlatform()

  let prismaPath: string | undefined = undefined

  // overwrite query engine if the version is provided
  if (version) {
    const downloadParams: DownloadOptions = {
      binaries: {
        'query-engine': eval(`require('path').join(__dirname, '..')`),
      },
      binaryTargets: [platform],
      showProgress: false,
      version,
      skipDownload,
    }

    const binaryPathsWithEngineType = await download(downloadParams)
    prismaPath = binaryPathsWithEngineType['query-engine']![platform]
  }

  const datamodel = fs.readFileSync(schemaPath, 'utf-8')
  const dmmf = await getDMMF({
    datamodel,
    datamodelPath: schemaPath,
    prismaPath,
  })

  if (dmmf.datamodel.models.length === 0) {
    throw new Error(missingModelMessage)
  }

  const config = await getConfig({
    datamodel,
    datamodelPath: schemaPath,
    prismaPath,
    ignoreEnvVarErrors: true,
  })

  const generatorConfigs = overrideGenerators || config.generators

  await validateGenerators(generatorConfigs)

  const runningGenerators: Generator[] = []
  try {
    // 1. Get all generators
    const generators = await pMap(
      generatorConfigs,
      async (generator, index) => {
        let generatorPath = generator.provider
        let paths: GeneratorPaths | undefined

        // as of now mostly used by studio
        if (aliases && aliases[generator.provider]) {
          generatorPath = aliases[generator.provider].generatorPath
          paths = aliases[generator.provider]
        } else if (predefinedGeneratorResolvers[generator.provider]) {
          paths = await predefinedGeneratorResolvers[generator.provider](
            baseDir,
            cliVersion,
          )
          generatorPath = paths.generatorPath
        }

        const generatorInstance = new Generator(generatorPath)

        await generatorInstance.init()
{'fraction_non_alphanumeric': 0.10026784674507977, 'fraction_numerical': 0.000698730639338535, 'mean_word_length': 3.5729499467518635, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6423283', 'n_tokens_mistral': 2426, 'n_tokens_neox': 2323, 'n_words': 663}