{"version":3,"sources":["../../src/lib/verify-typescript-setup.ts"],"sourcesContent":["import { bold, cyan, red, yellow } from './picocolors'\nimport path, { join } from 'path'\n\nimport { hasNecessaryDependencies } from './has-necessary-dependencies'\nimport type {\n  MissingDependency,\n  NecessaryDependencies,\n} from './has-necessary-dependencies'\nimport semver from 'next/dist/compiled/semver'\nimport { CompileError } from './compile-error'\nimport * as log from '../build/output/log'\n\nimport { getTypeScriptIntent } from './typescript/getTypeScriptIntent'\nimport type { TypeCheckResult } from './typescript/runTypeCheck'\nimport { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'\nimport { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'\nimport { installDependencies } from './install-dependencies'\nimport { isCI } from '../server/ci-info'\nimport { missingDepsError } from './typescript/missingDependencyError'\nimport { resolveFrom } from './resolve-from'\n\nconst typescriptPackage: MissingDependency = {\n  file: 'typescript/lib/typescript.js',\n  pkg: 'typescript',\n  exportsRestrict: true,\n}\n\nconst requiredPackages: MissingDependency[] = [\n  typescriptPackage,\n  {\n    file: '@types/react/index.d.ts',\n    pkg: '@types/react',\n    exportsRestrict: true,\n  },\n  {\n    file: '@types/node/index.d.ts',\n    pkg: '@types/node',\n    exportsRestrict: true,\n  },\n]\n\n/**\n * Check if @typescript/native-preview is installed as an alternative TypeScript compiler.\n * This is a Go-based native TypeScript compiler that can be used instead of the standard\n * TypeScript package for faster compilation.\n */\nfunction hasNativeTypeScriptPreview(dir: string): boolean {\n  try {\n    resolveFrom(dir, '@typescript/native-preview/package.json')\n    return true\n  } catch {\n    return false\n  }\n}\n\nexport async function verifyAndRunTypeScript({\n  dir,\n  distDir,\n  cacheDir,\n  strictRouteTypes,\n  tsconfigPath,\n  shouldRunTypeCheck,\n  typedRoutes,\n  disableStaticImages,\n  hasAppDir,\n  hasPagesDir,\n  appDir,\n  pagesDir,\n  debugBuildPaths,\n}: {\n  dir: string\n  distDir: string\n  cacheDir?: string\n  strictRouteTypes: boolean\n  tsconfigPath: string | undefined\n  shouldRunTypeCheck: boolean\n  typedRoutes: boolean\n  disableStaticImages: boolean\n  hasAppDir: boolean\n  hasPagesDir: boolean\n  appDir?: string\n  pagesDir?: string\n  debugBuildPaths?: { app?: string[]; pages?: string[] }\n}): Promise<{ result?: TypeCheckResult; version: string | null }> {\n  const tsConfigFileName = tsconfigPath || 'tsconfig.json'\n  const resolvedTsConfigPath = path.join(dir, tsConfigFileName)\n\n  // Construct intentDirs from appDir and pagesDir for getTypeScriptIntent\n  const intentDirs = [pagesDir, appDir].filter(Boolean) as string[]\n\n  try {\n    // Check if the project uses TypeScript:\n    const intent = await getTypeScriptIntent(dir, intentDirs, tsConfigFileName)\n    if (!intent) {\n      return { version: null }\n    }\n\n    // Check if @typescript/native-preview is installed as an alternative\n    const hasNativePreview = hasNativeTypeScriptPreview(dir)\n\n    // Ensure TypeScript and necessary `@types/*` are installed:\n    let deps: NecessaryDependencies = hasNecessaryDependencies(\n      dir,\n      requiredPackages\n    )\n\n    // If @typescript/native-preview is installed and only the typescript package is missing,\n    // we can skip auto-installing typescript since the native preview provides TS compilation.\n    // However, we still need @types/react and @types/node for type checking.\n    if (hasNativePreview && deps.missing?.length > 0) {\n      const missingWithoutTypescript = deps.missing.filter(\n        (dep) => dep.pkg !== 'typescript'\n      )\n      const onlyTypescriptMissing =\n        deps.missing.length === 1 && deps.missing[0].pkg === 'typescript'\n\n      if (onlyTypescriptMissing) {\n        // @typescript/native-preview is installed and only typescript is missing\n        // Skip installation and return early - the project can use the native preview\n        log.info(\n          `Detected ${bold('@typescript/native-preview')} as TypeScript compiler. ` +\n            `Some Next.js TypeScript features (like type checking during build) require the standard ${bold('typescript')} package.`\n        )\n\n        // Still write type declarations since they don't require the typescript package\n        await writeAppTypeDeclarations({\n          baseDir: dir,\n          distDir,\n          imageImportsEnabled: !disableStaticImages,\n          hasPagesDir,\n          hasAppDir,\n          strictRouteTypes,\n          typedRoutes,\n        })\n\n        return { version: null }\n      }\n\n      // If there are other missing deps besides typescript, only install those\n      if (\n        missingWithoutTypescript.length > 0 &&\n        missingWithoutTypescript.length < deps.missing.length\n      ) {\n        deps.missing = missingWithoutTypescript\n      }\n    }\n\n    if (deps.missing?.length > 0) {\n      if (isCI) {\n        // we don't attempt auto install in CI to avoid side-effects\n        // and instead log the error for installing needed packages\n        missingDepsError(dir, deps.missing)\n      }\n      console.log(\n        bold(\n          yellow(\n            `It looks like you're trying to use TypeScript but do not have the required package(s) installed.`\n          )\n        ) +\n          '\\n' +\n          'Installing dependencies' +\n          '\\n\\n' +\n          bold(\n            'If you are not trying to use TypeScript, please remove the ' +\n              cyan('tsconfig.json') +\n              ' file from your package root (and any TypeScript files in your app and pages directories).'\n          ) +\n          '\\n'\n      )\n      await installDependencies(dir, deps.missing, true).catch((err) => {\n        if (err && typeof err === 'object' && 'command' in err) {\n          console.error(\n            `Failed to install required TypeScript dependencies, please install them manually to continue:\\n` +\n              (err as any).command +\n              '\\n'\n          )\n        }\n        throw err\n      })\n      deps = hasNecessaryDependencies(dir, requiredPackages)\n    }\n\n    // Load TypeScript after we're sure it exists:\n    const tsPackageJsonPath = deps.resolved.get(\n      join('typescript', 'package.json')\n    )!\n    const typescriptPackageJson = require(tsPackageJsonPath)\n\n    const typescriptVersion = typescriptPackageJson.version\n\n    if (semver.lt(typescriptVersion, '5.1.0')) {\n      log.warn(\n        `Minimum recommended TypeScript version is v5.1.0, older versions can potentially be incompatible with Next.js. Detected: ${typescriptVersion}`\n      )\n    }\n\n    // Reconfigure (or create) the user's `tsconfig.json` for them:\n    await writeConfigurationDefaults(\n      typescriptVersion,\n      resolvedTsConfigPath,\n      intent.firstTimeSetup,\n      hasAppDir,\n      distDir,\n      hasPagesDir,\n      strictRouteTypes\n    )\n    // Write out the necessary `next-env.d.ts` file to correctly register\n    // Next.js' types:\n    await writeAppTypeDeclarations({\n      baseDir: dir,\n      distDir,\n      imageImportsEnabled: !disableStaticImages,\n      hasPagesDir,\n      hasAppDir,\n      strictRouteTypes,\n      typedRoutes,\n    })\n\n    let result\n    if (shouldRunTypeCheck) {\n      const { runTypeCheck } =\n        require('./typescript/runTypeCheck') as typeof import('./typescript/runTypeCheck')\n      // Install native bindings so that code frame rendering works in the worker\n      const { installBindings } =\n        require('../build/swc/install-bindings') as typeof import('../build/swc/install-bindings')\n      await installBindings()\n\n      const tsPath = deps.resolved.get('typescript')!\n      const typescript = (await Promise.resolve(\n        require(tsPath)\n      )) as typeof import('typescript')\n\n      // Verify the project passes type-checking before we go to webpack phase:\n      result = await runTypeCheck(\n        typescript,\n        dir,\n        distDir,\n        resolvedTsConfigPath,\n        cacheDir,\n        hasAppDir,\n        { app: appDir, pages: pagesDir },\n        debugBuildPaths\n      )\n    }\n    return { result, version: typescriptVersion }\n  } catch (err) {\n    // These are special errors that should not show a stack trace:\n    if (err instanceof CompileError) {\n      console.error(red('Failed to type check.\\n'))\n      console.error(err.message)\n      process.exit(1)\n    }\n\n    /**\n     * verifyAndRunTypeScript can be either invoked directly in the main thread (during next dev / next lint)\n     * or run in a worker (during next build). In the latter case, we need to print the error message, as the\n     * parent process will only receive an `Jest worker encountered 1 child process exceptions, exceeding retry limit`.\n     */\n\n    // we are in a worker, print the error message and exit the process\n    if (process.env.IS_NEXT_WORKER) {\n      if (err instanceof Error) {\n        console.error(err.message)\n      } else {\n        console.error(err)\n      }\n      process.exit(1)\n    }\n    // we are in the main thread, throw the error and it will be handled by the caller\n    throw err\n  }\n}\n"],"names":["verifyAndRunTypeScript","typescriptPackage","file","pkg","exportsRestrict","requiredPackages","hasNativeTypeScriptPreview","dir","resolveFrom","distDir","cacheDir","strictRouteTypes","tsconfigPath","shouldRunTypeCheck","typedRoutes","disableStaticImages","hasAppDir","hasPagesDir","appDir","pagesDir","debugBuildPaths","tsConfigFileName","resolvedTsConfigPath","path","join","intentDirs","filter","Boolean","deps","intent","getTypeScriptIntent","version","hasNativePreview","hasNecessaryDependencies","missing","length","missingWithoutTypescript","dep","onlyTypescriptMissing","log","info","bold","writeAppTypeDeclarations","baseDir","imageImportsEnabled","isCI","missingDepsError","console","yellow","cyan","installDependencies","catch","err","error","command","tsPackageJsonPath","resolved","get","typescriptPackageJson","require","typescriptVersion","semver","lt","warn","writeConfigurationDefaults","firstTimeSetup","result","runTypeCheck","installBindings","tsPath","typescript","Promise","resolve","app","pages","CompileError","red","message","process","exit","env","IS_NEXT_WORKER","Error"],"mappings":";;;;+BAuDsBA;;;eAAAA;;;4BAvDkB;8DACb;0CAEc;+DAKtB;8BACU;6DACR;qCAEe;0CAEK;4CACE;qCACP;wBACf;wCACY;6BACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE5B,MAAMC,oBAAuC;IAC3CC,MAAM;IACNC,KAAK;IACLC,iBAAiB;AACnB;AAEA,MAAMC,mBAAwC;IAC5CJ;IACA;QACEC,MAAM;QACNC,KAAK;QACLC,iBAAiB;IACnB;IACA;QACEF,MAAM;QACNC,KAAK;QACLC,iBAAiB;IACnB;CACD;AAED;;;;CAIC,GACD,SAASE,2BAA2BC,GAAW;IAC7C,IAAI;QACFC,IAAAA,wBAAW,EAACD,KAAK;QACjB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEO,eAAeP,uBAAuB,EAC3CO,GAAG,EACHE,OAAO,EACPC,QAAQ,EACRC,gBAAgB,EAChBC,YAAY,EACZC,kBAAkB,EAClBC,WAAW,EACXC,mBAAmB,EACnBC,SAAS,EACTC,WAAW,EACXC,MAAM,EACNC,QAAQ,EACRC,eAAe,EAehB;IACC,MAAMC,mBAAmBT,gBAAgB;IACzC,MAAMU,uBAAuBC,aAAI,CAACC,IAAI,CAACjB,KAAKc;IAE5C,wEAAwE;IACxE,MAAMI,aAAa;QAACN;QAAUD;KAAO,CAACQ,MAAM,CAACC;IAE7C,IAAI;YAmBsBC,eAsCpBA;QAxDJ,wCAAwC;QACxC,MAAMC,SAAS,MAAMC,IAAAA,wCAAmB,EAACvB,KAAKkB,YAAYJ;QAC1D,IAAI,CAACQ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