@nx/vite 0.0.0-pr-29720-06f67e5 → 0.0.0-pr-3-4fa8cf8
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 +3 -3
- package/src/executors/test/lib/utils.js +9 -2
- package/src/executors/test/lib/utils.js.map +1 -1
- package/src/generators/vitest/vitest-generator.js +5 -3
- package/src/generators/vitest/vitest-generator.js.map +1 -1
- package/src/plugins/plugin.js +26 -7
- package/src/plugins/plugin.js.map +1 -1
- package/src/utils/e2e-web-server-info-utils.d.ts +1 -0
- package/src/utils/e2e-web-server-info-utils.js +27 -3
- package/src/utils/e2e-web-server-info-utils.js.map +1 -1
- package/src/utils/generator-utils.js +2 -2
- package/src/utils/generator-utils.js.map +1 -1
- package/src/utils/vite-config-edit-utils.js +11 -0
- package/src/utils/vite-config-edit-utils.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nx/vite",
|
|
3
|
-
"version": "0.0.0-pr-
|
|
3
|
+
"version": "0.0.0-pr-3-4fa8cf8",
|
|
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-
|
|
33
|
+
"@nx/devkit": "0.0.0-pr-3-4fa8cf8",
|
|
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-
|
|
37
|
+
"@nx/js": "0.0.0-pr-3-4fa8cf8",
|
|
38
38
|
"tsconfig-paths": "^4.1.2",
|
|
39
39
|
"minimatch": "9.0.3",
|
|
40
40
|
"semver": "^7.6.3"
|
|
@@ -53,16 +53,23 @@ 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
|
+
]);
|
|
56
60
|
var _resolved_config_root;
|
|
57
61
|
const settings = _extends._({
|
|
58
62
|
// Explicitly set watch mode to false if not provided otherwise vitest
|
|
59
63
|
// will enable watch mode by default for non CI environments
|
|
60
64
|
watch: watch != null ? watch : false
|
|
61
|
-
},
|
|
65
|
+
}, restNormalizedArgs, {
|
|
62
66
|
// This should not be needed as it's going to be set in vite.config.ts
|
|
63
67
|
// but leaving it here in case someone did not migrate correctly
|
|
64
68
|
root: (_resolved_config_root = resolved.config.root) != null ? _resolved_config_root : root,
|
|
65
|
-
config: viteConfigPath
|
|
69
|
+
config: viteConfigPath,
|
|
70
|
+
coverage: _extends._({}, coverage != null ? coverage : {}, reportsDirectory && {
|
|
71
|
+
reportsDirectory
|
|
72
|
+
})
|
|
66
73
|
});
|
|
67
74
|
var _resolved_config_test;
|
|
68
75
|
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 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 ...
|
|
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,IAAI,CAACA,kBAAkB,EAACJ,6BAAAA,mBAAAA,SAAUY,MAAM,qBAAhBZ,gBAAkB,CAAC,OAAO,GAAE;YAEhDA;QADFa,cAAM,CAACC,IAAI,CAACL,IAAAA,oBAAY,CAAA,CAAC,4CAA4C,EACnET,CAAAA,iBAAAA,4BAAAA,SAAUe,IAAI,Y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AAON,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,6 +20,7 @@ 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");
|
|
23
24
|
const _path = require("path");
|
|
24
25
|
const _ensuredependencies = require("../../utils/ensure-dependencies");
|
|
25
26
|
const _generatorutils = require("../../utils/generator-utils");
|
|
@@ -140,9 +141,10 @@ getTestBed().initTestEnvironment(
|
|
|
140
141
|
nxJson.targetDefaults[testTarget].dependsOn.push('^build');
|
|
141
142
|
(0, _devkit.updateNxJson)(tree, nxJson);
|
|
142
143
|
}
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
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);
|
|
146
148
|
// Setup workspace config file (https://vitest.dev/guide/workspace.html)
|
|
147
149
|
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`)) {
|
|
148
150
|
tree.write('vitest.workspace.ts', `export default ['**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'];`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/vite/src/generators/vitest/vitest-generator.ts"],"sourcesContent":["import {\n addDependenciesToPackageJson,\n formatFiles,\n generateFiles,\n GeneratorCallback,\n joinPathFragments,\n logger,\n offsetFromRoot,\n ProjectType,\n readJson,\n readNxJson,\n readProjectConfiguration,\n runTasksInSerial,\n Tree,\n updateJson,\n updateNxJson,\n} from '@nx/devkit';\nimport { initGenerator as jsInitGenerator } from '@nx/js';\nimport {\n getProjectType,\n isUsingTsSolutionSetup,\n} from '@nx/js/src/utils/typescript/ts-solution-setup';\nimport { join } from 'path';\nimport { ensureDependencies } from '../../utils/ensure-dependencies';\nimport {\n addOrChangeTestTarget,\n createOrEditViteConfig,\n} from '../../utils/generator-utils';\nimport initGenerator from '../init/init';\nimport { VitestGeneratorSchema } from './schema';\nimport { detectUiFramework } from '../../utils/detect-ui-framework';\nimport { getVitestDependenciesVersionsToInstall } from '../../utils/version-utils';\nimport { coerce, major } from 'semver';\n\n/**\n * @param hasPlugin some frameworks (e.g. Nuxt) provide their own plugin. Their generators handle the plugin detection.\n */\nexport function vitestGenerator(\n tree: Tree,\n schema: VitestGeneratorSchema,\n hasPlugin = false\n) {\n return vitestGeneratorInternal(\n tree,\n { addPlugin: false, ...schema },\n hasPlugin\n );\n}\n\nexport async function vitestGeneratorInternal(\n tree: Tree,\n schema: VitestGeneratorSchema,\n hasPlugin = false\n) {\n // Setting default to jsdom since it is the most common use case (React, Web).\n // The @nx/js:lib generator specifically sets this to node to be more generic.\n schema.testEnvironment ??= 'jsdom';\n\n const tasks: GeneratorCallback[] = [];\n\n const { root, projectType: _projectType } = readProjectConfiguration(\n tree,\n schema.project\n );\n const projectType = schema.projectType ?? _projectType;\n const uiFramework =\n schema.uiFramework ?? (await detectUiFramework(schema.project));\n const isRootProject = root === '.';\n\n tasks.push(await jsInitGenerator(tree, { ...schema, skipFormat: true }));\n\n const pkgJson = readJson(tree, 'package.json');\n const useVite5 =\n major(coerce(pkgJson.devDependencies['vite']) ?? '6.0.0') === 5;\n const initTask = await initGenerator(tree, {\n projectRoot: root,\n skipFormat: true,\n addPlugin: schema.addPlugin,\n useViteV5: useVite5,\n });\n tasks.push(initTask);\n tasks.push(ensureDependencies(tree, { ...schema, uiFramework }));\n\n addOrChangeTestTarget(tree, schema, hasPlugin);\n\n if (!schema.skipViteConfig) {\n if (uiFramework === 'angular') {\n const relativeTestSetupPath = joinPathFragments('src', 'test-setup.ts');\n\n const setupFile = joinPathFragments(root, relativeTestSetupPath);\n if (!tree.exists(setupFile)) {\n tree.write(\n setupFile,\n `import '@analogjs/vitest-angular/setup-zone';\n\nimport {\n BrowserDynamicTestingModule,\n platformBrowserDynamicTesting,\n} from '@angular/platform-browser-dynamic/testing';\nimport { getTestBed } from '@angular/core/testing';\n\ngetTestBed().initTestEnvironment(\n BrowserDynamicTestingModule,\n platformBrowserDynamicTesting()\n);\n`\n );\n }\n\n createOrEditViteConfig(\n tree,\n {\n project: schema.project,\n includeLib: false,\n includeVitest: true,\n inSourceTests: false,\n imports: [`import angular from '@analogjs/vite-plugin-angular'`],\n plugins: ['angular()'],\n setupFile: relativeTestSetupPath,\n useEsmExtension: true,\n },\n true\n );\n } else if (uiFramework === 'react') {\n createOrEditViteConfig(\n tree,\n {\n project: schema.project,\n includeLib: getProjectType(tree, root, projectType) === 'library',\n includeVitest: true,\n inSourceTests: schema.inSourceTests,\n rollupOptionsExternal: [\n \"'react'\",\n \"'react-dom'\",\n \"'react/jsx-runtime'\",\n ],\n imports: [\n schema.compiler === 'swc'\n ? `import react from '@vitejs/plugin-react-swc'`\n : `import react from '@vitejs/plugin-react'`,\n ],\n plugins: ['react()'],\n coverageProvider: schema.coverageProvider,\n },\n true\n );\n } else {\n createOrEditViteConfig(\n tree,\n {\n ...schema,\n includeVitest: true,\n includeLib: getProjectType(tree, root, projectType) === 'library',\n },\n true\n );\n }\n }\n\n const isTsSolutionSetup = isUsingTsSolutionSetup(tree);\n\n createFiles(tree, schema, root, isTsSolutionSetup);\n updateTsConfig(tree, schema, root, projectType);\n\n if (isTsSolutionSetup) {\n // in the TS solution setup, the test target depends on the build outputs\n // so we need to setup the task pipeline accordingly\n const nxJson = readNxJson(tree);\n const testTarget = schema.testTarget ?? 'test';\n nxJson.targetDefaults ??= {};\n nxJson.targetDefaults[testTarget] ??= {};\n nxJson.targetDefaults[testTarget].dependsOn ??= [];\n nxJson.targetDefaults[testTarget].dependsOn.push('^build');\n updateNxJson(tree, nxJson);\n }\n\n const coverageProviderDependency = await getCoverageProviderDependency(\n tree,\n schema.coverageProvider\n );\n\n const installCoverageProviderTask = addDependenciesToPackageJson(\n tree,\n {},\n coverageProviderDependency\n );\n tasks.push(installCoverageProviderTask);\n\n // Setup workspace config file (https://vitest.dev/guide/workspace.html)\n if (\n !isRootProject &&\n !tree.exists(`vitest.workspace.ts`) &&\n !tree.exists(`vitest.workspace.js`) &&\n !tree.exists(`vitest.workspace.json`) &&\n !tree.exists(`vitest.projects.ts`) &&\n !tree.exists(`vitest.projects.js`) &&\n !tree.exists(`vitest.projects.json`)\n ) {\n tree.write(\n 'vitest.workspace.ts',\n `export default ['**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'];`\n );\n }\n\n if (!schema.skipFormat) {\n await formatFiles(tree);\n }\n\n return runTasksInSerial(...tasks);\n}\n\nfunction updateTsConfig(\n tree: Tree,\n options: VitestGeneratorSchema,\n projectRoot: string,\n projectType: ProjectType\n) {\n const setupFile = tryFindSetupFile(tree, projectRoot);\n\n if (tree.exists(joinPathFragments(projectRoot, 'tsconfig.spec.json'))) {\n updateJson(\n tree,\n joinPathFragments(projectRoot, 'tsconfig.spec.json'),\n (json) => {\n if (!json.compilerOptions?.types?.includes('vitest')) {\n if (json.compilerOptions?.types) {\n json.compilerOptions.types.push('vitest');\n } else {\n json.compilerOptions ??= {};\n json.compilerOptions.types = ['vitest'];\n }\n }\n\n if (setupFile) {\n json.files = [...(json.files ?? []), setupFile];\n }\n\n return json;\n }\n );\n\n updateJson(\n tree,\n joinPathFragments(projectRoot, 'tsconfig.json'),\n (json) => {\n if (\n json.references &&\n !json.references.some((r) => r.path === './tsconfig.spec.json')\n ) {\n json.references.push({\n path: './tsconfig.spec.json',\n });\n }\n return json;\n }\n );\n } else {\n updateJson(\n tree,\n joinPathFragments(projectRoot, 'tsconfig.json'),\n (json) => {\n if (!json.compilerOptions?.types?.includes('vitest')) {\n if (json.compilerOptions?.types) {\n json.compilerOptions.types.push('vitest');\n } else {\n json.compilerOptions ??= {};\n json.compilerOptions.types = ['vitest'];\n }\n }\n return json;\n }\n );\n }\n\n let runtimeTsconfigPath = joinPathFragments(\n projectRoot,\n getProjectType(tree, projectRoot, projectType) === 'application'\n ? 'tsconfig.app.json'\n : 'tsconfig.lib.json'\n );\n if (options.runtimeTsconfigFileName) {\n runtimeTsconfigPath = joinPathFragments(\n projectRoot,\n options.runtimeTsconfigFileName\n );\n if (!tree.exists(runtimeTsconfigPath)) {\n throw new Error(\n `Cannot find the specified runtimeTsConfigFileName (\"${options.runtimeTsconfigFileName}\") at the project root \"${projectRoot}\".`\n );\n }\n }\n\n if (tree.exists(runtimeTsconfigPath)) {\n updateJson(tree, runtimeTsconfigPath, (json) => {\n if (options.inSourceTests) {\n (json.compilerOptions.types ??= []).push('vitest/importMeta');\n } else {\n const uniqueExclude = new Set([\n ...(json.exclude || []),\n 'vite.config.ts',\n 'vite.config.mts',\n 'vitest.config.ts',\n 'vitest.config.mts',\n 'src/**/*.test.ts',\n 'src/**/*.spec.ts',\n 'src/**/*.test.tsx',\n 'src/**/*.spec.tsx',\n 'src/**/*.test.js',\n 'src/**/*.spec.js',\n 'src/**/*.test.jsx',\n 'src/**/*.spec.jsx',\n ]);\n json.exclude = [...uniqueExclude];\n }\n\n if (setupFile) {\n json.exclude = [...(json.exclude ?? []), setupFile];\n }\n\n return json;\n });\n } else {\n logger.warn(\n `Couldn't find a runtime tsconfig file at ${runtimeTsconfigPath} to exclude the test files from. ` +\n `If you're using a different filename for your runtime tsconfig, please provide it with the '--runtimeTsconfigFileName' flag.`\n );\n }\n}\n\nfunction createFiles(\n tree: Tree,\n options: VitestGeneratorSchema,\n projectRoot: string,\n isTsSolutionSetup: boolean\n) {\n const rootOffset = offsetFromRoot(projectRoot);\n\n generateFiles(tree, join(__dirname, 'files'), projectRoot, {\n tmpl: '',\n ...options,\n projectRoot,\n extendedConfig: isTsSolutionSetup\n ? `${rootOffset}tsconfig.base.json`\n : './tsconfig.json',\n outDir: isTsSolutionSetup\n ? `./out-tsc/vitest`\n : `${rootOffset}dist/out-tsc`,\n });\n}\n\nasync function getCoverageProviderDependency(\n tree: Tree,\n coverageProvider: VitestGeneratorSchema['coverageProvider']\n) {\n const { vitestCoverageV8, vitestCoverageIstanbul } =\n await getVitestDependenciesVersionsToInstall(tree);\n switch (coverageProvider) {\n case 'v8':\n return {\n '@vitest/coverage-v8': vitestCoverageV8,\n };\n case 'istanbul':\n return {\n '@vitest/coverage-istanbul': vitestCoverageIstanbul,\n };\n default:\n return {\n '@vitest/coverage-v8': vitestCoverageV8,\n };\n }\n}\n\nfunction tryFindSetupFile(tree: Tree, projectRoot: string) {\n const setupFile = joinPathFragments('src', 'test-setup.ts');\n if (tree.exists(joinPathFragments(projectRoot, setupFile))) {\n return setupFile;\n }\n}\n\nexport default vitestGenerator;\n"],"names":["vitestGenerator","vitestGeneratorInternal","tree","schema","hasPlugin","addPlugin","testEnvironment","tasks","root","projectType","_projectType","readProjectConfiguration","project","uiFramework","detectUiFramework","isRootProject","push","jsInitGenerator","skipFormat","pkgJson","readJson","coerce","useVite5","major","devDependencies","initTask","initGenerator","projectRoot","useViteV5","ensureDependencies","addOrChangeTestTarget","skipViteConfig","relativeTestSetupPath","joinPathFragments","setupFile","exists","write","createOrEditViteConfig","includeLib","includeVitest","inSourceTests","imports","plugins","useEsmExtension","getProjectType","rollupOptionsExternal","compiler","coverageProvider","isTsSolutionSetup","isUsingTsSolutionSetup","createFiles","updateTsConfig","nxJson","testTarget","readNxJson","targetDefaults","dependsOn","updateNxJson","coverageProviderDependency","getCoverageProviderDependency","installCoverageProviderTask","addDependenciesToPackageJson","formatFiles","runTasksInSerial","options","tryFindSetupFile","updateJson","json","compilerOptions","types","includes","files","references","some","r","path","runtimeTsconfigPath","runtimeTsconfigFileName","Error","uniqueExclude","Set","exclude","logger","warn","rootOffset","offsetFromRoot","generateFiles","join","__dirname","tmpl","extendedConfig","outDir","vitestCoverageV8","vitestCoverageIstanbul","getVitestDependenciesVersionsToInstall"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IA2XA,OAA+B;eAA/B;;IAtVgBA,eAAe;eAAfA;;IAYMC,uBAAuB;eAAvBA;;;;wBAjCf;oBAC0C;iCAI1C;sBACc;oCACc;gCAI5B;sBACmB;mCAEQ;8BACqB;wBACzB;AAKvB,SAASD,gBACdE,IAAU,EACVC,MAA6B,EAC7BC,YAAY,KAAK;IAEjB,OAAOH,wBACLC,MACA;QAAEG,WAAW;OAAUF,SACvBC;AAEJ;AAEO,eAAeH,wBACpBC,IAAU,EACVC,MAA6B,EAC7BC,YAAY,KAAK;QAEjB,8EAA8E;IAC9E,8EAA8E;IAC9ED;;IAAAA,qBAAAA,UAAAA,QAAOG,8CAAPH,QAAOG,kBAAoB;IAE3B,MAAMC,QAA6B,EAAE;IAErC,MAAM,EAAEC,IAAI,EAAEC,aAAaC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IAAAA,sBAAc,EAAC1D;IAElC2D,IAAAA,qBAAa,EAACpF,MAAMqF,IAAAA,UAAI,EAACC,WAAW,UAAU7D,aAAa;QACzD8D,MAAM;OACHzB;QACHrC;QACA+D,gBAAgB1C,oBACZ,CAAC,EAAEoC,WAAW,kBAAkB,CAAC,GACjC;QACJO,QAAQ3C,oBACJ,CAAC,gBAAgB,CAAC,GAClB,CAAC,EAAEoC,WAAW,YAAY,CAAC;;AAEnC;AAEA,eAAezB,8BACbzD,IAAU,EACV6C,gBAA2D;IAE3D,MAAM,EAAE6C,gBAAgB,EAAEC,sBAAsB,EAAE,GAChD,MAAMC,IAAAA,oDAAsC,EAAC5F;IAC/C,OAAQ6C;QACN,KAAK;YACH,OAAO;gBACL,uBAAuB6C;YACzB;QACF,KAAK;YACH,OAAO;gBACL,6BAA6BC;YAC/B;QACF;YACE,OAAO;gBACL,uBAAuBD;YACzB;IACJ;AACF;AAEA,SAAS3B,iBAAiB/D,IAAU,EAAEyB,WAAmB;IACvD,MAAMO,YAAYD,IAAAA,yBAAiB,EAAC,OAAO;IAC3C,IAAI/B,KAAKiC,MAAM,CAACF,IAAAA,yBAAiB,EAACN,aAAaO,aAAa;QAC1D,OAAOA;IACT;AACF;MAEA,WAAelC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/vite/src/generators/vitest/vitest-generator.ts"],"sourcesContent":["import {\n addDependenciesToPackageJson,\n formatFiles,\n generateFiles,\n GeneratorCallback,\n joinPathFragments,\n logger,\n offsetFromRoot,\n ProjectType,\n readJson,\n readNxJson,\n readProjectConfiguration,\n runTasksInSerial,\n Tree,\n updateJson,\n updateNxJson,\n} from '@nx/devkit';\nimport { initGenerator as jsInitGenerator } from '@nx/js';\nimport {\n getProjectType,\n isUsingTsSolutionSetup,\n} from '@nx/js/src/utils/typescript/ts-solution-setup';\nimport { typesNodeVersion } from '@nx/js/src/utils/versions';\nimport { join } from 'path';\nimport { ensureDependencies } from '../../utils/ensure-dependencies';\nimport {\n addOrChangeTestTarget,\n createOrEditViteConfig,\n} from '../../utils/generator-utils';\nimport initGenerator from '../init/init';\nimport { VitestGeneratorSchema } from './schema';\nimport { detectUiFramework } from '../../utils/detect-ui-framework';\nimport { getVitestDependenciesVersionsToInstall } from '../../utils/version-utils';\nimport { coerce, major } from 'semver';\n\n/**\n * @param hasPlugin some frameworks (e.g. Nuxt) provide their own plugin. Their generators handle the plugin detection.\n */\nexport function vitestGenerator(\n tree: Tree,\n schema: VitestGeneratorSchema,\n hasPlugin = false\n) {\n return vitestGeneratorInternal(\n tree,\n { addPlugin: false, ...schema },\n hasPlugin\n );\n}\n\nexport async function vitestGeneratorInternal(\n tree: Tree,\n schema: VitestGeneratorSchema,\n hasPlugin = false\n) {\n // Setting default to jsdom since it is the most common use case (React, Web).\n // The @nx/js:lib generator specifically sets this to node to be more generic.\n schema.testEnvironment ??= 'jsdom';\n\n const tasks: GeneratorCallback[] = [];\n\n const { root, projectType: _projectType } = readProjectConfiguration(\n tree,\n schema.project\n );\n const projectType = schema.projectType ?? _projectType;\n const uiFramework =\n schema.uiFramework ?? (await detectUiFramework(schema.project));\n const isRootProject = root === '.';\n\n tasks.push(await jsInitGenerator(tree, { ...schema, skipFormat: true }));\n\n const pkgJson = readJson(tree, 'package.json');\n const useVite5 =\n major(coerce(pkgJson.devDependencies['vite']) ?? '6.0.0') === 5;\n const initTask = await initGenerator(tree, {\n projectRoot: root,\n skipFormat: true,\n addPlugin: schema.addPlugin,\n useViteV5: useVite5,\n });\n tasks.push(initTask);\n tasks.push(ensureDependencies(tree, { ...schema, uiFramework }));\n\n addOrChangeTestTarget(tree, schema, hasPlugin);\n\n if (!schema.skipViteConfig) {\n if (uiFramework === 'angular') {\n const relativeTestSetupPath = joinPathFragments('src', 'test-setup.ts');\n\n const setupFile = joinPathFragments(root, relativeTestSetupPath);\n if (!tree.exists(setupFile)) {\n tree.write(\n setupFile,\n `import '@analogjs/vitest-angular/setup-zone';\n\nimport {\n BrowserDynamicTestingModule,\n platformBrowserDynamicTesting,\n} from '@angular/platform-browser-dynamic/testing';\nimport { getTestBed } from '@angular/core/testing';\n\ngetTestBed().initTestEnvironment(\n BrowserDynamicTestingModule,\n platformBrowserDynamicTesting()\n);\n`\n );\n }\n\n createOrEditViteConfig(\n tree,\n {\n project: schema.project,\n includeLib: false,\n includeVitest: true,\n inSourceTests: false,\n imports: [`import angular from '@analogjs/vite-plugin-angular'`],\n plugins: ['angular()'],\n setupFile: relativeTestSetupPath,\n useEsmExtension: true,\n },\n true\n );\n } else if (uiFramework === 'react') {\n createOrEditViteConfig(\n tree,\n {\n project: schema.project,\n includeLib: getProjectType(tree, root, projectType) === 'library',\n includeVitest: true,\n inSourceTests: schema.inSourceTests,\n rollupOptionsExternal: [\n \"'react'\",\n \"'react-dom'\",\n \"'react/jsx-runtime'\",\n ],\n imports: [\n schema.compiler === 'swc'\n ? `import react from '@vitejs/plugin-react-swc'`\n : `import react from '@vitejs/plugin-react'`,\n ],\n plugins: ['react()'],\n coverageProvider: schema.coverageProvider,\n },\n true\n );\n } else {\n createOrEditViteConfig(\n tree,\n {\n ...schema,\n includeVitest: true,\n includeLib: getProjectType(tree, root, projectType) === 'library',\n },\n true\n );\n }\n }\n\n const isTsSolutionSetup = isUsingTsSolutionSetup(tree);\n\n createFiles(tree, schema, root, isTsSolutionSetup);\n updateTsConfig(tree, schema, root, projectType);\n\n if (isTsSolutionSetup) {\n // in the TS solution setup, the test target depends on the build outputs\n // so we need to setup the task pipeline accordingly\n const nxJson = readNxJson(tree);\n const testTarget = schema.testTarget ?? 'test';\n nxJson.targetDefaults ??= {};\n nxJson.targetDefaults[testTarget] ??= {};\n nxJson.targetDefaults[testTarget].dependsOn ??= [];\n nxJson.targetDefaults[testTarget].dependsOn.push('^build');\n updateNxJson(tree, nxJson);\n }\n\n const devDependencies = await getCoverageProviderDependency(\n tree,\n schema.coverageProvider\n );\n devDependencies['@types/node'] = typesNodeVersion;\n\n const installDependenciesTask = addDependenciesToPackageJson(\n tree,\n {},\n devDependencies\n );\n tasks.push(installDependenciesTask);\n\n // Setup workspace config file (https://vitest.dev/guide/workspace.html)\n if (\n !isRootProject &&\n !tree.exists(`vitest.workspace.ts`) &&\n !tree.exists(`vitest.workspace.js`) &&\n !tree.exists(`vitest.workspace.json`) &&\n !tree.exists(`vitest.projects.ts`) &&\n !tree.exists(`vitest.projects.js`) &&\n !tree.exists(`vitest.projects.json`)\n ) {\n tree.write(\n 'vitest.workspace.ts',\n `export default ['**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'];`\n );\n }\n\n if (!schema.skipFormat) {\n await formatFiles(tree);\n }\n\n return runTasksInSerial(...tasks);\n}\n\nfunction updateTsConfig(\n tree: Tree,\n options: VitestGeneratorSchema,\n projectRoot: string,\n projectType: ProjectType\n) {\n const setupFile = tryFindSetupFile(tree, projectRoot);\n\n if (tree.exists(joinPathFragments(projectRoot, 'tsconfig.spec.json'))) {\n updateJson(\n tree,\n joinPathFragments(projectRoot, 'tsconfig.spec.json'),\n (json) => {\n if (!json.compilerOptions?.types?.includes('vitest')) {\n if (json.compilerOptions?.types) {\n json.compilerOptions.types.push('vitest');\n } else {\n json.compilerOptions ??= {};\n json.compilerOptions.types = ['vitest'];\n }\n }\n\n if (setupFile) {\n json.files = [...(json.files ?? []), setupFile];\n }\n\n return json;\n }\n );\n\n updateJson(\n tree,\n joinPathFragments(projectRoot, 'tsconfig.json'),\n (json) => {\n if (\n json.references &&\n !json.references.some((r) => r.path === './tsconfig.spec.json')\n ) {\n json.references.push({\n path: './tsconfig.spec.json',\n });\n }\n return json;\n }\n );\n } else {\n updateJson(\n tree,\n joinPathFragments(projectRoot, 'tsconfig.json'),\n (json) => {\n if (!json.compilerOptions?.types?.includes('vitest')) {\n if (json.compilerOptions?.types) {\n json.compilerOptions.types.push('vitest');\n } else {\n json.compilerOptions ??= {};\n json.compilerOptions.types = ['vitest'];\n }\n }\n return json;\n }\n );\n }\n\n let runtimeTsconfigPath = joinPathFragments(\n projectRoot,\n getProjectType(tree, projectRoot, projectType) === 'application'\n ? 'tsconfig.app.json'\n : 'tsconfig.lib.json'\n );\n if (options.runtimeTsconfigFileName) {\n runtimeTsconfigPath = joinPathFragments(\n projectRoot,\n options.runtimeTsconfigFileName\n );\n if (!tree.exists(runtimeTsconfigPath)) {\n throw new Error(\n `Cannot find the specified runtimeTsConfigFileName (\"${options.runtimeTsconfigFileName}\") at the project root \"${projectRoot}\".`\n );\n }\n }\n\n if (tree.exists(runtimeTsconfigPath)) {\n updateJson(tree, runtimeTsconfigPath, (json) => {\n if (options.inSourceTests) {\n (json.compilerOptions.types ??= []).push('vitest/importMeta');\n } else {\n const uniqueExclude = new Set([\n ...(json.exclude || []),\n 'vite.config.ts',\n 'vite.config.mts',\n 'vitest.config.ts',\n 'vitest.config.mts',\n 'src/**/*.test.ts',\n 'src/**/*.spec.ts',\n 'src/**/*.test.tsx',\n 'src/**/*.spec.tsx',\n 'src/**/*.test.js',\n 'src/**/*.spec.js',\n 'src/**/*.test.jsx',\n 'src/**/*.spec.jsx',\n ]);\n json.exclude = [...uniqueExclude];\n }\n\n if (setupFile) {\n json.exclude = [...(json.exclude ?? []), setupFile];\n }\n\n return json;\n });\n } else {\n logger.warn(\n `Couldn't find a runtime tsconfig file at ${runtimeTsconfigPath} to exclude the test files from. ` +\n `If you're using a different filename for your runtime tsconfig, please provide it with the '--runtimeTsconfigFileName' flag.`\n );\n }\n}\n\nfunction createFiles(\n tree: Tree,\n options: VitestGeneratorSchema,\n projectRoot: string,\n isTsSolutionSetup: boolean\n) {\n const rootOffset = offsetFromRoot(projectRoot);\n\n generateFiles(tree, join(__dirname, 'files'), projectRoot, {\n tmpl: '',\n ...options,\n projectRoot,\n extendedConfig: isTsSolutionSetup\n ? `${rootOffset}tsconfig.base.json`\n : './tsconfig.json',\n outDir: isTsSolutionSetup\n ? `./out-tsc/vitest`\n : `${rootOffset}dist/out-tsc`,\n });\n}\n\nasync function getCoverageProviderDependency(\n tree: Tree,\n coverageProvider: VitestGeneratorSchema['coverageProvider']\n): Promise<Record<string, string>> {\n const { vitestCoverageV8, vitestCoverageIstanbul } =\n await getVitestDependenciesVersionsToInstall(tree);\n switch (coverageProvider) {\n case 'v8':\n return {\n '@vitest/coverage-v8': vitestCoverageV8,\n };\n case 'istanbul':\n return {\n '@vitest/coverage-istanbul': vitestCoverageIstanbul,\n };\n default:\n return {\n '@vitest/coverage-v8': vitestCoverageV8,\n };\n }\n}\n\nfunction tryFindSetupFile(tree: Tree, projectRoot: string) {\n const setupFile = joinPathFragments('src', 'test-setup.ts');\n if (tree.exists(joinPathFragments(projectRoot, setupFile))) {\n return setupFile;\n }\n}\n\nexport default vitestGenerator;\n"],"names":["vitestGenerator","vitestGeneratorInternal","tree","schema","hasPlugin","addPlugin","testEnvironment","tasks","root","projectType","_projectType","readProjectConfiguration","project","uiFramework","detectUiFramework","isRootProject","push","jsInitGenerator","skipFormat","pkgJson","readJson","coerce","useVite5","major","devDependencies","initTask","initGenerator","projectRoot","useViteV5","ensureDependencies","addOrChangeTestTarget","skipViteConfig","relativeTestSetupPath","joinPathFragments","setupFile","exists","write","createOrEditViteConfig","includeLib","includeVitest","inSourceTests","imports","plugins","useEsmExtension","getProjectType","rollupOptionsExternal","compiler","coverageProvider","isTsSolutionSetup","isUsingTsSolutionSetup","createFiles","updateTsConfig","nxJson","testTarget","readNxJson","targetDefaults","dependsOn","updateNxJson","getCoverageProviderDependency","typesNodeVersion","installDependenciesTask","addDependenciesToPackageJson","formatFiles","runTasksInSerial","options","tryFindSetupFile","updateJson","json","compilerOptions","types","includes","files","references","some","r","path","runtimeTsconfigPath","runtimeTsconfigFileName","Error","uniqueExclude","Set","exclude","logger","warn","rootOffset","offsetFromRoot","generateFiles","join","__dirname","tmpl","extendedConfig","outDir","vitestCoverageV8","vitestCoverageIstanbul","getVitestDependenciesVersionsToInstall"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AE,GAChD,MAAMC,IAAAA,oDAAsC,EAAC5F;IAC/C,OAAQ6C;QACN,KAAK;YACH,OAAO;gBACL,uBAAuB6C;YACzB;QACF,KAAK;YACH,OAAO;gBACL,6BAA6BC;YAC/B;QACF;YACE,OAAO;gBACL,uBAAuBD;YACzB;IACJ;AACF;AAEA,SAAS3B,iBAAiB/D,IAAU,EAAEyB,WAAmB;IACvD,MAAMO,YAAYD,IAAAA,yBAAiB,EAAC,OAAO;IAC3C,IAAI/B,KAAKiC,MAAM,CAACF,IAAAA,yBAAiB,EAACN,aAAaO,aAAa;QAC1D,OAAOA;IACT;AACF;MAEA,WAAelC"}
|
package/src/plugins/plugin.js
CHANGED
|
@@ -73,13 +73,17 @@ const createNodesV2 = [
|
|
|
73
73
|
const siblingFiles = (0, _fs.readdirSync)((0, _path.join)(context.workspaceRoot, projectRoot));
|
|
74
74
|
var _siblingFiles_filter;
|
|
75
75
|
const tsConfigFiles = (_siblingFiles_filter = siblingFiles.filter((p)=>(0, _minimatch.minimatch)(p, 'tsconfig*{.json,.*.json}'))) != null ? _siblingFiles_filter : [];
|
|
76
|
+
const hasReactRouterConfig = siblingFiles.some((configFile)=>{
|
|
77
|
+
const parts = configFile.split('.');
|
|
78
|
+
return parts[0] === 'react-router' && parts[1] === 'config' && parts.length > 2;
|
|
79
|
+
});
|
|
76
80
|
// results from vitest.config.js will be different from results of vite.config.js
|
|
77
81
|
// but the hash will be the same because it is based on the files under the project root.
|
|
78
82
|
// Adding the config file path to the hash ensures that the final hash value is different
|
|
79
83
|
// for different config files.
|
|
80
84
|
const hash = hashes[idx] + configFile;
|
|
81
85
|
var _1;
|
|
82
|
-
const { projectType, metadata, targets } = (_1 = (_targetsCache = targetsCache)[_hash = hash]) != null ? _1 : _targetsCache[_hash] = await buildViteTargets(configFile, projectRoot, normalizedOptions, tsConfigFiles, isUsingTsSolutionSetup, context);
|
|
86
|
+
const { projectType, metadata, targets } = (_1 = (_targetsCache = targetsCache)[_hash = hash]) != null ? _1 : _targetsCache[_hash] = await buildViteTargets(configFile, projectRoot, normalizedOptions, tsConfigFiles, hasReactRouterConfig, isUsingTsSolutionSetup, context);
|
|
83
87
|
const project = {
|
|
84
88
|
root: projectRoot,
|
|
85
89
|
targets,
|
|
@@ -113,9 +117,13 @@ const createNodes = [
|
|
|
113
117
|
}
|
|
114
118
|
var _siblingFiles_filter;
|
|
115
119
|
const tsConfigFiles = (_siblingFiles_filter = siblingFiles.filter((p)=>(0, _minimatch.minimatch)(p, 'tsconfig*{.json,.*.json}'))) != null ? _siblingFiles_filter : [];
|
|
120
|
+
const hasReactRouterConfig = siblingFiles.some((configFile)=>{
|
|
121
|
+
const parts = configFile.split('.');
|
|
122
|
+
return parts[0] === 'react-router' && parts[1] === 'config' && parts.length > 2;
|
|
123
|
+
});
|
|
116
124
|
const normalizedOptions = normalizeOptions(options);
|
|
117
125
|
const isUsingTsSolutionSetup = (0, _tssolutionsetup.isUsingTsSolutionSetup)();
|
|
118
|
-
const { projectType, metadata, targets } = await buildViteTargets(configFilePath, projectRoot, normalizedOptions, tsConfigFiles, isUsingTsSolutionSetup, context);
|
|
126
|
+
const { projectType, metadata, targets } = await buildViteTargets(configFilePath, projectRoot, normalizedOptions, tsConfigFiles, hasReactRouterConfig, isUsingTsSolutionSetup, context);
|
|
119
127
|
const project = {
|
|
120
128
|
root: projectRoot,
|
|
121
129
|
targets,
|
|
@@ -133,7 +141,7 @@ const createNodes = [
|
|
|
133
141
|
};
|
|
134
142
|
}
|
|
135
143
|
];
|
|
136
|
-
async function buildViteTargets(configFilePath, projectRoot, options, tsConfigFiles, isUsingTsSolutionSetup, context) {
|
|
144
|
+
async function buildViteTargets(configFilePath, projectRoot, options, tsConfigFiles, hasReactRouterConfig, isUsingTsSolutionSetup, context) {
|
|
137
145
|
var _viteBuildConfig_build;
|
|
138
146
|
const absoluteConfigFilePath = (0, _devkit.joinPathFragments)(context.workspaceRoot, configFilePath);
|
|
139
147
|
// Workaround for the `build$3 is not a function` error that we sometimes see in agents.
|
|
@@ -152,6 +160,18 @@ async function buildViteTargets(configFilePath, projectRoot, options, tsConfigFi
|
|
|
152
160
|
const { buildOutputs, testOutputs, hasTest, isBuildable, hasServeConfig } = getOutputs(viteBuildConfig, projectRoot, context.workspaceRoot);
|
|
153
161
|
const namedInputs = (0, _getnamedinputs.getNamedInputs)(projectRoot, context);
|
|
154
162
|
const targets = {};
|
|
163
|
+
// if file is vitest.config or vite.config has definition for test, create target for test
|
|
164
|
+
if (configFilePath.includes('vitest.config') || hasTest) {
|
|
165
|
+
targets[options.testTargetName] = await testTarget(namedInputs, testOutputs, projectRoot);
|
|
166
|
+
}
|
|
167
|
+
if (hasReactRouterConfig) {
|
|
168
|
+
// If we have a react-router config, we can skip the rest of the targets
|
|
169
|
+
return {
|
|
170
|
+
targets,
|
|
171
|
+
metadata: {},
|
|
172
|
+
projectType: 'application'
|
|
173
|
+
};
|
|
174
|
+
}
|
|
155
175
|
// If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static
|
|
156
176
|
const hasRemixPlugin = viteBuildConfig.plugins && viteBuildConfig.plugins.some((p)=>p.name === 'remix');
|
|
157
177
|
if (!configFilePath.includes('vitest.config') && !hasRemixPlugin && isBuildable) {
|
|
@@ -225,10 +245,6 @@ async function buildViteTargets(configFilePath, projectRoot, options, tsConfigFi
|
|
|
225
245
|
];
|
|
226
246
|
}
|
|
227
247
|
}
|
|
228
|
-
// if file is vitest.config or vite.config has definition for test, create target for test
|
|
229
|
-
if (configFilePath.includes('vitest.config') || hasTest) {
|
|
230
|
-
targets[options.testTargetName] = await testTarget(namedInputs, testOutputs, projectRoot);
|
|
231
|
-
}
|
|
232
248
|
(0, _util.addBuildAndWatchDepsTargets)(context.workspaceRoot, projectRoot, targets, options, pmc);
|
|
233
249
|
const metadata = {};
|
|
234
250
|
return {
|
|
@@ -287,6 +303,7 @@ async function buildTarget(buildTargetName, namedInputs, outputs, projectRoot, i
|
|
|
287
303
|
}
|
|
288
304
|
function serveTarget(projectRoot, isUsingTsSolutionSetup) {
|
|
289
305
|
const targetConfig = {
|
|
306
|
+
continuous: true,
|
|
290
307
|
command: `vite`,
|
|
291
308
|
options: {
|
|
292
309
|
cwd: (0, _devkit.joinPathFragments)(projectRoot)
|
|
@@ -315,6 +332,7 @@ function serveTarget(projectRoot, isUsingTsSolutionSetup) {
|
|
|
315
332
|
}
|
|
316
333
|
function previewTarget(projectRoot, buildTargetName) {
|
|
317
334
|
const targetConfig = {
|
|
335
|
+
continuous: true,
|
|
318
336
|
command: `vite preview`,
|
|
319
337
|
dependsOn: [
|
|
320
338
|
buildTargetName
|
|
@@ -383,6 +401,7 @@ async function testTarget(namedInputs, outputs, projectRoot) {
|
|
|
383
401
|
}
|
|
384
402
|
function serveStaticTarget(options, isUsingTsSolutionSetup) {
|
|
385
403
|
const targetConfig = {
|
|
404
|
+
continuous: true,
|
|
386
405
|
executor: '@nx/web:file-server',
|
|
387
406
|
options: {
|
|
388
407
|
buildTarget: `${options.buildTargetName}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/vite/src/plugins/plugin.ts"],"sourcesContent":["import {\n CreateDependencies,\n CreateNodes,\n CreateNodesContext,\n CreateNodesContextV2,\n createNodesFromFiles,\n CreateNodesV2,\n detectPackageManager,\n getPackageManagerCommand,\n joinPathFragments,\n logger,\n ProjectConfiguration,\n readJsonFile,\n TargetConfiguration,\n writeJsonFile,\n} from '@nx/devkit';\nimport { dirname, isAbsolute, join, relative } from 'path';\nimport { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';\nimport { existsSync, readdirSync } from 'fs';\nimport {\n calculateHashesForCreateNodes,\n calculateHashForCreateNodes,\n} from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';\nimport { workspaceDataDirectory } from 'nx/src/utils/cache-directory';\nimport { getLockFileName } from '@nx/js';\nimport { loadViteDynamicImport } from '../utils/executor-utils';\nimport { hashObject } from 'nx/src/hasher/file-hasher';\nimport { minimatch } from 'minimatch';\nimport { isUsingTsSolutionSetup as _isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\nimport { addBuildAndWatchDepsTargets } from '@nx/js/src/plugins/typescript/util';\n\nconst pmc = getPackageManagerCommand();\n\nexport interface VitePluginOptions {\n buildTargetName?: string;\n testTargetName?: string;\n /**\n * @deprecated Use devTargetName instead. This option will be removed in Nx 22.\n */\n serveTargetName?: string;\n devTargetName?: string;\n previewTargetName?: string;\n serveStaticTargetName?: string;\n typecheckTargetName?: string;\n watchDepsTargetName?: string;\n buildDepsTargetName?: string;\n}\n\ntype ViteTargets = Pick<\n ProjectConfiguration,\n 'targets' | 'metadata' | 'projectType'\n>;\n\nfunction readTargetsCache(cachePath: string): Record<string, ViteTargets> {\n return process.env.NX_CACHE_PROJECT_GRAPH !== 'false' && existsSync(cachePath)\n ? readJsonFile(cachePath)\n : {};\n}\n\nfunction writeTargetsToCache(cachePath, results?: Record<string, ViteTargets>) {\n writeJsonFile(cachePath, results);\n}\n\n/**\n * @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.\n */\nexport const createDependencies: CreateDependencies = () => {\n return [];\n};\n\nconst viteVitestConfigGlob = '**/{vite,vitest}.config.{js,ts,mjs,mts,cjs,cts}';\n\nexport const createNodesV2: CreateNodesV2<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePaths, options, context) => {\n const optionsHash = hashObject(options);\n const normalizedOptions = normalizeOptions(options);\n const cachePath = join(workspaceDataDirectory, `vite-${optionsHash}.hash`);\n const targetsCache = readTargetsCache(cachePath);\n const isUsingTsSolutionSetup = _isUsingTsSolutionSetup();\n\n const { roots: projectRoots, configFiles: validConfigFiles } =\n configFilePaths.reduce(\n (acc, configFile) => {\n const potentialRoot = dirname(configFile);\n if (checkIfConfigFileShouldBeProject(potentialRoot, context)) {\n acc.roots.push(potentialRoot);\n acc.configFiles.push(configFile);\n }\n return acc;\n },\n {\n roots: [],\n configFiles: [],\n } as {\n roots: string[];\n configFiles: string[];\n }\n );\n\n const lockfile = getLockFileName(\n detectPackageManager(context.workspaceRoot)\n );\n const hashes = await calculateHashesForCreateNodes(\n projectRoots,\n { ...normalizedOptions, isUsingTsSolutionSetup },\n context,\n projectRoots.map((r) => [lockfile])\n );\n\n try {\n return await createNodesFromFiles(\n async (configFile, _, context, idx) => {\n const projectRoot = dirname(configFile);\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(\n join(context.workspaceRoot, projectRoot)\n );\n\n const tsConfigFiles =\n siblingFiles.filter((p) =>\n minimatch(p, 'tsconfig*{.json,.*.json}')\n ) ?? [];\n\n // results from vitest.config.js will be different from results of vite.config.js\n // but the hash will be the same because it is based on the files under the project root.\n // Adding the config file path to the hash ensures that the final hash value is different\n // for different config files.\n const hash = hashes[idx] + configFile;\n const { projectType, metadata, targets } = (targetsCache[hash] ??=\n await buildViteTargets(\n configFile,\n projectRoot,\n normalizedOptions,\n tsConfigFiles,\n isUsingTsSolutionSetup,\n context\n ));\n\n const project: ProjectConfiguration = {\n root: projectRoot,\n targets,\n metadata,\n };\n\n // If project is buildable, then the project type.\n // If it is not buildable, then leave it to other plugins/project.json to set the project type.\n if (project.targets[normalizedOptions.buildTargetName]) {\n project.projectType = projectType;\n }\n\n return {\n projects: {\n [projectRoot]: project,\n },\n };\n },\n validConfigFiles,\n options,\n context\n );\n } finally {\n writeTargetsToCache(cachePath, targetsCache);\n }\n },\n];\n\nexport const createNodes: CreateNodes<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePath, options, context) => {\n logger.warn(\n '`createNodes` is deprecated. Update your plugin to utilize createNodesV2 instead. In Nx 20, this will change to the createNodesV2 API.'\n );\n const projectRoot = dirname(configFilePath);\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot));\n if (\n !siblingFiles.includes('package.json') &&\n !siblingFiles.includes('project.json')\n ) {\n return {};\n }\n\n const tsConfigFiles =\n siblingFiles.filter((p) => minimatch(p, 'tsconfig*{.json,.*.json}')) ??\n [];\n\n const normalizedOptions = normalizeOptions(options);\n\n const isUsingTsSolutionSetup = _isUsingTsSolutionSetup();\n\n const { projectType, metadata, targets } = await buildViteTargets(\n configFilePath,\n projectRoot,\n normalizedOptions,\n tsConfigFiles,\n isUsingTsSolutionSetup,\n context\n );\n const project: ProjectConfiguration = {\n root: projectRoot,\n targets,\n metadata,\n };\n\n // If project is buildable, then the project type.\n // If it is not buildable, then leave it to other plugins/project.json to set the project type.\n if (project.targets[normalizedOptions.buildTargetName]) {\n project.projectType = projectType;\n }\n\n return {\n projects: {\n [projectRoot]: project,\n },\n };\n },\n];\n\nasync function buildViteTargets(\n configFilePath: string,\n projectRoot: string,\n options: VitePluginOptions,\n tsConfigFiles: string[],\n isUsingTsSolutionSetup: boolean,\n context: CreateNodesContext\n): Promise<ViteTargets> {\n const absoluteConfigFilePath = joinPathFragments(\n context.workspaceRoot,\n configFilePath\n );\n // Workaround for the `build$3 is not a function` error that we sometimes see in agents.\n // This should be removed later once we address the issue properly\n try {\n const importEsbuild = () => new Function('return import(\"esbuild\")')();\n await importEsbuild();\n } catch {\n // do nothing\n }\n const { resolveConfig } = await loadViteDynamicImport();\n const viteBuildConfig = await resolveConfig(\n {\n configFile: absoluteConfigFilePath,\n mode: 'development',\n },\n 'build'\n );\n\n const { buildOutputs, testOutputs, hasTest, isBuildable, hasServeConfig } =\n getOutputs(viteBuildConfig, projectRoot, context.workspaceRoot);\n\n const namedInputs = getNamedInputs(projectRoot, context);\n\n const targets: Record<string, TargetConfiguration> = {};\n\n // If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static\n const hasRemixPlugin =\n viteBuildConfig.plugins &&\n viteBuildConfig.plugins.some((p) => p.name === 'remix');\n if (\n !configFilePath.includes('vitest.config') &&\n !hasRemixPlugin &&\n isBuildable\n ) {\n targets[options.buildTargetName] = await buildTarget(\n options.buildTargetName,\n namedInputs,\n buildOutputs,\n projectRoot,\n isUsingTsSolutionSetup\n );\n\n // If running in library mode, then there is nothing to serve.\n if (!viteBuildConfig.build?.lib || hasServeConfig) {\n const devTarget = serveTarget(projectRoot, isUsingTsSolutionSetup);\n\n targets[options.serveTargetName] = {\n ...devTarget,\n metadata: {\n ...devTarget.metadata,\n deprecated:\n 'Use devTargetName instead. This option will be removed in Nx 22.',\n },\n };\n targets[options.devTargetName] = devTarget;\n targets[options.previewTargetName] = previewTarget(\n projectRoot,\n options.buildTargetName\n );\n targets[options.serveStaticTargetName] = serveStaticTarget(\n options,\n isUsingTsSolutionSetup\n );\n }\n }\n\n if (tsConfigFiles.length) {\n const tsConfigToUse =\n ['tsconfig.app.json', 'tsconfig.lib.json', 'tsconfig.json'].find((t) =>\n tsConfigFiles.includes(t)\n ) ?? tsConfigFiles[0];\n targets[options.typecheckTargetName] = {\n cache: true,\n inputs: [\n ...('production' in namedInputs\n ? ['production', '^production']\n : ['default', '^default']),\n { externalDependencies: ['typescript'] },\n ],\n command: isUsingTsSolutionSetup\n ? `tsc --build --emitDeclarationOnly`\n : `tsc --noEmit -p ${tsConfigToUse}`,\n options: { cwd: joinPathFragments(projectRoot) },\n metadata: {\n description: `Runs type-checking for the project.`,\n technologies: ['typescript'],\n help: {\n command: isUsingTsSolutionSetup\n ? `${pmc.exec} tsc --build --help`\n : `${pmc.exec} tsc -p ${tsConfigToUse} --help`,\n example: isUsingTsSolutionSetup\n ? { args: ['--force'] }\n : { options: { noEmit: true } },\n },\n },\n };\n\n if (isUsingTsSolutionSetup) {\n targets[options.typecheckTargetName].dependsOn = [\n `^${options.typecheckTargetName}`,\n ];\n targets[options.typecheckTargetName].syncGenerators = [\n '@nx/js:typescript-sync',\n ];\n }\n }\n\n // if file is vitest.config or vite.config has definition for test, create target for test\n if (configFilePath.includes('vitest.config') || hasTest) {\n targets[options.testTargetName] = await testTarget(\n namedInputs,\n testOutputs,\n projectRoot\n );\n }\n\n addBuildAndWatchDepsTargets(\n context.workspaceRoot,\n projectRoot,\n targets,\n options,\n pmc\n );\n\n const metadata = {};\n return {\n targets,\n metadata,\n projectType: viteBuildConfig.build?.lib ? 'library' : 'application',\n };\n}\n\nasync function buildTarget(\n buildTargetName: string,\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string,\n isUsingTsSolutionSetup: boolean\n) {\n const buildTarget: TargetConfiguration = {\n command: `vite build`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n dependsOn: [`^${buildTargetName}`],\n inputs: [\n ...('production' in namedInputs\n ? ['production', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vite'],\n },\n ],\n outputs,\n metadata: {\n technologies: ['vite'],\n description: `Run Vite build`,\n help: {\n command: `${pmc.exec} vite build --help`,\n example: {\n options: {\n sourcemap: true,\n manifest: 'manifest.json',\n },\n },\n },\n },\n };\n\n if (isUsingTsSolutionSetup) {\n buildTarget.syncGenerators = ['@nx/js:typescript-sync'];\n }\n\n return buildTarget;\n}\n\nfunction serveTarget(projectRoot: string, isUsingTsSolutionSetup: boolean) {\n const targetConfig: TargetConfiguration = {\n command: `vite`,\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n metadata: {\n technologies: ['vite'],\n description: `Starts Vite dev server`,\n help: {\n command: `${pmc.exec} vite --help`,\n example: {\n options: {\n port: 3000,\n },\n },\n },\n },\n };\n\n if (isUsingTsSolutionSetup) {\n targetConfig.syncGenerators = ['@nx/js:typescript-sync'];\n }\n\n return targetConfig;\n}\n\nfunction previewTarget(projectRoot: string, buildTargetName) {\n const targetConfig: TargetConfiguration = {\n command: `vite preview`,\n dependsOn: [buildTargetName],\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n metadata: {\n technologies: ['vite'],\n description: `Locally preview Vite production build`,\n help: {\n command: `${pmc.exec} vite preview --help`,\n example: {\n options: {\n port: 3000,\n },\n },\n },\n },\n };\n\n return targetConfig;\n}\n\nasync function testTarget(\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string\n) {\n return {\n command: `vitest`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n inputs: [\n ...('production' in namedInputs\n ? ['default', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vitest'],\n },\n { env: 'CI' },\n ],\n outputs,\n metadata: {\n technologies: ['vite'],\n description: `Run Vite tests`,\n help: {\n command: `${pmc.exec} vitest --help`,\n example: {\n options: {\n bail: 1,\n coverage: true,\n },\n },\n },\n },\n };\n}\n\nfunction serveStaticTarget(\n options: VitePluginOptions,\n isUsingTsSolutionSetup: boolean\n) {\n const targetConfig: TargetConfiguration = {\n executor: '@nx/web:file-server',\n options: {\n buildTarget: `${options.buildTargetName}`,\n spa: true,\n },\n };\n\n if (isUsingTsSolutionSetup) {\n targetConfig.syncGenerators = ['@nx/js:typescript-sync'];\n }\n\n return targetConfig;\n}\n\nfunction getOutputs(\n viteBuildConfig: Record<string, any> | undefined,\n projectRoot: string,\n workspaceRoot: string\n): {\n buildOutputs: string[];\n testOutputs: string[];\n hasTest: boolean;\n isBuildable: boolean;\n hasServeConfig: boolean;\n} {\n const { build, test, server } = viteBuildConfig;\n\n const buildOutputPath = normalizeOutputPath(\n build?.outDir,\n projectRoot,\n workspaceRoot,\n 'dist'\n );\n\n const isBuildable =\n build?.lib ||\n build?.rollupOptions?.input ||\n existsSync(join(workspaceRoot, projectRoot, 'index.html'));\n\n const hasServeConfig = Boolean(server);\n\n const reportsDirectoryPath = normalizeOutputPath(\n test?.coverage?.reportsDirectory,\n projectRoot,\n workspaceRoot,\n 'coverage'\n );\n\n return {\n buildOutputs: [buildOutputPath],\n testOutputs: [reportsDirectoryPath],\n hasTest: !!test,\n isBuildable,\n hasServeConfig,\n };\n}\n\nfunction normalizeOutputPath(\n outputPath: string | undefined,\n projectRoot: string,\n workspaceRoot: string,\n path: 'coverage' | 'dist'\n): string | undefined {\n if (!outputPath) {\n if (projectRoot === '.') {\n return `{projectRoot}/${path}`;\n } else {\n return `{workspaceRoot}/${path}/{projectRoot}`;\n }\n } else {\n if (isAbsolute(outputPath)) {\n return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`;\n } else {\n if (outputPath.startsWith('..')) {\n return join('{workspaceRoot}', join(projectRoot, outputPath));\n } else {\n return join('{projectRoot}', outputPath);\n }\n }\n }\n}\n\nfunction normalizeOptions(options: VitePluginOptions): VitePluginOptions {\n options ??= {};\n options.buildTargetName ??= 'build';\n options.serveTargetName ??= 'serve';\n options.devTargetName ??= 'dev';\n options.previewTargetName ??= 'preview';\n options.testTargetName ??= 'test';\n options.serveStaticTargetName ??= 'serve-static';\n options.typecheckTargetName ??= 'typecheck';\n return options;\n}\n\nfunction checkIfConfigFileShouldBeProject(\n projectRoot: string,\n context: CreateNodesContext | CreateNodesContextV2\n): boolean {\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot));\n if (\n !siblingFiles.includes('package.json') &&\n !siblingFiles.includes('project.json')\n ) {\n return false;\n }\n\n return true;\n}\n"],"names":["createDependencies","createNodes","createNodesV2","pmc","getPackageManagerCommand","readTargetsCache","cachePath","process","env","NX_CACHE_PROJECT_GRAPH","existsSync","readJsonFile","writeTargetsToCache","results","writeJsonFile","viteVitestConfigGlob","configFilePaths","options","context","optionsHash","hashObject","normalizedOptions","normalizeOptions","join","workspaceDataDirectory","targetsCache","isUsingTsSolutionSetup","_isUsingTsSolutionSetup","roots","projectRoots","configFiles","validConfigFiles","reduce","acc","configFile","potentialRoot","dirname","checkIfConfigFileShouldBeProject","push","lockfile","getLockFileName","detectPackageManager","workspaceRoot","hashes","calculateHashesForCreateNodes","map","r","createNodesFromFiles","_","idx","hash","projectRoot","siblingFiles","readdirSync","tsConfigFiles","filter","p","minimatch","projectType","metadata","targets","buildViteTargets","project","root","buildTargetName","projects","configFilePath","logger","warn","includes","viteBuildConfig","absoluteConfigFilePath","joinPathFragments","importEsbuild","Function","resolveConfig","loadViteDynamicImport","mode","buildOutputs","testOutputs","hasTest","isBuildable","hasServeConfig","getOutputs","namedInputs","getNamedInputs","hasRemixPlugin","plugins","some","name","buildTarget","build","lib","devTarget","serveTarget","serveTargetName","deprecated","devTargetName","previewTargetName","previewTarget","serveStaticTargetName","serveStaticTarget","length","tsConfigToUse","find","t","typecheckTargetName","cache","inputs","externalDependencies","command","cwd","description","technologies","help","exec","example","args","noEmit","dependsOn","syncGenerators","testTargetName","testTarget","addBuildAndWatchDepsTargets","outputs","sourcemap","manifest","targetConfig","port","bail","coverage","executor","spa","test","server","buildOutputPath","normalizeOutputPath","outDir","rollupOptions","input","Boolean","reportsDirectoryPath","reportsDirectory","outputPath","path","isAbsolute","relative","startsWith"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IAkEaA,kBAAkB;eAAlBA;;IAqGAC,WAAW;eAAXA;;IA/FAC,aAAa;eAAbA;;;;wBAzDN;sBAC6C;gCACrB;oBACS;6CAIjC;gCACgC;oBACP;+BACM;4BACX;2BACD;iCACwC;sBACtB;AAE5C,MAAMC,MAAMC,IAAAA,gCAAwB;AAsBpC,SAASC,iBAAiBC,SAAiB;IACzC,OAAOC,QAAQC,GAAG,CAAC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B/C,qBAAAA,YAAAA,SAAQ8E,8CAAR9E,UAAQ8E,kBAAoB;;IAC5B9E,mBAAAA,YAAAA,SAAQgF,0CAARhF,UAAQgF,gBAAkB;;IAC1BhF,uBAAAA,YAAAA,SAAQiF,kDAARjF,UAAQiF,oBAAsB;;IAC9BjF,oBAAAA,YAAAA,SAAQwG,4CAARxG,UAAQwG,iBAAmB;;IAC3BxG,2BAAAA,YAAAA,SAAQmF,0DAARnF,UAAQmF,wBAA0B;;IAClCnF,yBAAAA,YAAAA,SAAQyF,sDAARzF,UAAQyF,sBAAwB;IAChC,OAAOzF;AACT;AAEA,SAASoB,iCACPc,WAAmB,EACnBjC,OAAkD;IAElD,wEAAwE;IACxE,MAAMkC,eAAeC,IAAAA,eAAW,EAAC9B,IAAAA,UAAI,EAACL,QAAQwB,aAAa,EAAES;IAC7D,IACE,CAACC,aAAaiB,QAAQ,CAAC,mBACvB,CAACjB,aAAaiB,QAAQ,CAAC,iBACvB;QACA,OAAO;IACT;IAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/vite/src/plugins/plugin.ts"],"sourcesContent":["import {\n CreateDependencies,\n CreateNodes,\n CreateNodesContext,\n CreateNodesContextV2,\n createNodesFromFiles,\n CreateNodesV2,\n detectPackageManager,\n getPackageManagerCommand,\n joinPathFragments,\n logger,\n ProjectConfiguration,\n readJsonFile,\n TargetConfiguration,\n writeJsonFile,\n} from '@nx/devkit';\nimport { dirname, isAbsolute, join, relative } from 'path';\nimport { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';\nimport { existsSync, readdirSync } from 'fs';\nimport {\n calculateHashesForCreateNodes,\n calculateHashForCreateNodes,\n} from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';\nimport { workspaceDataDirectory } from 'nx/src/utils/cache-directory';\nimport { getLockFileName } from '@nx/js';\nimport { loadViteDynamicImport } from '../utils/executor-utils';\nimport { hashObject } from 'nx/src/hasher/file-hasher';\nimport { minimatch } from 'minimatch';\nimport { isUsingTsSolutionSetup as _isUsingTsSolutionSetup } from '@nx/js/src/utils/typescript/ts-solution-setup';\nimport { addBuildAndWatchDepsTargets } from '@nx/js/src/plugins/typescript/util';\n\nconst pmc = getPackageManagerCommand();\n\nexport interface VitePluginOptions {\n buildTargetName?: string;\n testTargetName?: string;\n /**\n * @deprecated Use devTargetName instead. This option will be removed in Nx 22.\n */\n serveTargetName?: string;\n devTargetName?: string;\n previewTargetName?: string;\n serveStaticTargetName?: string;\n typecheckTargetName?: string;\n watchDepsTargetName?: string;\n buildDepsTargetName?: string;\n}\n\ntype ViteTargets = Pick<\n ProjectConfiguration,\n 'targets' | 'metadata' | 'projectType'\n>;\n\nfunction readTargetsCache(cachePath: string): Record<string, ViteTargets> {\n return process.env.NX_CACHE_PROJECT_GRAPH !== 'false' && existsSync(cachePath)\n ? readJsonFile(cachePath)\n : {};\n}\n\nfunction writeTargetsToCache(cachePath, results?: Record<string, ViteTargets>) {\n writeJsonFile(cachePath, results);\n}\n\n/**\n * @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.\n */\nexport const createDependencies: CreateDependencies = () => {\n return [];\n};\n\nconst viteVitestConfigGlob = '**/{vite,vitest}.config.{js,ts,mjs,mts,cjs,cts}';\n\nexport const createNodesV2: CreateNodesV2<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePaths, options, context) => {\n const optionsHash = hashObject(options);\n const normalizedOptions = normalizeOptions(options);\n const cachePath = join(workspaceDataDirectory, `vite-${optionsHash}.hash`);\n const targetsCache = readTargetsCache(cachePath);\n const isUsingTsSolutionSetup = _isUsingTsSolutionSetup();\n\n const { roots: projectRoots, configFiles: validConfigFiles } =\n configFilePaths.reduce(\n (acc, configFile) => {\n const potentialRoot = dirname(configFile);\n if (checkIfConfigFileShouldBeProject(potentialRoot, context)) {\n acc.roots.push(potentialRoot);\n acc.configFiles.push(configFile);\n }\n return acc;\n },\n {\n roots: [],\n configFiles: [],\n } as {\n roots: string[];\n configFiles: string[];\n }\n );\n\n const lockfile = getLockFileName(\n detectPackageManager(context.workspaceRoot)\n );\n const hashes = await calculateHashesForCreateNodes(\n projectRoots,\n { ...normalizedOptions, isUsingTsSolutionSetup },\n context,\n projectRoots.map((r) => [lockfile])\n );\n\n try {\n return await createNodesFromFiles(\n async (configFile, _, context, idx) => {\n const projectRoot = dirname(configFile);\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(\n join(context.workspaceRoot, projectRoot)\n );\n\n const tsConfigFiles =\n siblingFiles.filter((p) =>\n minimatch(p, 'tsconfig*{.json,.*.json}')\n ) ?? [];\n\n const hasReactRouterConfig = siblingFiles.some((configFile) => {\n const parts = configFile.split('.');\n return (\n parts[0] === 'react-router' &&\n parts[1] === 'config' &&\n parts.length > 2\n );\n });\n\n // results from vitest.config.js will be different from results of vite.config.js\n // but the hash will be the same because it is based on the files under the project root.\n // Adding the config file path to the hash ensures that the final hash value is different\n // for different config files.\n const hash = hashes[idx] + configFile;\n const { projectType, metadata, targets } = (targetsCache[hash] ??=\n await buildViteTargets(\n configFile,\n projectRoot,\n normalizedOptions,\n tsConfigFiles,\n hasReactRouterConfig,\n isUsingTsSolutionSetup,\n context\n ));\n\n const project: ProjectConfiguration = {\n root: projectRoot,\n targets,\n metadata,\n };\n\n // If project is buildable, then the project type.\n // If it is not buildable, then leave it to other plugins/project.json to set the project type.\n if (project.targets[normalizedOptions.buildTargetName]) {\n project.projectType = projectType;\n }\n\n return {\n projects: {\n [projectRoot]: project,\n },\n };\n },\n validConfigFiles,\n options,\n context\n );\n } finally {\n writeTargetsToCache(cachePath, targetsCache);\n }\n },\n];\n\nexport const createNodes: CreateNodes<VitePluginOptions> = [\n viteVitestConfigGlob,\n async (configFilePath, options, context) => {\n logger.warn(\n '`createNodes` is deprecated. Update your plugin to utilize createNodesV2 instead. In Nx 20, this will change to the createNodesV2 API.'\n );\n const projectRoot = dirname(configFilePath);\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot));\n if (\n !siblingFiles.includes('package.json') &&\n !siblingFiles.includes('project.json')\n ) {\n return {};\n }\n\n const tsConfigFiles =\n siblingFiles.filter((p) => minimatch(p, 'tsconfig*{.json,.*.json}')) ??\n [];\n\n const hasReactRouterConfig = siblingFiles.some((configFile) => {\n const parts = configFile.split('.');\n return (\n parts[0] === 'react-router' && parts[1] === 'config' && parts.length > 2\n );\n });\n\n const normalizedOptions = normalizeOptions(options);\n\n const isUsingTsSolutionSetup = _isUsingTsSolutionSetup();\n\n const { projectType, metadata, targets } = await buildViteTargets(\n configFilePath,\n projectRoot,\n normalizedOptions,\n tsConfigFiles,\n hasReactRouterConfig,\n isUsingTsSolutionSetup,\n context\n );\n const project: ProjectConfiguration = {\n root: projectRoot,\n targets,\n metadata,\n };\n\n // If project is buildable, then the project type.\n // If it is not buildable, then leave it to other plugins/project.json to set the project type.\n if (project.targets[normalizedOptions.buildTargetName]) {\n project.projectType = projectType;\n }\n\n return {\n projects: {\n [projectRoot]: project,\n },\n };\n },\n];\n\nasync function buildViteTargets(\n configFilePath: string,\n projectRoot: string,\n options: VitePluginOptions,\n tsConfigFiles: string[],\n hasReactRouterConfig: boolean,\n isUsingTsSolutionSetup: boolean,\n context: CreateNodesContext\n): Promise<ViteTargets> {\n const absoluteConfigFilePath = joinPathFragments(\n context.workspaceRoot,\n configFilePath\n );\n // Workaround for the `build$3 is not a function` error that we sometimes see in agents.\n // This should be removed later once we address the issue properly\n try {\n const importEsbuild = () => new Function('return import(\"esbuild\")')();\n await importEsbuild();\n } catch {\n // do nothing\n }\n const { resolveConfig } = await loadViteDynamicImport();\n const viteBuildConfig = await resolveConfig(\n {\n configFile: absoluteConfigFilePath,\n mode: 'development',\n },\n 'build'\n );\n\n const { buildOutputs, testOutputs, hasTest, isBuildable, hasServeConfig } =\n getOutputs(viteBuildConfig, projectRoot, context.workspaceRoot);\n\n const namedInputs = getNamedInputs(projectRoot, context);\n\n const targets: Record<string, TargetConfiguration> = {};\n\n // if file is vitest.config or vite.config has definition for test, create target for test\n if (configFilePath.includes('vitest.config') || hasTest) {\n targets[options.testTargetName] = await testTarget(\n namedInputs,\n testOutputs,\n projectRoot\n );\n }\n\n if (hasReactRouterConfig) {\n // If we have a react-router config, we can skip the rest of the targets\n return { targets, metadata: {}, projectType: 'application' };\n }\n // If file is not vitest.config and buildable, create targets for build, serve, preview and serve-static\n const hasRemixPlugin =\n viteBuildConfig.plugins &&\n viteBuildConfig.plugins.some((p) => p.name === 'remix');\n if (\n !configFilePath.includes('vitest.config') &&\n !hasRemixPlugin &&\n isBuildable\n ) {\n targets[options.buildTargetName] = await buildTarget(\n options.buildTargetName,\n namedInputs,\n buildOutputs,\n projectRoot,\n isUsingTsSolutionSetup\n );\n\n // If running in library mode, then there is nothing to serve.\n if (!viteBuildConfig.build?.lib || hasServeConfig) {\n const devTarget = serveTarget(projectRoot, isUsingTsSolutionSetup);\n\n targets[options.serveTargetName] = {\n ...devTarget,\n metadata: {\n ...devTarget.metadata,\n deprecated:\n 'Use devTargetName instead. This option will be removed in Nx 22.',\n },\n };\n targets[options.devTargetName] = devTarget;\n targets[options.previewTargetName] = previewTarget(\n projectRoot,\n options.buildTargetName\n );\n targets[options.serveStaticTargetName] = serveStaticTarget(\n options,\n isUsingTsSolutionSetup\n );\n }\n }\n\n if (tsConfigFiles.length) {\n const tsConfigToUse =\n ['tsconfig.app.json', 'tsconfig.lib.json', 'tsconfig.json'].find((t) =>\n tsConfigFiles.includes(t)\n ) ?? tsConfigFiles[0];\n targets[options.typecheckTargetName] = {\n cache: true,\n inputs: [\n ...('production' in namedInputs\n ? ['production', '^production']\n : ['default', '^default']),\n { externalDependencies: ['typescript'] },\n ],\n command: isUsingTsSolutionSetup\n ? `tsc --build --emitDeclarationOnly`\n : `tsc --noEmit -p ${tsConfigToUse}`,\n options: { cwd: joinPathFragments(projectRoot) },\n metadata: {\n description: `Runs type-checking for the project.`,\n technologies: ['typescript'],\n help: {\n command: isUsingTsSolutionSetup\n ? `${pmc.exec} tsc --build --help`\n : `${pmc.exec} tsc -p ${tsConfigToUse} --help`,\n example: isUsingTsSolutionSetup\n ? { args: ['--force'] }\n : { options: { noEmit: true } },\n },\n },\n };\n\n if (isUsingTsSolutionSetup) {\n targets[options.typecheckTargetName].dependsOn = [\n `^${options.typecheckTargetName}`,\n ];\n targets[options.typecheckTargetName].syncGenerators = [\n '@nx/js:typescript-sync',\n ];\n }\n }\n\n addBuildAndWatchDepsTargets(\n context.workspaceRoot,\n projectRoot,\n targets,\n options,\n pmc\n );\n\n const metadata = {};\n return {\n targets,\n metadata,\n projectType: viteBuildConfig.build?.lib ? 'library' : 'application',\n };\n}\n\nasync function buildTarget(\n buildTargetName: string,\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string,\n isUsingTsSolutionSetup: boolean\n) {\n const buildTarget: TargetConfiguration = {\n command: `vite build`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n dependsOn: [`^${buildTargetName}`],\n inputs: [\n ...('production' in namedInputs\n ? ['production', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vite'],\n },\n ],\n outputs,\n metadata: {\n technologies: ['vite'],\n description: `Run Vite build`,\n help: {\n command: `${pmc.exec} vite build --help`,\n example: {\n options: {\n sourcemap: true,\n manifest: 'manifest.json',\n },\n },\n },\n },\n };\n\n if (isUsingTsSolutionSetup) {\n buildTarget.syncGenerators = ['@nx/js:typescript-sync'];\n }\n\n return buildTarget;\n}\n\nfunction serveTarget(projectRoot: string, isUsingTsSolutionSetup: boolean) {\n const targetConfig: TargetConfiguration = {\n continuous: true,\n command: `vite`,\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n metadata: {\n technologies: ['vite'],\n description: `Starts Vite dev server`,\n help: {\n command: `${pmc.exec} vite --help`,\n example: {\n options: {\n port: 3000,\n },\n },\n },\n },\n };\n\n if (isUsingTsSolutionSetup) {\n targetConfig.syncGenerators = ['@nx/js:typescript-sync'];\n }\n\n return targetConfig;\n}\n\nfunction previewTarget(projectRoot: string, buildTargetName) {\n const targetConfig: TargetConfiguration = {\n continuous: true,\n command: `vite preview`,\n dependsOn: [buildTargetName],\n options: {\n cwd: joinPathFragments(projectRoot),\n },\n metadata: {\n technologies: ['vite'],\n description: `Locally preview Vite production build`,\n help: {\n command: `${pmc.exec} vite preview --help`,\n example: {\n options: {\n port: 3000,\n },\n },\n },\n },\n };\n\n return targetConfig;\n}\n\nasync function testTarget(\n namedInputs: {\n [inputName: string]: any[];\n },\n outputs: string[],\n projectRoot: string\n) {\n return {\n command: `vitest`,\n options: { cwd: joinPathFragments(projectRoot) },\n cache: true,\n inputs: [\n ...('production' in namedInputs\n ? ['default', '^production']\n : ['default', '^default']),\n {\n externalDependencies: ['vitest'],\n },\n { env: 'CI' },\n ],\n outputs,\n metadata: {\n technologies: ['vite'],\n description: `Run Vite tests`,\n help: {\n command: `${pmc.exec} vitest --help`,\n example: {\n options: {\n bail: 1,\n coverage: true,\n },\n },\n },\n },\n };\n}\n\nfunction serveStaticTarget(\n options: VitePluginOptions,\n isUsingTsSolutionSetup: boolean\n) {\n const targetConfig: TargetConfiguration = {\n continuous: true,\n executor: '@nx/web:file-server',\n options: {\n buildTarget: `${options.buildTargetName}`,\n spa: true,\n },\n };\n\n if (isUsingTsSolutionSetup) {\n targetConfig.syncGenerators = ['@nx/js:typescript-sync'];\n }\n\n return targetConfig;\n}\n\nfunction getOutputs(\n viteBuildConfig: Record<string, any> | undefined,\n projectRoot: string,\n workspaceRoot: string\n): {\n buildOutputs: string[];\n testOutputs: string[];\n hasTest: boolean;\n isBuildable: boolean;\n hasServeConfig: boolean;\n} {\n const { build, test, server } = viteBuildConfig;\n\n const buildOutputPath = normalizeOutputPath(\n build?.outDir,\n projectRoot,\n workspaceRoot,\n 'dist'\n );\n\n const isBuildable =\n build?.lib ||\n build?.rollupOptions?.input ||\n existsSync(join(workspaceRoot, projectRoot, 'index.html'));\n\n const hasServeConfig = Boolean(server);\n\n const reportsDirectoryPath = normalizeOutputPath(\n test?.coverage?.reportsDirectory,\n projectRoot,\n workspaceRoot,\n 'coverage'\n );\n\n return {\n buildOutputs: [buildOutputPath],\n testOutputs: [reportsDirectoryPath],\n hasTest: !!test,\n isBuildable,\n hasServeConfig,\n };\n}\n\nfunction normalizeOutputPath(\n outputPath: string | undefined,\n projectRoot: string,\n workspaceRoot: string,\n path: 'coverage' | 'dist'\n): string | undefined {\n if (!outputPath) {\n if (projectRoot === '.') {\n return `{projectRoot}/${path}`;\n } else {\n return `{workspaceRoot}/${path}/{projectRoot}`;\n }\n } else {\n if (isAbsolute(outputPath)) {\n return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`;\n } else {\n if (outputPath.startsWith('..')) {\n return join('{workspaceRoot}', join(projectRoot, outputPath));\n } else {\n return join('{projectRoot}', outputPath);\n }\n }\n }\n}\n\nfunction normalizeOptions(options: VitePluginOptions): VitePluginOptions {\n options ??= {};\n options.buildTargetName ??= 'build';\n options.serveTargetName ??= 'serve';\n options.devTargetName ??= 'dev';\n options.previewTargetName ??= 'preview';\n options.testTargetName ??= 'test';\n options.serveStaticTargetName ??= 'serve-static';\n options.typecheckTargetName ??= 'typecheck';\n return options;\n}\n\nfunction checkIfConfigFileShouldBeProject(\n projectRoot: string,\n context: CreateNodesContext | CreateNodesContextV2\n): boolean {\n // Do not create a project if package.json and project.json isn't there.\n const siblingFiles = readdirSync(join(context.workspaceRoot, projectRoot));\n if (\n !siblingFiles.includes('package.json') &&\n !siblingFiles.includes('project.json')\n ) {\n return false;\n }\n\n return true;\n}\n"],"names":["createDependencies","createNodes","createNodesV2","pmc","getPackageManagerCommand","readTargetsCache","cachePath","process","env","NX_CACHE_PROJECT_GRAPH","existsSync","readJsonFile","writeTargetsToCache","results","writeJsonFile","viteVitestConfigGlob","configFilePaths","options","context","optionsHash","hashObject","normalizedOptions","normalizeOptions","join","workspaceDataDirectory","targetsCache","isUsingTsSolutionSetup","_isUsingTsSolutionSetup","roots","projectRoots","configFiles","validConfigFiles","reduce","acc","configFile","potentialRoot","dirname","checkIfConfigFileShouldBeProject","push","lockfile","getLockFileName","detectPackageManager","workspaceRoot","hashes","calculateHashesForCreateNodes","map","r","createNodesFromFiles","_","idx","hash","projectRoot","siblingFiles","readdirSync","tsConfigFiles","filter","p","minimatch","hasReactRouterConfig","some","parts","split","length","projectType","metadata","targets","buildViteTargets","project","root","buildTargetName","projects","configFilePath","logger","warn","includes","viteBuildConfig","absoluteConfigFilePath","joinPathFragments","importEsbuild","Function","resolveConfig","loadViteDynamicImport","mode","buildOutputs","testOutputs","hasTest","isBuildable","hasServeConfig","getOutputs","namedInputs","getNamedInputs","testTargetName","testTarget","hasRemixPlugin","plugins","name","buildTarget","build","lib","devTarget","serveTarget","serveTargetName","deprecated","devTargetName","previewTargetName","previewTarget","serveStaticTargetName","serveStaticTarget","tsConfigToUse","find","t","typecheckTargetName","cache","inputs","externalDependencies","command","cwd","description","technologies","help","exec","example","args","noEmit","dependsOn","syncGenerators","addBuildAndWatchDepsTargets","outputs","sourcemap","manifest","targetConfig","continuous","port","bail","coverage","executor","spa","test","server","buildOutputPath","normalizeOutputPath","outDir","rollupOptions","input","Boolean","reportsDirectoryPath","reportsDirectory","outputPath","path","isAbsolute","relative","startsWith"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,SAAQyF,0DAARzF,UAAQyF,wBAA0B;;IAClCzF,yBAAAA,YAAAA,SAAQ8F,sDAAR9F,UAAQ8F,sBAAwB;IAChC,OAAO9F;AACT;AAEA,SAASoB,iCACPc,WAAmB,EACnBjC,OAAkD;IAElD,wEAAwE;IACxE,MAAMkC,eAAeC,IAAAA,eAAW,EAAC9B,IAAAA,UAAI,EAACL,QAAQwB,aAAa,EAAES;IAC7D,IACE,CAACC,aAAasB,QAAQ,CAAC,mBACvB,CAACtB,aAAasB,QAAQ,CAAC,iBACvB;QACA,OAAO;IACT;IAEA,OAAO;AACT"}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
import { type Tree } from '@nx/devkit';
|
|
2
2
|
export declare function getViteE2EWebServerInfo(tree: Tree, projectName: string, configFilePath: string, isPluginBeingAdded: boolean, e2ePortOverride?: number): Promise<import("@nx/devkit/src/generators/e2e-web-server-info-utils").E2EWebServerDetails>;
|
|
3
|
+
export declare function getReactRouterE2EWebServerInfo(tree: Tree, projectName: string, configFilePath: string, isPluginBeingAdded: boolean, e2ePortOverride?: number): Promise<import("@nx/devkit/src/generators/e2e-web-server-info-utils").E2EWebServerDetails>;
|
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
function _export(target, all) {
|
|
3
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
4
|
+
enumerable: true,
|
|
5
|
+
get: all[name]
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
_export(exports, {
|
|
9
|
+
getReactRouterE2EWebServerInfo: function() {
|
|
10
|
+
return getReactRouterE2EWebServerInfo;
|
|
11
|
+
},
|
|
12
|
+
getViteE2EWebServerInfo: function() {
|
|
5
13
|
return getViteE2EWebServerInfo;
|
|
6
14
|
}
|
|
7
15
|
});
|
|
@@ -29,5 +37,21 @@ async function getViteE2EWebServerInfo(tree, projectName, configFilePath, isPlug
|
|
|
29
37
|
defaultE2EPort: e2ePort
|
|
30
38
|
}, isPluginBeingAdded);
|
|
31
39
|
}
|
|
40
|
+
async function getReactRouterE2EWebServerInfo(tree, projectName, configFilePath, isPluginBeingAdded, e2ePortOverride) {
|
|
41
|
+
var _ref;
|
|
42
|
+
const e2ePort = (_ref = e2ePortOverride != null ? e2ePortOverride : parseInt(process.env.PORT)) != null ? _ref : 4200;
|
|
43
|
+
return await (0, _e2ewebserverinfoutils.getE2EWebServerInfo)(tree, projectName, {
|
|
44
|
+
plugin: '@nx/react/router-plugin',
|
|
45
|
+
serveTargetName: 'devTargetName',
|
|
46
|
+
serveStaticTargetName: 'devTargetName',
|
|
47
|
+
configFilePath
|
|
48
|
+
}, {
|
|
49
|
+
defaultServeTargetName: 'dev',
|
|
50
|
+
defaultServeStaticTargetName: 'dev',
|
|
51
|
+
defaultE2EWebServerAddress: `http://localhost:${e2ePort}`,
|
|
52
|
+
defaultE2ECiBaseUrl: 'http://localhost:4200',
|
|
53
|
+
defaultE2EPort: e2ePort
|
|
54
|
+
}, isPluginBeingAdded);
|
|
55
|
+
}
|
|
32
56
|
|
|
33
57
|
//# sourceMappingURL=e2e-web-server-info-utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/vite/src/utils/e2e-web-server-info-utils.ts"],"sourcesContent":["import { type Tree, readNxJson } from '@nx/devkit';\nimport { getE2EWebServerInfo } from '@nx/devkit/src/generators/e2e-web-server-info-utils';\n\nexport async function getViteE2EWebServerInfo(\n tree: Tree,\n projectName: string,\n configFilePath: string,\n isPluginBeingAdded: boolean,\n e2ePortOverride?: number\n) {\n const nxJson = readNxJson(tree);\n let e2ePort = e2ePortOverride ?? 4200;\n\n if (\n (nxJson.targetDefaults?.['dev'] &&\n nxJson.targetDefaults?.['dev'].options?.port) ||\n (nxJson.targetDefaults?.['serve'] &&\n nxJson.targetDefaults?.['serve'].options?.port)\n ) {\n e2ePort =\n nxJson.targetDefaults?.['dev'].options?.port ??\n nxJson.targetDefaults?.['serve'].options?.port;\n }\n\n return getE2EWebServerInfo(\n tree,\n projectName,\n {\n plugin: '@nx/vite/plugin',\n serveTargetName: 'devTargetName',\n serveStaticTargetName: 'previewTargetName',\n configFilePath,\n },\n {\n defaultServeTargetName: 'dev',\n defaultServeStaticTargetName: 'preview',\n defaultE2EWebServerAddress: `http://localhost:${e2ePort}`,\n defaultE2ECiBaseUrl: 'http://localhost:4300',\n defaultE2EPort: e2ePort,\n },\n isPluginBeingAdded\n );\n}\n"],"names":["getViteE2EWebServerInfo","tree","projectName","configFilePath","isPluginBeingAdded","e2ePortOverride","nxJson","readNxJson","e2ePort","targetDefaults","options","port","getE2EWebServerInfo","plugin","serveTargetName","serveStaticTargetName","defaultServeTargetName","defaultServeStaticTargetName","defaultE2EWebServerAddress","defaultE2ECiBaseUrl","defaultE2EPort"],"rangeMappings":"
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/vite/src/utils/e2e-web-server-info-utils.ts"],"sourcesContent":["import { type Tree, readNxJson } from '@nx/devkit';\nimport { getE2EWebServerInfo } from '@nx/devkit/src/generators/e2e-web-server-info-utils';\n\nexport async function getViteE2EWebServerInfo(\n tree: Tree,\n projectName: string,\n configFilePath: string,\n isPluginBeingAdded: boolean,\n e2ePortOverride?: number\n) {\n const nxJson = readNxJson(tree);\n let e2ePort = e2ePortOverride ?? 4200;\n\n if (\n (nxJson.targetDefaults?.['dev'] &&\n nxJson.targetDefaults?.['dev'].options?.port) ||\n (nxJson.targetDefaults?.['serve'] &&\n nxJson.targetDefaults?.['serve'].options?.port)\n ) {\n e2ePort =\n nxJson.targetDefaults?.['dev'].options?.port ??\n nxJson.targetDefaults?.['serve'].options?.port;\n }\n\n return getE2EWebServerInfo(\n tree,\n projectName,\n {\n plugin: '@nx/vite/plugin',\n serveTargetName: 'devTargetName',\n serveStaticTargetName: 'previewTargetName',\n configFilePath,\n },\n {\n defaultServeTargetName: 'dev',\n defaultServeStaticTargetName: 'preview',\n defaultE2EWebServerAddress: `http://localhost:${e2ePort}`,\n defaultE2ECiBaseUrl: 'http://localhost:4300',\n defaultE2EPort: e2ePort,\n },\n isPluginBeingAdded\n );\n}\n\nexport async function getReactRouterE2EWebServerInfo(\n tree: Tree,\n projectName: string,\n configFilePath: string,\n isPluginBeingAdded: boolean,\n e2ePortOverride?: number\n) {\n const e2ePort = e2ePortOverride ?? parseInt(process.env.PORT) ?? 4200;\n\n return await getE2EWebServerInfo(\n tree,\n projectName,\n {\n plugin: '@nx/react/router-plugin',\n serveTargetName: 'devTargetName',\n serveStaticTargetName: 'devTargetName',\n configFilePath,\n },\n {\n defaultServeTargetName: 'dev',\n defaultServeStaticTargetName: 'dev',\n defaultE2EWebServerAddress: `http://localhost:${e2ePort}`,\n defaultE2ECiBaseUrl: 'http://localhost:4200',\n defaultE2EPort: e2ePort,\n },\n isPluginBeingAdded\n );\n}\n"],"names":["getReactRouterE2EWebServerInfo","getViteE2EWebServerInfo","tree","projectName","configFilePath","isPluginBeingAdded","e2ePortOverride","nxJson","readNxJson","e2ePort","targetDefaults","options","port","getE2EWebServerInfo","plugin","serveTargetName","serveStaticTargetName","defaultServeTargetName","defaultServeStaticTargetName","defaultE2EWebServerAddress","defaultE2ECiBaseUrl","defaultE2EPort","parseInt","process","env","PORT"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":";;;;;;;;IA4CsBA,8BAA8B;eAA9BA;;IAzCAC,uBAAuB;eAAvBA;;;wBAHgB;uCACF;AAE7B,eAAeA,wBACpBC,IAAU,EACVC,WAAmB,EACnBC,cAAsB,EACtBC,kBAA2B,EAC3BC,eAAwB;QAMrBC,wBACCA,oCAAAA,yBACDA,yBACCA,sCAAAA;IAPJ,MAAMA,SAASC,IAAAA,kBAAU,EAACN;IAC1B,IAAIO,UAAUH,0BAAAA,kBAAmB;IAEjC,IACE,EAACC,yBAAAA,OAAOG,cAAc,qBAArBH,sBAAuB,CAAC,MAAM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gBAAgBZ;IAClB,GACAJ;AAEJ"}
|
|
@@ -322,7 +322,7 @@ function createOrEditViteConfig(tree, options, onlyVitest, projectAlreadyHasVite
|
|
|
322
322
|
fileName: 'index',
|
|
323
323
|
// Change this to the formats you want to support.
|
|
324
324
|
// Don't forget to update your package.json as well.
|
|
325
|
-
formats: ['es']
|
|
325
|
+
formats: ['es' as const]
|
|
326
326
|
},
|
|
327
327
|
rollupOptions: {
|
|
328
328
|
// External packages that should not be bundled into your library.
|
|
@@ -358,7 +358,7 @@ function createOrEditViteConfig(tree, options, onlyVitest, projectAlreadyHasVite
|
|
|
358
358
|
watch: false,
|
|
359
359
|
globals: true,
|
|
360
360
|
environment: '${(_options_testEnvironment = options.testEnvironment) != null ? _options_testEnvironment : 'jsdom'}',
|
|
361
|
-
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
|
361
|
+
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
|
362
362
|
${options.setupFile ? ` setupFiles: ['${options.setupFile}'],\n` : ''}\
|
|
363
363
|
${options.inSourceTests ? ` includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n` : ''}\
|
|
364
364
|
reporters: ['default'],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/vite/src/utils/generator-utils.ts"],"sourcesContent":["import {\n joinPathFragments,\n logger,\n offsetFromRoot,\n readJson,\n readNxJson,\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';\nimport { VitestGeneratorSchema } from '../generators/vitest/schema';\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: VitestGeneratorSchema,\n hasPlugin: boolean\n) {\n const nxJson = readNxJson(tree);\n\n hasPlugin = nxJson.plugins?.some((p) =>\n typeof p === 'string'\n ? p === '@nx/vite/plugin'\n : p.plugin === '@nx/vite/plugin' || hasPlugin\n );\n\n if (hasPlugin) {\n return;\n }\n\n const project = readProjectConfiguration(tree, options.project);\n const target = options.testTarget ?? 'test';\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 throw new Error(`Target \"${target}\" already exists in the project.`);\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\n const isTsSolutionSetup = isUsingTsSolutionSetup(tree);\n const buildOptions: ViteBuildExecutorOptions = {\n outputPath: isTsSolutionSetup\n ? joinPathFragments(project.root, 'dist')\n : 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 let tsconfigPath = joinPathFragments(projectConfig.root, 'tsconfig.json');\n const isTsSolutionSetup = isUsingTsSolutionSetup(tree);\n if (isTsSolutionSetup) {\n tsconfigPath = [\n joinPathFragments(projectConfig.root, 'tsconfig.app.json'),\n joinPathFragments(projectConfig.root, 'tsconfig.lib.json'),\n ].find((p) => tree.exists(p));\n }\n const config = readJson(tree, tsconfigPath);\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 if (!isTsSolutionSetup) {\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 }\n break;\n default:\n break;\n }\n\n writeJson(tree, tsconfigPath, 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 setupFile?: string;\n useEsmExtension?: boolean;\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 extension = options.useEsmExtension ? 'mts' : 'ts';\n const viteConfigPath = vitestFileName\n ? `${projectRoot}/vitest.config.${extension}`\n : `${projectRoot}/vite.config.${extension}`;\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']\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 const plugins: string[] = options.plugins ? [...options.plugins] : [];\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 if (!isUsingTsPlugin) {\n imports.push(\n `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'`,\n `import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin'`\n );\n plugins.push(`nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`);\n }\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 = isUsingTsPlugin\n ? './test-output/vitest/coverage'\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.setupFile ? ` setupFiles: ['${options.setupFile}'],\\n` : ''}\\\n${\n options.inSourceTests\n ? ` includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\\n`\n : ''\n}\\\n reporters: ['default'],\n coverage: {\n reportsDirectory: '${reportsDirectory}',\n provider: ${\n options.coverageProvider\n ? `'${options.coverageProvider}' as const`\n : `'v8' as const`\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 const viteConfigContent = `/// <reference types='vitest' />\nimport { defineConfig } from 'vite';\n${imports.join(';\\n')}${imports.length ? ';' : ''}\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'],\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","hasPlugin","nxJson","project","readNxJson","plugins","some","p","plugin","readProjectConfiguration","testTarget","reportsDirectory","joinPathFragments","offsetFromRoot","root","testOptions","Error","outputs","updateProjectConfiguration","addBuildTargetDefaults","isTsSolutionSetup","isUsingTsSolutionSetup","buildOptions","outputPath","defaultConfiguration","configurations","development","mode","production","buildTarget","hmr","serveTarget","previewOptions","proxyConfig","https","open","preview","dependsOn","projectConfig","tsconfigPath","find","exists","config","readJson","uiFramework","compilerOptions","jsx","allowJs","esModuleInterop","allowSyntheticDefaultImports","strict","module","forceConsistentCasingInFileNames","noImplicitOverride","noPropertyAccessFromIndexSignature","noImplicitReturns","noFallthroughCasesInSwitch","writeJson","projectRoot","webpackConfigFilePath","webpackConfigPath","delete","indexHtmlPath","mainPath","replace","indexHtmlContent","read","write","onlyVitest","projectAlreadyHasViteTargets","vitestFileName","extension","useEsmExtension","viteConfigPath","isUsingTsPlugin","buildOutDir","buildOption","includeLib","rollupOptionsExternal","imports","push","testOption","includeVitest","testEnvironment","setupFile","inSourceTests","coverageProvider","defineOption","devServerOption","previewServerOption","workerOption","cacheDir","normalizedJoinPaths","handleViteConfigFileExists","viteConfigContent","join","length","printOptions","filter","Boolean","configFile","undefined","projectName","Object","values","userProvidedTargetIsUnsupported","userProvidedTargetName","validFoundTargetName","handleUnsupportedUserProvidedTargetsErrors","serve","test","logger","warn","Confirm","require","prompt","name","message","initial","shouldConvert","run","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":";;;;;;;;IA+HgBA,cAAc;eAAdA;;IA5CAC,qBAAqB;eAArBA;;IAqHAC,gBAAgB;eAAhBA;;IArCAC,cAAc;eAAdA;;IA2NAC,sBAAsB;eAAtBA;;IA9FAC,mBAAmB;eAAnBA;;IA9CAC,YAAY;eAAZA;;I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IAAAA,8CAAyB,EACvClJ,MACA0E,gBACAG,aACAkD,mBACA/C,SACA1E,SACA4E,YACAwD,kBACA9C,UACAtB,uCAAAA,+BAAgC,CAAC;IAGnC,IAAI,CAAC2E,SAAS;QACZjC,cAAM,CAACC,IAAI,CACT,CAAC,wEAAwE,EAAEvC,eAAe;;QAExF,EAAEG,YAAY;;QAEd,CAAC;IAEP;AACF;AAEA,SAASgB,oBAAoB,GAAGsD,KAAe;IAC7C,MAAMC,OAAOvI,IAAAA,yBAAiB,KAAIsI;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 readNxJson,\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';\nimport { VitestGeneratorSchema } from '../generators/vitest/schema';\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: VitestGeneratorSchema,\n hasPlugin: boolean\n) {\n const nxJson = readNxJson(tree);\n\n hasPlugin = nxJson.plugins?.some((p) =>\n typeof p === 'string'\n ? p === '@nx/vite/plugin'\n : p.plugin === '@nx/vite/plugin' || hasPlugin\n );\n\n if (hasPlugin) {\n return;\n }\n\n const project = readProjectConfiguration(tree, options.project);\n const target = options.testTarget ?? 'test';\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 throw new Error(`Target \"${target}\" already exists in the project.`);\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\n const isTsSolutionSetup = isUsingTsSolutionSetup(tree);\n const buildOptions: ViteBuildExecutorOptions = {\n outputPath: isTsSolutionSetup\n ? joinPathFragments(project.root, 'dist')\n : 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 let tsconfigPath = joinPathFragments(projectConfig.root, 'tsconfig.json');\n const isTsSolutionSetup = isUsingTsSolutionSetup(tree);\n if (isTsSolutionSetup) {\n tsconfigPath = [\n joinPathFragments(projectConfig.root, 'tsconfig.app.json'),\n joinPathFragments(projectConfig.root, 'tsconfig.lib.json'),\n ].find((p) => tree.exists(p));\n }\n const config = readJson(tree, tsconfigPath);\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 if (!isTsSolutionSetup) {\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 }\n break;\n default:\n break;\n }\n\n writeJson(tree, tsconfigPath, 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 setupFile?: string;\n useEsmExtension?: boolean;\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 extension = options.useEsmExtension ? 'mts' : 'ts';\n const viteConfigPath = vitestFileName\n ? `${projectRoot}/vitest.config.${extension}`\n : `${projectRoot}/vite.config.${extension}`;\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' as const]\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 const plugins: string[] = options.plugins ? [...options.plugins] : [];\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 if (!isUsingTsPlugin) {\n imports.push(\n `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'`,\n `import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin'`\n );\n plugins.push(`nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`);\n }\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 = isUsingTsPlugin\n ? './test-output/vitest/coverage'\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,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\n${options.setupFile ? ` setupFiles: ['${options.setupFile}'],\\n` : ''}\\\n${\n options.inSourceTests\n ? ` includeSource: ['src/**/*.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],\\n`\n : ''\n}\\\n reporters: ['default'],\n coverage: {\n reportsDirectory: '${reportsDirectory}',\n provider: ${\n options.coverageProvider\n ? `'${options.coverageProvider}' as const`\n : `'v8' as const`\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 const viteConfigContent = `/// <reference types='vitest' />\nimport { defineConfig } from 'vite';\n${imports.join(';\\n')}${imports.length ? ';' : ''}\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'],\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","hasPlugin","nxJson","project","readNxJson","plugins","some","p","plugin","readProjectConfiguration","testTarget","reportsDirectory","joinPathFragments","offsetFromRoot","root","testOptions","Error","outputs","updateProjectConfiguration","addBuildTargetDefaults","isTsSolutionSetup","isUsingTsSolutionSetup","buildOptions","outputPath","defaultConfiguration","configurations","development","mode","production","buildTarget","hmr","serveTarget","previewOptions","proxyConfig","https","open","preview","dependsOn","projectConfig","tsconfigPath","find","exists","config","readJson","uiFramework","compilerOptions","jsx","allowJs","esModuleInterop","allowSyntheticDefaultImports","strict","module","forceConsistentCasingInFileNames","noImplicitOverride","noPropertyAccessFromIndexSignature","noImplicitReturns","noFallthroughCasesInSwitch","writeJson","projectRoot","webpackConfigFilePath","webpackConfigPath","delete","indexHtmlPath","mainPath","replace","indexHtmlContent","read","write","onlyVitest","projectAlreadyHasViteTargets","vitestFileName","extension","useEsmExtension","viteConfigPath","isUsingTsPlugin","buildOutDir","buildOption","includeLib","rollupOptionsExternal","imports","push","testOption","includeVitest","testEnvironment","setupFile","inSourceTests","coverageProvider","defineOption","devServerOption","previewServerOption","workerOption","cacheDir","normalizedJoinPaths","handleViteConfigFileExists","viteConfigContent","join","length","printOptions","filter","Boolean","configFile","undefined","projectName","Object","values","userProvidedTargetIsUnsupported","userProvidedTargetName","validFoundTargetName","handleUnsupportedUserProvidedTargetsErrors","serve","test","logger","warn","Confirm","require","prompt","name","message","initial","shouldConvert","run","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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K,CAAC;AAClD"}
|
|
@@ -55,6 +55,17 @@ function handleBuildOrTestNode(updatedFileContent, configContentString, configCo
|
|
|
55
55
|
}
|
|
56
56
|
propString += `}`;
|
|
57
57
|
updatedPropsString += `${propString}\n`;
|
|
58
|
+
} else if (propName === 'lib') {
|
|
59
|
+
let propString = ` '${propName}': {\n`;
|
|
60
|
+
for (const [pName, pValue] of Object.entries(propValue)){
|
|
61
|
+
if (pName === 'formats') {
|
|
62
|
+
propString += ` '${pName}': [${pValue.map((format)=>`'${format}' as const`).join(', ')}],\n`;
|
|
63
|
+
} else {
|
|
64
|
+
propString += ` '${pName}': ${JSON.stringify(pValue)},\n`;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
propString += ` },`;
|
|
68
|
+
updatedPropsString += `${propString}\n`;
|
|
58
69
|
} else {
|
|
59
70
|
updatedPropsString += ` '${propName}': ${JSON.stringify(propValue)},\n`;
|
|
60
71
|
}
|
|
@@ -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 // 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 if (propName === 'coverage') {\n let propString = ` '${propName}': {\\n`;\n for (const [pName, pValue] of Object.entries(propValue)) {\n if (pName === 'provider') {\n propString += ` '${pName}': ${pValue} as const,\\n`;\n } else {\n propString += ` '${pName}': '${pValue}',\\n`;\n }\n }\n propString += `}`;\n updatedPropsString += `${propString}\\n`;\n } else {\n updatedPropsString += ` '${propName}': ${JSON.stringify(\n propValue\n )},\\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","propString","pName","pValue","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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qBACD;gBACH,OAAO;oBACLqD,iBAAiBZ,IAAAA,4BAAoB,EAACY,gBAAgB;wBACpD;4BACEX,MAAMC,kBAAU,CAACC,MAAM;4BACvBC,OAAOR,iBAAiB,CAAC,EAAE,CAACS,QAAQ,KAAK;4BACzCC,MAAM/C;wBACR;qBACD;gBACH;YACF;QACF,OAAO;YACL,8DAA8D;YAC9D,yDAAyD;YACzD,IAAI;gBACF,MAAMgD,gBAAgB/B,QAAQG,KAAK,CAACyD,MAAM;gBAC1C,MAAM5B,QAAQhC,2BAAAA,QAASG,KAAK,CAC1B4B,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,MAAM/C;oBACR;iBACD;YACH,EAAE,UAAM,CAAC;QACX;IACF;IAEA,OAAOqD;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 if (propName === 'coverage') {\n let propString = ` '${propName}': {\\n`;\n for (const [pName, pValue] of Object.entries(propValue)) {\n if (pName === 'provider') {\n propString += ` '${pName}': ${pValue} as const,\\n`;\n } else {\n propString += ` '${pName}': '${pValue}',\\n`;\n }\n }\n propString += `}`;\n updatedPropsString += `${propString}\\n`;\n } else if (propName === 'lib') {\n let propString = ` '${propName}': {\\n`;\n for (const [pName, pValue] of Object.entries(propValue)) {\n if (pName === 'formats') {\n propString += ` '${pName}': [${pValue\n .map((format: string) => `'${format}' as const`)\n .join(', ')}],\\n`;\n } else {\n propString += ` '${pName}': ${JSON.stringify(pValue)},\\n`;\n }\n }\n propString += ` },`;\n updatedPropsString += `${propString}\\n`;\n } else {\n updatedPropsString += ` '${propName}': ${JSON.stringify(\n propValue\n )},\\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","propString","pName","pValue","map","format","join","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","filteredImports","filterImport","importNodes","importsArrayExisting","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,QAAgB,EAChBC,4BAA0C;IAE1C,MAAMC,cAAcV,KAAKW,IAAI,CAACV,MAAM;IAEpC,IAAIW,iBAAiBC;IAErB,IAAI,EAACJ,gDAAAA,6BAA8BK,IAAI,MAAIR,oCAAAA,iBAAkBS,MAAM,GAAE;QACnEH,iBAAiBI,sBACfN,aACAJ,kBACAC,kBACA;IAEJ;IAEA,IAAI,EAACE,gDAAAA,6BAA8BQ,KAAK,MAAIf,qCAAAA,kBAAmBa,MAAM,GAAE;QACrEH,iBAAiBI,sBACfJ,yBAAAA,iBAAkBF,aAClBR,mBACAC,mBACA;IAEJ;QAGEe;IADFN,iBACEM,CAAAA,oBAAAA,iBAAiBN,yBAAAA,iBAAkBF,aAAaN,SAASC,oBAAzDa,oBACAN;IAEF,IAAIJ,4BAAAA,SAAUO,MAAM,EAAE;QACpBH,iBAAi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