@nx/vite 0.0.0-pr-30418-4e2b721 → 0.0.0-pr-3-ec41644

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/vite",
3
- "version": "0.0.0-pr-30418-4e2b721",
3
+ "version": "0.0.0-pr-3-ec41644",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for building and testing applications using Vite",
6
6
  "repository": {
@@ -30,11 +30,11 @@
30
30
  "migrations": "./migrations.json"
31
31
  },
32
32
  "dependencies": {
33
- "@nx/devkit": "0.0.0-pr-30418-4e2b721",
33
+ "@nx/devkit": "0.0.0-pr-3-ec41644",
34
34
  "@phenomnomnominal/tsquery": "~5.0.1",
35
35
  "@swc/helpers": "~0.5.0",
36
36
  "enquirer": "~2.3.6",
37
- "@nx/js": "0.0.0-pr-30418-4e2b721",
37
+ "@nx/js": "0.0.0-pr-3-ec41644",
38
38
  "tsconfig-paths": "^4.1.2",
39
39
  "minimatch": "9.0.3",
40
40
  "semver": "^7.6.3"
@@ -2,8 +2,7 @@ import { Plugin } from 'vite';
2
2
  export interface nxViteTsPathsOptions {
3
3
  /**
4
4
  * Enable debug logging
5
- * If set to false, it will always ignore the debug logging even when `--verbose` or `NX_VERBOSE_LOGGING` is set to true.
6
- * @default undefined
5
+ * @default false
7
6
  **/
8
7
  debug?: boolean;
9
8
  /**
@@ -15,7 +15,6 @@ const _nxtsconfigpathsfindfile = require("../src/utils/nx-tsconfig-paths-find-fi
15
15
  const _tssolutionsetup = require("@nx/js/src/utils/typescript/ts-solution-setup");
16
16
  function nxViteTsPaths(options = {}) {
17
17
  var _options, _options1, _options2;
18
- let foundTsConfigPath;
19
18
  let matchTsPathEsm;
20
19
  let matchTsPathFallback;
21
20
  let tsConfigPathsEsm;
@@ -56,9 +55,12 @@ function nxViteTsPaths(options = {}) {
56
55
  async configResolved (config) {
57
56
  projectRoot = config.root;
58
57
  const projectRootFromWorkspaceRoot = (0, _nodepath.relative)(_devkit.workspaceRoot, projectRoot);
59
- var _process_env_NX_TASK_TARGET_TARGET, _process_env_NX_TSCONFIG_PATH;
60
- foundTsConfigPath = getTsConfig((_process_env_NX_TSCONFIG_PATH = process.env.NX_TSCONFIG_PATH) != null ? _process_env_NX_TSCONFIG_PATH : (0, _nodepath.join)(_devkit.workspaceRoot, 'tmp', projectRootFromWorkspaceRoot, (_process_env_NX_TASK_TARGET_TARGET = process.env.NX_TASK_TARGET_TARGET) != null ? _process_env_NX_TASK_TARGET_TARGET : 'build', 'tsconfig.generated.json'));
61
- if (!foundTsConfigPath) return;
58
+ var _process_env_NX_TASK_TARGET_TARGET;
59
+ let foundTsConfigPath = getTsConfig((0, _nodepath.join)(_devkit.workspaceRoot, 'tmp', projectRootFromWorkspaceRoot, (_process_env_NX_TASK_TARGET_TARGET = process.env.NX_TASK_TARGET_TARGET) != null ? _process_env_NX_TASK_TARGET_TARGET : 'build', 'tsconfig.generated.json'));
60
+ if (!foundTsConfigPath) {
61
+ throw new Error((0, _devkit.stripIndents)`Unable to find a tsconfig in the workspace!
62
+ There should at least be a tsconfig.base.json or tsconfig.json in the root of the workspace ${_devkit.workspaceRoot}`);
63
+ }
62
64
  if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION && config.mode !== 'test') {
63
65
  const projectGraph = await (0, _devkit.createProjectGraphAsync)({
64
66
  exitOnError: false,
@@ -97,8 +99,6 @@ function nxViteTsPaths(options = {}) {
97
99
  }
98
100
  },
99
101
  resolveId (importPath) {
100
- // Let other resolvers handle this path.
101
- if (!foundTsConfigPath) return null;
102
102
  let resolvedFile;
103
103
  try {
104
104
  resolvedFile = matchTsPathEsm(importPath);
@@ -137,8 +137,7 @@ function nxViteTsPaths(options = {}) {
137
137
  return [
138
138
  (0, _nodepath.resolve)(preferredTsConfigPath),
139
139
  (0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.base.json')),
140
- (0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.json')),
141
- (0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'jsconfig.json'))
140
+ (0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.json'))
142
141
  ].find((tsPath)=>{
143
142
  if ((0, _nodefs.existsSync)(tsPath)) {
144
143
  logIt('Found tsconfig at', tsPath);
@@ -147,7 +146,7 @@ function nxViteTsPaths(options = {}) {
147
146
  });
148
147
  }
149
148
  function logIt(...msg) {
150
- if (process.env.NX_VERBOSE_LOGGING === 'true' && (options == null ? void 0 : options.debug) !== false) {
149
+ if (process.env.NX_VERBOSE_LOGGING === 'true' || (options == null ? void 0 : options.debug)) {
151
150
  console.debug('\n[Nx Vite TsPaths]', ...msg);
152
151
  }
153
152
  }
@@ -160,11 +159,6 @@ function nxViteTsPaths(options = {}) {
160
159
  if (importPath === normalizedImport || importPath.startsWith(normalizedImport + '/')) {
161
160
  const joinedPath = (0, _devkit.joinPathFragments)(tsconfig.absoluteBaseUrl, paths[0].replace(/\/\*$/, ''));
162
161
  resolvedFile = (0, _nxtsconfigpathsfindfile.findFile)(importPath.replace(normalizedImport, joinedPath), options.extensions);
163
- if (resolvedFile === undefined && options.extensions.some((ext)=>importPath.endsWith(ext))) {
164
- const foundExtension = options.extensions.find((ext)=>importPath.endsWith(ext));
165
- const pathWithoutExtension = importPath.replace(normalizedImport, joinedPath).slice(0, -foundExtension.length);
166
- resolvedFile = (0, _nxtsconfigpathsfindfile.findFile)(pathWithoutExtension, options.extensions);
167
- }
168
162
  }
169
163
  }
170
164
  return resolvedFile;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../packages/vite/plugins/nx-tsconfig-paths.plugin.ts"],"sourcesContent":["import {\n createProjectGraphAsync,\n joinPathFragments,\n stripIndents,\n workspaceRoot,\n} from '@nx/devkit';\nimport { copyFileSync, existsSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport {\n loadConfig,\n createMatchPath,\n MatchPath,\n ConfigLoaderSuccessResult,\n} from 'tsconfig-paths';\nimport {\n calculateProjectBuildableDependencies,\n createTmpTsConfig,\n} from '@nx/js/src/utils/buildable-libs-utils';\nimport { Plugin } from 'vite';\nimport { nxViteBuildCoordinationPlugin } from './nx-vite-build-coordination.plugin';\nimport { findFile } from '../src/utils/nx-tsconfig-paths-find-file';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport interface nxViteTsPathsOptions {\n /**\n * Enable debug logging\n * If set to false, it will always ignore the debug logging even when `--verbose` or `NX_VERBOSE_LOGGING` is set to true.\n * @default undefined\n **/\n debug?: boolean;\n /**\n * export fields in package.json to use for resolving\n * @default [['exports', '.', 'import'], 'module', 'main']\n *\n * fallback resolution will use ['main', 'module']\n **/\n mainFields?: (string | string[])[];\n /**\n * extensions to check when resolving files when package.json resolution fails\n * @default ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs', '.cjs']\n **/\n extensions?: string[];\n /**\n * Inform Nx whether to use the raw source or to use the built output for buildable dependencies.\n * Set to `false` to use incremental builds.\n * @default true\n */\n buildLibsFromSource?: boolean;\n}\n\nexport function nxViteTsPaths(options: nxViteTsPathsOptions = {}) {\n let foundTsConfigPath: string;\n let matchTsPathEsm: MatchPath;\n let matchTsPathFallback: MatchPath | undefined;\n let tsConfigPathsEsm: ConfigLoaderSuccessResult;\n let tsConfigPathsFallback: ConfigLoaderSuccessResult;\n\n options.extensions ??= [\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.mts',\n '.mjs',\n '.cts',\n '.cjs',\n '.css',\n '.scss',\n '.less',\n ];\n options.mainFields ??= [['exports', '.', 'import'], 'module', 'main'];\n options.buildLibsFromSource ??= true;\n let projectRoot = '';\n\n return {\n name: 'nx-vite-ts-paths',\n // Ensure the resolveId aspect of the plugin is called before vite's internal resolver\n // Otherwise, issues can arise with Yarn Workspaces and Pnpm Workspaces\n enforce: 'pre',\n async configResolved(config: any) {\n projectRoot = config.root;\n const projectRootFromWorkspaceRoot = relative(workspaceRoot, projectRoot);\n foundTsConfigPath = getTsConfig(\n process.env.NX_TSCONFIG_PATH ??\n join(\n workspaceRoot,\n 'tmp',\n projectRootFromWorkspaceRoot,\n process.env.NX_TASK_TARGET_TARGET ?? 'build',\n 'tsconfig.generated.json'\n )\n );\n\n if (!foundTsConfigPath) return;\n\n if (\n !options.buildLibsFromSource &&\n !global.NX_GRAPH_CREATION &&\n config.mode !== 'test'\n ) {\n const projectGraph = await createProjectGraphAsync({\n exitOnError: false,\n resetDaemonClient: true,\n });\n const { dependencies } = calculateProjectBuildableDependencies(\n undefined,\n projectGraph,\n workspaceRoot,\n process.env.NX_TASK_TARGET_PROJECT,\n // When using incremental building and the serve target is called\n // we need to get the deps for the 'build' target instead.\n process.env.NX_TASK_TARGET_TARGET === 'serve'\n ? 'build'\n : process.env.NX_TASK_TARGET_TARGET,\n process.env.NX_TASK_TARGET_CONFIGURATION\n );\n // This tsconfig is used via the Vite ts paths plugin.\n // It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).\n foundTsConfigPath = createTmpTsConfig(\n foundTsConfigPath,\n workspaceRoot,\n relative(workspaceRoot, projectRoot),\n dependencies,\n true\n );\n\n if (config.command === 'serve') {\n const buildableLibraryDependencies = dependencies\n .filter((dep) => dep.node.type === 'lib')\n .map((dep) => dep.node.name)\n .join(',');\n const buildCommand = `npx nx run-many --target=${process.env.NX_TASK_TARGET_TARGET} --projects=${buildableLibraryDependencies}`;\n config.plugins.push(nxViteBuildCoordinationPlugin({ buildCommand }));\n }\n }\n\n const parsed = loadConfig(foundTsConfigPath);\n\n logIt('first parsed tsconfig: ', parsed);\n if (parsed.resultType === 'failed') {\n throw new Error(`Failed loading tsconfig at ${foundTsConfigPath}`);\n }\n tsConfigPathsEsm = parsed;\n\n matchTsPathEsm = createMatchPath(\n parsed.absoluteBaseUrl,\n parsed.paths,\n options.mainFields\n );\n\n const rootLevelTsConfig = getTsConfig(\n join(workspaceRoot, 'tsconfig.base.json')\n );\n const rootLevelParsed = loadConfig(rootLevelTsConfig);\n logIt('fallback parsed tsconfig: ', rootLevelParsed);\n if (rootLevelParsed.resultType === 'success') {\n tsConfigPathsFallback = rootLevelParsed;\n matchTsPathFallback = createMatchPath(\n rootLevelParsed.absoluteBaseUrl,\n rootLevelParsed.paths,\n ['main', 'module']\n );\n }\n },\n resolveId(importPath: string) {\n // Let other resolvers handle this path.\n if (!foundTsConfigPath) return null;\n\n let resolvedFile: string;\n try {\n resolvedFile = matchTsPathEsm(importPath);\n } catch (e) {\n logIt('Using fallback path matching.');\n resolvedFile = matchTsPathFallback?.(importPath);\n }\n\n if (!resolvedFile || !existsSync(resolvedFile)) {\n if (tsConfigPathsEsm || tsConfigPathsFallback) {\n logIt(\n `Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`\n );\n resolvedFile =\n loadFileFromPaths(tsConfigPathsEsm, importPath) ||\n loadFileFromPaths(tsConfigPathsFallback, importPath);\n } else {\n logIt(`Unable to resolve ${importPath} with tsconfig paths`);\n }\n }\n\n logIt(`Resolved ${importPath} to ${resolvedFile}`);\n // Returning null defers to other resolveId functions and eventually the default resolution behavior\n // https://rollupjs.org/plugin-development/#resolveid\n return resolvedFile || null;\n },\n async writeBundle(options) {\n if (isUsingTsSolutionSetup()) return;\n const outDir = options.dir || 'dist';\n const src = resolve(projectRoot, 'package.json');\n if (existsSync(src)) {\n const dest = join(outDir, 'package.json');\n\n try {\n copyFileSync(src, dest);\n } catch (err) {\n console.error('Error copying package.json:', err);\n }\n }\n },\n } as Plugin;\n\n function getTsConfig(preferredTsConfigPath: string): string {\n return [\n resolve(preferredTsConfigPath),\n resolve(join(workspaceRoot, 'tsconfig.base.json')),\n resolve(join(workspaceRoot, 'tsconfig.json')),\n resolve(join(workspaceRoot, 'jsconfig.json')),\n ].find((tsPath) => {\n if (existsSync(tsPath)) {\n logIt('Found tsconfig at', tsPath);\n return tsPath;\n }\n });\n }\n\n function logIt(...msg: any[]) {\n if (process.env.NX_VERBOSE_LOGGING === 'true' && options?.debug !== false) {\n console.debug('\\n[Nx Vite TsPaths]', ...msg);\n }\n }\n\n function loadFileFromPaths(\n tsconfig: ConfigLoaderSuccessResult,\n importPath: string\n ) {\n logIt(\n `Trying to resolve file from config in ${tsconfig.configFileAbsolutePath}`\n );\n let resolvedFile: string;\n for (const alias in tsconfig.paths) {\n const paths = tsconfig.paths[alias];\n\n const normalizedImport = alias.replace(/\\/\\*$/, '');\n\n if (\n importPath === normalizedImport ||\n importPath.startsWith(normalizedImport + '/')\n ) {\n const joinedPath = joinPathFragments(\n tsconfig.absoluteBaseUrl,\n paths[0].replace(/\\/\\*$/, '')\n );\n\n resolvedFile = findFile(\n importPath.replace(normalizedImport, joinedPath),\n options.extensions\n );\n\n if (\n resolvedFile === undefined &&\n options.extensions.some((ext) => importPath.endsWith(ext))\n ) {\n const foundExtension = options.extensions.find((ext) =>\n importPath.endsWith(ext)\n );\n const pathWithoutExtension = importPath\n .replace(normalizedImport, joinedPath)\n .slice(0, -foundExtension.length);\n resolvedFile = findFile(pathWithoutExtension, options.extensions);\n }\n }\n }\n\n return resolvedFile;\n }\n}\n"],"names":["nxViteTsPaths","options","foundTsConfigPath","matchTsPathEsm","matchTsPathFallback","tsConfigPathsEsm","tsConfigPathsFallback","extensions","mainFields","buildLibsFromSource","projectRoot","name","enforce","configResolved","config","root","projectRootFromWorkspaceRoot","relative","workspaceRoot","process","getTsConfig","env","NX_TSCONFIG_PATH","join","NX_TASK_TARGET_TARGET","global","NX_GRAPH_CREATION","mode","projectGraph","createProjectGraphAsync","exitOnError","resetDaemonClient","dependencies","calculateProjectBuildableDependencies","undefined","NX_TASK_TARGET_PROJECT","NX_TASK_TARGET_CONFIGURATION","createTmpTsConfig","command","buildableLibraryDependencies","filter","dep","node","type","map","buildCommand","plugins","push","nxViteBuildCoordinationPlugin","parsed","loadConfig","logIt","resultType","Error","createMatchPath","absoluteBaseUrl","paths","rootLevelTsConfig","rootLevelParsed","resolveId","importPath","resolvedFile","e","existsSync","loadFileFromPaths","writeBundle","isUsingTsSolutionSetup","outDir","dir","src","resolve","dest","copyFileSync","err","console","error","preferredTsConfigPath","find","tsPath","msg","NX_VERBOSE_LOGGING","debug","tsconfig","configFileAbsolutePath","alias","normalizedImport","replace","startsWith","joinedPath","joinPathFragments","findFile","some","ext","endsWith","foundExtension","pathWithoutExtension","slice","length"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BAkDgBA;;;eAAAA;;;wBA7CT;wBACkC;0BACD;+BAMjC;oCAIA;+CAEuC;yCACrB;iCACc;AA6BhC,SAASA,cAAcC,UAAgC,CAAC,CAAC;QAO9DA,UAcAA,WACAA;IArBA,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;;IAEJL,gBAAAA,WAAAA,SAAQM,oCAARN,SAAQM,aAAe;QACrB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD;;IACDN,gBAAAA,YAAAA,SAAQO,oCAARP,UAAQO,aAAe;QAAC;YAAC;YAAW;YAAK;SAAS;QAAE;QAAU;KAAO;;IACrEP,yBAAAA,YAAAA,SAAQQ,sDAARR,UAAQQ,sBAAwB;IAChC,IAAIC,cAAc;IAElB,OAAO;QACLC,MAAM;QACN,sFAAsF;QACtF,uEAAuE;QACvEC,SAAS;QACT,MAAMC,gBAAeC,MAAW;YAC9BJ,cAAcI,OAAOC,IAAI;YACzB,MAAMC,+BAA+BC,IAAAA,kBAAQ,EAACC,qBAAa,EAAER;gBAOvDS,oCALJA;YADFjB,oBAAoBkB,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UAAU,CAACF,mBAAmB,MACzC;gBACA,MAAMG,aAAaC,IAAAA,yBAAiB,EAClCP,SAAS3B,eAAe,EACxBC,KAAK,CAAC,EAAE,CAAC8B,OAAO,CAAC,SAAS;gBAG5BzB,eAAe6B,IAAAA,iCAAQ,EACrB9B,WAAW0B,OAAO,CAACD,kBAAkBG,aACrCvF,QAAQM,UAAU;gBAGpB,IACEsD,iBAAiB3B,aACjBjC,QAAQM,UAAU,CAACoF,IAAI,CAAC,CAACC,MAAQhC,WAAWiC,QAAQ,CAACD,OACrD;oBACA,MAAME,iBAAiB7F,QAAQM,UAAU,CAACsE,IAAI,CAAC,CAACe,MAC9ChC,WAAWiC,QAAQ,CAACD;oBAEtB,MAAMG,uBAAuBnC,WAC1B0B,OAAO,CAACD,kBAAkBG,YAC1BQ,KAAK,CAAC,GAAG,CAACF,eAAeG,MAAM;oBAClCpC,eAAe6B,IAAAA,iCAAQ,EAACK,sBAAsB9F,QAAQM,UAAU;gBAClE;YACF;QACF;QAEA,OAAOsD;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../packages/vite/plugins/nx-tsconfig-paths.plugin.ts"],"sourcesContent":["import {\n createProjectGraphAsync,\n joinPathFragments,\n stripIndents,\n workspaceRoot,\n} from '@nx/devkit';\nimport { copyFileSync, existsSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport {\n loadConfig,\n createMatchPath,\n MatchPath,\n ConfigLoaderSuccessResult,\n} from 'tsconfig-paths';\nimport {\n calculateProjectBuildableDependencies,\n createTmpTsConfig,\n} from '@nx/js/src/utils/buildable-libs-utils';\nimport { Plugin } from 'vite';\nimport { nxViteBuildCoordinationPlugin } from './nx-vite-build-coordination.plugin';\nimport { findFile } from '../src/utils/nx-tsconfig-paths-find-file';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport interface nxViteTsPathsOptions {\n /**\n * Enable debug logging\n * @default false\n **/\n debug?: boolean;\n /**\n * export fields in package.json to use for resolving\n * @default [['exports', '.', 'import'], 'module', 'main']\n *\n * fallback resolution will use ['main', 'module']\n **/\n mainFields?: (string | string[])[];\n /**\n * extensions to check when resolving files when package.json resolution fails\n * @default ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs', '.cjs']\n **/\n extensions?: string[];\n /**\n * Inform Nx whether to use the raw source or to use the built output for buildable dependencies.\n * Set to `false` to use incremental builds.\n * @default true\n */\n buildLibsFromSource?: boolean;\n}\n\nexport function nxViteTsPaths(options: nxViteTsPathsOptions = {}) {\n let matchTsPathEsm: MatchPath;\n let matchTsPathFallback: MatchPath | undefined;\n let tsConfigPathsEsm: ConfigLoaderSuccessResult;\n let tsConfigPathsFallback: ConfigLoaderSuccessResult;\n\n options.extensions ??= [\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.mts',\n '.mjs',\n '.cts',\n '.cjs',\n '.css',\n '.scss',\n '.less',\n ];\n options.mainFields ??= [['exports', '.', 'import'], 'module', 'main'];\n options.buildLibsFromSource ??= true;\n let projectRoot = '';\n\n return {\n name: 'nx-vite-ts-paths',\n // Ensure the resolveId aspect of the plugin is called before vite's internal resolver\n // Otherwise, issues can arise with Yarn Workspaces and Pnpm Workspaces\n enforce: 'pre',\n async configResolved(config: any) {\n projectRoot = config.root;\n const projectRootFromWorkspaceRoot = relative(workspaceRoot, projectRoot);\n let foundTsConfigPath = getTsConfig(\n join(\n workspaceRoot,\n 'tmp',\n projectRootFromWorkspaceRoot,\n process.env.NX_TASK_TARGET_TARGET ?? 'build',\n 'tsconfig.generated.json'\n )\n );\n if (!foundTsConfigPath) {\n throw new Error(stripIndents`Unable to find a tsconfig in the workspace! \nThere should at least be a tsconfig.base.json or tsconfig.json in the root of the workspace ${workspaceRoot}`);\n }\n\n if (\n !options.buildLibsFromSource &&\n !global.NX_GRAPH_CREATION &&\n config.mode !== 'test'\n ) {\n const projectGraph = await createProjectGraphAsync({\n exitOnError: false,\n resetDaemonClient: true,\n });\n const { dependencies } = calculateProjectBuildableDependencies(\n undefined,\n projectGraph,\n workspaceRoot,\n process.env.NX_TASK_TARGET_PROJECT,\n // When using incremental building and the serve target is called\n // we need to get the deps for the 'build' target instead.\n process.env.NX_TASK_TARGET_TARGET === 'serve'\n ? 'build'\n : process.env.NX_TASK_TARGET_TARGET,\n process.env.NX_TASK_TARGET_CONFIGURATION\n );\n // This tsconfig is used via the Vite ts paths plugin.\n // It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).\n foundTsConfigPath = createTmpTsConfig(\n foundTsConfigPath,\n workspaceRoot,\n relative(workspaceRoot, projectRoot),\n dependencies,\n true\n );\n\n if (config.command === 'serve') {\n const buildableLibraryDependencies = dependencies\n .filter((dep) => dep.node.type === 'lib')\n .map((dep) => dep.node.name)\n .join(',');\n const buildCommand = `npx nx run-many --target=${process.env.NX_TASK_TARGET_TARGET} --projects=${buildableLibraryDependencies}`;\n config.plugins.push(nxViteBuildCoordinationPlugin({ buildCommand }));\n }\n }\n\n const parsed = loadConfig(foundTsConfigPath);\n\n logIt('first parsed tsconfig: ', parsed);\n if (parsed.resultType === 'failed') {\n throw new Error(`Failed loading tsconfig at ${foundTsConfigPath}`);\n }\n tsConfigPathsEsm = parsed;\n\n matchTsPathEsm = createMatchPath(\n parsed.absoluteBaseUrl,\n parsed.paths,\n options.mainFields\n );\n\n const rootLevelTsConfig = getTsConfig(\n join(workspaceRoot, 'tsconfig.base.json')\n );\n const rootLevelParsed = loadConfig(rootLevelTsConfig);\n logIt('fallback parsed tsconfig: ', rootLevelParsed);\n if (rootLevelParsed.resultType === 'success') {\n tsConfigPathsFallback = rootLevelParsed;\n matchTsPathFallback = createMatchPath(\n rootLevelParsed.absoluteBaseUrl,\n rootLevelParsed.paths,\n ['main', 'module']\n );\n }\n },\n resolveId(importPath: string) {\n let resolvedFile: string;\n try {\n resolvedFile = matchTsPathEsm(importPath);\n } catch (e) {\n logIt('Using fallback path matching.');\n resolvedFile = matchTsPathFallback?.(importPath);\n }\n\n if (!resolvedFile || !existsSync(resolvedFile)) {\n if (tsConfigPathsEsm || tsConfigPathsFallback) {\n logIt(\n `Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`\n );\n resolvedFile =\n loadFileFromPaths(tsConfigPathsEsm, importPath) ||\n loadFileFromPaths(tsConfigPathsFallback, importPath);\n } else {\n logIt(`Unable to resolve ${importPath} with tsconfig paths`);\n }\n }\n\n logIt(`Resolved ${importPath} to ${resolvedFile}`);\n // Returning null defers to other resolveId functions and eventually the default resolution behavior\n // https://rollupjs.org/plugin-development/#resolveid\n return resolvedFile || null;\n },\n async writeBundle(options) {\n if (isUsingTsSolutionSetup()) return;\n const outDir = options.dir || 'dist';\n const src = resolve(projectRoot, 'package.json');\n if (existsSync(src)) {\n const dest = join(outDir, 'package.json');\n\n try {\n copyFileSync(src, dest);\n } catch (err) {\n console.error('Error copying package.json:', err);\n }\n }\n },\n } as Plugin;\n\n function getTsConfig(preferredTsConfigPath: string): string {\n return [\n resolve(preferredTsConfigPath),\n resolve(join(workspaceRoot, 'tsconfig.base.json')),\n resolve(join(workspaceRoot, 'tsconfig.json')),\n ].find((tsPath) => {\n if (existsSync(tsPath)) {\n logIt('Found tsconfig at', tsPath);\n return tsPath;\n }\n });\n }\n\n function logIt(...msg: any[]) {\n if (process.env.NX_VERBOSE_LOGGING === 'true' || options?.debug) {\n console.debug('\\n[Nx Vite TsPaths]', ...msg);\n }\n }\n\n function loadFileFromPaths(\n tsconfig: ConfigLoaderSuccessResult,\n importPath: string\n ) {\n logIt(\n `Trying to resolve file from config in ${tsconfig.configFileAbsolutePath}`\n );\n let resolvedFile: string;\n for (const alias in tsconfig.paths) {\n const paths = tsconfig.paths[alias];\n\n const normalizedImport = alias.replace(/\\/\\*$/, '');\n\n if (\n importPath === normalizedImport ||\n importPath.startsWith(normalizedImport + '/')\n ) {\n const joinedPath = joinPathFragments(\n tsconfig.absoluteBaseUrl,\n paths[0].replace(/\\/\\*$/, '')\n );\n\n resolvedFile = findFile(\n importPath.replace(normalizedImport, joinedPath),\n options.extensions\n );\n }\n }\n\n return resolvedFile;\n }\n}\n"],"names":["nxViteTsPaths","options","matchTsPathEsm","matchTsPathFallback","tsConfigPathsEsm","tsConfigPathsFallback","extensions","mainFields","buildLibsFromSource","projectRoot","name","enforce","configResolved","config","root","projectRootFromWorkspaceRoot","relative","workspaceRoot","process","foundTsConfigPath","getTsConfig","join","env","NX_TASK_TARGET_TARGET","Error","stripIndents","global","NX_GRAPH_CREATION","mode","projectGraph","createProjectGraphAsync","exitOnError","resetDaemonClient","dependencies","calculateProjectBuildableDependencies","undefined","NX_TASK_TARGET_PROJECT","NX_TASK_TARGET_CONFIGURATION","createTmpTsConfig","command","buildableLibraryDependencies","filter","dep","node","type","map","buildCommand","plugins","push","nxViteBuildCoordinationPlugin","parsed","loadConfig","logIt","resultType","createMatchPath","absoluteBaseUrl","paths","rootLevelTsConfig","rootLevelParsed","resolveId","importPath","resolvedFile","e","existsSync","loadFileFromPaths","writeBundle","isUsingTsSolutionSetup","outDir","dir","src","resolve","dest","copyFileSync","err","console","error","preferredTsConfigPath","find","tsPath","msg","NX_VERBOSE_LOGGING","debug","tsconfig","configFileAbsolutePath","alias","normalizedImport","replace","startsWith","joinedPath","joinPathFragments","findFile"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BAiDgBA;;;eAAAA;;;wBA5CT;wBACkC;0BACD;+BAMjC;oCAIA;+CAEuC;yCACrB;iCACc;AA4BhC,SAASA,cAAcC,UAAgC,CAAC,CAAC;QAM9DA,UAcAA,WACAA;IApBA,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;;IAEJJ,gBAAAA,WAAAA,SAAQK,oCAARL,SAAQK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F,KAAK,GAAE;YAC/DP,QAAQO,KAAK,CAAC,0BAA0BF;QAC1C;IACF;IAEA,SAASf,kBACPkB,QAAmC,EACnCtB,UAAkB;QAElBR,MACE,CAAC,sCAAsC,EAAE8B,SAASC,sBAAsB,CAAC,CAAC;QAE5E,IAAItB;QACJ,IAAK,MAAMuB,SAASF,SAAS1B,KAAK,CAAE;YAClC,MAAMA,QAAQ0B,SAAS1B,KAAK,CAAC4B,MAAM;YAEnC,MAAMC,mBAAmBD,MAAME,OAAO,CAAC,SAAS;YAEhD,IACE1B,eAAeyB,oBACfzB,WAAW2B,UAAU,CAACF,mBAAmB,MACzC;gBACA,MAAMG,aAAaC,IAAAA,yBAAiB,EAClCP,SAAS3B,eAAe,EACxBC,KAAK,CAAC,EAAE,CAAC8B,OAAO,CAAC,SAAS;gBAG5BzB,eAAe6B,IAAAA,iCAAQ,EACrB9B,WAAW0B,OAAO,CAACD,kBAAkBG,aACrCvF,QAAQK,UAAU;YAEtB;QACF;QAEA,OAAOuD;IACT;AACF"}
@@ -2,8 +2,10 @@ import { ExecutorContext } from '@nx/devkit';
2
2
  import { ViteBuildExecutorOptions } from './schema';
3
3
  export declare function viteBuildExecutor(options: Record<string, any> & ViteBuildExecutorOptions, context: ExecutorContext): AsyncGenerator<{
4
4
  success: boolean;
5
- outfile?: string;
6
- }, any, any>;
5
+ } | {
6
+ success: boolean;
7
+ outfile: string;
8
+ }, void, any>;
7
9
  export declare function getBuildExtraArgs(options: ViteBuildExecutorOptions): Promise<{
8
10
  buildOptions: Record<string, unknown>;
9
11
  otherOptions: Record<string, any>;
@@ -29,11 +29,11 @@ async function* viteBuildExecutor(options, context) {
29
29
  var _resolved_build;
30
30
  process.env.VITE_CJS_IGNORE_WARNING = 'true';
31
31
  // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
32
- const { mergeConfig, build, resolveConfig, createBuilder } = await (0, _executorutils.loadViteDynamicImport)();
32
+ const { mergeConfig, build, resolveConfig } = await (0, _executorutils.loadViteDynamicImport)();
33
33
  const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
34
34
  const tsConfigForBuild = (0, _executorutils.createBuildableTsConfig)(projectRoot, options, context);
35
35
  const viteConfigPath = (0, _optionsutils.normalizeViteConfigFilePath)(context.root, projectRoot, options.configFile);
36
- const root = projectRoot === '.' || projectRoot === '' ? process.cwd() : (0, _path.relative)(context.cwd, (0, _devkit.joinPathFragments)(context.root, projectRoot));
36
+ const root = projectRoot === '.' ? process.cwd() : (0, _path.relative)(context.cwd, (0, _devkit.joinPathFragments)(context.root, projectRoot));
37
37
  const { buildOptions, otherOptions } = await getBuildExtraArgs(options);
38
38
  var _otherOptions_mode;
39
39
  const defaultMode = (_otherOptions_mode = otherOptions == null ? void 0 : otherOptions.mode) != null ? _otherOptions_mode : 'production';
@@ -64,94 +64,78 @@ async function* viteBuildExecutor(options, context) {
64
64
  isVueProject: Boolean((_resolved_plugins = resolved.plugins) == null ? void 0 : _resolved_plugins.find((plugin)=>typeof plugin === 'object' && (plugin == null ? void 0 : plugin.name) === 'vite:vue'))
65
65
  });
66
66
  }
67
- const builder = createBuilder !== undefined && options.useEnvironmentsApi ? await createBuilder(buildConfig) : {
68
- build: (inlineConfig)=>build(inlineConfig),
69
- environments: {
70
- build: buildConfig
71
- }
72
- };
73
- let iterables = [];
74
- for (const env of Object.values(builder.environments)){
75
- var _env_config;
76
- // This is needed to overwrite the resolve build config with executor options in Vite 6
77
- if ((_env_config = env.config) == null ? void 0 : _env_config.build) {
78
- env.config.build = _extends._({}, env.config.build, buildConfig.build);
79
- }
80
- const watcherOrOutput = await builder.build(env);
81
- const libraryPackageJson = (0, _path.resolve)(projectRoot, 'package.json');
82
- const rootPackageJson = (0, _path.resolve)(context.root, 'package.json');
83
- // Here, we want the outdir relative to the workspace root.
84
- // So, we calculate the relative path from the workspace root to the outdir.
85
- const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');
86
- const distPackageJson = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, 'package.json');
87
- // Generate a package.json if option has been set.
88
- if (options.generatePackageJson) {
89
- var _builtPackageJson;
90
- if (context.projectGraph.nodes[context.projectName].type !== 'app') {
91
- _devkit.logger.warn((0, _devkit.stripIndents)`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.
67
+ const watcherOrOutput = await build(buildConfig);
68
+ const libraryPackageJson = (0, _path.resolve)(projectRoot, 'package.json');
69
+ const rootPackageJson = (0, _path.resolve)(context.root, 'package.json');
70
+ // Here, we want the outdir relative to the workspace root.
71
+ // So, we calculate the relative path from the workspace root to the outdir.
72
+ const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');
73
+ const distPackageJson = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, 'package.json');
74
+ // Generate a package.json if option has been set.
75
+ if (options.generatePackageJson) {
76
+ var _builtPackageJson;
77
+ if (context.projectGraph.nodes[context.projectName].type !== 'app') {
78
+ _devkit.logger.warn((0, _devkit.stripIndents)`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.
92
79
  For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`);
93
- }
94
- const builtPackageJson = (0, _js.createPackageJson)(context.projectName, context.projectGraph, {
95
- target: context.targetName,
96
- root: context.root,
97
- isProduction: !options.includeDevDependenciesInPackageJson,
98
- skipOverrides: options.skipOverrides,
99
- skipPackageManager: options.skipPackageManager
100
- });
101
- var _type;
102
- (_type = (_builtPackageJson = builtPackageJson).type) != null ? _type : _builtPackageJson.type = 'module';
103
- (0, _devkit.writeJsonFile)(`${outDirRelativeToWorkspaceRoot}/package.json`, builtPackageJson);
104
- const packageManager = (0, _devkit.detectPackageManager)(context.root);
105
- const lockFile = (0, _js.createLockFile)(builtPackageJson, context.projectGraph, packageManager);
106
- (0, _fs.writeFileSync)(`${outDirRelativeToWorkspaceRoot}/${(0, _js.getLockFileName)(packageManager)}`, lockFile, {
107
- encoding: 'utf-8'
108
- });
109
- } else if (options.generatePackageJson !== false && !(0, _fs.existsSync)(distPackageJson) && (0, _fs.existsSync)(libraryPackageJson) && rootPackageJson !== libraryPackageJson) {
110
- await (0, _js.copyAssets)({
111
- outputPath: outDirRelativeToWorkspaceRoot,
112
- assets: [
113
- {
114
- input: projectRoot,
115
- output: '.',
116
- glob: 'package.json'
117
- }
118
- ]
119
- }, context);
120
80
  }
121
- const iterable = (0, _asynciterable.createAsyncIterable)(({ next, done })=>{
122
- if ('on' in watcherOrOutput) {
123
- let success = true;
124
- watcherOrOutput.on('event', (event)=>{
125
- if (event.code === 'START') {
126
- success = true;
127
- } else if (event.code === 'ERROR') {
128
- success = false;
129
- } else if (event.code === 'END') {
130
- next({
131
- success
132
- });
133
- }
134
- // result must be closed when present.
135
- // see https://rollupjs.org/guide/en/#rollupwatch
136
- if ('result' in event && event.result) {
137
- event.result.close();
138
- }
139
- });
140
- } else {
141
- var _watcherOrOutput_, _output_;
142
- const output = (watcherOrOutput == null ? void 0 : watcherOrOutput['output']) || (watcherOrOutput == null ? void 0 : (_watcherOrOutput_ = watcherOrOutput[0]) == null ? void 0 : _watcherOrOutput_.output);
143
- const fileName = (output == null ? void 0 : (_output_ = output[0]) == null ? void 0 : _output_.fileName) || 'main.cjs';
144
- const outfile = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, fileName);
145
- next({
146
- success: true,
147
- outfile
148
- });
149
- done();
150
- }
81
+ const builtPackageJson = (0, _js.createPackageJson)(context.projectName, context.projectGraph, {
82
+ target: context.targetName,
83
+ root: context.root,
84
+ isProduction: !options.includeDevDependenciesInPackageJson,
85
+ skipOverrides: options.skipOverrides,
86
+ skipPackageManager: options.skipPackageManager
87
+ });
88
+ var _type;
89
+ (_type = (_builtPackageJson = builtPackageJson).type) != null ? _type : _builtPackageJson.type = 'module';
90
+ (0, _devkit.writeJsonFile)(`${outDirRelativeToWorkspaceRoot}/package.json`, builtPackageJson);
91
+ const packageManager = (0, _devkit.detectPackageManager)(context.root);
92
+ const lockFile = (0, _js.createLockFile)(builtPackageJson, context.projectGraph, packageManager);
93
+ (0, _fs.writeFileSync)(`${outDirRelativeToWorkspaceRoot}/${(0, _js.getLockFileName)(packageManager)}`, lockFile, {
94
+ encoding: 'utf-8'
95
+ });
96
+ } else if (options.generatePackageJson !== false && !(0, _fs.existsSync)(distPackageJson) && (0, _fs.existsSync)(libraryPackageJson) && rootPackageJson !== libraryPackageJson) {
97
+ await (0, _js.copyAssets)({
98
+ outputPath: outDirRelativeToWorkspaceRoot,
99
+ assets: [
100
+ {
101
+ input: projectRoot,
102
+ output: '.',
103
+ glob: 'package.json'
104
+ }
105
+ ]
106
+ }, context);
107
+ }
108
+ if ('on' in watcherOrOutput) {
109
+ const iterable = (0, _asynciterable.createAsyncIterable)(({ next })=>{
110
+ let success = true;
111
+ watcherOrOutput.on('event', (event)=>{
112
+ if (event.code === 'START') {
113
+ success = true;
114
+ } else if (event.code === 'ERROR') {
115
+ success = false;
116
+ } else if (event.code === 'END') {
117
+ next({
118
+ success
119
+ });
120
+ }
121
+ // result must be closed when present.
122
+ // see https://rollupjs.org/guide/en/#rollupwatch
123
+ if ('result' in event && event.result) {
124
+ event.result.close();
125
+ }
126
+ });
151
127
  });
152
- iterables.push(iterable);
128
+ yield* iterable;
129
+ } else {
130
+ var _watcherOrOutput_, _output_;
131
+ const output = (watcherOrOutput == null ? void 0 : watcherOrOutput['output']) || (watcherOrOutput == null ? void 0 : (_watcherOrOutput_ = watcherOrOutput[0]) == null ? void 0 : _watcherOrOutput_.output);
132
+ const fileName = (output == null ? void 0 : (_output_ = output[0]) == null ? void 0 : _output_.fileName) || 'main.cjs';
133
+ const outfile = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, fileName);
134
+ yield {
135
+ success: true,
136
+ outfile
137
+ };
153
138
  }
154
- return yield* (0, _asynciterable.combineAsyncIterables)(iterables.shift(), ...iterables != null ? iterables : []);
155
139
  }
156
140
  async function getBuildExtraArgs(options) {
157
141
  // support passing extra args to vite cli
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/vite/src/executors/build/build.impl.ts"],"sourcesContent":["import {\n detectPackageManager,\n ExecutorContext,\n joinPathFragments,\n logger,\n offsetFromRoot,\n stripIndents,\n writeJsonFile,\n} from '@nx/devkit';\nimport {\n getProjectTsConfigPath,\n normalizeViteConfigFilePath,\n} from '../../utils/options-utils';\nimport { ViteBuildExecutorOptions } from './schema';\nimport {\n copyAssets,\n createLockFile,\n createPackageJson,\n getLockFileName,\n} from '@nx/js';\nimport { existsSync, writeFileSync } from 'fs';\nimport { relative, resolve } from 'path';\nimport {\n combineAsyncIterables,\n createAsyncIterable,\n} from '@nx/devkit/src/utils/async-iterable';\nimport {\n createBuildableTsConfig,\n loadViteDynamicImport,\n validateTypes,\n} from '../../utils/executor-utils';\nimport { type Plugin } from 'vite';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport async function* viteBuildExecutor(\n options: Record<string, any> & ViteBuildExecutorOptions,\n context: ExecutorContext\n) {\n process.env.VITE_CJS_IGNORE_WARNING = 'true';\n // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.\n const { mergeConfig, build, resolveConfig, createBuilder } =\n await loadViteDynamicImport();\n const projectRoot =\n context.projectsConfigurations.projects[context.projectName].root;\n const tsConfigForBuild = createBuildableTsConfig(\n projectRoot,\n options,\n context\n );\n\n const viteConfigPath = normalizeViteConfigFilePath(\n context.root,\n projectRoot,\n options.configFile\n );\n const root =\n projectRoot === '.' || projectRoot === ''\n ? process.cwd()\n : relative(context.cwd, joinPathFragments(context.root, projectRoot));\n\n const { buildOptions, otherOptions } = await getBuildExtraArgs(options);\n const defaultMode = otherOptions?.mode ?? 'production';\n\n const resolved = await resolveConfig(\n {\n configFile: viteConfigPath,\n mode: defaultMode,\n },\n 'build',\n defaultMode,\n process.env.NODE_ENV ?? defaultMode\n );\n\n const outDir =\n joinPathFragments(offsetFromRoot(projectRoot), options.outputPath) ??\n resolved?.build?.outDir;\n\n const buildConfig = mergeConfig(\n {\n // This should not be needed as it's going to be set in vite.config.ts\n // but leaving it here in case someone did not migrate correctly\n root: resolved.root ?? root,\n configFile: viteConfigPath,\n },\n {\n build: {\n outDir,\n ...buildOptions,\n },\n ...otherOptions,\n }\n );\n // New TS Solution already has a typecheck target\n if (!options.skipTypeCheck && !isUsingTsSolutionSetup()) {\n await validateTypes({\n workspaceRoot: context.root,\n tsconfig: tsConfigForBuild,\n isVueProject: Boolean(\n resolved.plugins?.find(\n (plugin: Plugin) =>\n typeof plugin === 'object' && plugin?.name === 'vite:vue'\n )\n ),\n });\n }\n\n const builder =\n createBuilder !== undefined && options.useEnvironmentsApi\n ? await createBuilder(buildConfig)\n : // This is needed to ensure support for Vite 5\n {\n build: (inlineConfig) => build(inlineConfig),\n environments: { build: buildConfig },\n };\n\n let iterables: AsyncIterable<{ success: boolean; outfile?: string }>[] = [];\n for (const env of Object.values(builder.environments)) {\n // This is needed to overwrite the resolve build config with executor options in Vite 6\n if (env.config?.build) {\n env.config.build = {\n ...env.config.build,\n ...buildConfig.build,\n };\n }\n const watcherOrOutput = await builder.build(env as any);\n\n const libraryPackageJson = resolve(projectRoot, 'package.json');\n const rootPackageJson = resolve(context.root, 'package.json');\n\n // Here, we want the outdir relative to the workspace root.\n // So, we calculate the relative path from the workspace root to the outdir.\n const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');\n const distPackageJson = resolve(\n outDirRelativeToWorkspaceRoot,\n 'package.json'\n );\n\n // Generate a package.json if option has been set.\n if (options.generatePackageJson) {\n if (context.projectGraph.nodes[context.projectName].type !== 'app') {\n logger.warn(\n stripIndents`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.\n For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`\n );\n }\n\n const builtPackageJson = createPackageJson(\n context.projectName,\n context.projectGraph,\n {\n target: context.targetName,\n root: context.root,\n isProduction: !options.includeDevDependenciesInPackageJson, // By default we remove devDependencies since this is a production build.\n skipOverrides: options.skipOverrides,\n skipPackageManager: options.skipPackageManager,\n }\n );\n\n builtPackageJson.type ??= 'module';\n\n writeJsonFile(\n `${outDirRelativeToWorkspaceRoot}/package.json`,\n builtPackageJson\n );\n const packageManager = detectPackageManager(context.root);\n\n const lockFile = createLockFile(\n builtPackageJson,\n context.projectGraph,\n packageManager\n );\n writeFileSync(\n `${outDirRelativeToWorkspaceRoot}/${getLockFileName(packageManager)}`,\n lockFile,\n {\n encoding: 'utf-8',\n }\n );\n }\n // For buildable libs, copy package.json if it exists.\n else if (\n options.generatePackageJson !== false &&\n !existsSync(distPackageJson) &&\n existsSync(libraryPackageJson) &&\n rootPackageJson !== libraryPackageJson\n ) {\n await copyAssets(\n {\n outputPath: outDirRelativeToWorkspaceRoot,\n assets: [\n {\n input: projectRoot,\n output: '.',\n glob: 'package.json',\n },\n ],\n },\n context\n );\n }\n\n const iterable = createAsyncIterable<{\n success: boolean;\n outfile?: string;\n }>(({ next, done }) => {\n if ('on' in watcherOrOutput) {\n let success = true;\n watcherOrOutput.on('event', (event) => {\n if (event.code === 'START') {\n success = true;\n } else if (event.code === 'ERROR') {\n success = false;\n } else if (event.code === 'END') {\n next({ success });\n }\n // result must be closed when present.\n // see https://rollupjs.org/guide/en/#rollupwatch\n if ('result' in event && event.result) {\n event.result.close();\n }\n });\n } else {\n const output =\n watcherOrOutput?.['output'] || watcherOrOutput?.[0]?.output;\n const fileName = output?.[0]?.fileName || 'main.cjs';\n const outfile = resolve(outDirRelativeToWorkspaceRoot, fileName);\n next({ success: true, outfile });\n done();\n }\n });\n iterables.push(iterable);\n }\n return yield* combineAsyncIterables(iterables.shift(), ...(iterables ?? []));\n}\n\nexport async function getBuildExtraArgs(\n options: ViteBuildExecutorOptions\n): Promise<{\n // vite BuildOptions\n buildOptions: Record<string, unknown>;\n otherOptions: Record<string, any>;\n}> {\n // support passing extra args to vite cli\n const schema = await import('./schema.json');\n const extraArgs = {};\n for (const key of Object.keys(options)) {\n if (!schema.properties[key]) {\n extraArgs[key] = options[key];\n }\n }\n\n const buildOptions = {};\n const buildSchemaKeys = [\n 'target',\n 'polyfillModulePreload',\n 'modulePreload',\n 'outDir',\n 'assetsDir',\n 'assetsInlineLimit',\n 'cssCodeSplit',\n 'cssTarget',\n 'cssMinify',\n 'sourcemap',\n 'minify',\n 'terserOptions',\n 'rollupOptions',\n 'commonjsOptions',\n 'dynamicImportVarsOptions',\n 'write',\n 'emptyOutDir',\n 'copyPublicDir',\n 'manifest',\n 'lib',\n 'ssr',\n 'ssrManifest',\n 'ssrEmitAssets',\n 'reportCompressedSize',\n 'chunkSizeWarningLimit',\n 'watch',\n ];\n const otherOptions = {};\n for (const key of Object.keys(extraArgs)) {\n if (buildSchemaKeys.includes(key)) {\n buildOptions[key] = extraArgs[key];\n } else {\n otherOptions[key] = extraArgs[key];\n }\n }\n\n buildOptions['watch'] = options.watch ?? undefined;\n\n return {\n buildOptions,\n otherOptions,\n };\n}\n\nexport default viteBuildExecutor;\n"],"names":["getBuildExtraArgs","viteBuildExecutor","options","context","resolved","process","env","VITE_CJS_IGNORE_WARNING","mergeConfig","build","resolveConfig","createBuilder","loadViteDynamicImport","projectRoot","projectsConfigurations","projects","projectName","root","tsConfigForBuild","createBuildableTsConfig","viteConfigPath","normalizeViteConfigFilePath","configFile","cwd","relative","joinPathFragments","buildOptions","otherOptions","defaultMode","mode","NODE_ENV","outDir","offsetFromRoot","outputPath","buildConfig","skipTypeCheck","isUsingTsSolutionSetup","validateTypes","workspaceRoot","tsconfig","isVueProject","Boolean","plugins","find","plugin","name","builder","undefined","useEnvironmentsApi","inlineConfig","environments","iterables","Object","values","config","watcherOrOutput","libraryPackageJson","resolve","rootPackageJson","outDirRelativeToWorkspaceRoot","replaceAll","distPackageJson","generatePackageJson","builtPackageJson","projectGraph","nodes","type","logger","warn","stripIndents","createPackageJson","target","targetName","isProduction","includeDevDependenciesInPackageJson","skipOverrides","skipPackageManager","writeJsonFile","packageManager","detectPackageManager","lockFile","createLockFile","writeFileSync","getLockFileName","encoding","existsSync","copyAssets","assets","input","output","glob","iterable","createAsyncIterable","next","done","success","on","event","code","result","close","fileName","outfile","push","combineAsyncIterables","shift","schema","extraArgs","key","keys","properties","buildSchemaKeys","includes","watch"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAySA,OAAiC;eAAjC;;IA9DsBA,iBAAiB;eAAjBA;;IAzMCC,iBAAiB;eAAjBA;;;;wBA1BhB;8BAIA;oBAOA;oBACmC;sBACR;+BAI3B;+BAKA;iCAEgC;AAEhC,gBAAgBA,kBACrBC,OAAuD,EACvDC,OAAwB;QAuCtBC;IArCFC,QAAQC,GAAG,CAACC,uBAAuB,GAAG;IACtC,yFAAyF;IACzF,MAAM,EAAEC,WAAW,EAAEC,KAAK,EAAEC,aAAa,EAAEC,aAAa,EAAE,GACxD,MAAMC,IAAAA,oCAAqB;IAC7B,MAAMC,cACJV,QAAQW,sBAAsB,CAACC,QAAQ,CAACZ,QAAQa,WAAW,CAAC,CAACC,IAAI;IACnE,MAAMC,mBAAmBC,IAAAA,sCAAuB,EAC9CN,aACAX,SACAC;IAGF,MAAMiB,iBAAiBC,IAAAA,yCAA2B,EAChDlB,QAAQc,IAAI,EACZJ,aACAX,QAAQoB,UAAU;IAEpB,MAAML,OACJJ,gBAAgB,OAAOA,gBAAgB,KACnCR,QAAQkB,GAAG,KACXC,IAAAA,cAAQ,EAACrB,QAAQoB,GAAG,EAAEE,IAAAA,yBAAiB,EA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,MAAQ,CAAC,EAAE,qBAAXA,SAAaY,QAAQ,KAAI;gBAC1C,MAAMC,UAAU7C,IAAAA,aAAO,EAACE,+BAA+B0C;gBACvDR,KAAK;oBAAEE,SAAS;oBAAMO;gBAAQ;gBAC9BR;YACF;QACF;QACA3C,UAAUoD,IAAI,CAACZ;IACjB;IACA,OAAO,OAAOa,IAAAA,oCAAqB,EAACrD,UAAUsD,KAAK,OAAQtD,oBAAAA,YAAa,EAAE;AAC5E;AAEO,eAAenD,kBACpBE,OAAiC;IAMjC,yCAAyC;IACzC,MAAMwG,SAAS,MAAM,2BAAA,QAAO;IAC5B,MAAMC,YAAY,CAAC;IACnB,KAAK,MAAMC,OAAOxD,OAAOyD,IAAI,CAAC3G,SAAU;QACtC,IAAI,CAACwG,OAAOI,UAAU,CAACF,IAAI,EAAE;YAC3BD,SAAS,CAACC,IAAI,GAAG1G,OAAO,CAAC0G,IAAI;QAC/B;IACF;IAEA,MAAMlF,eAAe,CAAC;IACtB,MAAMqF,kBAAkB;QACtB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD;IACD,MAAMpF,eAAe,CAAC;IACtB,KAAK,MAAMiF,OAAOxD,OAAOyD,IAAI,CAACF,WAAY;QACxC,IAAII,gBAAgBC,QAAQ,CAACJ,MAAM;YACjClF,YAAY,CAACkF,IAAI,GAAGD,SAAS,CAACC,IAAI;QACpC,OAAO;YACLjF,YAAY,CAACiF,IAAI,GAAGD,SAAS,CAACC,IAAI;QACpC;IACF;QAEwB1G;IAAxBwB,YAAY,CAAC,QAAQ,GAAGxB,CAAAA,iBAAAA,QAAQ+G,KAAK,YAAb/G,iBAAiB6C;IAEzC,OAAO;QACLrB;QACAC;IACF;AACF;MAEA,WAAe1B"}
1
+ {"version":3,"sources":["../../../../../../packages/vite/src/executors/build/build.impl.ts"],"sourcesContent":["import {\n detectPackageManager,\n ExecutorContext,\n joinPathFragments,\n logger,\n offsetFromRoot,\n stripIndents,\n writeJsonFile,\n} from '@nx/devkit';\nimport {\n getProjectTsConfigPath,\n normalizeViteConfigFilePath,\n} from '../../utils/options-utils';\nimport { ViteBuildExecutorOptions } from './schema';\nimport {\n copyAssets,\n createLockFile,\n createPackageJson,\n getLockFileName,\n} from '@nx/js';\nimport { existsSync, writeFileSync } from 'fs';\nimport { relative, resolve } from 'path';\nimport { createAsyncIterable } from '@nx/devkit/src/utils/async-iterable';\nimport {\n createBuildableTsConfig,\n loadViteDynamicImport,\n validateTypes,\n} from '../../utils/executor-utils';\nimport { type Plugin } from 'vite';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\n\nexport async function* viteBuildExecutor(\n options: Record<string, any> & ViteBuildExecutorOptions,\n context: ExecutorContext\n) {\n process.env.VITE_CJS_IGNORE_WARNING = 'true';\n // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.\n const { mergeConfig, build, resolveConfig } = await loadViteDynamicImport();\n const projectRoot =\n context.projectsConfigurations.projects[context.projectName].root;\n const tsConfigForBuild = createBuildableTsConfig(\n projectRoot,\n options,\n context\n );\n\n const viteConfigPath = normalizeViteConfigFilePath(\n context.root,\n projectRoot,\n options.configFile\n );\n const root =\n projectRoot === '.'\n ? process.cwd()\n : relative(context.cwd, joinPathFragments(context.root, projectRoot));\n\n const { buildOptions, otherOptions } = await getBuildExtraArgs(options);\n const defaultMode = otherOptions?.mode ?? 'production';\n\n const resolved = await resolveConfig(\n {\n configFile: viteConfigPath,\n mode: defaultMode,\n },\n 'build',\n defaultMode,\n process.env.NODE_ENV ?? defaultMode\n );\n\n const outDir =\n joinPathFragments(offsetFromRoot(projectRoot), options.outputPath) ??\n resolved?.build?.outDir;\n\n const buildConfig = mergeConfig(\n {\n // This should not be needed as it's going to be set in vite.config.ts\n // but leaving it here in case someone did not migrate correctly\n root: resolved.root ?? root,\n configFile: viteConfigPath,\n },\n {\n build: {\n outDir,\n ...buildOptions,\n },\n ...otherOptions,\n }\n );\n // New TS Solution already has a typecheck target\n if (!options.skipTypeCheck && !isUsingTsSolutionSetup()) {\n await validateTypes({\n workspaceRoot: context.root,\n tsconfig: tsConfigForBuild,\n isVueProject: Boolean(\n resolved.plugins?.find(\n (plugin: Plugin) =>\n typeof plugin === 'object' && plugin?.name === 'vite:vue'\n )\n ),\n });\n }\n\n const watcherOrOutput = await build(buildConfig);\n\n const libraryPackageJson = resolve(projectRoot, 'package.json');\n const rootPackageJson = resolve(context.root, 'package.json');\n\n // Here, we want the outdir relative to the workspace root.\n // So, we calculate the relative path from the workspace root to the outdir.\n const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', '');\n const distPackageJson = resolve(\n outDirRelativeToWorkspaceRoot,\n 'package.json'\n );\n\n // Generate a package.json if option has been set.\n if (options.generatePackageJson) {\n if (context.projectGraph.nodes[context.projectName].type !== 'app') {\n logger.warn(\n stripIndents`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications.\n For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`\n );\n }\n\n const builtPackageJson = createPackageJson(\n context.projectName,\n context.projectGraph,\n {\n target: context.targetName,\n root: context.root,\n isProduction: !options.includeDevDependenciesInPackageJson, // By default we remove devDependencies since this is a production build.\n skipOverrides: options.skipOverrides,\n skipPackageManager: options.skipPackageManager,\n }\n );\n\n builtPackageJson.type ??= 'module';\n\n writeJsonFile(\n `${outDirRelativeToWorkspaceRoot}/package.json`,\n builtPackageJson\n );\n const packageManager = detectPackageManager(context.root);\n\n const lockFile = createLockFile(\n builtPackageJson,\n context.projectGraph,\n packageManager\n );\n writeFileSync(\n `${outDirRelativeToWorkspaceRoot}/${getLockFileName(packageManager)}`,\n lockFile,\n {\n encoding: 'utf-8',\n }\n );\n }\n // For buildable libs, copy package.json if it exists.\n else if (\n options.generatePackageJson !== false &&\n !existsSync(distPackageJson) &&\n existsSync(libraryPackageJson) &&\n rootPackageJson !== libraryPackageJson\n ) {\n await copyAssets(\n {\n outputPath: outDirRelativeToWorkspaceRoot,\n assets: [\n {\n input: projectRoot,\n output: '.',\n glob: 'package.json',\n },\n ],\n },\n context\n );\n }\n\n if ('on' in watcherOrOutput) {\n const iterable = createAsyncIterable<{ success: boolean }>(({ next }) => {\n let success = true;\n watcherOrOutput.on('event', (event) => {\n if (event.code === 'START') {\n success = true;\n } else if (event.code === 'ERROR') {\n success = false;\n } else if (event.code === 'END') {\n next({ success });\n }\n // result must be closed when present.\n // see https://rollupjs.org/guide/en/#rollupwatch\n if ('result' in event && event.result) {\n event.result.close();\n }\n });\n });\n yield* iterable;\n } else {\n const output = watcherOrOutput?.['output'] || watcherOrOutput?.[0]?.output;\n const fileName = output?.[0]?.fileName || 'main.cjs';\n const outfile = resolve(outDirRelativeToWorkspaceRoot, fileName);\n yield { success: true, outfile };\n }\n}\n\nexport async function getBuildExtraArgs(\n options: ViteBuildExecutorOptions\n): Promise<{\n // vite BuildOptions\n buildOptions: Record<string, unknown>;\n otherOptions: Record<string, any>;\n}> {\n // support passing extra args to vite cli\n const schema = await import('./schema.json');\n const extraArgs = {};\n for (const key of Object.keys(options)) {\n if (!schema.properties[key]) {\n extraArgs[key] = options[key];\n }\n }\n\n const buildOptions = {};\n const buildSchemaKeys = [\n 'target',\n 'polyfillModulePreload',\n 'modulePreload',\n 'outDir',\n 'assetsDir',\n 'assetsInlineLimit',\n 'cssCodeSplit',\n 'cssTarget',\n 'cssMinify',\n 'sourcemap',\n 'minify',\n 'terserOptions',\n 'rollupOptions',\n 'commonjsOptions',\n 'dynamicImportVarsOptions',\n 'write',\n 'emptyOutDir',\n 'copyPublicDir',\n 'manifest',\n 'lib',\n 'ssr',\n 'ssrManifest',\n 'ssrEmitAssets',\n 'reportCompressedSize',\n 'chunkSizeWarningLimit',\n 'watch',\n ];\n const otherOptions = {};\n for (const key of Object.keys(extraArgs)) {\n if (buildSchemaKeys.includes(key)) {\n buildOptions[key] = extraArgs[key];\n } else {\n otherOptions[key] = extraArgs[key];\n }\n }\n\n buildOptions['watch'] = options.watch ?? undefined;\n\n return {\n buildOptions,\n otherOptions,\n };\n}\n\nexport default viteBuildExecutor;\n"],"names":["getBuildExtraArgs","viteBuildExecutor","options","context","resolved","process","env","VITE_CJS_IGNORE_WARNING","mergeConfig","build","resolveConfig","loadViteDynamicImport","projectRoot","projectsConfigurations","projects","projectName","root","tsConfigForBuild","createBuildableTsConfig","viteConfigPath","normalizeViteConfigFilePath","configFile","cwd","relative","joinPathFragments","buildOptions","otherOptions","defaultMode","mode","NODE_ENV","outDir","offsetFromRoot","outputPath","buildConfig","skipTypeCheck","isUsingTsSolutionSetup","validateTypes","workspaceRoot","tsconfig","isVueProject","Boolean","plugins","find","plugin","name","watcherOrOutput","libraryPackageJson","resolve","rootPackageJson","outDirRelativeToWorkspaceRoot","replaceAll","distPackageJson","generatePackageJson","builtPackageJson","projectGraph","nodes","type","logger","warn","stripIndents","createPackageJson","target","targetName","isProduction","includeDevDependenciesInPackageJson","skipOverrides","skipPackageManager","writeJsonFile","packageManager","detectPackageManager","lockFile","createLockFile","writeFileSync","getLockFileName","encoding","existsSync","copyAssets","assets","input","output","glob","iterable","createAsyncIterable","next","success","on","event","code","result","close","fileName","outfile","schema","extraArgs","key","Object","keys","properties","buildSchemaKeys","includes","watch","undefined"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IA4QA,OAAiC;eAAjC;;IA9DsBA,iBAAiB;eAAjBA;;IA/KCC,iBAAiB;eAAjBA;;;;wBAvBhB;8BAIA;oB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,oCAAAA,oBAAAA,eAAiB,CAAC,EAAE,qBAApBA,kBAAsBkC,MAAM;QAC1E,MAAMW,WAAWX,CAAAA,2BAAAA,WAAAA,MAAQ,CAAC,EAAE,qBAAXA,SAAaW,QAAQ,KAAI;QAC1C,MAAMC,UAAU5C,IAAAA,aAAO,EAACE,+BAA+ByC;QACvD,MAAM;YAAEN,SAAS;YAAMO;QAAQ;IACjC;AACF;AAEO,eAAe3F,kBACpBE,OAAiC;IAMjC,yCAAyC;IACzC,MAAM0F,SAAS,MAAM,2BAAA,QAAO;IAC5B,MAAMC,YAAY,CAAC;IACnB,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAAC9F,SAAU;QACtC,IAAI,CAAC0F,OAAOK,UAAU,CAACH,IAAI,EAAE;YAC3BD,SAAS,CAACC,IAAI,GAAG5F,OAAO,CAAC4F,IAAI;QAC/B;IACF;IAEA,MAAMrE,eAAe,CAAC;IACtB,MAAMyE,kBAAkB;QACtB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD;IACD,MAAMxE,eAAe,CAAC;IACtB,KAAK,MAAMoE,OAAOC,OAAOC,IAAI,CAACH,WAAY;QACxC,IAAIK,gBAAgBC,QAAQ,CAACL,MAAM;YACjCrE,YAAY,CAACqE,IAAI,GAAGD,SAAS,CAACC,IAAI;QACpC,OAAO;YACLpE,YAAY,CAACoE,IAAI,GAAGD,SAAS,CAACC,IAAI;QACpC;IACF;QAEwB5F;IAAxBuB,YAAY,CAAC,QAAQ,GAAGvB,CAAAA,iBAAAA,QAAQkG,KAAK,YAAblG,iBAAiBmG;IAEzC,OAAO;QACL5E;QACAC;IACF;AACF;MAEA,WAAezB"}
@@ -9,5 +9,4 @@ export interface ViteBuildExecutorOptions {
9
9
  skipTypeCheck?: boolean;
10
10
  tsConfig?: string;
11
11
  watch?: boolean;
12
- useEnvironmentsApi?: boolean;
13
12
  }
@@ -67,12 +67,6 @@
67
67
  "skipPackageManager": {
68
68
  "type": "boolean",
69
69
  "description": "Do not add a `packageManager` entry to the generated package.json file. Only works in conjunction with `generatePackageJson` option."
70
- },
71
- "useEnvironmentsApi": {
72
- "alias": "app",
73
- "type": "boolean",
74
- "description": "Use the new Environments API for building multiple environments at once. Only works with Vite 6.0.0 or higher.",
75
- "default": false
76
70
  }
77
71
  },
78
72
  "definitions": {},
@@ -53,23 +53,16 @@ async function getOptions(options, context, projectRoot) {
53
53
  ]), { options: { watch } } = _parseCLI, normalizedExtraArgs = _object_without_properties_loose._(_parseCLI.options, [
54
54
  "watch"
55
55
  ]);
56
- const { reportsDirectory, coverage } = normalizedExtraArgs, restNormalizedArgs = _object_without_properties_loose._(normalizedExtraArgs, [
57
- "reportsDirectory",
58
- "coverage"
59
- ]);
60
56
  var _resolved_config_root;
61
57
  const settings = _extends._({
62
58
  // Explicitly set watch mode to false if not provided otherwise vitest
63
59
  // will enable watch mode by default for non CI environments
64
60
  watch: watch != null ? watch : false
65
- }, restNormalizedArgs, {
61
+ }, normalizedExtraArgs, {
66
62
  // This should not be needed as it's going to be set in vite.config.ts
67
63
  // but leaving it here in case someone did not migrate correctly
68
64
  root: (_resolved_config_root = resolved.config.root) != null ? _resolved_config_root : root,
69
- config: viteConfigPath,
70
- coverage: _extends._({}, coverage != null ? coverage : {}, reportsDirectory && {
71
- reportsDirectory
72
- })
65
+ config: viteConfigPath
73
66
  });
74
67
  var _resolved_config_test;
75
68
  return mergeConfig((_resolved_config_test = resolved == null ? void 0 : (_resolved_config1 = resolved.config) == null ? void 0 : _resolved_config1['test']) != null ? _resolved_config_test : {}, settings);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../packages/vite/src/executors/test/lib/utils.ts"],"sourcesContent":["import {\n ExecutorContext,\n joinPathFragments,\n logger,\n stripIndents,\n} from '@nx/devkit';\nimport { VitestExecutorOptions } from '../schema';\nimport { normalizeViteConfigFilePath } from '../../../utils/options-utils';\nimport { relative } from 'path';\nimport {\n loadViteDynamicImport,\n loadVitestDynamicImport,\n} from '../../../utils/executor-utils';\n\nexport async function getOptions(\n options: VitestExecutorOptions,\n context: ExecutorContext,\n projectRoot: string\n) {\n // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.\n const { loadConfigFromFile, mergeConfig } = await loadViteDynamicImport();\n\n const viteConfigPath = normalizeViteConfigFilePath(\n context.root,\n projectRoot,\n options.configFile\n );\n\n if (!viteConfigPath) {\n throw new Error(\n stripIndents`\n Unable to load test config from config file ${viteConfigPath}.\n \n Please make sure that vitest is configured correctly, \n or use the @nx/vite:vitest generator to configure it for you.\n You can read more here: https://nx.dev/nx-api/vite/generators/vitest\n `\n );\n }\n\n const resolved = await loadConfigFromFile(\n {\n mode: options?.mode ?? 'production',\n command: 'serve',\n },\n viteConfigPath\n );\n\n if (!viteConfigPath || !resolved?.config?.['test']) {\n logger.warn(stripIndents`Unable to load test config from config file ${\n resolved?.path ?? viteConfigPath\n }\n Some settings may not be applied as expected.\n You can manually set the config in the project, ${\n context.projectName\n }, configuration.\n `);\n }\n const root =\n projectRoot === '.'\n ? process.cwd()\n : relative(context.cwd, joinPathFragments(context.root, projectRoot));\n\n const { parseCLI } = await loadVitestDynamicImport();\n\n const {\n options: { watch, ...normalizedExtraArgs },\n } = parseCLI(['vitest', ...getOptionsAsArgv(options)]);\n\n const { reportsDirectory, coverage, ...restNormalizedArgs } =\n normalizedExtraArgs as Record<string, any>;\n\n const settings = {\n // Explicitly set watch mode to false if not provided otherwise vitest\n // will enable watch mode by default for non CI environments\n watch: watch ?? false,\n ...restNormalizedArgs,\n // This should not be needed as it's going to be set in vite.config.ts\n // but leaving it here in case someone did not migrate correctly\n root: resolved.config.root ?? root,\n config: viteConfigPath,\n coverage: {\n ...(coverage ?? {}),\n ...(reportsDirectory && { reportsDirectory }),\n },\n };\n\n return mergeConfig(resolved?.config?.['test'] ?? {}, settings);\n}\n\nexport function getOptionsAsArgv(obj: Record<string, any>): string[] {\n const argv: string[] = [];\n\n for (const [key, value] of Object.entries(obj)) {\n if (Array.isArray(value)) {\n value.forEach((item) => argv.push(`--${key}=${item}`));\n } else if (typeof value === 'object' && value !== null) {\n argv.push(`--${key}='${JSON.stringify(value)}'`);\n } else {\n argv.push(`--${key}=${value}`);\n }\n }\n\n return argv;\n}\n"],"names":["getOptions","getOptionsAsArgv","options","context","projectRoot","resolved","loadConfigFromFile","mergeConfig","loadViteDynamicImport","viteConfigPath","normalizeViteConfigFilePath","root","configFile","Error","stripIndents","mode","command","config","logger","warn","path","projectName","process","cwd","relative","joinPathFragments","parseCLI","loadVitestDynamicImport","watch","normalizedExtraArgs","reportsDirectory","coverage","restNormalizedArgs","settings","obj","argv","key","value","Object","entries","Array","isArray","forEach","item","push","JSON","stringify"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAcsBA,UAAU;eAAVA;;IA4ENC,gBAAgB;eAAhBA;;;;;wBArFT;8BAEqC;sBACnB;+BAIlB;AAEA,eAAeD,WACpBE,OAA8B,EAC9BC,OAAwB,EACxBC,WAAmB;QA+BKC,kBAuCLA;IApEnB,yFAAyF;IACzF,MAAM,EAAEC,kBAAkB,EAAEC,WAAW,EAAE,GAAG,MAAMC,IAAAA,oCAAqB;IAEvE,MAAMC,iBAAiBC,IAAAA,yCAA2B,EAChDP,QAAQQ,IAAI,EACZP,aACAF,QAAQU,UAAU;IAGpB,IAAI,CAACH,gBAAgB;QACnB,MAAM,IAAII,MACRC,IAAAA,oBAAY,CAAA,CAAC;oDACiC,EAAEL,eAAe;;;;;QAK7D,CAAC;IAEP;QAIUP;IAFV,MAAMG,WAAW,MAAMC,mBACrB;QACES,MAAMb,CAAAA,gBAAAA,2BAAAA,QAASa,IAAI,YAAbb,gBAAiB;QACvBc,SAAS;IACX,GACAP;IAGF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KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,KAAM;QAC9C,IAAIM,MAAMC,OAAO,CAACJ,QAAQ;YACxBA,MAAMK,OAAO,CAAC,CAACC,OAASR,KAAKS,IAAI,CAAC,CAAC,EAAE,EAAER,IAAI,CAAC,EAAEO,KAAK,CAAC;QACtD,OAAO,IAAI,OAAON,UAAU,YAAYA,UAAU,MAAM;YACtDF,KAAKS,IAAI,CAAC,CAAC,EAAE,EAAER,IAAI,EAAE,EAAES,KAAKC,SAAS,CAACT,OAAO,CAAC,CAAC;QACjD,OAAO;YACLF,KAAKS,IAAI,CAAC,CAAC,EAAE,EAAER,IAAI,CAAC,EAAEC,MAAM,CAAC;QAC/B;IACF;IAEA,OAAOF;AACT"}
1
+ {"version":3,"sources":["../../../../../../../packages/vite/src/executors/test/lib/utils.ts"],"sourcesContent":["import {\n ExecutorContext,\n joinPathFragments,\n logger,\n stripIndents,\n} from '@nx/devkit';\nimport { VitestExecutorOptions } from '../schema';\nimport { normalizeViteConfigFilePath } from '../../../utils/options-utils';\nimport { relative } from 'path';\nimport {\n loadViteDynamicImport,\n loadVitestDynamicImport,\n} from '../../../utils/executor-utils';\n\nexport async function getOptions(\n options: VitestExecutorOptions,\n context: ExecutorContext,\n projectRoot: string\n) {\n // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.\n const { loadConfigFromFile, mergeConfig } = await loadViteDynamicImport();\n\n const viteConfigPath = normalizeViteConfigFilePath(\n context.root,\n projectRoot,\n options.configFile\n );\n\n if (!viteConfigPath) {\n throw new Error(\n stripIndents`\n Unable to load test config from config file ${viteConfigPath}.\n \n Please make sure that vitest is configured correctly, \n or use the @nx/vite:vitest generator to configure it for you.\n You can read more here: https://nx.dev/nx-api/vite/generators/vitest\n `\n );\n }\n\n const resolved = await loadConfigFromFile(\n {\n mode: options?.mode ?? 'production',\n command: 'serve',\n },\n viteConfigPath\n );\n\n if (!viteConfigPath || !resolved?.config?.['test']) {\n logger.warn(stripIndents`Unable to load test config from config file ${\n resolved?.path ?? viteConfigPath\n }\n Some settings may not be applied as expected.\n You can manually set the config in the project, ${\n context.projectName\n }, configuration.\n `);\n }\n const root =\n projectRoot === '.'\n ? process.cwd()\n : relative(context.cwd, joinPathFragments(context.root, projectRoot));\n\n const { parseCLI } = await loadVitestDynamicImport();\n\n const {\n options: { watch, ...normalizedExtraArgs },\n } = parseCLI(['vitest', ...getOptionsAsArgv(options)]);\n\n const settings = {\n // Explicitly set watch mode to false if not provided otherwise vitest\n // will enable watch mode by default for non CI environments\n watch: watch ?? false,\n ...normalizedExtraArgs,\n // This should not be needed as it's going to be set in vite.config.ts\n // but leaving it here in case someone did not migrate correctly\n root: resolved.config.root ?? root,\n config: viteConfigPath,\n };\n\n return mergeConfig(resolved?.config?.['test'] ?? {}, settings);\n}\n\nexport function getOptionsAsArgv(obj: Record<string, any>): string[] {\n const argv: string[] = [];\n\n for (const [key, value] of Object.entries(obj)) {\n if (Array.isArray(value)) {\n value.forEach((item) => argv.push(`--${key}=${item}`));\n } else if (typeof value === 'object' && value !== null) {\n argv.push(`--${key}='${JSON.stringify(value)}'`);\n } else {\n argv.push(`--${key}=${value}`);\n }\n }\n\n return argv;\n}\n"],"names":["getOptions","getOptionsAsArgv","options","context","projectRoot","resolved","loadConfigFromFile","mergeConfig","loadViteDynamicImport","viteConfigPath","normalizeViteConfigFilePath","root","configFile","Error","stripIndents","mode","command","config","logger","warn","path","projectName","process","cwd","relative","joinPathFragments","parseCLI","loadVitestDynamicImport","watch","normalizedExtraArgs","settings","obj","argv","key","value","Object","entries","Array","isArray","forEach","item","push","JSON","stringify"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAcsBA,UAAU;eAAVA;;IAqENC,gBAAgB;eAAhBA;;;;;wBA9ET;8BAEqC;sBACnB;+BAIlB;AAEA,eAAeD,WACpBE,OAA8B,E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AAgE;QAChElB,MAAMN,CAAAA,wBAAAA,SAASY,MAAM,CAACN,IAAI,YAApBN,wBAAwBM;QAC9BM,QAAQR;;QAGSJ;IAAnB,OAAOE,YAAYF,CAAAA,wBAAAA,6BAAAA,oBAAAA,SAAUY,MAAM,qBAAhBZ,iBAAkB,CAAC,OAAO,YAA1BA,wBAA8B,CAAC,GAAGyB;AACvD;AAEO,SAAS7B,iBAAiB8B,GAAwB;IACvD,MAAMC,OAAiB,EAAE;IAEzB,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,KAAM;QAC9C,IAAIM,MAAMC,OAAO,CAACJ,QAAQ;YACxBA,MAAMK,OAAO,CAAC,CAACC,OAASR,KAAKS,IAAI,CAAC,CAAC,EAAE,EAAER,IAAI,CAAC,EAAEO,KAAK,CAAC;QACtD,OAAO,IAAI,OAAON,UAAU,YAAYA,UAAU,MAAM;YACtDF,KAAKS,IAAI,CAAC,CAAC,EAAE,EAAER,IAAI,EAAE,EAAES,KAAKC,SAAS,CAACT,OAAO,CAAC,CAAC;QACjD,OAAO;YACLF,KAAKS,IAAI,CAAC,CAAC,EAAE,EAAER,IAAI,CAAC,EAAEC,MAAM,CAAC;QAC/B;IACF;IAEA,OAAOF;AACT"}
@@ -20,7 +20,6 @@ const _extends = require("@swc/helpers/_/_extends");
20
20
  const _devkit = require("@nx/devkit");
21
21
  const _js = require("@nx/js");
22
22
  const _tssolutionsetup = require("@nx/js/src/utils/typescript/ts-solution-setup");
23
- const _versions = require("@nx/js/src/utils/versions");
24
23
  const _path = require("path");
25
24
  const _ensuredependencies = require("../../utils/ensure-dependencies");
26
25
  const _generatorutils = require("../../utils/generator-utils");
@@ -141,10 +140,9 @@ getTestBed().initTestEnvironment(
141
140
  nxJson.targetDefaults[testTarget].dependsOn.push('^build');
142
141
  (0, _devkit.updateNxJson)(tree, nxJson);
143
142
  }
144
- const devDependencies = await getCoverageProviderDependency(tree, schema.coverageProvider);
145
- devDependencies['@types/node'] = _versions.typesNodeVersion;
146
- const installDependenciesTask = (0, _devkit.addDependenciesToPackageJson)(tree, {}, devDependencies);
147
- tasks.push(installDependenciesTask);
143
+ const coverageProviderDependency = await getCoverageProviderDependency(tree, schema.coverageProvider);
144
+ const installCoverageProviderTask = (0, _devkit.addDependenciesToPackageJson)(tree, {}, coverageProviderDependency);
145
+ tasks.push(installCoverageProviderTask);
148
146
  // Setup workspace config file (https://vitest.dev/guide/workspace.html)
149
147
  if (!isRootProject && !tree.exists(`vitest.workspace.ts`) && !tree.exists(`vitest.workspace.js`) && !tree.exists(`vitest.workspace.json`) && !tree.exists(`vitest.projects.ts`) && !tree.exists(`vitest.projects.js`) && !tree.exists(`vitest.projects.json`)) {
150
148
  tree.write('vitest.workspace.ts', `export default ['**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'];`);