import path from "path"; import type { Plugin } from "vite"; import type { Plugin as RollupPlugin } from "rollup"; import { replace, swc as swcPlugin, minify, header, sourcemapUrl, outputOptions, collectSnTranslate, } from "../index"; import { createUpdateSrcPath } from "../servicenow/react-plugins"; import { buildOnly } from "./build-only"; import { servicenowCssAssetPlugin } from "./css-asset"; import { servicenowHtmlPlugin } from "./html"; import { servicenowImageAssetPlugin } from "./image-asset"; import { servicenowSeismicPlugin } from "./seismic"; import type { RegisterExplicitIdFunction, Credential, } from "../servicenow/types"; export interface ServicenowVitePluginOptions { scope: string; rootDir: string; registerExplicitId?: RegisterExplicitIdFunction; enableCacheBusting?: boolean; credential?: Credential; /** * Enable/disable SWC transpilation in favor of another transpiler (esbuild/oxc). * @default true */ swc?: boolean; } export async function servicenowVitePlugins( options: ServicenowVitePluginOptions, ): Promise { const { scope, rootDir, registerExplicitId, enableCacheBusting = false, swc: swc = true, } = options; return [ servicenowSeismicPlugin(), servicenowCssAssetPlugin({ registerExplicitId }), servicenowHtmlPlugin({ rootDir, entryPath(entry: string, { fullPath }: { fullPath: string }) { const entryWithoutQueryParams = entry.replace(/\?.+/, ""); const fullPathWithoutQueryParams = fullPath.replace(/\?.+/, ""); const normalizedPath = path.normalize( entryWithoutQueryParams.replace(/^(?:\.\.\/)+/, ""), ); const ext = path.extname(normalizedPath); const outName = normalizedPath.substring( 0, normalizedPath.length - ext.length, ); return { [`${outName}`]: fullPathWithoutQueryParams, }; }, updateSrcPath: createUpdateSrcPath({ scope, // This plugin is never used for the dev server, so we don't need to preserve source paths preserveSrc: false, enableCacheBusting, }), }), buildOnly( outputOptions((rawOptions) => { const fileNames = "[name].jsdbx"; if (Array.isArray(rawOptions)) { for (const output of rawOptions) { output.entryFileNames = fileNames; output.chunkFileNames = fileNames; } } else { rawOptions.entryFileNames = fileNames; rawOptions.chunkFileNames = fileNames; } return rawOptions; }), ), buildOnly( replace({ "process.env.NODE_ENV": JSON.stringify("production"), preventAssignment: true, }), ), // No json() here: Vite has handled `.json` imports natively since v6 buildOnly(collectSnTranslate()), ...(swc ? [ buildOnly( swcPlugin({ swc: { jsc: { parser: { tsx: true, syntax: "typescript", }, transform: { react: { runtime: "automatic", }, }, experimental: { keepImportAssertions: true, }, }, }, }), ), ] : []), buildOnly(minify({ compress: true, mangle: false })), buildOnly(header("/*__ESM_BODY_START__*/window.process={versions:null};")), buildOnly( sourcemapUrl({ replaceUrl: (url: string) => `${url.replace("dbx", "")}.jsdbx`, }), ), buildOnly(servicenowImageAssetPlugin({ scope })), ]; }