@nx/vite 20.0.0-beta.2 → 20.0.0-beta.4

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": "20.0.0-beta.2",
3
+ "version": "20.0.0-beta.4",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for building and testing applications using Vite",
6
6
  "repository": {
@@ -30,14 +30,14 @@
30
30
  "migrations": "./migrations.json"
31
31
  },
32
32
  "dependencies": {
33
- "@nx/devkit": "20.0.0-beta.2",
33
+ "@nx/devkit": "20.0.0-beta.4",
34
34
  "@phenomnomnominal/tsquery": "~5.0.1",
35
35
  "@swc/helpers": "~0.5.0",
36
36
  "enquirer": "~2.3.6",
37
- "@nx/js": "20.0.0-beta.2",
37
+ "@nx/js": "20.0.0-beta.4",
38
38
  "tsconfig-paths": "^4.1.2",
39
39
  "minimatch": "9.0.3",
40
- "@nrwl/vite": "20.0.0-beta.2"
40
+ "@nrwl/vite": "20.0.0-beta.4"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "vite": "^5.0.0",
@@ -47,8 +47,9 @@ _export(exports, {
47
47
  }
48
48
  });
49
49
  const _devkit = require("@nx/devkit");
50
- const _viteconfigeditutils = require("./vite-config-edit-utils");
51
50
  const _targetdefaultsutils = require("@nx/devkit/src/generators/target-defaults-utils");
51
+ const _tssolutionsetup = require("@nx/js/src/utils/typescript/ts-solution-setup");
52
+ const _viteconfigeditutils = require("./vite-config-edit-utils");
52
53
  function findExistingJsBuildTargetInProject(targets) {
53
54
  const output = {};
54
55
  const supportedExecutors = {
@@ -284,41 +285,39 @@ function moveAndEditIndexHtml(tree, options) {
284
285
  function createOrEditViteConfig(tree, options, onlyVitest, projectAlreadyHasViteTargets, vitestFileName) {
285
286
  const { root: projectRoot } = (0, _devkit.readProjectConfiguration)(tree, options.project);
286
287
  const viteConfigPath = vitestFileName ? `${projectRoot}/vitest.config.ts` : `${projectRoot}/vite.config.ts`;
287
- const buildOutDir = projectRoot === '.' ? `./dist/${options.project}` : `${(0, _devkit.offsetFromRoot)(projectRoot)}dist/${projectRoot}`;
288
+ const isUsingTsPlugin = (0, _tssolutionsetup.isUsingTsSolutionSetup)(tree);
289
+ const buildOutDir = isUsingTsPlugin ? './dist' : projectRoot === '.' ? `./dist/${options.project}` : `${(0, _devkit.offsetFromRoot)(projectRoot)}dist/${projectRoot}`;
288
290
  var _options_rollupOptionsExternal;
289
- const buildOption = onlyVitest ? '' : options.includeLib ? `
290
- // Configuration for building your library.
291
- // See: https://vitejs.dev/guide/build.html#library-mode
292
- build: {
293
- outDir: '${buildOutDir}',
294
- emptyOutDir: true,
295
- reportCompressedSize: true,
296
- commonjsOptions: {
297
- transformMixedEsModules: true,
298
- },
299
- lib: {
300
- // Could also be a dictionary or array of multiple entry points.
301
- entry: 'src/index.ts',
302
- name: '${options.project}',
303
- fileName: 'index',
304
- // Change this to the formats you want to support.
305
- // Don't forget to update your package.json as well.
306
- formats: ['es', 'cjs']
307
- },
308
- rollupOptions: {
309
- // External packages that should not be bundled into your library.
310
- external: [${(_options_rollupOptionsExternal = options.rollupOptionsExternal) != null ? _options_rollupOptionsExternal : ''}]
311
- },
312
- },` : `
313
- build: {
314
- outDir: '${buildOutDir}',
315
- emptyOutDir: true,
316
- reportCompressedSize: true,
317
- commonjsOptions: {
318
- transformMixedEsModules: true,
319
- },
291
+ const buildOption = onlyVitest ? '' : options.includeLib ? ` // Configuration for building your library.
292
+ // See: https://vitejs.dev/guide/build.html#library-mode
293
+ build: {
294
+ outDir: '${buildOutDir}',
295
+ emptyOutDir: true,
296
+ reportCompressedSize: true,
297
+ commonjsOptions: {
298
+ transformMixedEsModules: true,
320
299
  },
321
- `;
300
+ lib: {
301
+ // Could also be a dictionary or array of multiple entry points.
302
+ entry: 'src/index.ts',
303
+ name: '${options.project}',
304
+ fileName: 'index',
305
+ // Change this to the formats you want to support.
306
+ // Don't forget to update your package.json as well.
307
+ formats: ['es', 'cjs']
308
+ },
309
+ rollupOptions: {
310
+ // External packages that should not be bundled into your library.
311
+ external: [${(_options_rollupOptionsExternal = options.rollupOptionsExternal) != null ? _options_rollupOptionsExternal : ''}]
312
+ },
313
+ },` : ` build: {
314
+ outDir: '${buildOutDir}',
315
+ emptyOutDir: true,
316
+ reportCompressedSize: true,
317
+ commonjsOptions: {
318
+ transformMixedEsModules: true,
319
+ },
320
+ },`;
322
321
  const imports = options.imports ? options.imports : [];
323
322
  if (!onlyVitest && options.includeLib) {
324
323
  imports.push(`import dts from 'vite-plugin-dts'`, `import * as path from 'path'`);
@@ -337,62 +336,54 @@ function createOrEditViteConfig(tree, options, onlyVitest, projectAlreadyHasVite
337
336
  }
338
337
  const reportsDirectory = projectRoot === '.' ? `./coverage/${options.project}` : `${(0, _devkit.offsetFromRoot)(projectRoot)}coverage/${projectRoot}`;
339
338
  var _options_testEnvironment;
340
- const testOption = options.includeVitest ? `test: {
339
+ const testOption = options.includeVitest ? ` test: {
341
340
  watch: false,
342
341
  globals: true,
343
342
  environment: '${(_options_testEnvironment = options.testEnvironment) != null ? _options_testEnvironment : 'jsdom'}',
344
- include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
345
- ${options.inSourceTests ? `includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],` : ''}
343
+ include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],${options.inSourceTests ? `
344
+ includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],` : ''}
346
345
  reporters: ['default'],
347
346
  coverage: {
348
347
  reportsDirectory: '${reportsDirectory}',
349
348
  provider: ${options.coverageProvider ? `'${options.coverageProvider}'` : `'v8'`},
350
349
  }
351
350
  },` : '';
352
- const defineOption = options.inSourceTests ? `define: {
351
+ const defineOption = options.inSourceTests ? ` define: {
353
352
  'import.meta.vitest': undefined
354
353
  },` : '';
355
- const devServerOption = onlyVitest ? '' : options.includeLib ? '' : `
356
- server:{
357
- port: 4200,
358
- host: 'localhost',
359
- },`;
360
- const previewServerOption = onlyVitest ? '' : options.includeLib ? '' : `
361
- preview:{
362
- port: 4300,
363
- host: 'localhost',
364
- },`;
365
- const workerOption = `
366
- // Uncomment this if you are using workers.
367
- // worker: {
368
- // plugins: [ nxViteTsPaths() ],
369
- // },`;
354
+ const devServerOption = onlyVitest ? '' : options.includeLib ? '' : ` server:{
355
+ port: 4200,
356
+ host: 'localhost',
357
+ },`;
358
+ const previewServerOption = onlyVitest ? '' : options.includeLib ? '' : ` preview:{
359
+ port: 4300,
360
+ host: 'localhost',
361
+ },`;
362
+ const workerOption = ` // Uncomment this if you are using workers.
363
+ // worker: {
364
+ // plugins: [ nxViteTsPaths() ],
365
+ // },`;
370
366
  const cacheDir = `cacheDir: '${normalizedJoinPaths((0, _devkit.offsetFromRoot)(projectRoot), 'node_modules', '.vite', projectRoot === '.' ? options.project : projectRoot)}',`;
371
367
  if (tree.exists(viteConfigPath)) {
372
368
  handleViteConfigFileExists(tree, viteConfigPath, options, buildOption, buildOutDir, imports, plugins, testOption, reportsDirectory, cacheDir, projectRoot, (0, _devkit.offsetFromRoot)(projectRoot), projectAlreadyHasViteTargets);
373
369
  return;
374
370
  }
375
- viteConfigContent = `
376
- /// <reference types='vitest' />
377
- import { defineConfig } from 'vite';
378
- ${imports.join(';\n')}${imports.length ? ';' : ''}
379
- import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
380
- import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
381
-
382
- export default defineConfig({
383
- root: __dirname,
384
- ${cacheDir}
385
- ${devServerOption}
386
- ${previewServerOption}
387
-
388
- plugins: [${plugins.join(',\n')}],
389
- ${workerOption}
390
- ${buildOption}
391
- ${defineOption}
392
- ${testOption}
393
- });`;
371
+ viteConfigContent = `/// <reference types='vitest' />
372
+ import { defineConfig } from 'vite';
373
+ ${imports.join(';\n')}${imports.length ? ';' : ''}
374
+ import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
375
+ import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
376
+
377
+ export default defineConfig({
378
+ root: __dirname,
379
+ ${printOptions(cacheDir, devServerOption, previewServerOption, ` plugins: [${plugins.join(', ')}],`, workerOption, buildOption, defineOption, testOption)}
380
+ });
381
+ `.replace(/\s+(?=(\n|$))/gm, '\n');
394
382
  tree.write(viteConfigPath, viteConfigContent);
395
383
  }
384
+ function printOptions(...options) {
385
+ return options.filter(Boolean).join('\n');
386
+ }
396
387
  function normalizeViteConfigFilePathWithTree(tree, projectRoot, configFile) {
397
388
  return configFile && tree.exists(configFile) ? configFile : tree.exists((0, _devkit.joinPathFragments)(`${projectRoot}/vite.config.ts`)) ? (0, _devkit.joinPathFragments)(`${projectRoot}/vite.config.ts`) : tree.exists((0, _devkit.joinPathFragments)(`${projectRoot}/vite.config.js`)) ? (0, _devkit.joinPathFragments)(`${projectRoot}/vite.config.js`) : undefined;
398
389
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../packages/vite/src/utils/generator-utils.ts"],"sourcesContent":["import {\n joinPathFragments,\n logger,\n offsetFromRoot,\n readJson,\n readProjectConfiguration,\n TargetConfiguration,\n Tree,\n updateProjectConfiguration,\n writeJson,\n} from '@nx/devkit';\nimport { ViteBuildExecutorOptions } from '../executors/build/schema';\nimport { VitePreviewServerExecutorOptions } from '../executors/preview-server/schema';\nimport { VitestExecutorOptions } from '../executors/test/schema';\nimport { ViteConfigurationGeneratorSchema } from '../generators/configuration/schema';\nimport { ensureViteConfigIsCorrect } from './vite-config-edit-utils';\nimport { addBuildTargetDefaults } from '@nx/devkit/src/generators/target-defaults-utils';\n\nexport type Target = 'build' | 'serve' | 'test' | 'preview';\nexport type TargetFlags = Partial<Record<Target, boolean>>;\nexport type UserProvidedTargetName = Partial<Record<Target, string>>;\nexport type ValidFoundTargetName = Partial<Record<Target, string>>;\n\nexport function findExistingJsBuildTargetInProject(targets: {\n [targetName: string]: TargetConfiguration;\n}): {\n supported?: string;\n unsupported?: string;\n} {\n const output: {\n supported?: string;\n unsupported?: string;\n } = {};\n\n const supportedExecutors = {\n build: ['@nx/js:babel', '@nx/js:swc', '@nx/rollup:rollup'],\n };\n const unsupportedExecutors = [\n '@nx/angular:ng-packagr-lite',\n '@nx/angular:package',\n '@nx/angular:webpack-browser',\n '@nx/esbuild:esbuild',\n '@nx/react-native:run-ios',\n '@nx/react-native:start',\n '@nx/react-native:run-android',\n '@nx/react-native:bundle',\n '@nx/react-native:build-android',\n '@nx/react-native:bundle',\n '@nx/next:build',\n '@nx/js:tsc',\n '@nrwl/angular:ng-packagr-lite',\n '@nrwl/angular:package',\n '@nrwl/angular:webpack-browser',\n '@nrwl/esbuild:esbuild',\n '@nrwl/react-native:run-ios',\n '@nrwl/react-native:start',\n '@nrwl/react-native:run-android',\n '@nrwl/react-native:bundle',\n '@nrwl/react-native:build-android',\n '@nrwl/react-native:bundle',\n '@nrwl/next:build',\n '@nrwl/js:tsc',\n '@angular-devkit/build-angular:browser',\n '@angular-devkit/build-angular:browser-esbuild',\n '@angular-devkit/build-angular:application',\n ];\n\n // We try to find the target that is using the supported executors\n // for build since this is the one we will be converting\n for (const target in targets) {\n const executorName = targets[target].executor;\n if (supportedExecutors.build.includes(executorName)) {\n output.supported = target;\n } else if (unsupportedExecutors.includes(executorName)) {\n output.unsupported = target;\n }\n }\n return output;\n}\n\nexport function addOrChangeTestTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n target: string\n) {\n const project = readProjectConfiguration(tree, options.project);\n\n const reportsDirectory = joinPathFragments(\n offsetFromRoot(project.root),\n 'coverage',\n project.root === '.' ? options.project : project.root\n );\n const testOptions: VitestExecutorOptions = {\n reportsDirectory,\n };\n\n project.targets ??= {};\n\n if (project.targets[target]) {\n project.targets[target].executor = '@nx/vite:test';\n delete project.targets[target].options?.jestConfig;\n } else {\n project.targets[target] = {\n executor: '@nx/vite:test',\n outputs: ['{options.reportsDirectory}'],\n options: testOptions,\n };\n }\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\nexport function addBuildTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n target: string\n) {\n addBuildTargetDefaults(tree, '@nx/vite:build');\n const project = readProjectConfiguration(tree, options.project);\n const buildOptions: ViteBuildExecutorOptions = {\n outputPath: joinPathFragments(\n 'dist',\n project.root != '.' ? project.root : options.project\n ),\n };\n project.targets ??= {};\n project.targets[target] = {\n executor: '@nx/vite:build',\n outputs: ['{options.outputPath}'],\n defaultConfiguration: 'production',\n options: buildOptions,\n configurations: {\n development: {\n mode: 'development',\n },\n production: {\n mode: 'production',\n },\n },\n };\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\nexport function addServeTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n target: string\n) {\n const project = readProjectConfiguration(tree, options.project);\n\n project.targets ??= {};\n\n project.targets[target] = {\n executor: '@nx/vite:dev-server',\n defaultConfiguration: 'development',\n options: {\n buildTarget: `${options.project}:build`,\n },\n configurations: {\n development: {\n buildTarget: `${options.project}:build:development`,\n hmr: true,\n },\n production: {\n buildTarget: `${options.project}:build:production`,\n hmr: false,\n },\n },\n };\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\n/**\n * Adds a target for the preview server.\n *\n * @param tree\n * @param options\n * @param serveTarget An existing serve target.\n */\nexport function addPreviewTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n serveTarget: string\n) {\n const project = readProjectConfiguration(tree, options.project);\n\n const previewOptions: VitePreviewServerExecutorOptions = {\n buildTarget: `${options.project}:build`,\n };\n\n project.targets ??= {};\n\n // Update the options from the passed serve target.\n if (project.targets[serveTarget]) {\n const target = project.targets[serveTarget];\n if (target.executor === '@nxext/vite:dev') {\n previewOptions.proxyConfig = target.options.proxyConfig;\n }\n previewOptions['https'] = target.options?.https;\n previewOptions['open'] = target.options?.open;\n }\n\n // Adds a preview target.\n project.targets.preview = {\n dependsOn: ['build'],\n executor: '@nx/vite:preview-server',\n defaultConfiguration: 'development',\n options: previewOptions,\n configurations: {\n development: {\n buildTarget: `${options.project}:build:development`,\n },\n production: {\n buildTarget: `${options.project}:build:production`,\n },\n },\n };\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\nexport function editTsConfig(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema\n) {\n const projectConfig = readProjectConfiguration(tree, options.project);\n\n const config = readJson(tree, `${projectConfig.root}/tsconfig.json`);\n\n switch (options.uiFramework) {\n case 'react':\n config.compilerOptions = {\n jsx: 'react-jsx',\n allowJs: false,\n esModuleInterop: false,\n allowSyntheticDefaultImports: true,\n strict: true,\n };\n break;\n case 'none':\n config.compilerOptions = {\n module: 'commonjs',\n forceConsistentCasingInFileNames: true,\n strict: true,\n noImplicitOverride: true,\n noPropertyAccessFromIndexSignature: true,\n noImplicitReturns: true,\n noFallthroughCasesInSwitch: true,\n };\n break;\n default:\n break;\n }\n\n writeJson(tree, `${projectConfig.root}/tsconfig.json`, config);\n}\n\nexport function deleteWebpackConfig(\n tree: Tree,\n projectRoot: string,\n webpackConfigFilePath?: string\n) {\n const webpackConfigPath =\n webpackConfigFilePath && tree.exists(webpackConfigFilePath)\n ? webpackConfigFilePath\n : tree.exists(`${projectRoot}/webpack.config.js`)\n ? `${projectRoot}/webpack.config.js`\n : tree.exists(`${projectRoot}/webpack.config.ts`)\n ? `${projectRoot}/webpack.config.ts`\n : null;\n if (webpackConfigPath) {\n tree.delete(webpackConfigPath);\n }\n}\n\nexport function moveAndEditIndexHtml(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema\n) {\n const projectConfig = readProjectConfiguration(tree, options.project);\n\n let indexHtmlPath = `${projectConfig.root}/src/index.html`;\n let mainPath = `${projectConfig.root}/src/main.ts${\n options.uiFramework === 'react' ? 'x' : ''\n }`;\n\n if (projectConfig.root !== '.') {\n mainPath = mainPath.replace(projectConfig.root, '');\n }\n\n if (\n !tree.exists(indexHtmlPath) &&\n tree.exists(`${projectConfig.root}/index.html`)\n ) {\n indexHtmlPath = `${projectConfig.root}/index.html`;\n }\n\n if (tree.exists(indexHtmlPath)) {\n const indexHtmlContent = tree.read(indexHtmlPath, 'utf8');\n if (\n !indexHtmlContent.includes(\n `<script type='module' src='${mainPath}'></script>`\n )\n ) {\n tree.write(\n `${projectConfig.root}/index.html`,\n indexHtmlContent.replace(\n '</body>',\n `<script type='module' src='${mainPath}'></script>\n </body>`\n )\n );\n\n if (tree.exists(`${projectConfig.root}/src/index.html`)) {\n tree.delete(`${projectConfig.root}/src/index.html`);\n }\n }\n } else {\n tree.write(\n `${projectConfig.root}/index.html`,\n `<!DOCTYPE html>\n <html lang='en'>\n <head>\n <meta charset='UTF-8' />\n <link rel='icon' href='/favicon.ico' />\n <meta name='viewport' content='width=device-width, initial-scale=1.0' />\n <title>Vite</title>\n </head>\n <body>\n <div id='root'></div>\n <script type='module' src='${mainPath}'></script>\n </body>\n </html>`\n );\n }\n}\n\nexport interface ViteConfigFileOptions {\n project: string;\n includeLib?: boolean;\n includeVitest?: boolean;\n inSourceTests?: boolean;\n testEnvironment?: 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string;\n rollupOptionsExternal?: string[];\n imports?: string[];\n plugins?: string[];\n coverageProvider?: 'v8' | 'istanbul' | 'custom';\n}\n\nexport function createOrEditViteConfig(\n tree: Tree,\n options: ViteConfigFileOptions,\n onlyVitest: boolean,\n projectAlreadyHasViteTargets?: TargetFlags,\n vitestFileName?: boolean\n) {\n const { root: projectRoot } = readProjectConfiguration(tree, options.project);\n\n const viteConfigPath = vitestFileName\n ? `${projectRoot}/vitest.config.ts`\n : `${projectRoot}/vite.config.ts`;\n\n const buildOutDir =\n projectRoot === '.'\n ? `./dist/${options.project}`\n : `${offsetFromRoot(projectRoot)}dist/${projectRoot}`;\n\n const buildOption = onlyVitest\n ? ''\n : options.includeLib\n ? `\n // Configuration for building your library.\n // See: https://vitejs.dev/guide/build.html#library-mode\n build: {\n outDir: '${buildOutDir}',\n emptyOutDir: true,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n lib: {\n // Could also be a dictionary or array of multiple entry points.\n entry: 'src/index.ts',\n name: '${options.project}',\n fileName: 'index',\n // Change this to the formats you want to support.\n // Don't forget to update your package.json as well.\n formats: ['es', 'cjs']\n },\n rollupOptions: {\n // External packages that should not be bundled into your library.\n external: [${options.rollupOptionsExternal ?? ''}]\n },\n },`\n : `\n build: {\n outDir: '${buildOutDir}',\n emptyOutDir: true,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n },\n `;\n\n const imports: string[] = options.imports ? options.imports : [];\n\n if (!onlyVitest && options.includeLib) {\n imports.push(\n `import dts from 'vite-plugin-dts'`,\n `import * as path from 'path'`\n );\n }\n\n let viteConfigContent = '';\n\n const plugins = options.plugins\n ? [...options.plugins, `nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`]\n : [`nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`];\n\n if (!onlyVitest && options.includeLib) {\n plugins.push(\n `dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.lib.json') })`\n );\n }\n\n const reportsDirectory =\n projectRoot === '.'\n ? `./coverage/${options.project}`\n : `${offsetFromRoot(projectRoot)}coverage/${projectRoot}`;\n\n const testOption = options.includeVitest\n ? `test: {\n watch: false,\n globals: true,\n environment: '${options.testEnvironment ?? 'jsdom'}',\n include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n ${\n options.inSourceTests\n ? `includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],`\n : ''\n }\n reporters: ['default'],\n coverage: {\n reportsDirectory: '${reportsDirectory}',\n provider: ${\n options.coverageProvider ? `'${options.coverageProvider}'` : `'v8'`\n },\n }\n },`\n : '';\n\n const defineOption = options.inSourceTests\n ? `define: {\n 'import.meta.vitest': undefined\n },`\n : '';\n\n const devServerOption = onlyVitest\n ? ''\n : options.includeLib\n ? ''\n : `\n server:{\n port: 4200,\n host: 'localhost',\n },`;\n\n const previewServerOption = onlyVitest\n ? ''\n : options.includeLib\n ? ''\n : `\n preview:{\n port: 4300,\n host: 'localhost',\n },`;\n\n const workerOption = `\n // Uncomment this if you are using workers. \n // worker: {\n // plugins: [ nxViteTsPaths() ],\n // },`;\n\n const cacheDir = `cacheDir: '${normalizedJoinPaths(\n offsetFromRoot(projectRoot),\n 'node_modules',\n '.vite',\n projectRoot === '.' ? options.project : projectRoot\n )}',`;\n\n if (tree.exists(viteConfigPath)) {\n handleViteConfigFileExists(\n tree,\n viteConfigPath,\n options,\n buildOption,\n buildOutDir,\n imports,\n plugins,\n testOption,\n reportsDirectory,\n cacheDir,\n projectRoot,\n offsetFromRoot(projectRoot),\n projectAlreadyHasViteTargets\n );\n return;\n }\n\n viteConfigContent = `\n /// <reference types='vitest' />\n import { defineConfig } from 'vite';\n ${imports.join(';\\n')}${imports.length ? ';' : ''}\n import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\n import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';\n \n export default defineConfig({\n root: __dirname,\n ${cacheDir}\n ${devServerOption}\n ${previewServerOption}\n \n plugins: [${plugins.join(',\\n')}],\n ${workerOption}\n ${buildOption}\n ${defineOption}\n ${testOption}\n });`;\n\n tree.write(viteConfigPath, viteConfigContent);\n}\n\nexport function normalizeViteConfigFilePathWithTree(\n tree: Tree,\n projectRoot: string,\n configFile?: string\n): string {\n return configFile && tree.exists(configFile)\n ? configFile\n : tree.exists(joinPathFragments(`${projectRoot}/vite.config.ts`))\n ? joinPathFragments(`${projectRoot}/vite.config.ts`)\n : tree.exists(joinPathFragments(`${projectRoot}/vite.config.js`))\n ? joinPathFragments(`${projectRoot}/vite.config.js`)\n : undefined;\n}\n\nexport function getViteConfigPathForProject(\n tree: Tree,\n projectName: string,\n target?: string\n) {\n let viteConfigPath: string | undefined;\n const { targets, root } = readProjectConfiguration(tree, projectName);\n if (target) {\n viteConfigPath = targets?.[target]?.options?.configFile;\n } else {\n const config = Object.values(targets).find(\n (config) =>\n config.executor === '@nrwl/nx:build' ||\n config.executor === '@nrwl/vite:build'\n );\n viteConfigPath = config?.options?.configFile;\n }\n\n return normalizeViteConfigFilePathWithTree(tree, root, viteConfigPath);\n}\n\nexport async function handleUnsupportedUserProvidedTargets(\n userProvidedTargetIsUnsupported: TargetFlags,\n userProvidedTargetName: UserProvidedTargetName,\n validFoundTargetName: ValidFoundTargetName\n) {\n if (userProvidedTargetIsUnsupported.build && validFoundTargetName.build) {\n await handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName.build,\n validFoundTargetName.build,\n 'build',\n 'build'\n );\n }\n\n if (userProvidedTargetIsUnsupported.serve && validFoundTargetName.serve) {\n await handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName.serve,\n validFoundTargetName.serve,\n 'serve',\n 'dev-server'\n );\n }\n\n if (userProvidedTargetIsUnsupported.test && validFoundTargetName.test) {\n await handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName.test,\n validFoundTargetName.test,\n 'test',\n 'test'\n );\n }\n}\n\nasync function handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName: string,\n validFoundTargetName: string,\n target: Target,\n executor: 'build' | 'dev-server' | 'test'\n) {\n logger.warn(\n `The custom ${target} target you provided (${userProvidedTargetName}) cannot be converted to use the @nx/vite:${executor} executor.\n However, we found the following ${target} target in your project that can be converted: ${validFoundTargetName}\n\n Please note that converting a potentially non-compatible project to use Vite.js may result in unexpected behavior. Always commit\n your changes before converting a project to use Vite.js, and test the converted project thoroughly before deploying it.\n `\n );\n const { Confirm } = require('enquirer');\n const prompt = new Confirm({\n name: 'question',\n message: `Should we convert the ${validFoundTargetName} target to use the @nx/vite:${executor} executor?`,\n initial: true,\n });\n const shouldConvert = await prompt.run();\n if (!shouldConvert) {\n throw new Error(\n `The ${target} target ${userProvidedTargetName} cannot be converted to use the @nx/vite:${executor} executor.\n Please try again, either by providing a different ${target} target or by not providing a target at all (Nx will\n convert the first one it finds, most probably this one: ${validFoundTargetName})\n\n Please note that converting a potentially non-compatible project to use Vite.js may result in unexpected behavior. Always commit\n your changes before converting a project to use Vite.js, and test the converted project thoroughly before deploying it.\n `\n );\n }\n}\n\nexport async function handleUnknownConfiguration(projectName: string) {\n if (process.env.NX_INTERACTIVE === 'false') {\n return;\n }\n\n logger.warn(\n `\n We could not find any configuration in project ${projectName} that \n indicates whether we can definitely convert to Vite.\n \n If you still want to convert your project to use Vite,\n please make sure to commit your changes before running this generator.\n `\n );\n\n const { Confirm } = require('enquirer');\n const prompt = new Confirm({\n name: 'question',\n message: `Should Nx convert your project to use Vite?`,\n initial: true,\n });\n const shouldConvert = await prompt.run();\n if (!shouldConvert) {\n throw new Error(`\n Nx could not verify that your project can be converted to use Vite.\n Please try again with a different project.\n `);\n }\n}\n\nfunction handleViteConfigFileExists(\n tree: Tree,\n viteConfigPath: string,\n options: ViteConfigFileOptions,\n buildOption: string,\n buildOutDir: string,\n imports: string[],\n plugins: string[],\n testOption: string,\n reportsDirectory: string,\n cacheDir: string,\n projectRoot: string,\n offsetFromRoot: string,\n projectAlreadyHasViteTargets?: TargetFlags\n) {\n if (\n projectAlreadyHasViteTargets?.build &&\n projectAlreadyHasViteTargets?.test\n ) {\n return;\n }\n\n if (process.env.NX_VERBOSE_LOGGING === 'true') {\n logger.info(\n `vite.config.ts already exists for project ${options.project}.`\n );\n }\n\n const buildOptionObject = options.includeLib\n ? {\n lib: {\n entry: 'src/index.ts',\n name: options.project,\n fileName: 'index',\n formats: ['es', 'cjs'],\n },\n rollupOptions: {\n external: options.rollupOptionsExternal ?? [],\n },\n outDir: buildOutDir,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n }\n : {\n outDir: buildOutDir,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n };\n\n const testOptionObject = {\n globals: true,\n environment: options.testEnvironment ?? 'jsdom',\n include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n reporters: ['default'],\n coverage: {\n reportsDirectory: reportsDirectory,\n provider: `${options.coverageProvider ?? 'v8'}`,\n },\n };\n\n const changed = ensureViteConfigIsCorrect(\n tree,\n viteConfigPath,\n buildOption,\n buildOptionObject,\n imports,\n plugins,\n testOption,\n testOptionObject,\n cacheDir,\n projectAlreadyHasViteTargets ?? {}\n );\n\n if (!changed) {\n logger.warn(\n `Make sure the following setting exists in your Vite configuration file (${viteConfigPath}):\n \n ${buildOption}\n \n `\n );\n }\n}\n\nfunction normalizedJoinPaths(...paths: string[]): string {\n const path = joinPathFragments(...paths);\n\n return path.startsWith('.') ? path : `./${path}`;\n}\n"],"names":["addBuildTarget","addOrChangeTestTarget","addPreviewTarget","addServeTarget","createOrEditViteConfig","deleteWebpackConfig","editTsConfig","findExistingJsBuildTargetInProject","getViteConfigPathForProject","handleUnknownConfiguration","handleUnsupportedUserProvidedTargets","moveAndEditIndexHtml","normalizeViteConfigFilePathWithTree","targets","output","supportedExecutors","build","unsupportedExecutors","target","executorName","executor","includes","supported","unsupported","tree","options","project","readProjectConfiguration","reportsDirectory","joinPathFragments","offsetFromRoot","root","testOptions","jestConfig","outputs","updateProjectConfiguration","addBuildTargetDefaults","buildOptions","outputPath","defaultConfiguration","configurations","development","mode","production","buildTarget","hmr","serveTarget","previewOptions","proxyConfig","https","open","preview","dependsOn","projectConfig","config","readJson","uiFramework","compilerOptions","jsx","allowJs","esModuleInterop","allowSyntheticDefaultImports","strict","module","forceConsistentCasingInFileNames","noImplicitOverride","noPropertyAccessFromIndexSignature","noImplicitReturns","noFallthroughCasesInSwitch","writeJson","projectRoot","webpackConfigFilePath","webpackConfigPath","exists","delete","indexHtmlPath","mainPath","replace","indexHtmlContent","read","write","onlyVitest","projectAlreadyHasViteTargets","vitestFileName","viteConfigPath","buildOutDir","buildOption","includeLib","rollupOptionsExternal","imports","push","viteConfigContent","plugins","testOption","includeVitest","testEnvironment","inSourceTests","coverageProvider","defineOption","devServerOption","previewServerOption","workerOption","cacheDir","normalizedJoinPaths","handleViteConfigFileExists","join","length","configFile","undefined","projectName","Object","values","find","userProvidedTargetIsUnsupported","userProvidedTargetName","validFoundTargetName","handleUnsupportedUserProvidedTargetsErrors","serve","test","logger","warn","Confirm","require","prompt","name","message","initial","shouldConvert","run","Error","process","env","NX_INTERACTIVE","NX_VERBOSE_LOGGING","info","buildOptionObject","lib","entry","fileName","formats","rollupOptions","external","outDir","reportCompressedSize","commonjsOptions","transformMixedEsModules","testOptionObject","globals","environment","include","reporters","coverage","provider","changed","ensureViteConfigIsCorrect","paths","path","startsWith"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAgHgBA,cAAc;eAAdA;;IAhC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MyH,mBAAmB;QACvBC,SAAS;QACTC,aAAa3H,CAAAA,2BAAAA,QAAQsE,eAAe,YAAvBtE,2BAA2B;QACxC4H,SAAS;YAAC;SAAuD;QACjEC,WAAW;YAAC;SAAU;QACtBC,UAAU;YACR3H,kBAAkBA;YAClB4H,UAAU,CAAC,EAAE/H,CAAAA,4BAAAA,QAAQwE,gBAAgB,YAAxBxE,4BAA4B,KAAK,CAAC;QACjD;IACF;IAEA,MAAMgI,UAAUC,IAAAA,8CAAyB,EACvClI,MACA4D,gBACAE,aACAiD,mBACA9C,SACAG,SACAC,YACAqD,kBACA5C,UACApB,uCAAAA,+BAAgC,CAAC;IAGnC,IAAI,CAACuE,SAAS;QACZlC,cAAM,CAACC,IAAI,CACT,CAAC,wEAAwE,EAAEpC,eAAe;;QAExF,EAAEE,YAAY;;QAEd,CAAC;IAEP;AACF;AAEA,SAASiB,oBAAoB,GAAGoD,KAAe;IAC7C,MAAMC,OAAO/H,IAAAA,yBAAiB,KAAI8H;IAElC,OAAOC,KAAKC,UAAU,CAAC,OAAOD,OAAO,CAAC,EAAE,EAAEA,KAAK,CAAC;AAClD"}
1
+ {"version":3,"sources":["../../../../../packages/vite/src/utils/generator-utils.ts"],"sourcesContent":["import {\n joinPathFragments,\n logger,\n offsetFromRoot,\n readJson,\n readProjectConfiguration,\n TargetConfiguration,\n Tree,\n updateProjectConfiguration,\n writeJson,\n} from '@nx/devkit';\nimport { addBuildTargetDefaults } from '@nx/devkit/src/generators/target-defaults-utils';\nimport { isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\nimport { ViteBuildExecutorOptions } from '../executors/build/schema';\nimport { VitePreviewServerExecutorOptions } from '../executors/preview-server/schema';\nimport { VitestExecutorOptions } from '../executors/test/schema';\nimport { ViteConfigurationGeneratorSchema } from '../generators/configuration/schema';\nimport { ensureViteConfigIsCorrect } from './vite-config-edit-utils';\n\nexport type Target = 'build' | 'serve' | 'test' | 'preview';\nexport type TargetFlags = Partial<Record<Target, boolean>>;\nexport type UserProvidedTargetName = Partial<Record<Target, string>>;\nexport type ValidFoundTargetName = Partial<Record<Target, string>>;\n\nexport function findExistingJsBuildTargetInProject(targets: {\n [targetName: string]: TargetConfiguration;\n}): {\n supported?: string;\n unsupported?: string;\n} {\n const output: {\n supported?: string;\n unsupported?: string;\n } = {};\n\n const supportedExecutors = {\n build: ['@nx/js:babel', '@nx/js:swc', '@nx/rollup:rollup'],\n };\n const unsupportedExecutors = [\n '@nx/angular:ng-packagr-lite',\n '@nx/angular:package',\n '@nx/angular:webpack-browser',\n '@nx/esbuild:esbuild',\n '@nx/react-native:run-ios',\n '@nx/react-native:start',\n '@nx/react-native:run-android',\n '@nx/react-native:bundle',\n '@nx/react-native:build-android',\n '@nx/react-native:bundle',\n '@nx/next:build',\n '@nx/js:tsc',\n '@nrwl/angular:ng-packagr-lite',\n '@nrwl/angular:package',\n '@nrwl/angular:webpack-browser',\n '@nrwl/esbuild:esbuild',\n '@nrwl/react-native:run-ios',\n '@nrwl/react-native:start',\n '@nrwl/react-native:run-android',\n '@nrwl/react-native:bundle',\n '@nrwl/react-native:build-android',\n '@nrwl/react-native:bundle',\n '@nrwl/next:build',\n '@nrwl/js:tsc',\n '@angular-devkit/build-angular:browser',\n '@angular-devkit/build-angular:browser-esbuild',\n '@angular-devkit/build-angular:application',\n ];\n\n // We try to find the target that is using the supported executors\n // for build since this is the one we will be converting\n for (const target in targets) {\n const executorName = targets[target].executor;\n if (supportedExecutors.build.includes(executorName)) {\n output.supported = target;\n } else if (unsupportedExecutors.includes(executorName)) {\n output.unsupported = target;\n }\n }\n return output;\n}\n\nexport function addOrChangeTestTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n target: string\n) {\n const project = readProjectConfiguration(tree, options.project);\n\n const reportsDirectory = joinPathFragments(\n offsetFromRoot(project.root),\n 'coverage',\n project.root === '.' ? options.project : project.root\n );\n const testOptions: VitestExecutorOptions = {\n reportsDirectory,\n };\n\n project.targets ??= {};\n\n if (project.targets[target]) {\n project.targets[target].executor = '@nx/vite:test';\n delete project.targets[target].options?.jestConfig;\n } else {\n project.targets[target] = {\n executor: '@nx/vite:test',\n outputs: ['{options.reportsDirectory}'],\n options: testOptions,\n };\n }\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\nexport function addBuildTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n target: string\n) {\n addBuildTargetDefaults(tree, '@nx/vite:build');\n const project = readProjectConfiguration(tree, options.project);\n const buildOptions: ViteBuildExecutorOptions = {\n outputPath: joinPathFragments(\n 'dist',\n project.root != '.' ? project.root : options.project\n ),\n };\n project.targets ??= {};\n project.targets[target] = {\n executor: '@nx/vite:build',\n outputs: ['{options.outputPath}'],\n defaultConfiguration: 'production',\n options: buildOptions,\n configurations: {\n development: {\n mode: 'development',\n },\n production: {\n mode: 'production',\n },\n },\n };\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\nexport function addServeTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n target: string\n) {\n const project = readProjectConfiguration(tree, options.project);\n\n project.targets ??= {};\n\n project.targets[target] = {\n executor: '@nx/vite:dev-server',\n defaultConfiguration: 'development',\n options: {\n buildTarget: `${options.project}:build`,\n },\n configurations: {\n development: {\n buildTarget: `${options.project}:build:development`,\n hmr: true,\n },\n production: {\n buildTarget: `${options.project}:build:production`,\n hmr: false,\n },\n },\n };\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\n/**\n * Adds a target for the preview server.\n *\n * @param tree\n * @param options\n * @param serveTarget An existing serve target.\n */\nexport function addPreviewTarget(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema,\n serveTarget: string\n) {\n const project = readProjectConfiguration(tree, options.project);\n\n const previewOptions: VitePreviewServerExecutorOptions = {\n buildTarget: `${options.project}:build`,\n };\n\n project.targets ??= {};\n\n // Update the options from the passed serve target.\n if (project.targets[serveTarget]) {\n const target = project.targets[serveTarget];\n if (target.executor === '@nxext/vite:dev') {\n previewOptions.proxyConfig = target.options.proxyConfig;\n }\n previewOptions['https'] = target.options?.https;\n previewOptions['open'] = target.options?.open;\n }\n\n // Adds a preview target.\n project.targets.preview = {\n dependsOn: ['build'],\n executor: '@nx/vite:preview-server',\n defaultConfiguration: 'development',\n options: previewOptions,\n configurations: {\n development: {\n buildTarget: `${options.project}:build:development`,\n },\n production: {\n buildTarget: `${options.project}:build:production`,\n },\n },\n };\n\n updateProjectConfiguration(tree, options.project, project);\n}\n\nexport function editTsConfig(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema\n) {\n const projectConfig = readProjectConfiguration(tree, options.project);\n\n const config = readJson(tree, `${projectConfig.root}/tsconfig.json`);\n\n switch (options.uiFramework) {\n case 'react':\n config.compilerOptions = {\n jsx: 'react-jsx',\n allowJs: false,\n esModuleInterop: false,\n allowSyntheticDefaultImports: true,\n strict: true,\n };\n break;\n case 'none':\n config.compilerOptions = {\n module: 'commonjs',\n forceConsistentCasingInFileNames: true,\n strict: true,\n noImplicitOverride: true,\n noPropertyAccessFromIndexSignature: true,\n noImplicitReturns: true,\n noFallthroughCasesInSwitch: true,\n };\n break;\n default:\n break;\n }\n\n writeJson(tree, `${projectConfig.root}/tsconfig.json`, config);\n}\n\nexport function deleteWebpackConfig(\n tree: Tree,\n projectRoot: string,\n webpackConfigFilePath?: string\n) {\n const webpackConfigPath =\n webpackConfigFilePath && tree.exists(webpackConfigFilePath)\n ? webpackConfigFilePath\n : tree.exists(`${projectRoot}/webpack.config.js`)\n ? `${projectRoot}/webpack.config.js`\n : tree.exists(`${projectRoot}/webpack.config.ts`)\n ? `${projectRoot}/webpack.config.ts`\n : null;\n if (webpackConfigPath) {\n tree.delete(webpackConfigPath);\n }\n}\n\nexport function moveAndEditIndexHtml(\n tree: Tree,\n options: ViteConfigurationGeneratorSchema\n) {\n const projectConfig = readProjectConfiguration(tree, options.project);\n\n let indexHtmlPath = `${projectConfig.root}/src/index.html`;\n let mainPath = `${projectConfig.root}/src/main.ts${\n options.uiFramework === 'react' ? 'x' : ''\n }`;\n\n if (projectConfig.root !== '.') {\n mainPath = mainPath.replace(projectConfig.root, '');\n }\n\n if (\n !tree.exists(indexHtmlPath) &&\n tree.exists(`${projectConfig.root}/index.html`)\n ) {\n indexHtmlPath = `${projectConfig.root}/index.html`;\n }\n\n if (tree.exists(indexHtmlPath)) {\n const indexHtmlContent = tree.read(indexHtmlPath, 'utf8');\n if (\n !indexHtmlContent.includes(\n `<script type='module' src='${mainPath}'></script>`\n )\n ) {\n tree.write(\n `${projectConfig.root}/index.html`,\n indexHtmlContent.replace(\n '</body>',\n `<script type='module' src='${mainPath}'></script>\n </body>`\n )\n );\n\n if (tree.exists(`${projectConfig.root}/src/index.html`)) {\n tree.delete(`${projectConfig.root}/src/index.html`);\n }\n }\n } else {\n tree.write(\n `${projectConfig.root}/index.html`,\n `<!DOCTYPE html>\n <html lang='en'>\n <head>\n <meta charset='UTF-8' />\n <link rel='icon' href='/favicon.ico' />\n <meta name='viewport' content='width=device-width, initial-scale=1.0' />\n <title>Vite</title>\n </head>\n <body>\n <div id='root'></div>\n <script type='module' src='${mainPath}'></script>\n </body>\n </html>`\n );\n }\n}\n\nexport interface ViteConfigFileOptions {\n project: string;\n includeLib?: boolean;\n includeVitest?: boolean;\n inSourceTests?: boolean;\n testEnvironment?: 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string;\n rollupOptionsExternal?: string[];\n imports?: string[];\n plugins?: string[];\n coverageProvider?: 'v8' | 'istanbul' | 'custom';\n}\n\nexport function createOrEditViteConfig(\n tree: Tree,\n options: ViteConfigFileOptions,\n onlyVitest: boolean,\n projectAlreadyHasViteTargets?: TargetFlags,\n vitestFileName?: boolean\n) {\n const { root: projectRoot } = readProjectConfiguration(tree, options.project);\n\n const viteConfigPath = vitestFileName\n ? `${projectRoot}/vitest.config.ts`\n : `${projectRoot}/vite.config.ts`;\n\n const isUsingTsPlugin = isUsingTsSolutionSetup(tree);\n const buildOutDir = isUsingTsPlugin\n ? './dist'\n : projectRoot === '.'\n ? `./dist/${options.project}`\n : `${offsetFromRoot(projectRoot)}dist/${projectRoot}`;\n\n const buildOption = onlyVitest\n ? ''\n : options.includeLib\n ? ` // Configuration for building your library.\n // See: https://vitejs.dev/guide/build.html#library-mode\n build: {\n outDir: '${buildOutDir}',\n emptyOutDir: true,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n lib: {\n // Could also be a dictionary or array of multiple entry points.\n entry: 'src/index.ts',\n name: '${options.project}',\n fileName: 'index',\n // Change this to the formats you want to support.\n // Don't forget to update your package.json as well.\n formats: ['es', 'cjs']\n },\n rollupOptions: {\n // External packages that should not be bundled into your library.\n external: [${options.rollupOptionsExternal ?? ''}]\n },\n },`\n : ` build: {\n outDir: '${buildOutDir}',\n emptyOutDir: true,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n },`;\n\n const imports: string[] = options.imports ? options.imports : [];\n\n if (!onlyVitest && options.includeLib) {\n imports.push(\n `import dts from 'vite-plugin-dts'`,\n `import * as path from 'path'`\n );\n }\n\n let viteConfigContent = '';\n\n const plugins = options.plugins\n ? [...options.plugins, `nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`]\n : [`nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`];\n\n if (!onlyVitest && options.includeLib) {\n plugins.push(\n `dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.lib.json') })`\n );\n }\n\n const reportsDirectory =\n projectRoot === '.'\n ? `./coverage/${options.project}`\n : `${offsetFromRoot(projectRoot)}coverage/${projectRoot}`;\n\n const testOption = options.includeVitest\n ? ` test: {\n watch: false,\n globals: true,\n environment: '${options.testEnvironment ?? 'jsdom'}',\n include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],${\n options.inSourceTests\n ? `\n includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],`\n : ''\n }\n reporters: ['default'],\n coverage: {\n reportsDirectory: '${reportsDirectory}',\n provider: ${\n options.coverageProvider ? `'${options.coverageProvider}'` : `'v8'`\n },\n }\n },`\n : '';\n\n const defineOption = options.inSourceTests\n ? ` define: {\n 'import.meta.vitest': undefined\n },`\n : '';\n\n const devServerOption = onlyVitest\n ? ''\n : options.includeLib\n ? ''\n : ` server:{\n port: 4200,\n host: 'localhost',\n },`;\n\n const previewServerOption = onlyVitest\n ? ''\n : options.includeLib\n ? ''\n : ` preview:{\n port: 4300,\n host: 'localhost',\n },`;\n\n const workerOption = ` // Uncomment this if you are using workers.\n // worker: {\n // plugins: [ nxViteTsPaths() ],\n // },`;\n\n const cacheDir = `cacheDir: '${normalizedJoinPaths(\n offsetFromRoot(projectRoot),\n 'node_modules',\n '.vite',\n projectRoot === '.' ? options.project : projectRoot\n )}',`;\n\n if (tree.exists(viteConfigPath)) {\n handleViteConfigFileExists(\n tree,\n viteConfigPath,\n options,\n buildOption,\n buildOutDir,\n imports,\n plugins,\n testOption,\n reportsDirectory,\n cacheDir,\n projectRoot,\n offsetFromRoot(projectRoot),\n projectAlreadyHasViteTargets\n );\n return;\n }\n\n viteConfigContent = `/// <reference types='vitest' />\nimport { defineConfig } from 'vite';\n${imports.join(';\\n')}${imports.length ? ';' : ''}\nimport { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\nimport { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';\n\nexport default defineConfig({\n root: __dirname,\n ${printOptions(\n cacheDir,\n devServerOption,\n previewServerOption,\n ` plugins: [${plugins.join(', ')}],`,\n workerOption,\n buildOption,\n defineOption,\n testOption\n )}\n});\n`.replace(/\\s+(?=(\\n|$))/gm, '\\n');\n\n tree.write(viteConfigPath, viteConfigContent);\n}\n\nfunction printOptions(...options: string[]): string {\n return options.filter(Boolean).join('\\n');\n}\n\nexport function normalizeViteConfigFilePathWithTree(\n tree: Tree,\n projectRoot: string,\n configFile?: string\n): string {\n return configFile && tree.exists(configFile)\n ? configFile\n : tree.exists(joinPathFragments(`${projectRoot}/vite.config.ts`))\n ? joinPathFragments(`${projectRoot}/vite.config.ts`)\n : tree.exists(joinPathFragments(`${projectRoot}/vite.config.js`))\n ? joinPathFragments(`${projectRoot}/vite.config.js`)\n : undefined;\n}\n\nexport function getViteConfigPathForProject(\n tree: Tree,\n projectName: string,\n target?: string\n) {\n let viteConfigPath: string | undefined;\n const { targets, root } = readProjectConfiguration(tree, projectName);\n if (target) {\n viteConfigPath = targets?.[target]?.options?.configFile;\n } else {\n const config = Object.values(targets).find(\n (config) =>\n config.executor === '@nrwl/nx:build' ||\n config.executor === '@nrwl/vite:build'\n );\n viteConfigPath = config?.options?.configFile;\n }\n\n return normalizeViteConfigFilePathWithTree(tree, root, viteConfigPath);\n}\n\nexport async function handleUnsupportedUserProvidedTargets(\n userProvidedTargetIsUnsupported: TargetFlags,\n userProvidedTargetName: UserProvidedTargetName,\n validFoundTargetName: ValidFoundTargetName\n) {\n if (userProvidedTargetIsUnsupported.build && validFoundTargetName.build) {\n await handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName.build,\n validFoundTargetName.build,\n 'build',\n 'build'\n );\n }\n\n if (userProvidedTargetIsUnsupported.serve && validFoundTargetName.serve) {\n await handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName.serve,\n validFoundTargetName.serve,\n 'serve',\n 'dev-server'\n );\n }\n\n if (userProvidedTargetIsUnsupported.test && validFoundTargetName.test) {\n await handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName.test,\n validFoundTargetName.test,\n 'test',\n 'test'\n );\n }\n}\n\nasync function handleUnsupportedUserProvidedTargetsErrors(\n userProvidedTargetName: string,\n validFoundTargetName: string,\n target: Target,\n executor: 'build' | 'dev-server' | 'test'\n) {\n logger.warn(\n `The custom ${target} target you provided (${userProvidedTargetName}) cannot be converted to use the @nx/vite:${executor} executor.\n However, we found the following ${target} target in your project that can be converted: ${validFoundTargetName}\n\n Please note that converting a potentially non-compatible project to use Vite.js may result in unexpected behavior. Always commit\n your changes before converting a project to use Vite.js, and test the converted project thoroughly before deploying it.\n `\n );\n const { Confirm } = require('enquirer');\n const prompt = new Confirm({\n name: 'question',\n message: `Should we convert the ${validFoundTargetName} target to use the @nx/vite:${executor} executor?`,\n initial: true,\n });\n const shouldConvert = await prompt.run();\n if (!shouldConvert) {\n throw new Error(\n `The ${target} target ${userProvidedTargetName} cannot be converted to use the @nx/vite:${executor} executor.\n Please try again, either by providing a different ${target} target or by not providing a target at all (Nx will\n convert the first one it finds, most probably this one: ${validFoundTargetName})\n\n Please note that converting a potentially non-compatible project to use Vite.js may result in unexpected behavior. Always commit\n your changes before converting a project to use Vite.js, and test the converted project thoroughly before deploying it.\n `\n );\n }\n}\n\nexport async function handleUnknownConfiguration(projectName: string) {\n if (process.env.NX_INTERACTIVE === 'false') {\n return;\n }\n\n logger.warn(\n `\n We could not find any configuration in project ${projectName} that \n indicates whether we can definitely convert to Vite.\n \n If you still want to convert your project to use Vite,\n please make sure to commit your changes before running this generator.\n `\n );\n\n const { Confirm } = require('enquirer');\n const prompt = new Confirm({\n name: 'question',\n message: `Should Nx convert your project to use Vite?`,\n initial: true,\n });\n const shouldConvert = await prompt.run();\n if (!shouldConvert) {\n throw new Error(`\n Nx could not verify that your project can be converted to use Vite.\n Please try again with a different project.\n `);\n }\n}\n\nfunction handleViteConfigFileExists(\n tree: Tree,\n viteConfigPath: string,\n options: ViteConfigFileOptions,\n buildOption: string,\n buildOutDir: string,\n imports: string[],\n plugins: string[],\n testOption: string,\n reportsDirectory: string,\n cacheDir: string,\n projectRoot: string,\n offsetFromRoot: string,\n projectAlreadyHasViteTargets?: TargetFlags\n) {\n if (\n projectAlreadyHasViteTargets?.build &&\n projectAlreadyHasViteTargets?.test\n ) {\n return;\n }\n\n if (process.env.NX_VERBOSE_LOGGING === 'true') {\n logger.info(\n `vite.config.ts already exists for project ${options.project}.`\n );\n }\n\n const buildOptionObject = options.includeLib\n ? {\n lib: {\n entry: 'src/index.ts',\n name: options.project,\n fileName: 'index',\n formats: ['es', 'cjs'],\n },\n rollupOptions: {\n external: options.rollupOptionsExternal ?? [],\n },\n outDir: buildOutDir,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n }\n : {\n outDir: buildOutDir,\n reportCompressedSize: true,\n commonjsOptions: {\n transformMixedEsModules: true,\n },\n };\n\n const testOptionObject = {\n globals: true,\n environment: options.testEnvironment ?? 'jsdom',\n include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n reporters: ['default'],\n coverage: {\n reportsDirectory: reportsDirectory,\n provider: `${options.coverageProvider ?? 'v8'}`,\n },\n };\n\n const changed = ensureViteConfigIsCorrect(\n tree,\n viteConfigPath,\n buildOption,\n buildOptionObject,\n imports,\n plugins,\n testOption,\n testOptionObject,\n cacheDir,\n projectAlreadyHasViteTargets ?? {}\n );\n\n if (!changed) {\n logger.warn(\n `Make sure the following setting exists in your Vite configuration file (${viteConfigPath}):\n \n ${buildOption}\n \n `\n );\n }\n}\n\nfunction normalizedJoinPaths(...paths: string[]): string {\n const path = joinPathFragments(...paths);\n\n return path.startsWith('.') ? path : `./${path}`;\n}\n"],"names":["addBuildTarget","addOrChangeTestTarget","addPreviewTarget","addServeTarget","createOrEditViteConfig","deleteWebpackConfig","editTsConfig","findExistingJsBuildTargetInProject","getViteConfigPathForProject","handleUnknownConfiguration","handleUnsupportedUserProvidedTargets","moveAndEditIndexHtml","normalizeViteConfigFilePathWithTree","targets","output","supportedExecutors","build","unsupportedExecutors","target","executorName","executor","includes","supported","unsupported","tree","options","project","readProjectConfiguration","reportsDirectory","joinPathFragments","offsetFromRoot","root","testOptions","jestConfig","outputs","updateProjectConfiguration","addBuildTargetDefaults","buildOptions","outputPath","defaultConfiguration","configurations","development","mode","production","buildTarget","hmr","serveTarget","previewOptions","proxyConfig","https","open","preview","dependsOn","projectConfig","config","readJson","uiFramework","compilerOptions","jsx","allowJs","esModuleInterop","allowSyntheticDefaultImports","strict","module","forceConsistentCasingInFileNames","noImplicitOverride","noPropertyAccessFromIndexSignature","noImplicitReturns","noFallthroughCasesInSwitch","writeJson","projectRoot","webpackConfigFilePath","webpackConfigPath","exists","delete","indexHtmlPath","mainPath","replace","indexHtmlContent","read","write","onlyVitest","projectAlreadyHasViteTargets","vitestFileName","viteConfigPath","isUsingTsPlugin","isUsingTsSolutionSetup","buildOutDir","buildOption","includeLib","rollupOptionsExternal","imports","push","viteConfigContent","plugins","testOption","includeVitest","testEnvironment","inSourceTests","coverageProvider","defineOption","devServerOption","previewServerOption","workerOption","cacheDir","normalizedJoinPaths","handleViteConfigFileExists","join","length","printOptions","filter","Boolean","configFile","undefined","projectName","Object","values","find","userProvidedTargetIsUnsupported","userProvidedTargetName","validFoundTargetName","handleUnsupportedUserProvidedTargetsErrors","serve","test","logger","warn","Confirm","require","prompt","name","message","initial","shouldConvert","run","Error","process","env","NX_INTERACTIVE","NX_VERBOSE_LOGGING","info","buildOptionObject","lib","entry","fileName","formats","rollupOptions","external","outDir","reportCompressedSize","commonjsOptions","transformMixedEsModules","testOptionObject","globals","environment","include","reporters","coverage","provider","changed","ensureViteConfigIsCorrect","paths","path","startsWith"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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O;YACPb,MAAMxG,QAAQC,OAAO;YACrBqH,UAAU;YACVC,SAAS;gBAAC;gBAAM;aAAM;QACxB;QACAC,eAAe;YACbC,UAAUzH,CAAAA,iCAAAA,QAAQiE,qBAAqB,YAA7BjE,iCAAiC,EAAE;QAC/C;QACA0H,QAAQ5D;QACR6D,sBAAsB;QACtBC,iBAAiB;YACfC,yBAAyB;QAC3B;IACF,IACA;QACEH,QAAQ5D;QACR6D,sBAAsB;QACtBC,iBAAiB;YACfC,yBAAyB;QAC3B;IACF;QAIW7H,0BAKEA;IAPjB,MAAM8H,mBAAmB;QACvBC,SAAS;QACTC,aAAahI,CAAAA,2BAAAA,QAAQwE,eAAe,YAAvBxE,2BAA2B;QACxCiI,SAAS;YAAC;SAAuD;QACjEC,WAAW;YAAC;SAAU;QACtBC,UAAU;YACRhI,kBAAkBA;YAClBiI,UAAU,CAAC,EAAEpI,CAAAA,4BAAAA,QAAQ0E,gBAAgB,YAAxB1E,4BAA4B,KAAK,CAAC;QACjD;IACF;IAEA,MAAMqI,UAAUC,IAAAA,8CAAyB,EACvCvI,MACA4D,gBACAI,aACAoD,mBACAjD,SACAG,SACAC,YACAwD,kBACA/C,UACAtB,uCAAAA,+BAAgC,CAAC;IAGnC,IAAI,CAAC4E,SAAS;QACZlC,cAAM,CAACC,IAAI,CACT,CAAC,wEAAwE,EAAEzC,eAAe;;QAExF,EAAEI,YAAY;;QAEd,CAAC;IAEP;AACF;AAEA,SAASiB,oBAAoB,GAAGuD,KAAe;IAC7C,MAAMC,OAAOpI,IAAAA,yBAAiB,KAAImI;IAElC,OAAOC,KAAKC,UAAU,CAAC,OAAOD,OAAO,CAAC,EAAE,EAAEA,KAAK,CAAC;AAClD"}
@@ -38,15 +38,16 @@ function handleBuildOrTestNode(updatedFileContent, configContentString, configCo
38
38
  for (const prop of existingProperties){
39
39
  const propName = prop.name.getText();
40
40
  if (!configContentObject[propName] && propName !== 'dir' && propName !== 'reportsDirectory' && propName !== 'provider') {
41
- updatedPropsString += `'${propName}': ${prop.initializer.getText()},\n`;
41
+ // NOTE: Watch for formatting.
42
+ updatedPropsString += ` '${propName}': ${prop.initializer.getText()},\n`;
42
43
  }
43
44
  }
44
45
  for (const [propName, propValue] of Object.entries(configContentObject)){
45
- updatedPropsString += `'${propName}': ${JSON.stringify(propValue)},\n`;
46
+ // NOTE: Watch for formatting.
47
+ updatedPropsString += ` '${propName}': ${JSON.stringify(propValue)},\n`;
46
48
  }
47
49
  return `${name}: {
48
- ${updatedPropsString}
49
- }`;
50
+ ${updatedPropsString} }`;
50
51
  });
51
52
  } else {
52
53
  const foundDefineConfig = tsquery.query(updatedFileContent, 'CallExpression:has(Identifier[name="defineConfig"])');
@@ -180,11 +181,11 @@ function handlePluginNode(appFileContent, imports, plugins) {
180
181
  var _found__elements;
181
182
  const existingPluginNodes = (_found__elements = found == null ? void 0 : found[0].elements) != null ? _found__elements : [];
182
183
  for (const plugin of existingPluginNodes){
183
- updatedPluginsString += `${plugin.getText()},\n`;
184
+ updatedPluginsString += `${plugin.getText()}, `;
184
185
  }
185
186
  for (const plugin of plugins){
186
187
  if (!(existingPluginNodes == null ? void 0 : existingPluginNodes.some((node)=>node.getText().includes(plugin)))) {
187
- updatedPluginsString += `${plugin},\n`;
188
+ updatedPluginsString += `${plugin}, `;
188
189
  }
189
190
  }
190
191
  return `plugins: [${updatedPluginsString}]`;
@@ -207,7 +208,7 @@ function handlePluginNode(appFileContent, imports, plugins) {
207
208
  {
208
209
  type: _devkit.ChangeType.Insert,
209
210
  index: propertyAssignments[0].getStart(),
210
- text: `plugins: [${plugins.join(',\n')}],`
211
+ text: `plugins: [${plugins.join(', ')}],`
211
212
  }
212
213
  ]);
213
214
  writeFile = true;
@@ -216,7 +217,7 @@ function handlePluginNode(appFileContent, imports, plugins) {
216
217
  {
217
218
  type: _devkit.ChangeType.Insert,
218
219
  index: foundDefineConfig[0].getStart() + 14,
219
- text: `plugins: [${plugins.join(',\n')}],`
220
+ text: `plugins: [${plugins.join(', ')}],`
220
221
  }
221
222
  ]);
222
223
  writeFile = true;
@@ -233,7 +234,7 @@ function handlePluginNode(appFileContent, imports, plugins) {
233
234
  {
234
235
  type: _devkit.ChangeType.Insert,
235
236
  index: startOfObject + 1,
236
- text: `plugins: [${plugins.join(',\n')}],`
237
+ text: `plugins: [${plugins.join(', ')}],`
237
238
  }
238
239
  ]);
239
240
  writeFile = true;
@@ -244,7 +245,7 @@ function handlePluginNode(appFileContent, imports, plugins) {
244
245
  }
245
246
  if (writeFile) {
246
247
  const filteredImports = filterImport(appFileContent, imports);
247
- return filteredImports.join(';') + '\n' + appFileContent;
248
+ return filteredImports.join(';\n') + '\n' + appFileContent;
248
249
  }
249
250
  }
250
251
  function filterImport(appFileContent, imports) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../packages/vite/src/utils/vite-config-edit-utils.ts"],"sourcesContent":["import { applyChangesToString, ChangeType, Tree } from '@nx/devkit';\nimport { findNodes } from '@nx/js';\nimport { TargetFlags } from './generator-utils';\nimport type {\n ArrayLiteralExpression,\n Node,\n PropertyAssignment,\n ReturnStatement,\n} from 'typescript';\n\nexport function ensureViteConfigIsCorrect(\n tree: Tree,\n path: string,\n buildConfigString: string,\n buildConfigObject: {},\n imports: string[],\n plugins: string[],\n testConfigString: string,\n testConfigObject: {},\n cacheDir: string,\n projectAlreadyHasViteTargets?: TargetFlags\n): boolean {\n const fileContent = tree.read(path, 'utf-8');\n\n let updatedContent = undefined;\n\n if (!projectAlreadyHasViteTargets?.test && testConfigString?.length) {\n updatedContent = handleBuildOrTestNode(\n fileContent,\n testConfigString,\n testConfigObject,\n 'test'\n );\n }\n\n if (!projectAlreadyHasViteTargets?.build && buildConfigString?.length) {\n updatedContent = handleBuildOrTestNode(\n updatedContent ?? fileContent,\n buildConfigString,\n buildConfigObject,\n 'build'\n );\n }\n\n updatedContent =\n handlePluginNode(updatedContent ?? fileContent, imports, plugins) ??\n updatedContent;\n\n if (cacheDir?.length) {\n updatedContent = handleCacheDirNode(\n updatedContent ?? fileContent,\n cacheDir\n );\n }\n\n if (updatedContent) {\n tree.write(path, updatedContent);\n return true;\n } else {\n return false;\n }\n}\n\nfunction handleBuildOrTestNode(\n updatedFileContent: string,\n configContentString: string,\n configContentObject: {},\n name: 'build' | 'test'\n): string | undefined {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const buildOrTestNode = tsquery.query(\n updatedFileContent,\n `PropertyAssignment:has(Identifier[name=\"${name}\"])`\n );\n\n if (buildOrTestNode.length) {\n return tsquery.replace(\n updatedFileContent,\n `PropertyAssignment:has(Identifier[name=\"${name}\"])`,\n (node: PropertyAssignment) => {\n const existingProperties = tsquery.query(\n node.initializer,\n 'PropertyAssignment'\n ) as PropertyAssignment[];\n let updatedPropsString = '';\n for (const prop of existingProperties) {\n const propName = prop.name.getText();\n if (\n !configContentObject[propName] &&\n propName !== 'dir' &&\n propName !== 'reportsDirectory' &&\n propName !== 'provider'\n ) {\n updatedPropsString += `'${propName}': ${prop.initializer.getText()},\\n`;\n }\n }\n for (const [propName, propValue] of Object.entries(\n configContentObject\n )) {\n updatedPropsString += `'${propName}': ${JSON.stringify(\n propValue\n )},\\n`;\n }\n return `${name}: {\n ${updatedPropsString}\n }`;\n }\n );\n } else {\n const foundDefineConfig = tsquery.query(\n updatedFileContent,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n\n if (foundDefineConfig.length) {\n const conditionalConfig = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n\n if (conditionalConfig.length) {\n if (name === 'build') {\n return transformConditionalConfig(\n conditionalConfig,\n updatedFileContent,\n configContentString\n );\n } else {\n // no test config in conditional config\n return updatedFileContent;\n }\n } else {\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n return applyChangesToString(updatedFileContent, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: configContentString,\n },\n ]);\n } else {\n return applyChangesToString(updatedFileContent, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14,\n text: configContentString,\n },\n ]);\n }\n }\n } else {\n // build config does not exist and defineConfig is not used\n // could also potentially be invalid syntax, so try-catch\n try {\n const defaultExport = tsquery.query(\n updatedFileContent,\n 'ExportAssignment'\n );\n const found = tsquery.query(\n defaultExport?.[0],\n 'ObjectLiteralExpression'\n );\n const startOfObject = found?.[0].getStart();\n return applyChangesToString(updatedFileContent, [\n {\n type: ChangeType.Insert,\n index: startOfObject + 1,\n text: configContentString,\n },\n ]);\n } catch {\n return updatedFileContent;\n }\n }\n }\n}\n\nfunction transformCurrentBuildObject(\n index: number,\n returnStatements: ReturnStatement[],\n appFileContent: string,\n buildConfigObject: {}\n): string | undefined {\n if (!returnStatements?.[index]) {\n return undefined;\n }\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const currentBuildObject = tsquery\n .query(returnStatements[index], 'ObjectLiteralExpression')?.[0]\n .getText();\n\n const currentBuildObjectStart = returnStatements[index].getStart();\n const currentBuildObjectEnd = returnStatements[index].getEnd();\n const newReturnObject = tsquery.replace(\n returnStatements[index].getText(),\n 'ObjectLiteralExpression',\n (_node: Node) => {\n return `{\n ...${currentBuildObject},\n ...${JSON.stringify(buildConfigObject)}\n }`;\n }\n );\n\n const newContents = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Delete,\n start: currentBuildObjectStart,\n length: currentBuildObjectEnd - currentBuildObjectStart,\n },\n {\n type: ChangeType.Insert,\n index: currentBuildObjectStart,\n text: newReturnObject,\n },\n ]);\n\n return newContents;\n}\n\nfunction transformConditionalConfig(\n conditionalConfig: Node[],\n appFileContent: string,\n buildConfigObject: {}\n): string | undefined {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const { SyntaxKind } = require('typescript');\n const functionBlock = tsquery.query(conditionalConfig[0], 'Block');\n const ifStatement = tsquery.query(functionBlock?.[0], 'IfStatement');\n\n const binaryExpressions = tsquery.query(ifStatement?.[0], 'BinaryExpression');\n\n const buildExists = binaryExpressions?.find(\n (binaryExpression) => binaryExpression.getText() === `command === 'build'`\n );\n\n const buildExistsExpressionIndex = binaryExpressions?.findIndex(\n (binaryExpression) => binaryExpression.getText() === `command === 'build'`\n );\n\n const serveExists = binaryExpressions?.find(\n (binaryExpression) => binaryExpression.getText() === `command === 'serve'`\n );\n\n const elseKeywordExists = findNodes(ifStatement?.[0], SyntaxKind.ElseKeyword);\n const returnStatements: ReturnStatement[] = tsquery.query(\n ifStatement[0],\n 'ReturnStatement'\n );\n\n if (!buildExists) {\n if (serveExists && elseKeywordExists) {\n // build options live inside the else block\n return (\n transformCurrentBuildObject(\n returnStatements?.length - 1,\n returnStatements,\n appFileContent,\n buildConfigObject\n ) ?? appFileContent\n );\n } else {\n // no build options exist yet\n const functionBlockStart = functionBlock?.[0].getStart();\n const newContents = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: functionBlockStart + 1,\n text: `\n if (command === 'build') {\n return ${JSON.stringify(buildConfigObject)}\n }\n `,\n },\n ]);\n return newContents;\n }\n } else {\n // build already exists\n // it will be the return statement which lives\n // at the buildExistsExpressionIndex\n\n return (\n transformCurrentBuildObject(\n buildExistsExpressionIndex,\n returnStatements,\n appFileContent,\n buildConfigObject\n ) ?? appFileContent\n );\n }\n}\n\nfunction handlePluginNode(\n appFileContent: string,\n imports: string[],\n plugins: string[]\n): string | undefined {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const file = tsquery.ast(appFileContent);\n const pluginsNode = tsquery.query(\n file,\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])'\n );\n\n let writeFile = false;\n\n if (pluginsNode.length) {\n appFileContent = tsquery.replace(\n file.getText(),\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])',\n (node: Node) => {\n const found = tsquery.query(\n node,\n 'ArrayLiteralExpression'\n ) as ArrayLiteralExpression[];\n let updatedPluginsString = '';\n\n const existingPluginNodes = found?.[0].elements ?? [];\n\n for (const plugin of existingPluginNodes) {\n updatedPluginsString += `${plugin.getText()},\\n`;\n }\n\n for (const plugin of plugins) {\n if (\n !existingPluginNodes?.some((node) =>\n node.getText().includes(plugin)\n )\n ) {\n updatedPluginsString += `${plugin},\\n`;\n }\n }\n\n return `plugins: [${updatedPluginsString}]`;\n }\n );\n writeFile = true;\n } else {\n // Plugins node does not exist yet\n // So make one from scratch\n\n const foundDefineConfig = tsquery.query(\n file,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n\n if (foundDefineConfig.length) {\n const conditionalConfig = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n\n if (conditionalConfig.length) {\n // We are NOT transforming the conditional config\n // with plugins\n writeFile = false;\n } else {\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: `plugins: [${plugins.join(',\\n')}],`,\n },\n ]);\n writeFile = true;\n } else {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14,\n text: `plugins: [${plugins.join(',\\n')}],`,\n },\n ]);\n writeFile = true;\n }\n }\n } else {\n // Plugins option does not exist and defineConfig is not used\n // could also potentially be invalid syntax, so try-catch\n try {\n const defaultExport = tsquery.query(file, 'ExportAssignment');\n const found = tsquery?.query(\n defaultExport?.[0],\n 'ObjectLiteralExpression'\n );\n const startOfObject = found?.[0].getStart();\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: startOfObject + 1,\n text: `plugins: [${plugins.join(',\\n')}],`,\n },\n ]);\n writeFile = true;\n } catch {\n writeFile = false;\n }\n }\n }\n if (writeFile) {\n const filteredImports = filterImport(appFileContent, imports);\n return filteredImports.join(';') + '\\n' + appFileContent;\n }\n}\n\nfunction filterImport(appFileContent: string, imports: string[]): string[] {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const file = tsquery.ast(appFileContent);\n const importNodes = tsquery.query(\n file,\n ':matches(ImportDeclaration, VariableStatement)'\n );\n\n const importsArrayExisting = importNodes?.map((node) => {\n return node.getText().slice(0, -1);\n });\n\n return imports.filter((importString) => {\n return !importsArrayExisting?.includes(importString);\n });\n}\n\nfunction handleCacheDirNode(appFileContent: string, cacheDir: string): string {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n\n const file = tsquery.ast(appFileContent);\n const cacheDirNode = tsquery.query(\n file,\n 'PropertyAssignment:has(Identifier[name=\"cacheDir\"])'\n );\n\n if (!cacheDirNode?.length || cacheDirNode?.length === 0) {\n // cacheDir node does not exist yet\n // So make one from scratch\n\n const foundDefineConfig = tsquery.query(\n file,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n\n if (foundDefineConfig.length) {\n const conditionalConfig = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n\n if (conditionalConfig.length) {\n // We are NOT transforming the conditional config\n // with cacheDir\n } else {\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: cacheDir,\n },\n ]);\n } else {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14,\n text: cacheDir,\n },\n ]);\n }\n }\n } else {\n // cacheDir option does not exist and defineConfig is not used\n // could also potentially be invalid syntax, so try-catch\n try {\n const defaultExport = tsquery.query(file, 'ExportAssignment');\n const found = tsquery?.query(\n defaultExport?.[0],\n 'ObjectLiteralExpression'\n );\n const startOfObject = found?.[0].getStart();\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: startOfObject + 1,\n text: cacheDir,\n },\n ]);\n } catch {}\n }\n }\n\n return appFileContent;\n}\n"],"names":["ensureViteConfigIsCorrect","tree","path","buildConfigString","buildConfigObject","imports","plugins","testConfigString","testConfigObject","cacheDir","projectAlreadyHasViteTargets","fileContent","read","updatedContent","undefined","test","length","handleBuildOrTestNode","build","handlePluginNode","handleCacheDirNode","write","updatedFileContent","configContentString","configContentObject","name","tsquery","require","buildOrTestNode","query","replace","node","existingProperties","initializer","updatedPropsString","prop","propName","getText","propValue","Object","entries","JSON","stringify","foundDefineConfig","conditionalConfig","transformConditionalConfig","propertyAssignments","applyChangesToString","type","ChangeType","Insert","index","getStart","text","defaultExport","found","startOfObject","transformCurrentBuildObject","returnStatements","appFileContent","currentBuildObject","currentBuildObjectStart","currentBuildObjectEnd","getEnd","newReturnObject","_node","newContents","Delete","start","SyntaxKind","functionBlock","ifStatement","binaryExpressions","buildExists","find","binaryExpression","buildExistsExpressionIndex","findIndex","serveExists","elseKeywordExists","findNodes","ElseKeyword","functionBlockStart","file","ast","pluginsNode","writeFile","updatedPluginsString","existingPluginNodes","elements","plugin","some","includes","join","filteredImports","filterImport","importNodes","importsArrayExisting","map","slice","filter","importString","cacheDirNode"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";+BAUgBA;;;eAAAA;;;wBAVuC;oBAC7B;AASnB,SAASA,0BACdC,IAAU,EACVC,IAAY,EACZC,iBAAyB,EACzBC,iBAAqB,EACrBC,OAAiB,EACjBC,OAAiB,EACjBC,gBAAwB,EACxBC,gBAAoB,EACpBC,QAAg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5B,MAAM,EAAE;YAC5B,iDAAiD;YACjD,gBAAgB;YAClB,OAAO;gBACL,MAAM8B,sBAAsBpB,QAAQG,KAAK,CACvCc,iBAAiB,CAAC,EAAE,EACpB;gBAGF,IAAIG,oBAAoB9B,MAAM,EAAE;oBAC9B2C,iBAAiBZ,IAAAA,4BAAoB,EAACY,gBAAgB;wBACpD;4BACEX,MAAMC,kBAAU,CAACC,MAAM;4BACvBC,OAAOL,mBAAmB,CAAC,EAAE,CAACM,QAAQ;4BACtCC,MAAM5C;wBACR;qBACD;gBACH,OAAO;oBACLkD,iBAAiBZ,IAAAA,4BAAoB,EAACY,gBAAgB;wBACpD;4BACEX,MAAMC,kBAAU,CAACC,MAAM;4BACvBC,OAAOR,iBAAiB,CAAC,EAAE,CAACS,QAAQ,KAAK;4BACzCC,MAAM5C;wBACR;qBACD;gBACH;YACF;QACF,OAAO;YACL,8DAA8D;YAC9D,yDAAyD;YACzD,IAAI;gBACF,MAAM6C,gBAAgB5B,QAAQG,KAAK,CAACsD,MAAM;gBAC1C,MAAM5B,QAAQ7B,2BAAAA,QAASG,KAAK,CAC1ByB,iCAAAA,aAAe,CAAC,EAAE,EAClB;gBAEF,MAAME,gBAAgBD,yBAAAA,KAAO,CAAC,EAAE,CAACH,QAAQ;gBACzCO,iBAAiBZ,IAAAA,4BAAoB,EAACY,gBAAgB;oBACpD;wBACEX,MAAMC,kBAAU,CAACC,MAAM;wBACvBC,OAAOK,gBAAgB;wBACvBH,MAAM5C;oBACR;iBACD;YACH,EAAE,UAAM,CAAC;QACX;IACF;IAEA,OAAOkD;AACT"}
1
+ {"version":3,"sources":["../../../../../packages/vite/src/utils/vite-config-edit-utils.ts"],"sourcesContent":["import { applyChangesToString, ChangeType, Tree } from '@nx/devkit';\nimport { findNodes } from '@nx/js';\nimport { TargetFlags } from './generator-utils';\nimport type {\n ArrayLiteralExpression,\n Node,\n PropertyAssignment,\n ReturnStatement,\n} from 'typescript';\n\nexport function ensureViteConfigIsCorrect(\n tree: Tree,\n path: string,\n buildConfigString: string,\n buildConfigObject: {},\n imports: string[],\n plugins: string[],\n testConfigString: string,\n testConfigObject: {},\n cacheDir: string,\n projectAlreadyHasViteTargets?: TargetFlags\n): boolean {\n const fileContent = tree.read(path, 'utf-8');\n\n let updatedContent = undefined;\n\n if (!projectAlreadyHasViteTargets?.test && testConfigString?.length) {\n updatedContent = handleBuildOrTestNode(\n fileContent,\n testConfigString,\n testConfigObject,\n 'test'\n );\n }\n\n if (!projectAlreadyHasViteTargets?.build && buildConfigString?.length) {\n updatedContent = handleBuildOrTestNode(\n updatedContent ?? fileContent,\n buildConfigString,\n buildConfigObject,\n 'build'\n );\n }\n\n updatedContent =\n handlePluginNode(updatedContent ?? fileContent, imports, plugins) ??\n updatedContent;\n\n if (cacheDir?.length) {\n updatedContent = handleCacheDirNode(\n updatedContent ?? fileContent,\n cacheDir\n );\n }\n\n if (updatedContent) {\n tree.write(path, updatedContent);\n return true;\n } else {\n return false;\n }\n}\n\nfunction handleBuildOrTestNode(\n updatedFileContent: string,\n configContentString: string,\n configContentObject: {},\n name: 'build' | 'test'\n): string | undefined {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const buildOrTestNode = tsquery.query(\n updatedFileContent,\n `PropertyAssignment:has(Identifier[name=\"${name}\"])`\n );\n\n if (buildOrTestNode.length) {\n return tsquery.replace(\n updatedFileContent,\n `PropertyAssignment:has(Identifier[name=\"${name}\"])`,\n (node: PropertyAssignment) => {\n const existingProperties = tsquery.query(\n node.initializer,\n 'PropertyAssignment'\n ) as PropertyAssignment[];\n let updatedPropsString = '';\n for (const prop of existingProperties) {\n const propName = prop.name.getText();\n if (\n !configContentObject[propName] &&\n propName !== 'dir' &&\n propName !== 'reportsDirectory' &&\n propName !== 'provider'\n ) {\n // NOTE: Watch for formatting.\n updatedPropsString += ` '${propName}': ${prop.initializer.getText()},\\n`;\n }\n }\n for (const [propName, propValue] of Object.entries(\n configContentObject\n )) {\n // NOTE: Watch for formatting.\n updatedPropsString += ` '${propName}': ${JSON.stringify(\n propValue\n )},\\n`;\n }\n return `${name}: {\n${updatedPropsString} }`;\n }\n );\n } else {\n const foundDefineConfig = tsquery.query(\n updatedFileContent,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n\n if (foundDefineConfig.length) {\n const conditionalConfig = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n\n if (conditionalConfig.length) {\n if (name === 'build') {\n return transformConditionalConfig(\n conditionalConfig,\n updatedFileContent,\n configContentString\n );\n } else {\n // no test config in conditional config\n return updatedFileContent;\n }\n } else {\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n return applyChangesToString(updatedFileContent, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: configContentString,\n },\n ]);\n } else {\n return applyChangesToString(updatedFileContent, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14,\n text: configContentString,\n },\n ]);\n }\n }\n } else {\n // build config does not exist and defineConfig is not used\n // could also potentially be invalid syntax, so try-catch\n try {\n const defaultExport = tsquery.query(\n updatedFileContent,\n 'ExportAssignment'\n );\n const found = tsquery.query(\n defaultExport?.[0],\n 'ObjectLiteralExpression'\n );\n const startOfObject = found?.[0].getStart();\n return applyChangesToString(updatedFileContent, [\n {\n type: ChangeType.Insert,\n index: startOfObject + 1,\n text: configContentString,\n },\n ]);\n } catch {\n return updatedFileContent;\n }\n }\n }\n}\n\nfunction transformCurrentBuildObject(\n index: number,\n returnStatements: ReturnStatement[],\n appFileContent: string,\n buildConfigObject: {}\n): string | undefined {\n if (!returnStatements?.[index]) {\n return undefined;\n }\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const currentBuildObject = tsquery\n .query(returnStatements[index], 'ObjectLiteralExpression')?.[0]\n .getText();\n\n const currentBuildObjectStart = returnStatements[index].getStart();\n const currentBuildObjectEnd = returnStatements[index].getEnd();\n const newReturnObject = tsquery.replace(\n returnStatements[index].getText(),\n 'ObjectLiteralExpression',\n (_node: Node) => {\n return `{\n ...${currentBuildObject},\n ...${JSON.stringify(buildConfigObject)}\n }`;\n }\n );\n\n const newContents = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Delete,\n start: currentBuildObjectStart,\n length: currentBuildObjectEnd - currentBuildObjectStart,\n },\n {\n type: ChangeType.Insert,\n index: currentBuildObjectStart,\n text: newReturnObject,\n },\n ]);\n\n return newContents;\n}\n\nfunction transformConditionalConfig(\n conditionalConfig: Node[],\n appFileContent: string,\n buildConfigObject: {}\n): string | undefined {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const { SyntaxKind } = require('typescript');\n const functionBlock = tsquery.query(conditionalConfig[0], 'Block');\n const ifStatement = tsquery.query(functionBlock?.[0], 'IfStatement');\n\n const binaryExpressions = tsquery.query(ifStatement?.[0], 'BinaryExpression');\n\n const buildExists = binaryExpressions?.find(\n (binaryExpression) => binaryExpression.getText() === `command === 'build'`\n );\n\n const buildExistsExpressionIndex = binaryExpressions?.findIndex(\n (binaryExpression) => binaryExpression.getText() === `command === 'build'`\n );\n\n const serveExists = binaryExpressions?.find(\n (binaryExpression) => binaryExpression.getText() === `command === 'serve'`\n );\n\n const elseKeywordExists = findNodes(ifStatement?.[0], SyntaxKind.ElseKeyword);\n const returnStatements: ReturnStatement[] = tsquery.query(\n ifStatement[0],\n 'ReturnStatement'\n );\n\n if (!buildExists) {\n if (serveExists && elseKeywordExists) {\n // build options live inside the else block\n return (\n transformCurrentBuildObject(\n returnStatements?.length - 1,\n returnStatements,\n appFileContent,\n buildConfigObject\n ) ?? appFileContent\n );\n } else {\n // no build options exist yet\n const functionBlockStart = functionBlock?.[0].getStart();\n const newContents = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: functionBlockStart + 1,\n text: `\n if (command === 'build') {\n return ${JSON.stringify(buildConfigObject)}\n }\n `,\n },\n ]);\n return newContents;\n }\n } else {\n // build already exists\n // it will be the return statement which lives\n // at the buildExistsExpressionIndex\n\n return (\n transformCurrentBuildObject(\n buildExistsExpressionIndex,\n returnStatements,\n appFileContent,\n buildConfigObject\n ) ?? appFileContent\n );\n }\n}\n\nfunction handlePluginNode(\n appFileContent: string,\n imports: string[],\n plugins: string[]\n): string | undefined {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const file = tsquery.ast(appFileContent);\n const pluginsNode = tsquery.query(\n file,\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])'\n );\n\n let writeFile = false;\n\n if (pluginsNode.length) {\n appFileContent = tsquery.replace(\n file.getText(),\n 'PropertyAssignment:has(Identifier[name=\"plugins\"])',\n (node: Node) => {\n const found = tsquery.query(\n node,\n 'ArrayLiteralExpression'\n ) as ArrayLiteralExpression[];\n let updatedPluginsString = '';\n\n const existingPluginNodes = found?.[0].elements ?? [];\n\n for (const plugin of existingPluginNodes) {\n updatedPluginsString += `${plugin.getText()}, `;\n }\n\n for (const plugin of plugins) {\n if (\n !existingPluginNodes?.some((node) =>\n node.getText().includes(plugin)\n )\n ) {\n updatedPluginsString += `${plugin}, `;\n }\n }\n\n return `plugins: [${updatedPluginsString}]`;\n }\n );\n writeFile = true;\n } else {\n // Plugins node does not exist yet\n // So make one from scratch\n\n const foundDefineConfig = tsquery.query(\n file,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n\n if (foundDefineConfig.length) {\n const conditionalConfig = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n\n if (conditionalConfig.length) {\n // We are NOT transforming the conditional config\n // with plugins\n writeFile = false;\n } else {\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: `plugins: [${plugins.join(', ')}],`,\n },\n ]);\n writeFile = true;\n } else {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14,\n text: `plugins: [${plugins.join(', ')}],`,\n },\n ]);\n writeFile = true;\n }\n }\n } else {\n // Plugins option does not exist and defineConfig is not used\n // could also potentially be invalid syntax, so try-catch\n try {\n const defaultExport = tsquery.query(file, 'ExportAssignment');\n const found = tsquery?.query(\n defaultExport?.[0],\n 'ObjectLiteralExpression'\n );\n const startOfObject = found?.[0].getStart();\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: startOfObject + 1,\n text: `plugins: [${plugins.join(', ')}],`,\n },\n ]);\n writeFile = true;\n } catch {\n writeFile = false;\n }\n }\n }\n if (writeFile) {\n const filteredImports = filterImport(appFileContent, imports);\n return filteredImports.join(';\\n') + '\\n' + appFileContent;\n }\n}\n\nfunction filterImport(appFileContent: string, imports: string[]): string[] {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n const file = tsquery.ast(appFileContent);\n const importNodes = tsquery.query(\n file,\n ':matches(ImportDeclaration, VariableStatement)'\n );\n\n const importsArrayExisting = importNodes?.map((node) => {\n return node.getText().slice(0, -1);\n });\n\n return imports.filter((importString) => {\n return !importsArrayExisting?.includes(importString);\n });\n}\n\nfunction handleCacheDirNode(appFileContent: string, cacheDir: string): string {\n const { tsquery } = require('@phenomnomnominal/tsquery');\n\n const file = tsquery.ast(appFileContent);\n const cacheDirNode = tsquery.query(\n file,\n 'PropertyAssignment:has(Identifier[name=\"cacheDir\"])'\n );\n\n if (!cacheDirNode?.length || cacheDirNode?.length === 0) {\n // cacheDir node does not exist yet\n // So make one from scratch\n\n const foundDefineConfig = tsquery.query(\n file,\n 'CallExpression:has(Identifier[name=\"defineConfig\"])'\n );\n\n if (foundDefineConfig.length) {\n const conditionalConfig = tsquery.query(\n foundDefineConfig[0],\n 'ArrowFunction'\n );\n\n if (conditionalConfig.length) {\n // We are NOT transforming the conditional config\n // with cacheDir\n } else {\n const propertyAssignments = tsquery.query(\n foundDefineConfig[0],\n 'PropertyAssignment'\n );\n\n if (propertyAssignments.length) {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: propertyAssignments[0].getStart(),\n text: cacheDir,\n },\n ]);\n } else {\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: foundDefineConfig[0].getStart() + 14,\n text: cacheDir,\n },\n ]);\n }\n }\n } else {\n // cacheDir option does not exist and defineConfig is not used\n // could also potentially be invalid syntax, so try-catch\n try {\n const defaultExport = tsquery.query(file, 'ExportAssignment');\n const found = tsquery?.query(\n defaultExport?.[0],\n 'ObjectLiteralExpression'\n );\n const startOfObject = found?.[0].getStart();\n appFileContent = applyChangesToString(appFileContent, [\n {\n type: ChangeType.Insert,\n index: startOfObject + 1,\n text: cacheDir,\n },\n ]);\n } catch {}\n }\n }\n\n return appFileContent;\n}\n"],"names":["ensureViteConfigIsCorrect","tree","path","buildConfigString","buildConfigObject","imports","plugins","testConfigString","testConfigObject","cacheDir","projectAlreadyHasViteTargets","fileContent","read","updatedContent","undefined","test","length","handleBuildOrTestNode","build","handlePluginNode","handleCacheDirNode","write","updatedFileContent","configContentString","configContentObject","name","tsquery","require","buildOrTestNode","query","replace","node","existingProperties","initializer","updatedPropsString","prop","propName","getText","propValue","Object","entries","JSON","stringify","foundDefineConfig","conditionalConfig","transformConditionalConfig","propertyAssignments","applyChangesToString","type","ChangeType","Insert","index","getStart","text","defaultExport","found","startOfObject","transformCurrentBuildObject","returnStatements","appFileContent","currentBuildObject","currentBuildObjectStart","currentBuildObjectEnd","getEnd","newReturnObject","_node","newContents","Delete","start","SyntaxKind","functionBlock","ifStatement","binaryExpressions","buildExists","find","binaryExpression","buildExistsExpressionIndex","findIndex","serveExists","elseKeywordExists","findNodes","ElseKeyword","functionBlockStart","file","ast","pluginsNode","writeFile","updatedPluginsString","existingPluginNodes","elements","plugin","some","includes","join","filteredImports","filterImport","importNodes","importsArrayExisting","map","slice","filter","importString","cacheDirNode"],"rangeMappings":";;;;;;;;;;;;;;;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