@lomray/vite-ssr-boost 2.8.1 → 3.0.0-beta.2

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/cli/build.d.ts CHANGED
@@ -1,17 +1,6 @@
1
- interface IBuildParams {
2
- onFinish?: () => void;
3
- mode?: string;
4
- clientOptions?: string;
5
- serverOptions?: string;
6
- isOnlyClient?: boolean;
7
- isWatch?: boolean;
8
- isUnlockRobots?: boolean;
9
- isEject?: boolean;
10
- isServerless?: boolean;
11
- isNoWarnings?: boolean;
12
- }
1
+ import { IBuildParams } from "../services/build.js";
13
2
  /**
14
- * Build production application
3
+ * Build application
15
4
  */
16
- declare function build({ onFinish, mode, clientOptions, serverOptions, isOnlyClient, isWatch, isUnlockRobots, isEject, isServerless, isNoWarnings, }: IBuildParams): Promise<void>;
5
+ declare function build(params: IBuildParams): Promise<void>;
17
6
  export { build as default };
package/cli/build.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:child_process";import{performance as o}from"node:perf_hooks";import i from"chalk";import s from"./helpers/vite-reset-cache.js";import t from"../constants/cli-name.js";import{createDevMarker as r}from"../helpers/dev-marker.js";import n from"../helpers/process-stop.js";import{removeMeta as l}from"../helpers/ssr-meta.js";import a from"../services/build.js";async function m({onFinish:m,mode:p="",clientOptions:c="",serverOptions:d="",isOnlyClient:f=!1,isWatch:u=!1,isUnlockRobots:v=!1,isEject:O=!1,isServerless:S=!1,isNoWarnings:h=!1}){const $=o.now(),b=new a({mode:p}),_=["client"],g=new AbortController,w=p?`--mode ${p}`:"";await b.makeConfig(),await s(),b.clearBuildFolder();const C=b.promisifyProcess(e.spawn(`vite build ${c} --emptyOutDir --outDir ${b.outDir}/client ${w}`,{signal:g.signal,stdio:[process.stdin,"pipe","pipe"],shell:!0,env:{...process.env,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:f?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}}),h);if(!u){const e=await C.promise;n(e,!0)}let R=null;if(!f){if(R=b.promisifyProcess(e.spawn(`vite build ${d} --emptyOutDir --outDir ${b.outDir}/server --ssr ${b.serverFile} ${w}`,{signal:g.signal,stdio:[process.stdin,"pipe","pipe"],shell:!0,env:{...process.env,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:f?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}}),h),!u){const e=await R.promise;n(e,!0),await b.buildManifest(),O&&b.eject(),S&&b.createServerless()}_.push("server")}if(u){process.on("exit",(()=>{g.abort()}));let e=f?1:2;const o=i=>{Buffer.from(i).toString().includes("built in")&&(e-=1,e||(C.command.stdout?.removeListener("data",o),R?.command.stdout?.removeListener("data",o),r(b.isProd,b.viteConfig),m?.()))};return C.command.stdout?.on("data",o),void R?.command.stdout?.on("data",o)}v&&b.unlockRobots(),r(b.isProd,b.viteConfig),l(b.buildDir),m?.();const B=Math.ceil(o.now()-$),j=B>1e3?(B/1e3).toFixed(2):B,D=B>1e3?"s":"ms",y=i.dim(`${i.yellowBright(_.join(","))} built in ${i.reset(i.bold(j))} ${D}`);console.info(`\n ${i.green(`${i.bold(t.toUpperCase())}`)} ${y} ${b.isProd?"":i.redBright(`NODE_ENV=${b.nodeEnv}`)}\n`)}export{m as default};
1
+ import{performance as o}from"node:perf_hooks";import e from"chalk";import n from"../constants/cli-name.js";import t from"../services/build.js";async function i(i){const r=o.now(),s=new t(i);await s.build();const l=Math.ceil(o.now()-r),d=l>1e3?(l/1e3).toFixed(2):l,m=l>1e3?"s":"ms",a=e.dim(`${e.yellowBright(s.getRunningBuildNames().join(","))} built in ${e.reset(e.bold(d))} ${m}`);console.info(`\n ${e.green(`${e.bold(n.toUpperCase())}`)} ${a} ${s.getIsProd()?"":e.redBright(`NODE_ENV=${s.getNodeEnv()}`)}\n`)}export{i as default};
2
2
  //# sourceMappingURL=build.js.map
package/cli/build.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sources":["../../src/cli/build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport viteResetCache from '@cli/helpers/vite-reset-cache';\nimport cliName from '@constants/cli-name';\nimport { createDevMarker } from '@helpers/dev-marker';\nimport processStop from '@helpers/process-stop';\nimport { removeMeta } from '@helpers/ssr-meta';\nimport Build from '@services/build';\n\ninterface IBuildParams {\n onFinish?: () => void;\n mode?: string;\n clientOptions?: string;\n serverOptions?: string;\n isOnlyClient?: boolean;\n isWatch?: boolean;\n isUnlockRobots?: boolean;\n isEject?: boolean;\n isServerless?: boolean;\n isNoWarnings?: boolean;\n}\n\n/**\n * Build production application\n */\nasync function build({\n onFinish,\n mode = '',\n clientOptions = '',\n serverOptions = '',\n isOnlyClient = false,\n isWatch = false,\n isUnlockRobots = false,\n isEject = false,\n isServerless = false,\n isNoWarnings = false,\n}: IBuildParams): Promise<void> {\n const perfStart = performance.now();\n const buildService = new Build({ mode });\n const types = ['client'];\n const controller = new AbortController();\n const modeOpt = mode ? `--mode ${mode}` : '';\n\n await buildService.makeConfig();\n\n // this is required step - build with different env may cause problems\n await viteResetCache();\n buildService.clearBuildFolder();\n\n /**\n * Build client\n */\n const clientProcess = buildService.promisifyProcess(\n childProcess.spawn(\n `vite build ${clientOptions} --emptyOutDir --outDir ${buildService.outDir}/client ${modeOpt}`,\n {\n signal: controller.signal,\n stdio: [process.stdin, 'pipe', 'pipe'],\n shell: true,\n env: {\n ...process.env,\n FORCE_COLOR: '2',\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n SSR_BOOST_ACTION: global.viteBoostAction,\n },\n },\n ),\n isNoWarnings,\n );\n\n if (!isWatch) {\n const exitCode = await clientProcess.promise;\n\n processStop(exitCode, true);\n }\n\n let serverProcess: ReturnType<Build['promisifyProcess']> | null = null;\n\n /**\n * Build server\n */\n if (!isOnlyClient) {\n serverProcess = buildService.promisifyProcess(\n childProcess.spawn(\n `vite build ${serverOptions} --emptyOutDir --outDir ${buildService.outDir}/server --ssr ${buildService.serverFile} ${modeOpt}`,\n {\n signal: controller.signal,\n stdio: [process.stdin, 'pipe', 'pipe'],\n shell: true,\n env: {\n ...process.env,\n FORCE_COLOR: '2',\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n SSR_BOOST_ACTION: global.viteBoostAction,\n },\n },\n ),\n isNoWarnings,\n );\n\n if (!isWatch) {\n const exitCode = await serverProcess.promise;\n\n processStop(exitCode, true);\n await buildService.buildManifest();\n\n if (isEject) {\n buildService.eject();\n }\n\n if (isServerless) {\n buildService.createServerless();\n }\n }\n\n types.push('server');\n }\n\n /**\n * Preview mode\n */\n if (isWatch) {\n process.on('exit', () => {\n controller.abort();\n });\n\n let buildCount = isOnlyClient ? 1 : 2;\n const listener = (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('built in')) {\n buildCount -= 1;\n\n if (!buildCount) {\n clientProcess.command.stdout?.removeListener('data', listener);\n serverProcess?.command.stdout?.removeListener('data', listener);\n createDevMarker(buildService.isProd, buildService.viteConfig);\n onFinish?.();\n }\n }\n };\n\n /**\n * Listen output for call onFinish\n */\n clientProcess.command.stdout?.on('data', listener);\n serverProcess?.command.stdout?.on('data', listener);\n\n return;\n }\n\n if (isUnlockRobots) {\n buildService.unlockRobots();\n }\n\n createDevMarker(buildService.isProd, buildService.viteConfig);\n removeMeta(buildService.buildDir);\n onFinish?.();\n\n const durationMs = Math.ceil(performance.now() - perfStart);\n const duration = durationMs > 1000 ? (durationMs / 1000).toFixed(2) : durationMs;\n const units = durationMs > 1000 ? 's' : 'ms';\n\n const buildDurationString = chalk.dim(\n `${chalk.yellowBright(types.join(','))} built in ${chalk.reset(chalk.bold(duration))} ${units}`,\n );\n\n console.info(\n `\\n ${chalk.green(`${chalk.bold(cliName.toUpperCase())}`)} ${buildDurationString} ${\n buildService.isProd ? '' : chalk.redBright(`NODE_ENV=${buildService.nodeEnv}`)\n }\\n`,\n );\n}\n\nexport default build;\n"],"names":["async","build","onFinish","mode","clientOptions","serverOptions","isOnlyClient","isWatch","isUnlockRobots","isEject","isServerless","isNoWarnings","perfStart","performance","now","buildService","Build","types","controller","AbortController","modeOpt","makeConfig","viteResetCache","clearBuildFolder","clientProcess","promisifyProcess","childProcess","spawn","outDir","signal","stdio","process","stdin","shell","env","FORCE_COLOR","SSR_BOOST_IS_SSR","SSR_BOOST_ACTION","global","viteBoostAction","exitCode","promise","processStop","serverProcess","serverFile","buildManifest","eject","createServerless","push","on","abort","buildCount","listener","buff","Buffer","from","toString","includes","command","stdout","removeListener","createDevMarker","isProd","viteConfig","unlockRobots","removeMeta","buildDir","durationMs","Math","ceil","duration","toFixed","units","buildDurationString","chalk","dim","yellowBright","join","reset","bold","console","info","green","cliName","toUpperCase","redBright","nodeEnv"],"mappings":"uXA0BAA,eAAeC,GAAMC,SACnBA,EAAQC,KACRA,EAAO,GAAEC,cACTA,EAAgB,GAAEC,cAClBA,EAAgB,GAAEC,aAClBA,GAAe,EAAKC,QACpBA,GAAU,EAAKC,eACfA,GAAiB,EAAKC,QACtBA,GAAU,EAAKC,aACfA,GAAe,EAAKC,aACpBA,GAAe,IAEf,MAAMC,EAAYC,EAAYC,MACxBC,EAAe,IAAIC,EAAM,CAAEb,SAC3Bc,EAAQ,CAAC,UACTC,EAAa,IAAIC,gBACjBC,EAAUjB,EAAO,UAAUA,IAAS,SAEpCY,EAAaM,mBAGbC,IACNP,EAAaQ,mBAKb,MAAMC,EAAgBT,EAAaU,iBACjCC,EAAaC,MACX,cAAcvB,4BAAwCW,EAAaa,iBAAiBR,IACpF,CACES,OAAQX,EAAWW,OACnBC,MAAO,CAACC,QAAQC,MAAO,OAAQ,QAC/BC,OAAO,EACPC,IAAK,IACAH,QAAQG,IACXC,YAAa,IACbC,iBAAkB9B,EAAe,IAAM,IACvC+B,iBAAkBC,OAAOC,mBAI/B5B,GAGF,IAAKJ,EAAS,CACZ,MAAMiC,QAAiBhB,EAAciB,QAErCC,EAAYF,GAAU,EACvB,CAED,IAAIG,E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,EAAMK,KAAKT,OAAcE,KAG1FQ,QAAQC,KACN,OAAOP,EAAMQ,MAAM,GAAGR,EAAMK,KAAKI,EAAQC,sBAAsBX,KAC7D1D,EAAa+C,OAAS,GAAKY,EAAMW,UAAU,YAAYtE,EAAauE,eAG1E"}
1
+ {"version":3,"file":"build.js","sources":["../../src/cli/build.ts"],"sourcesContent":["import { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport cliName from '@constants/cli-name';\nimport type { IBuildParams } from '@services/build';\nimport Build from '@services/build';\n\n/**\n * Build application\n */\nasync function build(params: IBuildParams): Promise<void> {\n const perfStart = performance.now();\n const buildService = new Build(params);\n\n await buildService.build();\n\n const durationMs = Math.ceil(performance.now() - perfStart);\n const duration = durationMs > 1000 ? (durationMs / 1000).toFixed(2) : durationMs;\n const units = durationMs > 1000 ? 's' : 'ms';\n\n const buildDurationString = chalk.dim(\n `${chalk.yellowBright(buildService.getRunningBuildNames().join(','))} built in ${chalk.reset(chalk.bold(duration))} ${units}`,\n );\n\n console.info(\n `\\n ${chalk.green(`${chalk.bold(cliName.toUpperCase())}`)} ${buildDurationString} ${\n buildService.getIsProd() ? '' : chalk.redBright(`NODE_ENV=${buildService.getNodeEnv()}`)\n }\\n`,\n );\n}\n\nexport default build;\n"],"names":["async","build","params","perfStart","performance","now","buildService","Build","durationMs","Math","ceil","duration","toFixed","units","buildDurationString","chalk","dim","yellowBright","getRunningBuildNames","join","reset","bold","console","info","green","cliName","toUpperCase","getIsProd","redBright","getNodeEnv"],"mappings":"+IASAA,eAAeC,EAAMC,GACnB,MAAMC,EAAYC,EAAYC,MACxBC,EAAe,IAAIC,EAAML,SAEzBI,EAAaL,QAEnB,MAAMO,EAAaC,KAAKC,KAAKN,EAAYC,MAAQF,GAC3CQ,EAAWH,EAAa,KAAQA,EAAa,KAAMI,QAAQ,GAAKJ,EAChEK,EAAQL,EAAa,IAAO,IAAM,KAElCM,EAAsBC,EAAMC,IAChC,GAAGD,EAAME,aAAaX,EAAaY,uBAAuBC,KAAK,kBAAkBJ,EAAMK,MAAML,EAAMM,KAAKV,OAAcE,KAGxHS,QAAQC,KACN,OAAOR,EAAMS,MAAM,GAAGT,EAAMM,KAAKI,EAAQC,sBAAsBZ,KAC7DR,EAAaqB,YAAc,GAAKZ,EAAMa,UAAU,YAAYtB,EAAauB,oBAG/E"}
@@ -1,10 +1,13 @@
1
+ import { IBuildParams } from "../../services/build.js";
1
2
  interface IDevActionParams {
2
3
  host?: boolean;
4
+ port?: number;
3
5
  resetCache?: boolean;
4
6
  mode?: string;
7
+ entrypoint?: string;
5
8
  }
6
9
  interface IBuildActionParams {
7
- onlyClient?: boolean;
10
+ focusOnly?: IBuildParams['focusOnly'];
8
11
  clientOptions?: string;
9
12
  serverOptions?: string;
10
13
  mode?: string;
@@ -16,7 +19,7 @@ interface IBuildActionParams {
16
19
  interface IStartActionParams {
17
20
  host?: boolean;
18
21
  port?: number;
19
- onlyClient?: boolean;
22
+ focusOnly?: IBuildParams['focusOnly'];
20
23
  modulePreload?: boolean;
21
24
  buildDir?: string;
22
25
  }
@@ -27,7 +30,7 @@ interface IBuildDockerActionParams {
27
30
  imageName: string;
28
31
  dockerOptions?: string;
29
32
  dockerFile?: string;
30
- onlyClient?: boolean;
33
+ focusOnly?: IBuildParams['focusOnly'];
31
34
  mode?: string;
32
35
  }
33
36
  interface IBuildAmplifyActionParams {
package/cli/run-dev.d.ts CHANGED
@@ -6,6 +6,8 @@ interface IRunDevParams {
6
6
  isHost?: boolean;
7
7
  isPrintInfo?: boolean;
8
8
  mode?: string;
9
+ port?: number;
10
+ entrypointName?: string;
9
11
  }
10
12
  interface IRunDevOut {
11
13
  server: Server;
@@ -14,5 +16,5 @@ interface IRunDevOut {
14
16
  /**
15
17
  * Run development server
16
18
  */
17
- declare function runDev({ version, isHost, isPrintInfo, mode }: IRunDevParams): Promise<IRunDevOut>;
19
+ declare function runDev({ version, isHost, isPrintInfo, mode, port, entrypointName, }: IRunDevParams): Promise<IRunDevOut>;
18
20
  export { runDev as default };
package/cli/run-dev.js CHANGED
@@ -1,2 +1,2 @@
1
- import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import e from"../services/server-config.js";async function i({version:i,isHost:s,isPrintInfo:n,mode:t}){global.viteBoostStartTime=o.now();const f=e.init({isHost:s,mode:t}),{run:m}=await r(f);return{server:m({version:i,isPrintInfo:n}),config:f}}export{i as default};
1
+ import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import{setCurrentEntrypointName as t}from"../plugins/handle-custom-entrypoint.js";import e from"../services/server-config.js";async function n({version:n,isHost:i,isPrintInfo:s,mode:m,port:p,entrypointName:f}){global.viteBoostStartTime=o.now(),f&&t(f);const a=e.init({isHost:i,mode:m,entrypointName:f},{port:p}),{run:c}=await r(a);return{server:c({version:n,isPrintInfo:s}),config:a}}export{n as default};
2
2
  //# sourceMappingURL=run-dev.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-dev.js","sources":["../../src/cli/run-dev.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunDevParams {\n version: string;\n isHost?: boolean;\n isPrintInfo?: boolean;\n mode?: string;\n}\n\ninterface IRunDevOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run development server\n */\nasync function runDev({ version, isHost, isPrintInfo, mode }: IRunDevParams): Promise<IRunDevOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init({ isHost, mode });\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runDev;\n"],"names":["async","runDev","version","isHost","isPrintInfo","mode","global","viteBoostStartTime","performance","now","config","ServerConfig","init","run","createServer","server"],"mappings":"2HAoBAA,eAAeC,GAAOC,QAAEA,EAAOC,OAAEA,EAAMC,YAAEA,EAAWC,KAAEA,IACpDC,OAAOC,mBAAqBC,EAAYC,MAExC,MAAMC,EAASC,EAAaC,KAAK,CAAET,SAAQE,UACrCQ,IAAEA,SAAcC,EAAaJ,GAEnC,MAAO,CACLK,OAAQF,EAAI,CAAEX,UAASE,gBACvBM,SAEJ"}
1
+ {"version":3,"file":"run-dev.js","sources":["../../src/cli/run-dev.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport { setCurrentEntrypointName } from '@plugins/handle-custom-entrypoint';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunDevParams {\n version: string;\n isHost?: boolean;\n isPrintInfo?: boolean;\n mode?: string;\n port?: number;\n entrypointName?: string;\n}\n\ninterface IRunDevOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run development server\n */\nasync function runDev({\n version,\n isHost,\n isPrintInfo,\n mode,\n port,\n entrypointName,\n}: IRunDevParams): Promise<IRunDevOut> {\n global.viteBoostStartTime = performance.now();\n\n if (entrypointName) {\n setCurrentEntrypointName(entrypointName);\n }\n\n const config = ServerConfig.init(\n { isHost, mode, entrypointName },\n {\n port,\n },\n );\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runDev;\n"],"names":["async","runDev","version","isHost","isPrintInfo","mode","port","entrypointName","global","viteBoostStartTime","performance","now","setCurrentEntrypointName","config","ServerConfig","init","run","createServer","server"],"mappings":"6MAuBAA,eAAeC,GAAOC,QACpBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,KACJA,EAAIC,eACJA,IAEAC,OAAOC,mBAAqBC,EAAYC,MAEpCJ,GACFK,EAAyBL,GAG3B,MAAMM,EAASC,EAAaC,KAC1B,CAAEZ,SAAQE,OAAME,kBAChB,CACED,UAGEU,IAAEA,SAAcC,EAAaJ,GAEnC,MAAO,CACLK,OAAQF,EAAI,CAAEd,UAASE,gBACvBS,SAEJ"}
@@ -1,12 +1,13 @@
1
+ import { IBuildParams } from "../services/build.js";
1
2
  interface IRunDockerBuildParams {
2
3
  imageName: string;
3
4
  dockerOptions?: string;
4
5
  dockerFile?: string;
5
- isOnlyClient?: boolean;
6
+ focusOnly?: IBuildParams['focusOnly'];
6
7
  mode?: string;
7
8
  }
8
9
  /**
9
10
  * Build docker image
10
11
  */
11
- declare function runDockerBuild({ imageName, dockerFile, isOnlyClient, dockerOptions, mode, }: IRunDockerBuildParams): Promise<void>;
12
+ declare function runDockerBuild({ imageName, dockerFile, focusOnly, dockerOptions, mode, }: IRunDockerBuildParams): Promise<void>;
12
13
  export { runDockerBuild as default };
@@ -1,2 +1,2 @@
1
- import o from"node:child_process";import e from"node:path";import{cwd as r}from"node:process";import{resolveConfig as i}from"vite";import t from"../helpers/plugin-config.js";async function n({imageName:n,dockerFile:d,isOnlyClient:l=!1,dockerOptions:p="",mode:s=""}){const c="production"===s?"production":"development",a=await i({},"build",s),m=t(a),{root:u,build:{outDir:f}}=a,$=r(),g=`.${e.resolve(u,f).replace($,"")}`,b=l?"spa":"ssr",h=d||`${m.pluginPath}/workflow/Dockerfile`;o.execSync(`docker build -f ${h} --build-arg BUILD_PATH=${g} --build-arg RUN_TYPE=${b} --build-arg ENV_MODE=${c} ${p} -t ${n} ${$}`,{stdio:"inherit",env:{...process.env}})}export{n as default};
1
+ import o from"node:child_process";import e from"node:path";import{cwd as r}from"node:process";import{resolveConfig as i}from"vite";import t from"../helpers/create-focus-only.js";import l from"../helpers/plugin-config.js";async function n({imageName:n,dockerFile:s,focusOnly:p,dockerOptions:c="",mode:d=""}){const m="production"===d?"production":"development",a=await i({},"build",d),u=l(a),{root:f,build:{outDir:$}}=a,g=r(),b=`.${e.resolve(f,$).replace(g,"")}`,h=t(p).isOnlyClient()?"spa":"ssr",k=s||`${u.pluginPath}/workflow/Dockerfile`;o.execSync(`docker build -f ${k} --build-arg BUILD_PATH=${b} --build-arg RUN_TYPE=${h} --build-arg ENV_MODE=${m} ${c} -t ${n} ${g}`,{stdio:"inherit",env:{...process.env}})}export{n as default};
2
2
  //# sourceMappingURL=run-docker-build.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-docker-build.js","sources":["../../src/cli/run-docker-build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport path from 'node:path';\nimport { cwd } from 'node:process';\nimport { resolveConfig } from 'vite';\nimport getPluginConfig from '@helpers/plugin-config';\n\ninterface IRunDockerBuildParams {\n imageName: string;\n dockerOptions?: string;\n dockerFile?: string;\n isOnlyClient?: boolean;\n mode?: string;\n}\n\n/**\n * Build docker image\n */\nasync function runDockerBuild({\n imageName,\n dockerFile,\n isOnlyClient = false,\n dockerOptions = '',\n mode = '',\n}: IRunDockerBuildParams): Promise<void> {\n const nodeEnv = mode === 'production' ? 'production' : 'development';\n const config = await resolveConfig({}, 'build', mode);\n const pluginConfig = getPluginConfig(config);\n const {\n root,\n build: { outDir },\n } = config;\n const projectRoot = cwd();\n const buildDir = `.${path.resolve(root, outDir).replace(projectRoot, '')}`; // relative path\n const runType = isOnlyClient ? 'spa' : 'ssr';\n const docFile = dockerFile || `${pluginConfig.pluginPath}/workflow/Dockerfile`;\n\n childProcess.execSync(\n `docker build -f ${docFile}` +\n ` --build-arg BUILD_PATH=${buildDir}` +\n ` --build-arg RUN_TYPE=${runType} --build-arg ENV_MODE=${nodeEnv}` +\n ` ${dockerOptions} -t ${imageName} ${projectRoot}`,\n {\n stdio: 'inherit',\n env: {\n ...process.env,\n },\n },\n );\n}\n\nexport default runDockerBuild;\n"],"names":["async","runDockerBuild","imageName","dockerFile","isOnlyClient","dockerOptions","mode","nodeEnv","config","resolveConfig","pluginConfig","getPluginConfig","root","build","outDir","projectRoot","cwd","buildDir","path","resolve","replace","runType","docFile","pluginPath","childProcess","execSync","stdio","env","process"],"mappings":"8KAiBAA,eAAeC,GAAeC,UAC5BA,EAASC,WACTA,EAAUC,aACVA,GAAe,EAAKC,cACpBA,EAAgB,GAAEC,KAClBA,EAAO,KAEP,MAAMC,EAAmB,eAATD,EAAwB,aAAe,cACjDE,QAAeC,EAAc,CAAE,EAAE,QAASH,GAC1CI,EAAeC,EAAgBH,IAC/BI,KACJA,EACAC,OAAOC,OAAEA,IACPN,EACEO,EAAcC,IACdC,EAAW,IAAIC,EAAKC,QAAQP,EAAME,GAAQM,QAAQL,EAAa,MAC/DM,EAAUjB,EAAe,MAAQ,MACjCkB,EAAUnB,GAAc,GAAGO,EAAaa,iCAE9CC,EAAaC,SACX,mBAAmBH,4BACUL,0BACFI,0BAAgCd,KACrDF,QAAoBH,KAAaa,IACvC,CACEW,MAAO,UACPC,IAAK,IACAC,QAAQD,MAInB"}
1
+ {"version":3,"file":"run-docker-build.js","sources":["../../src/cli/run-docker-build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport path from 'node:path';\nimport { cwd } from 'node:process';\nimport { resolveConfig } from 'vite';\nimport createFocusOnly from '@helpers/create-focus-only';\nimport getPluginConfig from '@helpers/plugin-config';\nimport type { IBuildParams } from '@services/build';\n\ninterface IRunDockerBuildParams {\n imageName: string;\n dockerOptions?: string;\n dockerFile?: string;\n focusOnly?: IBuildParams['focusOnly'];\n mode?: string;\n}\n\n/**\n * Build docker image\n */\nasync function runDockerBuild({\n imageName,\n dockerFile,\n focusOnly,\n dockerOptions = '',\n mode = '',\n}: IRunDockerBuildParams): Promise<void> {\n const nodeEnv = mode === 'production' ? 'production' : 'development';\n const config = await resolveConfig({}, 'build', mode);\n const pluginConfig = getPluginConfig(config);\n const {\n root,\n build: { outDir },\n } = config;\n const projectRoot = cwd();\n const buildDir = `.${path.resolve(root, outDir).replace(projectRoot, '')}`; // relative path\n const runType = createFocusOnly(focusOnly).isOnlyClient() ? 'spa' : 'ssr';\n const docFile = dockerFile || `${pluginConfig.pluginPath}/workflow/Dockerfile`;\n\n childProcess.execSync(\n `docker build -f ${docFile}` +\n ` --build-arg BUILD_PATH=${buildDir}` +\n ` --build-arg RUN_TYPE=${runType} --build-arg ENV_MODE=${nodeEnv}` +\n ` ${dockerOptions} -t ${imageName} ${projectRoot}`,\n {\n stdio: 'inherit',\n env: {\n ...process.env,\n },\n },\n );\n}\n\nexport default runDockerBuild;\n"],"names":["async","runDockerBuild","imageName","dockerFile","focusOnly","dockerOptions","mode","nodeEnv","config","resolveConfig","pluginConfig","getPluginConfig","root","build","outDir","projectRoot","cwd","buildDir","path","resolve","replace","runType","createFocusOnly","isOnlyClient","docFile","pluginPath","childProcess","execSync","stdio","env","process"],"mappings":"6NAmBAA,eAAeC,GAAeC,UAC5BA,EAASC,WACTA,EAAUC,UACVA,EAASC,cACTA,EAAgB,GAAEC,KAClBA,EAAO,KAEP,MAAMC,EAAmB,eAATD,EAAwB,aAAe,cACjDE,QAAeC,EAAc,CAAE,EAAE,QAASH,GAC1CI,EAAeC,EAAgBH,IAC/BI,KACJA,EACAC,OAAOC,OAAEA,IACPN,EACEO,EAAcC,IACdC,EAAW,IAAIC,EAAKC,QAAQP,EAAME,GAAQM,QAAQL,EAAa,MAC/DM,EAAUC,EAAgBlB,GAAWmB,eAAiB,MAAQ,MAC9DC,EAAUrB,GAAc,GAAGO,EAAae,iCAE9CC,EAAaC,SACX,mBAAmBH,4BACUP,0BACFI,0BAAgCd,KACrDF,QAAoBH,KAAaa,IACvC,CACEa,MAAO,UACPC,IAAK,IACAC,QAAQD,MAInB"}
package/cli/run-prod.d.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  /// <reference types="node" />
2
2
  import { Server } from 'node:net';
3
+ import { IBuildParams } from "../services/build.js";
3
4
  import ServerConfig from "../services/server-config.js";
4
5
  interface IRunProdParams {
5
6
  version: string;
6
7
  port?: number;
7
8
  isHost?: boolean;
8
9
  isPrintInfo?: boolean;
9
- onlyClient?: boolean;
10
+ focusOnly?: IBuildParams['focusOnly'];
10
11
  mode?: string;
11
12
  modulePreload?: boolean;
12
13
  buildDir?: string;
@@ -18,5 +19,5 @@ interface IRunProdOut {
18
19
  /**
19
20
  * Run production server
20
21
  */
21
- declare function runProd({ version, isHost, isPrintInfo, port, buildDir, onlyClient, modulePreload, }: IRunProdParams): Promise<IRunProdOut>;
22
+ declare function runProd({ version, isHost, isPrintInfo, port, buildDir, focusOnly, modulePreload, }: IRunProdParams): Promise<IRunProdOut>;
22
23
  export { runProd as default };
package/cli/run-prod.js CHANGED
@@ -1,2 +1,2 @@
1
- import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function t({version:t,isHost:e,isPrintInfo:s,port:n,buildDir:l,onlyClient:a=!1,modulePreload:f=!1}){global.viteBoostStartTime||(global.viteBoostStartTime=o.now());const d=i.init({isHost:e,isProd:!0,isOnlyClient:a,isModulePreload:f},{port:n,root:l}),{run:m}=await r(d);return{server:m({version:t,isPrintInfo:s}),config:d}}export{t as default};
1
+ import{performance as o}from"node:perf_hooks";import r from"../helpers/create-focus-only.js";import i from"../node/server.js";import e from"../services/server-config.js";async function s({version:s,isHost:t,isPrintInfo:n,port:l,buildDir:f,focusOnly:a,modulePreload:m=!1}){global.viteBoostStartTime||(global.viteBoostStartTime=o.now());const c=e.init({isHost:t,isProd:!0,isOnlyClient:r(a).isOnlyClient(),isModulePreload:m},{port:l,root:f}),{run:d}=await i(c);return{server:d({version:s,isPrintInfo:n}),config:c}}export{s as default};
2
2
  //# sourceMappingURL=run-prod.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-prod.js","sources":["../../src/cli/run-prod.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunProdParams {\n version: string;\n port?: number;\n isHost?: boolean;\n isPrintInfo?: boolean;\n onlyClient?: boolean; // SPA mode\n mode?: string;\n modulePreload?: boolean;\n buildDir?: string;\n}\n\ninterface IRunProdOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run production server\n */\nasync function runProd({\n version,\n isHost,\n isPrintInfo,\n port,\n buildDir,\n onlyClient = false,\n modulePreload = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n if (!global.viteBoostStartTime) {\n global.viteBoostStartTime = performance.now();\n }\n\n const config = ServerConfig.init(\n { isHost, isProd: true, isOnlyClient: onlyClient, isModulePreload: modulePreload },\n { port, root: buildDir },\n );\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runProd;\n"],"names":["async","runProd","version","isHost","isPrintInfo","port","buildDir","onlyClient","modulePreload","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","isModulePreload","root","run","createServer","server"],"mappings":"2HAwBAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,SACJA,EAAQC,WACRA,GAAa,EAAKC,cAClBA,GAAgB,IAEXC,OAAOC,qBACVD,OAAOC,mBAAqBC,EAAYC,OAG1C,MAAMC,EAASC,EAAaC,KAC1B,CAAEZ,SAAQa,QAAQ,EAAMC,aAAcV,EAAYW,gBAAiBV,GACnE,CAAEH,OAAMc,KAAMb,KAEVc,IAAEA,SAAcC,EAAaR,GAEnC,MAAO,CACLS,OAAQF,EAAI,CAAElB,UAASE,gBACvBS,SAEJ"}
1
+ {"version":3,"file":"run-prod.js","sources":["../../src/cli/run-prod.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createFocusOnly from '@helpers/create-focus-only';\nimport createServer from '@node/server';\nimport type { IBuildParams } from '@services/build';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunProdParams {\n version: string;\n port?: number;\n isHost?: boolean;\n isPrintInfo?: boolean;\n focusOnly?: IBuildParams['focusOnly'];\n mode?: string;\n modulePreload?: boolean;\n buildDir?: string;\n}\n\ninterface IRunProdOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run production server\n */\nasync function runProd({\n version,\n isHost,\n isPrintInfo,\n port,\n buildDir,\n focusOnly,\n modulePreload = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n if (!global.viteBoostStartTime) {\n global.viteBoostStartTime = performance.now();\n }\n\n const config = ServerConfig.init(\n {\n isHost,\n isProd: true,\n isOnlyClient: createFocusOnly(focusOnly).isOnlyClient(),\n isModulePreload: modulePreload,\n },\n { port, root: buildDir },\n );\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runProd;\n"],"names":["async","runProd","version","isHost","isPrintInfo","port","buildDir","focusOnly","modulePreload","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","createFocusOnly","isModulePreload","root","run","createServer","server"],"mappings":"0KA0BAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,SACJA,EAAQC,UACRA,EAASC,cACTA,GAAgB,IAEXC,OAAOC,qBACVD,OAAOC,mBAAqBC,EAAYC,OAG1C,MAAMC,EAASC,EAAaC,KAC1B,CACEZ,SACAa,QAAQ,EACRC,aAAcC,EAAgBX,GAAWU,eACzCE,gBAAiBX,GAEnB,CAAEH,OAAMe,KAAMd,KAEVe,IAAEA,SAAcC,EAAaT,GAEnC,MAAO,CACLU,OAAQF,EAAI,CAAEnB,UAASE,gBACvBS,SAEJ"}
package/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as e}from"fs";import o from"chalk";import{Command as i,Option as n}from"commander";import t from"./cli/build.js";import r from"./cli/helpers/keyboard-input.js";import s from"./cli/helpers/vite-reset-cache.js";import d from"./cli/run-amplify-build.js";import a from"./cli/run-dev.js";import l from"./cli/run-docker-build.js";import c from"./cli/run-prod.js";import p from"./cli/run-vercel-build.js";import m from"./constants/cli-actions.js";import f from"./constants/cli-context.js";import u from"./constants/cli-name.js";const{description:w,version:O}=JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")),v=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},g=new i;g.name(u).description(w).version(O).hook("preAction",((e,o)=>{global.viteBoostAction=o.name()}));const b=new n("--host","Ability to access the local instance on other devices under the same network.").default(!1),h=new n("--only-client","Build/run only client side part.").default(!1),y=new n("--port [port]","Server port.").default(3e3),k=new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production"),P=new n("--build-dir [buildDir]","Build directory output.");g.command(m.dev).description("Run development server.").addOption(b).addOption(new n("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).action((async({host:e,resetCache:i,mode:n})=>{i&&await s();const t=async i=>{console.info(o.cyan("Starting the development server..."));const{server:t,config:r}=await a({version:O,isHost:e,isPrintInfo:i,mode:n});f.server=t,f.config=r};return f.reboot=t,v(),t()})),g.command(m.build).description("Create production build.").addOption(h).addOption(k).addOption(new n("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new n("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).addOption(new n("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new n("--eject","Produces entrypoint file to run app without cli").default(!1)).addOption(new n("--serverless","Produces entrypoint file to run app like serverless function").default(!1)).addOption(new n("--throw-warnings","The build will abort with an error if warnings occur in the process.").default(!1)).action((async({onlyClient:e,clientOptions:o,serverOptions:i,mode:n,unlockRobots:r,eject:s,serverless:d,throwWarnings:a})=>{await t({isOnlyClient:e,isUnlockRobots:r,isNoWarnings:a,isEject:s,isServerless:d,clientOptions:o,serverOptions:i,mode:n})})),g.command(m.start).description("Run production server.").addOption(b).addOption(y).addOption(h).addOption(P).addOption(new n("--module-preload","Add module preload scripts to server output.").default(!1)).action((({host:e,port:o,onlyClient:i,modulePreload:n,buildDir:t})=>{const r=async r=>{const{server:s,config:d}=await c({version:O,isHost:e,isPrintInfo:r,port:o,onlyClient:i,modulePreload:n,buildDir:t});f.server=s,f.config=d};return f.reboot=r,v(),r()})),g.command(m.preview).description("Build and preview production.").addOption(h).addOption(b).addOption(y).addOption(k).addOption(P).action((async({host:e,port:i,onlyClient:n,mode:r,buildDir:s})=>{global.viteBoostStartTime=performance.now();const d=async t=>{const{server:r,config:d}=await c({version:O,isHost:e,isPrintInfo:t,port:i,onlyClient:n,buildDir:s});r.on("listening",(()=>{setTimeout((()=>{d.getLogger().info(o.yellow("\n Running preview mode... \n"))}),0)})),f.server=r,f.config=d};f.reboot=d,v();await t({mode:r,isWatch:!0,isOnlyClient:n,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{d()}})})),g.command(m.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new n("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new n("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(h).addOption(k).action((async({imageName:e,dockerOptions:o,dockerFile:i,onlyClient:n,mode:t})=>{await l({imageName:e,dockerOptions:o,dockerFile:i,isOnlyClient:n,mode:t})})),g.command(m.buildAmplify).description("Create AWS Amplify production build.").addOption(new n("--manifest-file [manifest-file]","Path to the Amplify manifest file (Default is PLUGIN_PATH/workflow/amplify-manifest.json).")).addOption(new n("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(k).action((async({manifestFile:e,mode:o,isOptimize:i})=>{await d({manifestFile:e,mode:o,isOptimize:i})})),g.command(m.buildVercel).description("Create Vercel serverless production build.").addOption(new n("--config-file [config-file]","Path to the Vercel config.json file (Default is PLUGIN_PATH/workflow/vercel.config.json).")).addOption(new n("--config-vc-file [config-vc-file]","Path to the Vercel vc-config.json file (Default is PLUGIN_PATH/workflow/vercel.vc-config.json).")).addOption(new n("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(k).action((async({configFile:e,configVcFile:o,mode:i,isOptimize:n})=>{await p({configFile:e,configVcFile:o,mode:i,isOptimize:n})})),g.parse();
2
+ import{readFileSync as e}from"fs";import o from"chalk";import{Command as i,Option as n}from"commander";import t from"./cli/build.js";import r from"./cli/helpers/keyboard-input.js";import s from"./cli/helpers/vite-reset-cache.js";import d from"./cli/run-amplify-build.js";import a from"./cli/run-dev.js";import c from"./cli/run-docker-build.js";import l from"./cli/run-prod.js";import p from"./cli/run-vercel-build.js";import m from"./constants/cli-actions.js";import f from"./constants/cli-context.js";import u from"./constants/cli-name.js";const{description:O,version:w}=JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")),v=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},y=new i;y.name(u).description(O).version(w).hook("preAction",((e,o)=>{global.viteBoostAction=o.name()}));const g=new n("--host","Ability to access the local instance on other devices under the same network.").default(!1),b=new n("--focus-only [focusOnly]","Build or Start only specified part of app.").default("app").choices(["all","app","client","server","entrypoint"]),h=new n("--port [port]","Server port.").default(3e3),k=new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production"),P=new n("--build-dir [buildDir]","Build directory output.");y.command(m.dev).description("Run development server.").addOption(g).addOption(h).addOption(new n("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).addOption(new n("--entrypoint [entrypoint]","Run only entrypoint by name.")).action((async({host:e,port:i,resetCache:n,mode:t,entrypoint:r})=>{n&&await s();const d=async n=>{console.info(o.cyan("Starting the development server..."));const{server:s,config:d}=await a({version:w,isHost:e,isPrintInfo:n,port:i,mode:t,entrypointName:r});f.server=s,f.config=d};return f.reboot=d,v(),d()})),y.command(m.build).description("Create production build.").addOption(b).addOption(k).addOption(new n("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new n("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).addOption(new n("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new n("--eject","Produces entrypoint file to run app without cli").default(!1)).addOption(new n("--serverless","Produces entrypoint file to run app like serverless function").default(!1)).addOption(new n("--throw-warnings","The build will abort with an error if warnings occur in the process.").default(!1)).action((async({focusOnly:e,clientOptions:o,serverOptions:i,mode:n,unlockRobots:r,eject:s,serverless:d,throwWarnings:a})=>{await t({focusOnly:e,isUnlockRobots:r,isNoWarnings:a,isEject:s,isServerless:d,clientOptions:o,serverOptions:i,mode:n})})),y.command(m.start).description("Run production server.").addOption(g).addOption(h).addOption(b).addOption(P).addOption(new n("--module-preload","Add module preload scripts to server output.").default(!1)).action((({host:e,port:o,focusOnly:i,modulePreload:n,buildDir:t})=>{const r=async r=>{const{server:s,config:d}=await l({version:w,isHost:e,isPrintInfo:r,port:o,focusOnly:i,modulePreload:n,buildDir:t});f.server=s,f.config=d};return f.reboot=r,v(),r()})),y.command(m.preview).description("Build and preview production.").addOption(b).addOption(g).addOption(h).addOption(k).addOption(P).action((async({host:e,port:i,focusOnly:n,mode:r,buildDir:s})=>{global.viteBoostStartTime=performance.now();const d=async t=>{const{server:r,config:d}=await l({version:w,isHost:e,isPrintInfo:t,port:i,focusOnly:n,buildDir:s});r.on("listening",(()=>{setTimeout((()=>{d.getLogger().info(o.yellow("\n Running preview mode... \n"))}),0)})),f.server=r,f.config=d};f.reboot=d,v();await t({mode:r,isWatch:!0,focusOnly:n,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{d()}})})),y.command(m.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new n("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new n("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(b).addOption(k).action((async({imageName:e,dockerOptions:o,dockerFile:i,focusOnly:n,mode:t})=>{await c({imageName:e,dockerOptions:o,dockerFile:i,focusOnly:n,mode:t})})),y.command(m.buildAmplify).description("Create AWS Amplify production build.").addOption(new n("--manifest-file [manifest-file]","Path to the Amplify manifest file (Default is PLUGIN_PATH/workflow/amplify-manifest.json).")).addOption(new n("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(k).action((async({manifestFile:e,mode:o,isOptimize:i})=>{await d({manifestFile:e,mode:o,isOptimize:i})})),y.command(m.buildVercel).description("Create Vercel serverless production build.").addOption(new n("--config-file [config-file]","Path to the Vercel config.json file (Default is PLUGIN_PATH/workflow/vercel.config.json).")).addOption(new n("--config-vc-file [config-vc-file]","Path to the Vercel vc-config.json file (Default is PLUGIN_PATH/workflow/vercel.vc-config.json).")).addOption(new n("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(k).action((async({configFile:e,configVcFile:o,mode:i,isOptimize:n})=>{await p({configFile:e,configVcFile:o,mode:i,isOptimize:n})})),y.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport { Command, Option } from 'commander';\nimport runBuild from '@cli/build';\nimport onKeyPress from '@cli/helpers/keyboard-input';\nimport viteResetCache from '@cli/helpers/vite-reset-cache';\nimport type {\n IBuildActionParams,\n IBuildAmplifyActionParams,\n IBuildDockerActionParams,\n IBuildVercelActionParams,\n IDevActionParams,\n IPreviewActionParams,\n IStartActionParams,\n} from '@cli/interfaces/actions';\nimport runAmplifyBuild from '@cli/run-amplify-build';\nimport runDev from '@cli/run-dev';\nimport runDockerBuild from '@cli/run-docker-build';\nimport runProd from '@cli/run-prod';\nimport runVercelBuild from '@cli/run-vercel-build';\nimport CliActions from '@constants/cli-actions';\nimport cliContext from '@constants/cli-context';\nimport cliName from '@constants/cli-name';\n\n/**\n * Parse package meta\n */\nconst { description, version } = JSON.parse(\n readFileSync(new URL('./package.json', import.meta.url), 'utf8'),\n) as { name: string; description: string; version: string };\n\n/**\n * Enable shortcuts\n * listen keyboard command\n */\nconst enableShortcuts = (): void => {\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.on('data', onKeyPress).setEncoding('utf8').resume();\n }\n};\n\nconst program = new Command();\n\nprogram\n .name(cliName)\n .description(description)\n .version(version)\n .hook('preAction', (_, actionCommand) => {\n // pass cli action to plugin config\n global.viteBoostAction = actionCommand.name();\n });\n\n/**\n * Common options\n */\nconst hostOption = new Option(\n '--host',\n 'Ability to access the local instance on other devices under the same network.',\n).default(false);\nconst onlyClientOption = new Option('--only-client', 'Build/run only client side part.').default(\n false,\n);\nconst portOption = new Option('--port [port]', 'Server port.').default(3000);\nconst envModeOption = new Option('--mode [mode]', 'Env mode.')\n .env('VITE_ENV_MODE')\n .default('production');\nconst buildDirOption = new Option('--build-dir [buildDir]', 'Build directory output.');\n\n/**\n * Cli commands\n */\n\nprogram\n .command(CliActions.dev)\n .description('Run development server.')\n .addOption(hostOption)\n .addOption(new Option('--reset-cache', 'Clear vite cache before run.').default(false))\n .addOption(new Option('--mode [mode]', 'Env mode.').env('VITE_ENV_MODE').default('development'))\n .action(async ({ host, resetCache, mode }: IDevActionParams) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n console.info(chalk.cyan('Starting the development server...'));\n\n const { server, config } = await runDev({\n version,\n isHost: host,\n isPrintInfo,\n mode,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.build)\n .description('Create production build.')\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .addOption(\n new Option(\n '--client-options [client-options]',\n 'Pass vite build options for client. Example: --client-options=\"--ssrManifest\"',\n )\n .env('VITE_BUILD_CLIENT_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option('--server-options [server-options]', 'Pass vite build options for server.')\n .env('VITE_BUILD_SERVER_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option(\n '--unlock-robots',\n 'Change general directive Disallow to Allow in robots.txt',\n ).default(false),\n )\n .addOption(\n new Option('--eject', 'Produces entrypoint file to run app without cli').default(false),\n )\n .addOption(\n new Option(\n '--serverless',\n 'Produces entrypoint file to run app like serverless function',\n ).default(false),\n )\n .addOption(\n new Option(\n '--throw-warnings',\n 'The build will abort with an error if warnings occur in the process.',\n ).default(false),\n )\n .action(\n async ({\n onlyClient,\n clientOptions,\n serverOptions,\n mode,\n unlockRobots,\n eject,\n serverless,\n throwWarnings,\n }: IBuildActionParams) => {\n await runBuild({\n isOnlyClient: onlyClient,\n isUnlockRobots: unlockRobots,\n isNoWarnings: throwWarnings,\n isEject: eject,\n isServerless: serverless,\n clientOptions,\n serverOptions,\n mode,\n });\n },\n );\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .addOption(buildDirOption)\n .addOption(\n new Option('--module-preload', 'Add module preload scripts to server output.').default(false),\n )\n .action(({ host, port, onlyClient, modulePreload, buildDir }: IStartActionParams) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n modulePreload,\n buildDir,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.preview)\n .description('Build and preview production.')\n .addOption(onlyClientOption)\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(envModeOption)\n .addOption(buildDirOption)\n .action(async ({ host, port, onlyClient, mode, buildDir }: IPreviewActionParams) => {\n global.viteBoostStartTime = performance.now();\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n buildDir,\n });\n\n server.on('listening', () => {\n setTimeout(() => {\n config.getLogger().info(chalk.yellow('\\n Running preview mode... \\n'));\n }, 0);\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n const buildOptions = '-w';\n\n await runBuild({\n mode,\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n onFinish: () => {\n void command();\n },\n });\n });\n\nprogram\n .command(CliActions.buildDocker)\n .description('Create docker image with production build.')\n .requiredOption('--image-name <image-name>', 'Docker image name.')\n .addOption(\n new Option(\n '--docker-options [docker-options]',\n 'Extra docker options which pass to docker build command.',\n ),\n )\n .addOption(\n new Option(\n '--docker-file [docker-file]',\n 'Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).',\n ),\n )\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .action(\n async ({\n imageName,\n dockerOptions,\n dockerFile,\n onlyClient,\n mode,\n }: IBuildDockerActionParams) => {\n await runDockerBuild({\n imageName,\n dockerOptions,\n dockerFile,\n isOnlyClient: onlyClient,\n mode,\n });\n },\n );\n\nprogram\n .command(CliActions.buildAmplify)\n .description('Create AWS Amplify production build.')\n .addOption(\n new Option(\n '--manifest-file [manifest-file]',\n 'Path to the Amplify manifest file (Default is PLUGIN_PATH/workflow/amplify-manifest.json).',\n ),\n )\n .addOption(new Option('--is-optimize', 'Optimize node_modules folder.').default(false))\n .addOption(envModeOption)\n .action(async ({ manifestFile, mode, isOptimize }: IBuildAmplifyActionParams) => {\n await runAmplifyBuild({\n manifestFile,\n mode,\n isOptimize,\n });\n });\n\nprogram\n .command(CliActions.buildVercel)\n .description('Create Vercel serverless production build.')\n .addOption(\n new Option(\n '--config-file [config-file]',\n 'Path to the Vercel config.json file (Default is PLUGIN_PATH/workflow/vercel.config.json).',\n ),\n )\n .addOption(\n new Option(\n '--config-vc-file [config-vc-file]',\n 'Path to the Vercel vc-config.json file (Default is PLUGIN_PATH/workflow/vercel.vc-config.json).',\n ),\n )\n .addOption(new Option('--is-optimize', 'Optimize node_modules folder.').default(false))\n .addOption(envModeOption)\n .action(async ({ configFile, configVcFile, mode, isOptimize }: IBuildVercelActionParams) => {\n await runVercelBuild({\n configFile,\n configVcFile,\n mode,\n isOptimize,\n });\n });\n\nprogram.parse();\n"],"names":["description","version","JSON","parse","readFileSync","URL","url","enableShortcuts","process","stdin","isTTY","setRawMode","on","onKeyPress","setEncoding","resume","program","Command","name","cliName","hook","_","actionCommand","global","viteBoostAction","hostOption","Option","default","onlyClientOption","portOption","envModeOption","env","buildDirOption","command","CliActions","dev","addOption","action","async","host","resetCache","mode","viteResetCache","isPrintInfo","console","info","chalk","cyan","server","config","runDev","isHost","cliContext","reboot","build","onlyClient","clientOptions","serverOptions","unlockRobots","eject","serverless","throwWarnings","runBuild","isOnlyClient","isUnlockRobots","isNoWarnings","isEject","isServerless","start","port","modulePreload","buildDir","runProd","preview","viteBoostStartTime","performance","now","setTimeout","getLogger","yellow","isWatch","onFinish","buildDocker","requiredOption","imageName","dockerOptions","dockerFile","runDockerBuild","buildAmplify","manifestFile","isOptimize","runAmplifyBuild","buildVercel","configFile","configVcFile","runVercelBuild"],"mappings":";6hBA6BA,MAAMA,YAAEA,EAAWC,QAAEA,GAAYC,KAAKC,MACpCC,EAAa,IAAIC,IAAI,6BAA8BC,KAAM,SAOrDC,EAAkB,KAClBC,QAAQC,MAAMC,QAChBF,QAAQC,MAAME,YAAW,GACzBH,QAAQC,MAAMG,GAAG,OAAQC,GAAYC,YAAY,QAAQC,SAC1D,EAGGC,EAAU,IAAIC,EAEpBD,EACGE,KAAKC,GACLnB,YAAYA,GACZC,QAAQA,GACRmB,KAAK,aAAa,CAACC,EAAGC,KAErBC,OAAOC,gBAAkBF,EAAcJ,MAAM,IAMjD,MAAMO,EAAa,IAAIC,EACrB,SACA,iFACAC,SAAQ,GACJC,EAAmB,IAAIF,EAAO,gBAAiB,oCAAoCC,SACvF,GAEIE,EAAa,IAAIH,EAAO,gBAAiB,gBAAgBC,QAAQ,KACjEG,EAAgB,IAAIJ,EAAO,gBAAiB,aAC/CK,IAAI,iBACJJ,QAAQ,cACLK,EAAiB,IAAIN,EAAO,yBAA0B,2BAM5DV,EACGiB,QAAQC,E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V,EAAO,gBAAiB,iCAAiCC,SAAQ,IAC/ES,UAAUN,GACVO,QAAOC,OAASmD,eAAchD,OAAMiD,uBAC7BC,EAAgB,CACpBF,eACAhD,OACAiD,cACA,IAGN1E,EACGiB,QAAQC,EAAW0D,aACnB5F,YAAY,8CACZoC,UACC,IAAIV,EACF,8BACA,8FAGHU,UACC,IAAIV,EACF,oCACA,oGAGHU,UAAU,IAAIV,EAAO,gBAAiB,iCAAiCC,SAAQ,IAC/ES,UAAUN,GACVO,QAAOC,OAASuD,aAAYC,eAAcrD,OAAMiD,uBACzCK,EAAe,CACnBF,aACAC,eACArD,OACAiD,cACA,IAGN1E,EAAQb"}
1
+ {"version":3,"file":"cli.js","sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport { Command, Option } from 'commander';\nimport runBuild from '@cli/build';\nimport onKeyPress from '@cli/helpers/keyboard-input';\nimport viteResetCache from '@cli/helpers/vite-reset-cache';\nimport type {\n IBuildActionParams,\n IBuildAmplifyActionParams,\n IBuildDockerActionParams,\n IBuildVercelActionParams,\n IDevActionParams,\n IPreviewActionParams,\n IStartActionParams,\n} from '@cli/interfaces/actions';\nimport runAmplifyBuild from '@cli/run-amplify-build';\nimport runDev from '@cli/run-dev';\nimport runDockerBuild from '@cli/run-docker-build';\nimport runProd from '@cli/run-prod';\nimport runVercelBuild from '@cli/run-vercel-build';\nimport CliActions from '@constants/cli-actions';\nimport cliContext from '@constants/cli-context';\nimport cliName from '@constants/cli-name';\n\n/**\n * Parse package meta\n */\nconst { description, version } = JSON.parse(\n readFileSync(new URL('./package.json', import.meta.url), 'utf8'),\n) as { name: string; description: string; version: string };\n\n/**\n * Enable shortcuts\n * listen keyboard command\n */\nconst enableShortcuts = (): void => {\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.on('data', onKeyPress).setEncoding('utf8').resume();\n }\n};\n\nconst program = new Command();\n\nprogram\n .name(cliName)\n .description(description)\n .version(version)\n .hook('preAction', (_, actionCommand) => {\n // pass cli action to plugin config\n global.viteBoostAction = actionCommand.name();\n });\n\n/**\n * Common options\n */\nconst hostOption = new Option(\n '--host',\n 'Ability to access the local instance on other devices under the same network.',\n).default(false);\nconst focusOnlyOption = new Option(\n '--focus-only [focusOnly]',\n 'Build or Start only specified part of app.',\n)\n .default('app')\n .choices(['all', 'app', 'client', 'server', 'entrypoint']);\nconst portOption = new Option('--port [port]', 'Server port.').default(3000);\nconst envModeOption = new Option('--mode [mode]', 'Env mode.')\n .env('VITE_ENV_MODE')\n .default('production');\nconst buildDirOption = new Option('--build-dir [buildDir]', 'Build directory output.');\n\n/**\n * Cli commands\n */\n\nprogram\n .command(CliActions.dev)\n .description('Run development server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(new Option('--reset-cache', 'Clear vite cache before run.').default(false))\n .addOption(new Option('--mode [mode]', 'Env mode.').env('VITE_ENV_MODE').default('development'))\n .addOption(new Option('--entrypoint [entrypoint]', 'Run only entrypoint by name.'))\n .action(async ({ host, port, resetCache, mode, entrypoint }: IDevActionParams) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n console.info(chalk.cyan('Starting the development server...'));\n\n const { server, config } = await runDev({\n version,\n isHost: host,\n isPrintInfo,\n port,\n mode,\n entrypointName: entrypoint,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.build)\n .description('Create production build.')\n .addOption(focusOnlyOption)\n .addOption(envModeOption)\n .addOption(\n new Option(\n '--client-options [client-options]',\n 'Pass vite build options for client. Example: --client-options=\"--ssrManifest\"',\n )\n .env('VITE_BUILD_CLIENT_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option('--server-options [server-options]', 'Pass vite build options for server.')\n .env('VITE_BUILD_SERVER_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option(\n '--unlock-robots',\n 'Change general directive Disallow to Allow in robots.txt',\n ).default(false),\n )\n .addOption(\n new Option('--eject', 'Produces entrypoint file to run app without cli').default(false),\n )\n .addOption(\n new Option(\n '--serverless',\n 'Produces entrypoint file to run app like serverless function',\n ).default(false),\n )\n .addOption(\n new Option(\n '--throw-warnings',\n 'The build will abort with an error if warnings occur in the process.',\n ).default(false),\n )\n .action(\n async ({\n focusOnly,\n clientOptions,\n serverOptions,\n mode,\n unlockRobots,\n eject,\n serverless,\n throwWarnings,\n }: IBuildActionParams) => {\n await runBuild({\n focusOnly,\n isUnlockRobots: unlockRobots,\n isNoWarnings: throwWarnings,\n isEject: eject,\n isServerless: serverless,\n clientOptions,\n serverOptions,\n mode: mode!,\n });\n },\n );\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(focusOnlyOption)\n .addOption(buildDirOption)\n .addOption(\n new Option('--module-preload', 'Add module preload scripts to server output.').default(false),\n )\n .action(({ host, port, focusOnly, modulePreload, buildDir }: IStartActionParams) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n focusOnly,\n modulePreload,\n buildDir,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.preview)\n .description('Build and preview production.')\n .addOption(focusOnlyOption)\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(envModeOption)\n .addOption(buildDirOption)\n .action(async ({ host, port, focusOnly, mode, buildDir }: IPreviewActionParams) => {\n global.viteBoostStartTime = performance.now();\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n focusOnly,\n buildDir,\n });\n\n server.on('listening', () => {\n setTimeout(() => {\n config.getLogger().info(chalk.yellow('\\n Running preview mode... \\n'));\n }, 0);\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n const buildOptions = '-w';\n\n await runBuild({\n mode: mode!,\n isWatch: true,\n focusOnly,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n onFinish: () => {\n void command();\n },\n });\n });\n\nprogram\n .command(CliActions.buildDocker)\n .description('Create docker image with production build.')\n .requiredOption('--image-name <image-name>', 'Docker image name.')\n .addOption(\n new Option(\n '--docker-options [docker-options]',\n 'Extra docker options which pass to docker build command.',\n ),\n )\n .addOption(\n new Option(\n '--docker-file [docker-file]',\n 'Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).',\n ),\n )\n .addOption(focusOnlyOption)\n .addOption(envModeOption)\n .action(\n async ({ imageName, dockerOptions, dockerFile, focusOnly, mode }: IBuildDockerActionParams) => {\n await runDockerBuild({\n imageName,\n dockerOptions,\n dockerFile,\n focusOnly,\n mode,\n });\n },\n );\n\nprogram\n .command(CliActions.buildAmplify)\n .description('Create AWS Amplify production build.')\n .addOption(\n new Option(\n '--manifest-file [manifest-file]',\n 'Path to the Amplify manifest file (Default is PLUGIN_PATH/workflow/amplify-manifest.json).',\n ),\n )\n .addOption(new Option('--is-optimize', 'Optimize node_modules folder.').default(false))\n .addOption(envModeOption)\n .action(async ({ manifestFile, mode, isOptimize }: IBuildAmplifyActionParams) => {\n await runAmplifyBuild({\n manifestFile,\n mode,\n isOptimize,\n });\n });\n\nprogram\n .command(CliActions.buildVercel)\n .description('Create Vercel serverless production build.')\n .addOption(\n new Option(\n '--config-file [config-file]',\n 'Path to the Vercel config.json file (Default is PLUGIN_PATH/workflow/vercel.config.json).',\n ),\n )\n .addOption(\n new Option(\n '--config-vc-file [config-vc-file]',\n 'Path to the Vercel vc-config.json file (Default is PLUGIN_PATH/workflow/vercel.vc-config.json).',\n ),\n )\n .addOption(new Option('--is-optimize', 'Optimize node_modules folder.').default(false))\n .addOption(envModeOption)\n .action(async ({ configFile, configVcFile, mode, isOptimize }: IBuildVercelActionParams) => {\n await runVercelBuild({\n configFile,\n configVcFile,\n mode,\n isOptimize,\n });\n });\n\nprogram.parse();\n"],"names":["description","version","JSON","parse","readFileSync","URL","url","enableShortcuts","process","stdin","isTTY","setRawMode","on","onKeyPress","setEncoding","resume","program","Command","name","cliName","hook","_","actionCommand","global","viteBoostAction","hostOption","Option","default","focusOnlyOption","choices","portOption","envModeOption","env","buildDirOption","command","CliActions","dev","addOption","action","async","host","port","resetCache","mode","entrypoint","viteResetCache","isPrintInfo","console","info","chalk","cyan","server","config","runDev","isHost","entrypointName","cliContext","reboot","build","focusOnly","clientOptions","serverOptions","unlockRobots","eject","serverless","throwWarnings","runBuild","isUnlockRobots","isNoWarnings","isEject","isServerless","start","modulePreload","buildDir","runProd","preview","viteBoostStartTime","performance","now","setTimeout","getLogger","yellow","isWatch","onFinish","buildDocker","requiredOption","imageName","dockerOptions","dockerFile","runDockerBuild","buildAmplify","manifestFile","isOptimize","runAmplifyBuild","buildVercel","configFile","configVcFile","runVercelBuild"],"mappings":";6hBA6BA,MAAMA,YAAEA,EAAWC,QAAEA,GAAYC,KAAKC,MACpCC,EAAa,IAAIC,IAAI,6BAA8BC,KAAM,SAOrDC,EAAkB,KAClBC,QAAQC,MAAMC,QAChBF,QAAQC,MAAME,YAAW,GACzBH,QAAQC,MAAMG,GAAG,OAAQC,GAAYC,YAAY,QAAQC,SAC1D,EAGGC,EAAU,IAAIC,EAEpBD,EACGE,KAAKC,GACLnB,YAAYA,GACZC,QAAQA,GACRmB,KAAK,aAAa,CAACC,EAAGC,KAErBC,OAAOC,gBAAkBF,EAAcJ,MAAM,IAMjD,MAAMO,EAAa,IAAIC,EACrB,SACA,iFACAC,SAAQ,GACJC,EAAkB,IAAIF,EAC1B,2BACA,8CAECC,QAAQ,OACRE,QAAQ,CAAC,MAAO,MAAO,SAAU,SAAU,eACxCC,EAAa,IAAIJ,EAAO,gBAAiB,gBAAgBC,QAAQ,KACjEI,EAAgB,IAAIL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AAWC,gBAAeC,aAAY7B,YAAWhB,iBAClD8C,EAAe,CACnBH,YACAC,gBACAC,aACA7B,YACAhB,QACA,IAIR3B,EACGkB,QAAQC,EAAWuD,cACnB1F,YAAY,wCACZqC,UACC,IAAIX,EACF,kCACA,+FAGHW,UAAU,IAAIX,EAAO,gBAAiB,iCAAiCC,SAAQ,IAC/EU,UAAUN,GACVO,QAAOC,OAASoD,eAAchD,OAAMiD,uBAC7BC,EAAgB,CACpBF,eACAhD,OACAiD,cACA,IAGN5E,EACGkB,QAAQC,EAAW2D,aACnB9F,YAAY,8CACZqC,UACC,IAAIX,EACF,8BACA,8FAGHW,UACC,IAAIX,EACF,oCACA,oGAGHW,UAAU,IAAIX,EAAO,gBAAiB,iCAAiCC,SAAQ,IAC/EU,UAAUN,GACVO,QAAOC,OAASwD,aAAYC,eAAcrD,OAAMiD,uBACzCK,EAAe,CACnBF,aACAC,eACArD,OACAiD,cACA,IAGN5E,EAAQb"}
@@ -0,0 +1,11 @@
1
+ import { IBuildParams } from "../services/build.js";
2
+ /**
3
+ * Small focus only helper to provide simple and useful methods to detect focus state
4
+ */
5
+ declare const createFocusOnly: (focus: IBuildParams['focusOnly']) => {
6
+ isOnlyClient: () => boolean;
7
+ isClient: () => boolean;
8
+ isServer: () => boolean;
9
+ isEntrypoint: () => boolean;
10
+ };
11
+ export { createFocusOnly as default };
@@ -0,0 +1,2 @@
1
+ const l=l=>({isOnlyClient:()=>"client"===l,isClient:()=>["all","app","client"].includes(l),isServer:()=>["all","app","server"].includes(l),isEntrypoint:()=>["all","entrypoint"].includes(l)});export{l as default};
2
+ //# sourceMappingURL=create-focus-only.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-focus-only.js","sources":["../../src/helpers/create-focus-only.ts"],"sourcesContent":["import type { IBuildParams } from '@services/build';\n\n/**\n * Small focus only helper to provide simple and useful methods to detect focus state\n */\nconst createFocusOnly = (focus: IBuildParams['focusOnly']) => ({\n isOnlyClient: () => focus === 'client',\n isClient: () => ['all', 'app', 'client'].includes(focus!),\n isServer: () => ['all', 'app', 'server'].includes(focus!),\n isEntrypoint: () => ['all', 'entrypoint'].includes(focus!),\n});\n\nexport default createFocusOnly;\n"],"names":["createFocusOnly","focus","isOnlyClient","isClient","includes","isServer","isEntrypoint"],"mappings":"AAKA,MAAMA,EAAmBC,IAAsC,CAC7DC,aAAc,IAAgB,WAAVD,EACpBE,SAAU,IAAM,CAAC,MAAO,MAAO,UAAUC,SAASH,GAClDI,SAAU,IAAM,CAAC,MAAO,MAAO,UAAUD,SAASH,GAClDK,aAAc,IAAM,CAAC,MAAO,cAAcF,SAASH"}
@@ -1,2 +1,2 @@
1
- import o from"node:fs";import{performance as e}from"node:perf_hooks";import r from"chalk";import s from"../constants/cli-actions.js";import t from"../constants/cli-name.js";import{getMarkerFile as n}from"./dev-marker.js";import i from"./print-server-urls.js";import m from"./resolve-server-urls.js";async function a(a,{server:d,version:l="unknown"}={}){const{action:p}=a.getPluginConfig()??{},{isProd:f,host:c,root:g}=a.getParams(),v=n(g),h=a.getLogger(),u=global.viteBoostStartTime??e.now(),w=r.dim(`ready in ${r.reset(r.bold(Math.ceil(e.now()-u)))} ms`);h.info(`\n ${r.green(`${r.bold(t.toUpperCase())} v${l}`)} ${w}\n`,{clear:!h.hasWarned});const $=a.getVite()?.config,b=!$?.mode&&!o.existsSync(v),j=d?await m(d,{host:c,isHttps:Boolean($?.server.https),rawBase:$?.rawBase}):null,k=$?.mode||b?a.mode:`production ${r.red("NODE_ENV=development")}`;if(h.info(r.dim(r.green(" ➜"))+r.dim(" Mode: ")+r.blue(k)),f)j&&i(j,(o=>h.info(o)));else{const o=a.getVite();o.resolvedUrls=j,o.printUrls()}p===s.dev&&h.info(r.dim(r.green(" ➜"))+r.dim(" press ")+r.bold("h")+r.dim(" to show help"))}export{a as default};
1
+ import e from"node:fs";import{performance as o}from"node:perf_hooks";import r from"chalk";import s from"../constants/cli-actions.js";import t from"../constants/cli-name.js";import{getMarkerFile as i}from"./dev-marker.js";import n from"./print-server-urls.js";import m from"./resolve-server-urls.js";async function a(a,{server:d,version:l="unknown"}={}){const{action:p}=a.getPluginConfig()??{},{isProd:f,host:c,root:g,isSPA:v}=a.getParams(),h=i(g),u=a.getLogger(),w=global.viteBoostStartTime??o.now(),b=r.dim(`ready in ${r.reset(r.bold(Math.ceil(o.now()-w)))} ms`);u.info(`\n ${r.green(`${r.bold(t.toUpperCase())} v${l}`)} ${b}\n`,{clear:!u.hasWarned});const S=a.getVite()?.config,$=!S?.mode&&!e.existsSync(h),j=d?await m(d,{host:c,isHttps:Boolean(S?.server.https),rawBase:S?.rawBase}):null,P=S?.mode||$?a.mode:`production ${r.red("NODE_ENV=development")}`,k=v?"SPA":"SSR";if(u.info(r.dim(r.green(" ➜"))+r.dim(" Mode: ")+r.blue(P)),u.info(r.dim(r.green(" ➜"))+r.dim(" Type: ")+r.blue(k)),f)j&&n(j,(e=>u.info(e)));else{const e=a.getVite();e.resolvedUrls=j,e.printUrls()}p===s.dev&&u.info(r.dim(r.green(" ➜"))+r.dim(" press ")+r.bold("h")+r.dim(" to show help"))}export{a as default};
2
2
  //# sourceMappingURL=print-server-info.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"print-server-info.js","sources":["../../src/helpers/print-server-info.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport type { ResolvedConfig } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport cliName from '@constants/cli-name';\nimport { getMarkerFile } from '@helpers/dev-marker';\nimport printServerUrls from '@helpers/print-server-urls';\nimport resolveServerUrls from '@helpers/resolve-server-urls';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrintServerInfoParams {\n version?: string;\n server?: Server;\n}\n\n/**\n * Print server info\n */\nasync function printServerInfo(\n config: ServerConfig,\n { server, version = 'unknown' }: IPrintServerInfoParams = {},\n): Promise<void> {\n const { action } = config.getPluginConfig() ?? {};\n const { isProd, host, root } = config.getParams();\n const devMarker = getMarkerFile(root);\n\n const Logger = config.getLogger();\n const perfStart = global.viteBoostStartTime ?? performance.now();\n const startupDurationString = chalk.dim(\n `ready in ${chalk.reset(chalk.bold(Math.ceil(performance.now() - perfStart)))} ms`,\n );\n\n Logger.info(\n `\\n ${chalk.green(\n `${chalk.bold(cliName.toUpperCase())} v${version}`,\n )} ${startupDurationString}\\n`,\n { clear: !Logger.hasWarned },\n );\n\n const viteConfig = config.getVite()?.config as\n | (ResolvedConfig & { rawBase?: string })\n | undefined;\n const isProdBuild = !viteConfig?.mode && !fs.existsSync(devMarker);\n const resolvedUrls = server\n ? await resolveServerUrls(server, {\n host,\n isHttps: Boolean(viteConfig?.server.https),\n rawBase: viteConfig?.rawBase,\n })\n : null;\n const mode =\n viteConfig?.mode || isProdBuild\n ? config.mode\n : `production ${chalk.red('NODE_ENV=development')}`;\n\n Logger.info(chalk.dim(chalk.green(' ➜')) + chalk.dim(' Mode: ') + chalk.blue(mode));\n\n if (!isProd) {\n const vite = config.getVite()!;\n\n vite.resolvedUrls = resolvedUrls;\n vite.printUrls();\n } else if (resolvedUrls) {\n printServerUrls(resolvedUrls, (msg) => Logger.info(msg));\n }\n\n if (action === CliActions.dev) {\n Logger.info(\n chalk.dim(chalk.green(' ➜')) +\n chalk.dim(' press ') +\n chalk.bold('h') +\n chalk.dim(' to show help'),\n );\n }\n}\n\nexport default printServerInfo;\n"],"names":["async","printServerInfo","config","server","version","action","getPluginConfig","isProd","host","root","getParams","devMarker","getMarkerFile","Logger","getLogger","perfStart","global","viteBoostStartTime","performance","now","startupDurationString","chalk","dim","reset","bold","Math","ceil","info","green","cliName","toUpperCase","clear","hasWarned","viteConfig","getVite","isProdBuild","mode","fs","existsSync","resolvedUrls","resolveServerUrls","isHttps","Boolean","https","rawBase","red","blue","printServerUrls","msg","vite","printUrls","CliActions","dev"],"mappings":"2SAoBAA,eAAeC,EACbC,GACAC,OAAEA,EAAMC,QAAEA,EAAU,WAAsC,IAE1D,MAAMC,OAAEA,GAAWH,EAAOI,mBAAqB,CAAA,GACzCC,OAAEA,EAAMC,KAAEA,EAAIC,KAAEA,GAASP,EAAOQ,YAChCC,EAAYC,EAAcH,GAE1BI,EAASX,EAAOY,YAChBC,EAAYC,OAAOC,oBAAsBC,EAAYC,MACrDC,EAAwBC,EAAMC,IAClC,YAAYD,EAAME,MAAMF,EAAMG,KAAKC,KAAKC,KAAKR,EAAYC,MAAQJ,WAGnEF,EAAOc,KACL,OAAON,EAAMO,MACX,GAAGP,EAAMG,KAAKK,EAAQC,mBAAmB1B,SACrCgB,MACN,CAAEW,OAAQlB,EAAOmB,YAGnB,MAAMC,EAAa/B,EAAOgC,WAAWhC,OAG/BiC,GAAeF,GAAYG,OAASC,EAAGC,WAAW3B,GAClD4B,EAAepC,QACXqC,EAAkBrC,EAAQ,CAC9BK,OACAiC,QAASC,QAAQT,GAAY9B,OAAOwC,OACpCC,QAASX,GAAYW,UAEvB,KACER,EACJH,GAAYG,MAAQD,EAChBjC,EAAOkC,KACP,cAAcf,EAAMwB,IAAI,0BAI9B,GAFAhC,EAAOc,KAAKN,EAAMC,IAAID,EAAMO,MAAM,QAAUP,EAAMC,IAAI,eAAiBD,EAAMyB,KAAKV,IAE7E7B,EAKMgC,GACTQ,EAAgBR,GAAeS,GAAQnC,EAAOc,KAAKqB,SANxC,CACX,MAAMC,EAAO/C,EAAOgC,UAEpBe,EAAKV,aAAeA,EACpBU,EAAKC,WACN,CAIG7C,IAAW8C,EAAWC,KACxBvC,EAAOc,KACLN,EAAMC,IAAID,EAAMO,MAAM,QACpBP,EAAMC,IAAI,YACVD,EAAMG,KAAK,KACXH,EAAMC,IAAI,iBAGlB"}
1
+ {"version":3,"file":"print-server-info.js","sources":["../../src/helpers/print-server-info.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport type { ResolvedConfig } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport cliName from '@constants/cli-name';\nimport { getMarkerFile } from '@helpers/dev-marker';\nimport printServerUrls from '@helpers/print-server-urls';\nimport resolveServerUrls from '@helpers/resolve-server-urls';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrintServerInfoParams {\n version?: string;\n server?: Server;\n}\n\n/**\n * Print server info\n */\nasync function printServerInfo(\n config: ServerConfig,\n { server, version = 'unknown' }: IPrintServerInfoParams = {},\n): Promise<void> {\n const { action } = config.getPluginConfig() ?? {};\n const { isProd, host, root, isSPA } = config.getParams();\n const devMarker = getMarkerFile(root);\n\n const Logger = config.getLogger();\n const perfStart = global.viteBoostStartTime ?? performance.now();\n const startupDurationString = chalk.dim(\n `ready in ${chalk.reset(chalk.bold(Math.ceil(performance.now() - perfStart)))} ms`,\n );\n\n Logger.info(\n `\\n ${chalk.green(\n `${chalk.bold(cliName.toUpperCase())} v${version}`,\n )} ${startupDurationString}\\n`,\n { clear: !Logger.hasWarned },\n );\n\n const viteConfig = config.getVite()?.config as\n | (ResolvedConfig & { rawBase?: string })\n | undefined;\n const isProdBuild = !viteConfig?.mode && !fs.existsSync(devMarker);\n const resolvedUrls = server\n ? await resolveServerUrls(server, {\n host,\n isHttps: Boolean(viteConfig?.server.https),\n rawBase: viteConfig?.rawBase,\n })\n : null;\n const mode =\n viteConfig?.mode || isProdBuild\n ? config.mode\n : `production ${chalk.red('NODE_ENV=development')}`;\n const type = isSPA ? 'SPA' : 'SSR';\n\n Logger.info(chalk.dim(chalk.green(' ➜')) + chalk.dim(' Mode: ') + chalk.blue(mode));\n Logger.info(chalk.dim(chalk.green(' ➜')) + chalk.dim(' Type: ') + chalk.blue(type));\n\n if (!isProd) {\n const vite = config.getVite()!;\n\n vite.resolvedUrls = resolvedUrls;\n vite.printUrls();\n } else if (resolvedUrls) {\n printServerUrls(resolvedUrls, (msg) => Logger.info(msg));\n }\n\n if (action === CliActions.dev) {\n Logger.info(\n chalk.dim(chalk.green(' ➜')) +\n chalk.dim(' press ') +\n chalk.bold('h') +\n chalk.dim(' to show help'),\n );\n }\n}\n\nexport default printServerInfo;\n"],"names":["async","printServerInfo","config","server","version","action","getPluginConfig","isProd","host","root","isSPA","getParams","devMarker","getMarkerFile","Logger","getLogger","perfStart","global","viteBoostStartTime","performance","now","startupDurationString","chalk","dim","reset","bold","Math","ceil","info","green","cliName","toUpperCase","clear","hasWarned","viteConfig","getVite","isProdBuild","mode","fs","existsSync","resolvedUrls","resolveServerUrls","isHttps","Boolean","https","rawBase","red","type","blue","printServerUrls","msg","vite","printUrls","CliActions","dev"],"mappings":"2SAoBAA,eAAeC,EACbC,GACAC,OAAEA,EAAMC,QAAEA,EAAU,WAAsC,IAE1D,MAAMC,OAAEA,GAAWH,EAAOI,mBAAqB,CAAA,GACzCC,OAAEA,EAAMC,KAAEA,EAAIC,KAAEA,EAAIC,MAAEA,GAAUR,EAAOS,YACvCC,EAAYC,EAAcJ,GAE1BK,EAASZ,EAAOa,YAChBC,EAAYC,OAAOC,oBAAsBC,EAAYC,MACrDC,EAAwBC,EAAMC,IAClC,YAAYD,EAAME,MAAMF,EAAMG,KAAKC,KAAKC,KAAKR,EAAYC,MAAQJ,WAGnEF,EAAOc,KACL,OAAON,EAAMO,MACX,GAAGP,EAAMG,KAAKK,EAAQC,mBAAmB3B,SACrCiB,MACN,CAAEW,OAAQlB,EAAOmB,YAGnB,MAAMC,EAAahC,EAAOiC,WAAWjC,OAG/BkC,GAAeF,GAAYG,OAASC,EAAGC,WAAW3B,GAClD4B,EAAerC,QACXsC,EAAkBtC,EAAQ,CAC9BK,OACAkC,QAASC,QAAQT,GAAY/B,OAAOyC,OACpCC,QAASX,GAAYW,UAEvB,KACER,EACJH,GAAYG,MAAQD,EAChBlC,EAAOmC,KACP,cAAcf,EAAMwB,IAAI,0BACxBC,EAAOrC,EAAQ,MAAQ,MAK7B,GAHAI,EAAOc,KAAKN,EAAMC,IAAID,EAAMO,MAAM,QAAUP,EAAMC,IAAI,eAAiBD,EAAM0B,KAAKX,IAClFvB,EAAOc,KAAKN,EAAMC,IAAID,EAAMO,MAAM,QAAUP,EAAMC,IAAI,eAAiBD,EAAM0B,KAAKD,IAE7ExC,EAKMiC,GACTS,EAAgBT,GAAeU,GAAQpC,EAAOc,KAAKsB,SANxC,CACX,MAAMC,EAAOjD,EAAOiC,UAEpBgB,EAAKX,aAAeA,EACpBW,EAAKC,WACN,CAIG/C,IAAWgD,EAAWC,KACxBxC,EAAOc,KACLN,EAAMC,IAAID,EAAMO,MAAM,QACpBP,EAAMC,IAAI,YACVD,EAAMG,KAAK,KACXH,EAAMC,IAAI,iBAGlB"}
package/node/server.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:http";import r from"node:https";import t from"path";import s from"compression";import o from"express";import i from"../helpers/print-server-info.js";import a from"../services/prepare-server.js";import n from"../services/server-api.js";async function p(p){const d=o().disable("x-powered-by"),c=new n;p.setApp(d);const m=a.init(p,c);if(!p.isProd){const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:p.mode});d.use(e.middlewares),p.setVite(e)}if(p.isSPA||await m.onAppCreated(),p.isProd){const{root:e,publicDir:r,isSPA:i}=p.getParams(),{compression:a,expressStatic:n}=m.getMiddlewaresConfig();a&&d.use(s(a)),i||d.use(((e,r,t)=>{"/index.html"!==e.url||c.hasAccessIndexHtml()||(e.url="/index-not-found.html"),t()})),n&&d.use(o.static(t.resolve(`${e}/${r}`),{...n,index:!!i&&void 0}))}return p.isSPA?d.use("*",((e,r,t)=>{(async()=>{try{const t=(await m.loadHtml(e)).join("");r.send(t)}catch(e){p.getLogger().error("Failed to handle request",{error:e}),t()}})()})):d.use("*",((e,r,t)=>{(async()=>{try{const[{render:t,onRequest:s,...o},i]=await Promise.all([m.loadEntrypoint(),m.loadHtml(e)]),{appProps:a,hasEarlyHints:n}=await(s?.(e,r))??{},[d,c]=i,l={req:e,res:r,hasEarlyHints:n,appProps:a??{},html:{header:d,footer:c}};await t(p,l,o)}catch(e){p.getLogger().error("Failed to handle request",{error:e}),t()}})()})),{run:({version:t,isPrintInfo:s=!0}={})=>{const{port:o,host:a}=p.getParams(),n=Boolean(p.getVite()?.config?.server?.https);p.isHost&&!p.isProd&&(p.getVite().config.server.host=a);const c=(n?r.createServer(p.getVite().config.server.https,d):e.createServer(d)).listen(o,a,(()=>{s&&i(p,{version:t,server:c})}));return c},app:d}}export{p as default};
1
+ import e from"node:http";import r from"node:https";import t from"path";import s from"compression";import o from"express";import i from"../helpers/print-server-info.js";import a from"../services/prepare-server.js";import n from"../services/server-api.js";async function p(p){const c=o().disable("x-powered-by"),d=new n;p.setApp(c);const m=a.init(p,d);if(!p.isProd){const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:p.mode});c.use(e.middlewares),p.setVite(e)}const{isSPA:l}=p.getParams();if(l||await m.onAppCreated(),p.isProd){const{root:e,publicDir:r}=p.getParams(),{compression:i,expressStatic:a}=m.getMiddlewaresConfig();i&&c.use(s(i)),l||c.use(((e,r,t)=>{"/index.html"!==e.url||d.hasAccessIndexHtml()||(e.url="/index-not-found.html"),t()})),a&&c.use(o.static(t.resolve(`${e}/${r}`),{...a,index:!!l&&void 0}))}return l?c.use("*",((e,r,t)=>{(async()=>{try{const t=(await m.loadHtml(e)).join("");r.send(t)}catch(e){p.getLogger().error("Failed to handle request",{error:e}),t()}})()})):c.use("*",((e,r,t)=>{(async()=>{try{const[{render:t,onRequest:s,...o},i]=await Promise.all([m.loadEntrypoint(),m.loadHtml(e)]),{appProps:a,hasEarlyHints:n}=await(s?.(e,r))??{},[c,d]=i,l={req:e,res:r,hasEarlyHints:n,appProps:a??{},html:{header:c,footer:d}};await t(p,l,o)}catch(e){p.getLogger().error("Failed to handle request",{error:e}),t()}})()})),{run:({version:t,isPrintInfo:s=!0}={})=>{const{port:o,host:a}=p.getParams(),n=Boolean(p.getVite()?.config?.server?.https);p.isHost&&!p.isProd&&(p.getVite().config.server.host=a);const d=(n?r.createServer(p.getVite().config.server.https,c):e.createServer(c)).listen(o,a,(()=>{s&&i(p,{version:t,server:d})}));return d},app:c}}export{p as default};
2
2
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n const serverApi = new ServerApi();\n\n config.setApp(app);\n\n const prepareServer = PrepareServer.init(config, serverApi);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n mode: config.mode,\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n }\n\n if (!config.isSPA) {\n await prepareServer.onAppCreated();\n }\n\n if (config.isProd) {\n const { root, publicDir, isSPA } = config.getParams();\n const { compression: compressionConfig, expressStatic } = prepareServer.getMiddlewaresConfig();\n\n if (compressionConfig) {\n app.use(compression(compressionConfig));\n }\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, _, next) => {\n if (req.url === '/index.html' && !serverApi.hasAccessIndexHtml()) {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n if (expressStatic) {\n app.use(\n express.static(path.resolve(`${root}/${publicDir}`), {\n ...expressStatic,\n index: isSPA ? undefined : false,\n }),\n );\n }\n }\n\n // SSR mode\n if (!config.isSPA) {\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n config.getLogger().error('Failed to handle request', { error: e as Error });\n next();\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n config.getLogger().error('Failed to handle request', { error: e as Error });\n next();\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","serverApi","ServerApi","setApp","prepareServer","PrepareServer","init","isProd","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","use","middlewares","setVite","isSPA","onAppCreated","root","publicDir","getParams","compression","compressionConfig","expressStatic","getMiddlewaresConfig","req","_","next","url","hasAccessIndexHtml","static","path","resolve","index","undefined","res","html","loadHtml","join","send","e","getLogger","error","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","printServerInfo"],"mappings":"8PAqBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBACxBC,EAAY,IAAIC,EAEtBL,EAAOM,OAAOL,GAEd,MAAMM,EAAgBC,EAAcC,KAAKT,EAAQI,GAEjD,IAAKJ,EAAOU,OAAQ,CAIlB,MAAMC,cACEC,OAAO,SACbb,aAAa,CACbc,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAMnB,EAAOmB,OAIflB,EAAImB,IAAIT,EAAKU,aAEbrB,EAAOsB,QAAQX,EAChB,CAMD,GAJKX,EAAOuB,aACJhB,EAAciB,eAGlBxB,EAAOU,OAAQ,CACjB,MAAMe,KAAEA,EAAIC,UAAEA,EAASH,MAAEA,GAAUvB,EAAO2B,aAClCC,YAAaC,EAAiBC,cAAEA,GAAkBvB,EAAcwB,uBAEpEF,GACF5B,EAAImB,IAAIQ,EAAYC,IAGjBN,GAEHtB,EAAImB,KAAI,CAACY,EAAKC,EAAGC,KACC,gBAAZF,EAAIG,KAA0B/B,EAAUgC,uBAC1CJ,EAAIG,IAAM,yBAGZD,GAAM,IAINJ,GACF7B,EAAImB,IACFlB,EAAQmC,OAAOC,EAAKC,QAAQ,GAAGd,KAAQC,KAAc,IAChDI,EACHU,QAAOjB,QAAQkB,IAItB,CA6CD,OA1CKzC,EAAOuB,MA4BVtB,EAAImB,IAAI,KAAK,CAACY,EAAKU,EAAKR,KACjB,WACH,IACE,MAAMS,SAAcpC,EAAcqC,SAASZ,IAAMa,KAAK,IAEtDH,EAAII,KAAKH,EACV,CAAC,MAAOI,GACP/C,EAAOgD,YAAYC,MAAM,2BAA4B,CAAEA,MAAOF,IAC9Db,GACD,CACF,EATI,EASD,IArCNjC,EAAImB,IAAI,KAAK,CAACY,EAAKU,EAAKR,KACjB,WACH,IACE,OAAOgB,OAAEA,EAAMC,UAAEA,KAAcC,GAAgBC,SAAoBC,QAAQC,IAAI,CAC7EhD,EAAciD,iBACdjD,EAAcqC,SAASZ,MAEnByB,SAAEA,EAAQC,cAAEA,SAAyBP,IAAYnB,EAAKU,KAAS,IAC9DiB,EAAQC,GAAUP,EAEnBQ,EAA2B,CAC/B7B,MACAU,MACAgB,gBACAD,SAAUA,GAAY,CAAE,EACxBd,KAAM,CAAEgB,SAAQC,iBAGZV,EAAOlD,EAAQ6D,EAAST,EAC/B,CAAC,MAAOL,GACP/C,EAAOgD,YAAYC,MAAM,2BAA4B,CAAEA,MAAOF,IAC9Db,GACD,CACF,EAtBI,EAsBD,IAkBD,CACL4B,IAAK,EAAGC,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAASlE,EAAO2B,YACxBwC,EAAUC,QAAQpE,EAAOqE,WAAWrE,QAAQa,QAAQyD,OAGtDtE,EAAOuE,SAAWvE,EAAOU,SAC3BV,EAAOqE,UAAWrE,OAAOa,OAAOqD,KAAOA,GAGzC,MAAMrD,GACJsD,EACIG,EAAMvE,aAAaC,EAAOqE,UAAWrE,OAAOa,OAAOyD,MAAQrE,GAC3DuE,EAAKzE,aAAaE,IACtBwE,OAAOR,EAAMC,GAAM,KACdF,GAIAU,EAAgB1E,EAAQ,CAAE+D,UAASlD,UAAS,IAGnD,OAAOA,CAAM,EAEfZ,MAEJ"}
1
+ {"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import http from 'node:http';\nimport https from 'node:https';\nimport type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport type { Express } from 'express';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerApi from '@services/server-api';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n app: Express;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express().disable('x-powered-by');\n const serverApi = new ServerApi();\n\n config.setApp(app);\n\n const prepareServer = PrepareServer.init(config, serverApi);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n mode: config.mode,\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n }\n\n const { isSPA } = config.getParams();\n\n if (!isSPA) {\n await prepareServer.onAppCreated();\n }\n\n if (config.isProd) {\n const { root, publicDir } = config.getParams();\n const { compression: compressionConfig, expressStatic } = prepareServer.getMiddlewaresConfig();\n\n if (compressionConfig) {\n app.use(compression(compressionConfig));\n }\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, _, next) => {\n if (req.url === '/index.html' && !serverApi.hasAccessIndexHtml()) {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n if (expressStatic) {\n app.use(\n express.static(path.resolve(`${root}/${publicDir}`), {\n ...expressStatic,\n index: isSPA ? undefined : false,\n }),\n );\n }\n }\n\n // SSR mode\n if (!isSPA) {\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [{ render, onRequest, ...renderParams }, clientHtml] = await Promise.all([\n prepareServer.loadEntrypoint(),\n prepareServer.loadHtml(req),\n ]);\n const { appProps, hasEarlyHints } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n hasEarlyHints,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, renderParams);\n } catch (e) {\n config.getLogger().error('Failed to handle request', { error: e as Error });\n next();\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n config.getLogger().error('Failed to handle request', { error: e as Error });\n next();\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n const isHTTPS = Boolean(config.getVite()?.config?.server?.https);\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = (\n isHTTPS\n ? https.createServer(config.getVite()!.config.server.https!, app)\n : http.createServer(app)\n ).listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(config, { version, server });\n });\n\n return server;\n },\n app,\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","disable","serverApi","ServerApi","setApp","prepareServer","PrepareServer","init","isProd","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","use","middlewares","setVite","isSPA","getParams","onAppCreated","root","publicDir","compression","compressionConfig","expressStatic","getMiddlewaresConfig","req","_","next","url","hasAccessIndexHtml","static","path","resolve","index","undefined","res","html","loadHtml","join","send","e","getLogger","error","render","onRequest","renderParams","clientHtml","Promise","all","loadEntrypoint","appProps","hasEarlyHints","header","footer","context","run","version","isPrintInfo","port","host","isHTTPS","Boolean","getVite","https","isHost","http","listen","printServerInfo"],"mappings":"8PAqBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAAUC,QAAQ,gBACxBC,EAAY,IAAIC,EAEtBL,EAAOM,OAAOL,GAEd,MAAMM,EAAgBC,EAAcC,KAAKT,EAAQI,GAEjD,IAAKJ,EAAOU,OAAQ,CAIlB,MAAMC,cACEC,OAAO,SACbb,aAAa,CACbc,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACT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BAA4B,CAAEA,MAAOF,IAC9Db,GACD,CACF,EAtBI,EAsBD,IAkBD,CACL4B,IAAK,EAAGC,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAASlE,EAAOwB,YACxB2C,EAAUC,QAAQpE,EAAOqE,WAAWrE,QAAQa,QAAQyD,OAGtDtE,EAAOuE,SAAWvE,EAAOU,SAC3BV,EAAOqE,UAAWrE,OAAOa,OAAOqD,KAAOA,GAGzC,MAAMrD,GACJsD,EACIG,EAAMvE,aAAaC,EAAOqE,UAAWrE,OAAOa,OAAOyD,MAAQrE,GAC3DuE,EAAKzE,aAAaE,IACtBwE,OAAOR,EAAMC,GAAM,KACdF,GAIAU,EAAgB1E,EAAQ,CAAE+D,UAASlD,UAAS,IAGnD,OAAOA,CAAM,EAEfZ,MAEJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/vite-ssr-boost",
3
- "version": "2.8.1",
3
+ "version": "3.0.0-beta.2",
4
4
  "description": "Vite plugin for create awesome SSR or SPA applications on React.",
5
5
  "type": "module",
6
6
  "keywords": [
package/plugin.d.ts CHANGED
@@ -2,6 +2,7 @@ import { Plugin } from 'vite';
2
2
  import { ICliContext } from "./constants/cli-context.js";
3
3
  import { IPluginOptions as ICreateSPAIndex } from "./plugins/create-spa-index.js";
4
4
  import { IPluginOptions as IMakeAliasesPluginOptions } from "./plugins/make-aliases.js";
5
+ import { IBuildEntrypoint } from "./services/build.js";
5
6
  interface IPluginOptions {
6
7
  indexFile?: string;
7
8
  serverFile?: string;
@@ -16,6 +17,7 @@ interface IPluginOptions {
16
17
  action: (cliContext: ICliContext) => Promise<void> | void;
17
18
  isOnlyDev?: boolean;
18
19
  }[];
20
+ entrypoint?: IBuildEntrypoint[];
19
21
  }
20
22
  /**
21
23
  * Init plugin
package/plugin.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:path";import i from"./constants/cli-actions.js";import s from"./constants/plugin-name.js";import o from"./plugins/create-spa-index.js";import n from"./plugins/make-aliases.js";import t from"./plugins/normalize-route.js";const r={indexFile:"index.html",serverFile:"server.ts",clientFile:"client.ts",routesParsing:"babel",tsconfigAliases:!0,spaIndex:!1};function a(a={}){const p=new URL(import.meta.url),l=global.viteBoostAction||process.env.SSR_BOOST_ACTION,u={...r,...a},m="1"===process.env.SSR_BOOST_IS_SSR||l===i.dev,d=l===i.build,c=[{name:s,enforce:"pre",pluginOptions:{...u,pluginPath:e.dirname(p.pathname),action:l,isDev:l===i.dev},config:(e,{isSsrBuild:i})=>(e.define={...e.define??{},__IS_SSR__:m},e.build={...e.build??{}},i?{...e,...d?{appType:"custom"}:{},publicDir:!1}:(m&&d&&(e.build.manifest=!0),e))}],{tsconfigAliases:f,routesPath:S,routesParsing:g,spaIndex:b}=u;return f&&c.push(n("boolean"==typeof f?void 0:f)),b&&c.push(o("boolean"==typeof b?void 0:b)),c.push(t({isSSR:m,isBuild:d,routesPath:S,isNodeParsing:"node"===g})),c}export{a as default};
1
+ import e from"node:path";import i from"node:process";import s from"./constants/cli-actions.js";import o from"./constants/plugin-name.js";import n from"./plugins/create-spa-index.js";import{getCurrentEntrypoint as t,ViteHandleCustomEntrypointPlugin as r}from"./plugins/handle-custom-entrypoint.js";import p from"./plugins/make-aliases.js";import a from"./plugins/normalize-route.js";const l={indexFile:"index.html",serverFile:"server.ts",clientFile:"client.ts",routesParsing:"babel",tsconfigAliases:!0,spaIndex:!1};function u(u={}){const m=new URL(import.meta.url),d=global.viteBoostAction||i.env.SSR_BOOST_ACTION,c={...l,...u},f=t(c.entrypoint??[]),S="1"===i.env.SSR_BOOST_IS_SSR||d===s.dev,g=d===s.build,h=[{name:o,enforce:"pre",pluginOptions:{...c,pluginPath:e.dirname(m.pathname),action:d,isDev:d===s.dev},config:(e,{isSsrBuild:i})=>(e.define={...e.define??{},__IS_SSR__:f?"ssr"===f.type:S},e.build={...e.build??{}},i?{...e,...g?{appType:"custom"}:{},publicDir:!1}:(S&&g&&(e.build.manifest=!0),e))}],{tsconfigAliases:b,routesPath:v,routesParsing:_,spaIndex:y}=c;return b&&h.push(p("boolean"==typeof b?void 0:b)),y&&h.push(n("boolean"==typeof y?void 0:y)),f&&h.push(r({entrypoint:f})),h.push(a({isSSR:S,isBuild:g,routesPath:v,isNodeParsing:"node"===_})),h}export{u as default};
2
2
  //# sourceMappingURL=plugin.js.map
package/plugin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Plugin } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport type { ICliContext } from '@constants/cli-context';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport ViteCreateSPAIndexPlugin from '@plugins/create-spa-index';\nimport type { IPluginOptions as ICreateSPAIndex } from '@plugins/create-spa-index';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\n\nexport interface IPluginOptions {\n // default: index.html\n indexFile?: string;\n // default: server.ts\n serverFile?: string;\n // default: client.ts\n clientFile?: string;\n // Path contains routes declaration files (need to detect route files). default: undefined, e.g.: /routes/\n routesPath?: string;\n // how parse routes\n // node - import routes file directly and walk through\n // babel - use babel travers to walk through and avoid import routes file\n // default: babel\n routesParsing?: 'node' | 'babel';\n // Create additional SPA entrypoint: index-spa.html\n spaIndex?: boolean | ICreateSPAIndex;\n // Read aliases from tsconfig\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions;\n customShortcuts?: {\n key: string;\n description: string;\n action: (cliContext: ICliContext) => Promise<void> | void;\n isOnlyDev?: boolean;\n }[];\n}\n\nconst defaultOptions: IPluginOptions = {\n indexFile: 'index.html',\n serverFile: 'server.ts',\n clientFile: 'client.ts',\n routesParsing: 'babel',\n tsconfigAliases: true,\n spaIndex: false,\n};\n\n/**\n * Init plugin\n * @constructor\n */\nfunction ViteSsrBoostPlugin(options: IPluginOptions = {}): Plugin[] {\n const dirInfo = new URL(import.meta.url);\n const action = (global.viteBoostAction || process.env.SSR_BOOST_ACTION) as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\n const isSSR = process.env.SSR_BOOST_IS_SSR === '1' || action === CliActions.dev;\n const isBuild = action === CliActions.build;\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n // @ts-ignore save custom options\n pluginOptions: {\n ...mergedOptions,\n pluginPath: path.dirname(dirInfo.pathname),\n action,\n isDev: action === CliActions.dev,\n },\n\n config(config, { isSsrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: isSSR,\n };\n\n config.build = {\n ...(config.build ?? {}),\n };\n\n if (!isSsrBuild) {\n if (isSSR && isBuild) {\n config.build.manifest = true;\n }\n\n return config;\n }\n\n return {\n ...config,\n ...(isBuild ? { appType: 'custom' } : {}),\n publicDir: false,\n };\n },\n },\n ];\n\n const { tsconfigAliases, routesPath, routesParsing, spaIndex } = mergedOptions;\n\n if (tsconfigAliases) {\n plugins.push(\n ViteMakeAliasesPlugin(typeof tsconfigAliases === 'boolean' ? undefined : tsconfigAliases),\n );\n }\n\n if (spaIndex) {\n plugins.push(ViteCreateSPAIndexPlugin(typeof spaIndex === 'boolean' ? undefined : spaIndex));\n }\n\n plugins.push(\n ViteNormalizeRouterPlugin({\n isSSR,\n isBuild,\n routesPath,\n isNodeParsing: routesParsing === 'node',\n }),\n );\n\n return plugins;\n}\n\nexport default ViteSsrBoostPlugin;\n"],"names":["defaultOptions","indexFile","serverFile","clientFile","routesParsing","tsconfigAliases","spaIndex","ViteSsrBoostPlugin","options","dirInfo","URL","url","action","global","viteBoostAction","process","env","SSR_BOOST_ACTION","mergedOptions","isSSR","SSR_BOOST_IS_SSR","CliActions","dev","isBuild","build","plugins","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","config","isSsrBuild","define","__IS_SSR__","appType","publicDir","manifest","routesPath","push","ViteMakeAliasesPlugin","undefined","ViteCreateSPAIndexPlugin","ViteNormalizeRouterPlugin","isNodeParsing"],"mappings":"+OAqCA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,YACZC,cAAe,QACfC,iBAAiB,EACjBC,UAAU,GAOZ,SAASC,EAAmBC,EAA0B,IACpD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAAUC,OAAOC,iBAAmBC,QAAQC,IAAIC,iBAChDC,EAAgC,IAAKlB,KAAmBQ,GACxDW,EAAyC,MAAjCJ,QAAQC,IAAII,kBAA4BR,IAAWS,EAAWC,IACtEC,EAAUX,IAAWS,EAAWG,MAEhCC,EAAoB,CACxB,CACEC,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVX,EACHY,WAAYC,EAAKC,QAAQvB,EAAQwB,UACjCrB,SACAsB,MAAOtB,IAAWS,EAAWC,KAG/Ba,OAAM,CAACA,GAAQC,WAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,CAAE,EACvBC,WAAYnB,GAGdgB,EAAOX,MAAQ,IACTW,EAAOX,OAAS,CAAE,GAGnBY,EAQE,IACFD,KACCZ,EAAU,CAAEgB,QAAS,UAAa,CAAE,EACxCC,WAAW,IAVPrB,GAASI,IACXY,EAAOX,MAAMiB,UAAW,GAGnBN,OAYT9B,gBAAEA,EAAeqC,WAAEA,EAAUtC,cAAEA,EAAaE,SAAEA,GAAaY,EAqBjE,OAnBIb,GACFoB,EAAQkB,KACNC,EAAiD,kBAApBvC,OAAgCwC,EAAYxC,IAIzEC,GACFmB,EAAQkB,KAAKG,EAA6C,kBAAbxC,OAAyBuC,EAAYvC,IAGpFmB,EAAQkB,KACNI,EAA0B,CACxB5B,QACAI,UACAmB,aACAM,cAAiC,SAAlB5C,KAIZqB,CACT"}
1
+ {"version":3,"file":"plugin.js","sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport process from 'node:process';\nimport type { Plugin } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport type { ICliContext } from '@constants/cli-context';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport ViteCreateSPAIndexPlugin from '@plugins/create-spa-index';\nimport type { IPluginOptions as ICreateSPAIndex } from '@plugins/create-spa-index';\nimport {\n ViteHandleCustomEntrypointPlugin,\n getCurrentEntrypoint,\n} from '@plugins/handle-custom-entrypoint';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\nimport type { IBuildEntrypoint } from '@services/build';\n\nexport interface IPluginOptions {\n // default: index.html\n indexFile?: string;\n // default: server.ts\n serverFile?: string;\n // default: client.ts\n clientFile?: string;\n // Path contains routes declaration files (need to detect route files). default: undefined, e.g.: /routes/\n routesPath?: string;\n // how parse routes\n // node - import routes file directly and walk through\n // babel - use babel travers to walk through and avoid import routes file\n // default: babel\n routesParsing?: 'node' | 'babel';\n // Create additional SPA entrypoint: index-spa.html\n // Can be used for service worker: createHandlerBoundToURL(\"index-spa.html\")\n spaIndex?: boolean | ICreateSPAIndex;\n // Read aliases from tsconfig\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions;\n customShortcuts?: {\n key: string;\n description: string;\n action: (cliContext: ICliContext) => Promise<void> | void;\n isOnlyDev?: boolean;\n }[];\n // Additional entry points for build\n entrypoint?: IBuildEntrypoint[];\n}\n\nconst defaultOptions: IPluginOptions = {\n indexFile: 'index.html',\n serverFile: 'server.ts',\n clientFile: 'client.ts',\n routesParsing: 'babel',\n tsconfigAliases: true,\n spaIndex: false,\n};\n\n/**\n * Init plugin\n * @constructor\n */\nfunction ViteSsrBoostPlugin(options: IPluginOptions = {}): Plugin[] {\n const dirInfo = new URL(import.meta.url);\n const action = (global.viteBoostAction || process.env.SSR_BOOST_ACTION) as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\n const entrypointConfig = getCurrentEntrypoint(mergedOptions.entrypoint ?? []);\n const isSSR = process.env.SSR_BOOST_IS_SSR === '1' || action === CliActions.dev;\n const isBuild = action === CliActions.build;\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n // @ts-ignore save custom options\n pluginOptions: {\n ...mergedOptions,\n pluginPath: path.dirname(dirInfo.pathname),\n action,\n isDev: action === CliActions.dev,\n },\n\n config(config, { isSsrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: entrypointConfig ? entrypointConfig.type === 'ssr' : isSSR,\n };\n\n config.build = {\n ...(config.build ?? {}),\n };\n\n if (!isSsrBuild) {\n if (isSSR && isBuild) {\n config.build.manifest = true;\n }\n\n return config;\n }\n\n return {\n ...config,\n ...(isBuild ? { appType: 'custom' } : {}),\n publicDir: false,\n };\n },\n },\n ];\n\n const { tsconfigAliases, routesPath, routesParsing, spaIndex } = mergedOptions;\n\n if (tsconfigAliases) {\n plugins.push(\n ViteMakeAliasesPlugin(typeof tsconfigAliases === 'boolean' ? undefined : tsconfigAliases),\n );\n }\n\n if (spaIndex) {\n plugins.push(ViteCreateSPAIndexPlugin(typeof spaIndex === 'boolean' ? undefined : spaIndex));\n }\n\n if (entrypointConfig) {\n plugins.push(ViteHandleCustomEntrypointPlugin({ entrypoint: entrypointConfig }));\n }\n\n plugins.push(\n ViteNormalizeRouterPlugin({\n isSSR,\n isBuild,\n routesPath,\n isNodeParsing: routesParsing === 'node',\n }),\n );\n\n return plugins;\n}\n\nexport default ViteSsrBoostPlugin;\n"],"names":["defaultOptions","indexFile","serverFile","clientFile","routesParsing","tsconfigAliases","spaIndex","ViteSsrBoostPlugin","options","dirInfo","URL","url","action","global","viteBoostAction","process","env","SSR_BOOST_ACTION","mergedOptions","entrypointConfig","getCurrentEntrypoint","entrypoint","isSSR","SSR_BOOST_IS_SSR","CliActions","dev","isBuild","build","plugins","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","config","isSsrBuild","define","__IS_SSR__","type","appType","publicDir","manifest","routesPath","push","ViteMakeAliasesPlugin","undefined","ViteCreateSPAIndexPlugin","ViteHandleCustomEntrypointPlugin","ViteNormalizeRouterPlugin","isNodeParsing"],"mappings":"8XA8CA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,YACZC,cAAe,QACfC,iBAAiB,EACjBC,UAAU,GAOZ,SAASC,EAAmBC,EAA0B,IACpD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAAUC,OAAOC,iBAAmBC,EAAQC,IAAIC,iBAChDC,EAAgC,IAAKlB,KAAmBQ,GACxDW,EAAmBC,EAAqBF,EAAcG,YAAc,IACpEC,EAAyC,MAAjCP,EAAQC,IAAIO,kBAA4BX,IAAWY,EAAWC,IACtEC,EAAUd,IAAWY,EAAWG,MAEhCC,EAAoB,CACxB,CACEC,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVd,EACHe,WAAYC,EAAKC,QAAQ1B,EAAQ2B,UACjCxB,SACAyB,MAAOzB,IAAWY,EAAWC,KAG/Ba,OAAM,CAACA,GAAQC,WAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,CAAE,EACvBC,WAAYtB,EAA6C,QAA1BA,EAAiBuB,KAAiBpB,GAGnEgB,EAAOX,MAAQ,IACTW,EAAOX,OAAS,CAAE,GAGnBY,EAQE,IACFD,KACCZ,EAAU,CAAEiB,QAAS,UAAa,CAAE,EACxCC,WAAW,IAVPtB,GAASI,IACXY,EAAOX,MAAMkB,UAAW,GAGnBP,OAYTjC,gBAAEA,EAAeyC,WAAEA,EAAU1C,cAAEA,EAAaE,SAAEA,GAAaY,EAyBjE,OAvBIb,GACFuB,EAAQmB,KACNC,EAAiD,kBAApB3C,OAAgC4C,EAAY5C,IAIzEC,GACFsB,EAAQmB,KAAKG,EAA6C,kBAAb5C,OAAyB2C,EAAY3C,IAGhFa,GACFS,EAAQmB,KAAKI,EAAiC,CAAE9B,WAAYF,KAG9DS,EAAQmB,KACNK,EAA0B,CACxB9B,QACAI,UACAoB,aACAO,cAAiC,SAAlBjD,KAIZwB,CACT"}
@@ -1,2 +1,2 @@
1
- import e from"../constants/plugin-name.js";const t=`${e}-create-spa-entrypoint`;function n(e={}){const{filename:n="index-spa.html",rootId:a="root"}=e;let o="";return{name:t,enforce:"post",apply:(e,{command:t,isSsrBuild:n})=>"build"===t&&!n,transformIndexHtml:e=>(o=e.replace(`id="${a}"`,`id="${a}" data-force-spa="1"`),e),generateBundle(){o&&this.emitFile({type:"asset",fileName:n,source:o})}}}export{n as default};
1
+ import e from"../constants/plugin-name.js";import{getCurrentEntrypointName as t}from"./handle-custom-entrypoint.js";const n=`${e}-create-spa-entrypoint`;function o(e={}){const{filename:o="index-spa.html",rootId:a="root"}=e;let r="";return{name:n,enforce:"post",apply:(e,{command:n,isSsrBuild:o})=>"build"===n&&!o&&!t(),transformIndexHtml:e=>(r=e.replace(`id="${a}"`,`id="${a}" data-force-spa="1"`),e),generateBundle(){r&&this.emitFile({type:"asset",fileName:o,source:r})}}}export{o as default};
2
2
  //# sourceMappingURL=create-spa-index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-spa-index.js","sources":["../../src/plugins/create-spa-index.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\n\nexport interface IPluginOptions {\n filename?: string;\n rootId?: string;\n}\n\nconst pluginName = `${PLUGIN_NAME}-create-spa-entrypoint`;\n\n/**\n * Create additional entrypoint for SPA.\n * File: index-spa.html\n *\n * E.g. for service worker entrypoint\n * @constructor\n */\nfunction ViteCreateSPAIndexPlugin(options: IPluginOptions = {}): Plugin {\n const { filename = 'index-spa.html', rootId = 'root' } = options;\n let spaHtml = '';\n\n return {\n name: pluginName,\n enforce: 'post',\n /**\n * Apply only on build but not for SSR\n */\n apply(_, { command, isSsrBuild }): boolean {\n return command === 'build' && !isSsrBuild;\n },\n transformIndexHtml(html): string {\n spaHtml = html.replace(`id=\"${rootId}\"`, `id=\"${rootId}\" data-force-spa=\"1\"`);\n\n return html;\n },\n generateBundle(): void {\n if (!spaHtml) {\n return;\n }\n\n this.emitFile({\n type: 'asset',\n fileName: filename,\n source: spaHtml,\n });\n },\n };\n}\n\nexport default ViteCreateSPAIndexPlugin;\n"],"names":["pluginName","PLUGIN_NAME","ViteCreateSPAIndexPlugin","options","filename","rootId","spaHtml","name","enforce","apply","_","command","isSsrBuild","transformIndexHtml","html","replace","generateBundle","this","emitFile","type","fileName","source"],"mappings":"2CAQA,MAAMA,EAAa,GAAGC,0BAStB,SAASC,EAAyBC,EAA0B,IAC1D,MAAMC,SAAEA,EAAW,iBAAgBC,OAAEA,EAAS,QAAWF,EACzD,IAAIG,EAAU,GAEd,MAAO,CACLC,KAAMP,EACNQ,QAAS,OAITC,MAAK,CAACC,GAAGC,QAAEA,EAAOC,WAAEA,KACC,UAAZD,IAAwBC,EAEjCC,mBAAmBC,IACjBR,EAAUQ,EAAKC,QAAQ,OAAOV,KAAW,OAAOA,yBAEzCS,GAETE,iBACOV,GAILW,KAAKC,SAAS,CACZC,KAAM,QACNC,SAAUhB,EACViB,OAAQf,GAEX,EAEL"}
1
+ {"version":3,"file":"create-spa-index.js","sources":["../../src/plugins/create-spa-index.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport { getCurrentEntrypointName } from '@plugins/handle-custom-entrypoint';\n\nexport interface IPluginOptions {\n filename?: string;\n rootId?: string;\n}\n\nconst pluginName = `${PLUGIN_NAME}-create-spa-entrypoint`;\n\n/**\n * Create additional entrypoint for SPA.\n * File: index-spa.html\n *\n * E.g. for service worker entrypoint\n * @constructor\n */\nfunction ViteCreateSPAIndexPlugin(options: IPluginOptions = {}): Plugin {\n const { filename = 'index-spa.html', rootId = 'root' } = options;\n let spaHtml = '';\n\n return {\n name: pluginName,\n enforce: 'post',\n /**\n * Apply only on build but not for SSR\n */\n apply(_, { command, isSsrBuild }): boolean {\n return command === 'build' && !isSsrBuild && !getCurrentEntrypointName();\n },\n transformIndexHtml(html): string {\n spaHtml = html.replace(`id=\"${rootId}\"`, `id=\"${rootId}\" data-force-spa=\"1\"`);\n\n return html;\n },\n generateBundle(): void {\n if (!spaHtml) {\n return;\n }\n\n this.emitFile({\n type: 'asset',\n fileName: filename,\n source: spaHtml,\n });\n },\n };\n}\n\nexport default ViteCreateSPAIndexPlugin;\n"],"names":["pluginName","PLUGIN_NAME","ViteCreateSPAIndexPlugin","options","filename","rootId","spaHtml","name","enforce","apply","_","command","isSsrBuild","getCurrentEntrypointName","transformIndexHtml","html","replace","generateBundle","this","emitFile","type","fileName","source"],"mappings":"oHASA,MAAMA,EAAa,GAAGC,0BAStB,SAASC,EAAyBC,EAA0B,IAC1D,MAAMC,SAAEA,EAAW,iBAAgBC,OAAEA,EAAS,QAAWF,EACzD,IAAIG,EAAU,GAEd,MAAO,CACLC,KAAMP,EACNQ,QAAS,OAITC,MAAK,CAACC,GAAGC,QAAEA,EAAOC,WAAEA,KACC,UAAZD,IAAwBC,IAAeC,IAEhDC,mBAAmBC,IACjBT,EAAUS,EAAKC,QAAQ,OAAOX,KAAW,OAAOA,yBAEzCU,GAETE,iBACOX,GAILY,KAAKC,SAAS,CACZC,KAAM,QACNC,SAAUjB,EACVkB,OAAQhB,GAEX,EAEL"}
@@ -0,0 +1,25 @@
1
+ import { Plugin } from 'vite';
2
+ import { IBuildEntrypoint } from "../services/build.js";
3
+ interface IPluginOptions {
4
+ entrypoint: IBuildEntrypoint;
5
+ }
6
+ /**
7
+ * Get current entrypoint name
8
+ */
9
+ declare const getCurrentEntrypointName: () => string | undefined;
10
+ /**
11
+ * Set current entrypoint name
12
+ */
13
+ declare const setCurrentEntrypointName: (name: string) => void;
14
+ /**
15
+ * Find current entrypoint by env
16
+ */
17
+ declare const getCurrentEntrypoint: (entrypoint: IBuildEntrypoint[], currentEntrypointName?: string | undefined) => IBuildEntrypoint | null;
18
+ /**
19
+ * Return custom entrypoint instead default (index.html).
20
+ *
21
+ * E.g. for build multiple entrypoint
22
+ * @constructor
23
+ */
24
+ declare function ViteHandleCustomEntrypointPlugin(options: IPluginOptions): Plugin;
25
+ export { IPluginOptions, ViteHandleCustomEntrypointPlugin, getCurrentEntrypoint, getCurrentEntrypointName, setCurrentEntrypointName };
@@ -0,0 +1,2 @@
1
+ import n from"node:fs";import e from"node:path";import o from"node:process";import r from"../constants/plugin-name.js";const t=`${r}-handle-custom-entrypoint`,i=()=>o.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME,l=n=>{o.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME=n},s=(n,e=i())=>{if(!n.length||!e)return null;for(const o of n)if(o.name===e&&!o.serverFile)return o;return null};function u(o){const{entrypoint:i}=o;let l="",s="";return{name:t,enforce:"pre",apply:(n,{command:e,isSsrBuild:o})=>"build"===e&&!o&&Boolean(i),config(n){const{indexFile:o}=i,r=n.build??{},t=o?e.resolve(n.root??"",o):void 0;return{...n,build:{...r,rollupOptions:{...r.rollupOptions??{},input:t}}}},configResolved(n){const o=n.plugins.find((n=>n.name===r));l=e.resolve(n.root,n.build.outDir),s=o.pluginOptions.clientFile},transform(n,o){if(o.endsWith(".html")){const{clientFile:o}=i;if(o)return n.replace(e.basename(s),o)}return n},closeBundle(){const{indexFile:o}=i;if(!o)return;const r=e.resolve(l,e.basename(o));n.existsSync(r)&&n.renameSync(r,e.resolve(l,"index.html"))}}}export{u as ViteHandleCustomEntrypointPlugin,s as getCurrentEntrypoint,i as getCurrentEntrypointName,l as setCurrentEntrypointName};
2
+ //# sourceMappingURL=handle-custom-entrypoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-custom-entrypoint.js","sources":["../../src/plugins/handle-custom-entrypoint.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport type { IBuildEntrypoint } from '@services/build';\n\nexport interface IPluginOptions {\n entrypoint: IBuildEntrypoint;\n}\n\nconst pluginName = `${PLUGIN_NAME}-handle-custom-entrypoint`;\n\n/**\n * Get current entrypoint name\n */\nconst getCurrentEntrypointName = (): string | undefined =>\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME;\n\n/**\n * Set current entrypoint name\n */\nconst setCurrentEntrypointName = (name: string): void => {\n process.env.SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME = name;\n};\n\n/**\n * Find current entrypoint by env\n */\nconst getCurrentEntrypoint = (\n entrypoint: IBuildEntrypoint[],\n currentEntrypointName = getCurrentEntrypointName(),\n): IBuildEntrypoint | null => {\n if (!entrypoint.length || !currentEntrypointName) {\n return null;\n }\n\n for (const entry of entrypoint) {\n if (entry.name === currentEntrypointName && !entry.serverFile) {\n return entry;\n }\n }\n\n return null;\n};\n\n/**\n * Return custom entrypoint instead default (index.html).\n *\n * E.g. for build multiple entrypoint\n * @constructor\n */\nfunction ViteHandleCustomEntrypointPlugin(options: IPluginOptions): Plugin {\n const { entrypoint } = options;\n let outPath = '';\n let origClientFile = '';\n\n return {\n name: pluginName,\n enforce: 'pre',\n /**\n * Apply only on build but not for SSR and only for custom entrypoint\n */\n apply(_, { command, isSsrBuild }): boolean {\n return command === 'build' && !isSsrBuild && Boolean(entrypoint);\n },\n config(config) {\n const { indexFile } = entrypoint;\n const buildConfig = config.build ?? {};\n const indexFilePath = indexFile ? path.resolve(config.root ?? '', indexFile) : undefined;\n\n return {\n ...config,\n build: {\n ...buildConfig,\n rollupOptions: {\n ...(buildConfig.rollupOptions ?? {}),\n input: indexFilePath,\n },\n },\n };\n },\n configResolved(config) {\n const pluginConfig = config.plugins.find((plugin) => plugin.name === PLUGIN_NAME);\n\n outPath = path.resolve(config.root, config.build.outDir);\n // @ts-expect-error pluginOptions is custom param\n origClientFile = (pluginConfig.pluginOptions as Record<string, any>).clientFile as string;\n },\n transform(code, id): string {\n if (id.endsWith('.html')) {\n const { clientFile } = entrypoint;\n\n if (clientFile) {\n return code.replace(path.basename(origClientFile), clientFile);\n }\n }\n\n return code;\n },\n closeBundle() {\n const { indexFile } = entrypoint;\n\n if (!indexFile) {\n return;\n }\n\n const indexFilePath = path.resolve(outPath, path.basename(indexFile));\n\n if (fs.existsSync(indexFilePath)) {\n fs.renameSync(indexFilePath, path.resolve(outPath, 'index.html'));\n }\n },\n };\n}\n\nexport {\n ViteHandleCustomEntrypointPlugin,\n getCurrentEntrypoint,\n getCurrentEntrypointName,\n setCurrentEntrypointName,\n};\n"],"names":["pluginName","PLUGIN_NAME","getCurrentEntrypointName","process","env","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","setCurrentEntrypointName","name","getCurrentEntrypoint","entrypoint","currentEntrypointName","length","entry","serverFile","ViteHandleCustomEntrypointPlugin","options","outPath","origClientFile","enforce","apply","_","command","isSsrBuild","Boolean","config","indexFile","buildConfig","build","indexFilePath","path","resolve","root","undefined","rollupOptions","input","configResolved","pluginConfig","plugins","find","plugin","outDir","pluginOptions","clientFile","transform","code","id","endsWith","replace","basename","closeBundle","fs","existsSync","renameSync"],"mappings":"uHAWA,MAAMA,EAAa,GAAGC,6BAKhBC,EAA2B,IAC/BC,EAAQC,IAAIC,uCAKRC,EAA4BC,IAChCJ,EAAQC,IAAIC,uCAAyCE,CAAI,EAMrDC,EAAuB,CAC3BC,EACAC,EAAwBR,OAExB,IAAKO,EAAWE,SAAWD,EACzB,OAAO,KAGT,IAAK,MAAME,KAASH,EAClB,GAAIG,EAAML,OAASG,IAA0BE,EAAMC,WACjD,OAAOD,EAIX,OAAO,IAAI,EASb,SAASE,EAAiCC,GACxC,MAAMN,WAAEA,GAAeM,EACvB,IAAIC,EAAU,GACVC,EAAiB,GAErB,MAAO,CACLV,KAAMP,EACNkB,QAAS,MAITC,MAAK,CAACC,GAAGC,QAAEA,EAAOC,WAAEA,KACC,UAAZD,IAAwBC,GAAcC,QAAQd,GAEvDe,OAAOA,GACL,MAAMC,UAAEA,GAAchB,EAChBiB,EAAcF,EAAOG,OAAS,GAC9BC,EAAgBH,EAAYI,EAAKC,QAAQN,EAAOO,MAAQ,GAAIN,QAAaO,EAE/E,MAAO,IACFR,EACHG,MAAO,IACFD,EACHO,cAAe,IACTP,EAAYO,eAAiB,CAAE,EACnCC,MAAON,IAId,EACDO,eAAeX,GACb,MAAMY,EAAeZ,EAAOa,QAAQC,MAAMC,GAAWA,EAAOhC,OAASN,IAErEe,EAAUa,EAAKC,QAAQN,EAAOO,KAAMP,EAAOG,MAAMa,QAEjDvB,EAAkBmB,EAAaK,cAAsCC,UACtE,EACDC,UAAUC,EAAMC,GACd,GAAIA,EAAGC,SAAS,SAAU,CACxB,MAAMJ,WAAEA,GAAejC,EAEvB,GAAIiC,EACF,OAAOE,EAAKG,QAAQlB,EAAKmB,SAAS/B,GAAiByB,EAEtD,CAED,OAAOE,CACR,EACDK,cACE,MAAMxB,UAAEA,GAAchB,EAEtB,IAAKgB,EACH,OAGF,MAAMG,EAAgBC,EAAKC,QAAQd,EAASa,EAAKmB,SAASvB,IAEtDyB,EAAGC,WAAWvB,IAChBsB,EAAGE,WAAWxB,EAAeC,EAAKC,QAAQd,EAAS,cAEtD,EAEL"}
@@ -4,6 +4,32 @@ import { ResolvedConfig } from 'vite';
4
4
  import { IPluginConfig } from "../helpers/plugin-config.js";
5
5
  interface IBuildParams {
6
6
  mode: string;
7
+ onFinish?: () => void;
8
+ clientOptions?: string;
9
+ serverOptions?: string;
10
+ focusOnly?: 'all' | 'app' | 'client' | 'server' | 'entrypoint';
11
+ isWatch?: boolean;
12
+ isUnlockRobots?: boolean;
13
+ isEject?: boolean;
14
+ isServerless?: boolean;
15
+ isNoWarnings?: boolean;
16
+ }
17
+ interface IBuildProcess {
18
+ promise: Promise<number | null | string>;
19
+ command: childProcess.ChildProcess;
20
+ }
21
+ interface ISpawnBuildParams {
22
+ shouldWait?: boolean;
23
+ focusOnly?: IBuildParams['focusOnly'];
24
+ env?: Record<string, string>;
25
+ }
26
+ interface IBuildEntrypoint {
27
+ name: string;
28
+ type: 'spa' | 'ssr';
29
+ indexFile?: string;
30
+ clientFile?: string;
31
+ serverFile?: string;
32
+ options?: string;
7
33
  }
8
34
  /**
9
35
  * Build service
@@ -12,35 +38,42 @@ declare class Build {
12
38
  /**
13
39
  * Is production build
14
40
  */
15
- isProd: boolean;
41
+ protected isProd: boolean;
16
42
  /**
17
43
  * Node environment
18
44
  */
19
- nodeEnv: string;
45
+ protected nodeEnv: string;
20
46
  /**
21
47
  * Build folder
22
48
  */
23
- buildDir: string;
24
- /**
25
- * Relative build dir
26
- */
27
- outDir: string;
28
- /**
29
- * Server file
30
- */
31
- serverFile: string;
49
+ protected buildDir: string;
32
50
  /**
33
51
  * Vite config
34
52
  */
35
- viteConfig: ResolvedConfig;
53
+ protected viteConfig: ResolvedConfig;
36
54
  /**
37
55
  * Plugin config
38
56
  */
39
- pluginConfig: IPluginConfig;
57
+ protected pluginConfig: IPluginConfig;
40
58
  /**
41
59
  * Build params
42
60
  */
43
61
  protected params: IBuildParams;
62
+ /**
63
+ * Abort controller for builds
64
+ */
65
+ protected abortController: AbortController | null;
66
+ /**
67
+ * Running builds
68
+ */
69
+ protected runningBuild: {
70
+ name: string;
71
+ buildProcess: IBuildProcess;
72
+ }[];
73
+ /**
74
+ * Listener for preview has attached
75
+ */
76
+ protected hasPreviewModeExitListener: boolean;
44
77
  /**
45
78
  * @constructor
46
79
  */
@@ -54,7 +87,7 @@ declare class Build {
54
87
  /**
55
88
  * Make config
56
89
  */
57
- makeConfig(): Promise<void>;
90
+ protected makeConfig(): Promise<void>;
58
91
  /**
59
92
  * Clear build folder
60
93
  */
@@ -62,23 +95,41 @@ declare class Build {
62
95
  * Clear build folder
63
96
  */
64
97
  clearBuildFolder(): void;
98
+ /**
99
+ * Return is prod indicator value
100
+ */
101
+ /**
102
+ * Return is prod indicator value
103
+ */
104
+ getIsProd(): boolean;
105
+ /**
106
+ * Return node env value
107
+ */
108
+ /**
109
+ * Return node env value
110
+ */
111
+ getNodeEnv(): string;
112
+ /**
113
+ * Return build names
114
+ */
115
+ /**
116
+ * Return build names
117
+ */
118
+ getRunningBuildNames(): string[];
65
119
  /**
66
120
  * Promisify spawn process
67
121
  */
68
122
  /**
69
123
  * Promisify spawn process
70
124
  */
71
- promisifyProcess(command: childProcess.ChildProcess, isRejectWarnings?: boolean): {
72
- promise: Promise<number | null | string>;
73
- command: childProcess.ChildProcess;
74
- };
125
+ protected promisifyProcess(command: childProcess.ChildProcess, isRejectWarnings?: boolean): IBuildProcess;
75
126
  /**
76
127
  * Build assets manifest file
77
128
  */
78
129
  /**
79
130
  * Build assets manifest file
80
131
  */
81
- buildManifest(): Promise<void>;
132
+ protected buildManifest(): Promise<void>;
82
133
  /**
83
134
  * Remove pathId from client route files
84
135
  */
@@ -92,20 +143,48 @@ declare class Build {
92
143
  /**
93
144
  * Change general directive Disallow to Allow in robots.txt.
94
145
  */
95
- unlockRobots(): void;
146
+ protected unlockRobots(): void;
96
147
  /**
97
148
  * Eject cli to run app via node
98
149
  */
99
150
  /**
100
151
  * Eject cli to run app via node
101
152
  */
102
- eject(): void;
153
+ protected eject(): void;
103
154
  /**
104
155
  * Create serverless entrypoint
105
156
  */
106
157
  /**
107
158
  * Create serverless entrypoint
108
159
  */
109
- createServerless(): void;
160
+ protected createServerless(): void;
161
+ /**
162
+ * Build specified entrypoint
163
+ */
164
+ /**
165
+ * Build specified entrypoint
166
+ */
167
+ protected spawnBuild(name: string, buildOptions: string, params?: ISpawnBuildParams): Promise<void>;
168
+ /**
169
+ * Wait latest build and stop process in case error
170
+ */
171
+ /**
172
+ * Wait latest build and stop process in case error
173
+ */
174
+ protected waitLastBuild(): Promise<void>;
175
+ /**
176
+ * Run preview mode
177
+ */
178
+ /**
179
+ * Run preview mode
180
+ */
181
+ protected runPreviewMode(): void;
182
+ /**
183
+ * Run app build
184
+ */
185
+ /**
186
+ * Run app build
187
+ */
188
+ build(): Promise<void>;
110
189
  }
111
- export { Build as default };
190
+ export { Build as default, IBuildParams, IBuildEntrypoint };
package/services/build.js CHANGED
@@ -1,2 +1,2 @@
1
- import i from"node:fs";import e from"node:path";import s from"chalk";import{resolveConfig as o}from"vite";import t from"../helpers/plugin-config.js";import{readMeta as r}from"../helpers/ssr-meta.js";import n from"./server-config.js";import l from"./ssr-manifest.js";class c{isProd;nodeEnv;buildDir;outDir;serverFile;viteConfig;pluginConfig;params;constructor(i){this.params=i}async makeConfig(){const{mode:i}=this.params;this.viteConfig=await o({},"build",i,"production"),this.pluginConfig=t(this.viteConfig),this.buildDir=e.resolve(this.viteConfig.root,this.viteConfig.build.outDir),this.outDir=this.viteConfig.build.outDir,this.serverFile=this.pluginConfig.serverFile,this.nodeEnv=process.env.NODE_ENV||"production",this.isProd="production"===this.nodeEnv}clearBuildFolder(){i.existsSync(this.buildDir)&&i.rmSync(this.buildDir,{recursive:!0})}promisifyProcess(i,e=!1){const s=new Promise(((s,o)=>{i.on("exit",(i=>{s(i)})),i.on("close",(i=>{s(i)})),i.on("error",(i=>{o(i)})),e&&i.stderr?.on("data",(i=>{const e=Buffer.from(i).toString();(e.includes("warning")||e.includes("WARNING"))&&s(1)}))}));return i.stdout?.pipe(process.stdout),i.stderr?.pipe(process.stderr),{promise:s,command:i}}async buildManifest(){console.info(s.blue(`Building routes manifest file: ${this.pluginConfig.routesParsing}`));const i="node"===this.pluginConfig.routesParsing,e=n.init({isProd:this.isProd,mode:this.params.mode},{root:this.viteConfig.root,clientFile:this.pluginConfig.clientFile});await l.get(e,{buildDir:this.viteConfig.build.outDir,viteAliases:this.viteConfig.resolve.alias}).buildRoutesManifest(i),i&&this.cleanupClientRoutes()}cleanupClientRoutes(){const{routeFiles:e}=r(this.buildDir),s=new Set(Object.values(e??[]));s.size&&s.forEach((e=>{const s=`${this.buildDir}/client/${e}`;try{const e=i.readFileSync(s,{encoding:"utf-8"}).replace(/(lazy:.*?\((.*?)\)),\s?".*?"\)/g,"$1)");i.writeFileSync(s,e)}catch(i){console.log(`Failed cleanup client route ${s}:`,i)}}))}unlockRobots(){const e=`${this.buildDir}/client/robots.txt`;if(!i.existsSync(e))return void console.warn(`Failed to unlock robots.txt, file not exist: ${e}`);const o=i.readFileSync(e,{encoding:"utf-8"}).replace(/Disallow: \/$/m,"Allow: /");i.writeFileSync(e,o,{encoding:"utf-8"}),console.info(s.blue("\nrobots.txt unlocked."))}eject(){const e=`${this.buildDir}/server/start.js`;i.writeFileSync(e,"import runProd from '@lomray/vite-ssr-boost/cli/run-prod.js';\n\nconst VERSION = process.env.VERSION || \"1.0.0\";\nconst PORT = process.env.PORT || 3000;\nconst IS_HOST = process.env.IS_HOST || \"0\";\nconst ONLY_CLIENT = process.env.ONLY_CLIENT || \"0\";\n\nawait runProd({\n version: VERSION,\n isHost: IS_HOST === '1',\n isPrintInfo: true,\n port: PORT,\n onlyClient: ONLY_CLIENT === '1',\n });\n",{encoding:"utf-8"})}createServerless(){const e=`${this.buildDir}/server/serverless.js`;i.writeFileSync(e,"import runServerless from '@lomray/vite-ssr-boost/cli/run-serverless.js';\n\nexport default await runServerless({ version: process.env.VERSION || \"1.0.0\" });\n",{encoding:"utf-8"})}}export{c as default};
1
+ import i from"node:child_process";import s from"node:fs";import t from"node:path";import e from"chalk";import{resolveConfig as o}from"vite";import n from"../cli/helpers/vite-reset-cache.js";import r from"../helpers/create-focus-only.js";import{createDevMarker as l}from"../helpers/dev-marker.js";import a from"../helpers/plugin-config.js";import c from"../helpers/process-stop.js";import{readMeta as u,removeMeta as d}from"../helpers/ssr-meta.js";import h from"./server-config.js";import p from"./ssr-manifest.js";class f{isProd;nodeEnv;buildDir;viteConfig;pluginConfig;params={mode:"",clientOptions:"",serverOptions:"",focusOnly:"app",isWatch:!1,isUnlockRobots:!1,isEject:!1,isServerless:!1,isNoWarnings:!1};abortController=null;runningBuild=[];hasPreviewModeExitListener=!1;constructor(i){this.params={...this.params,...i}}async makeConfig(){const{mode:i}=this.params;this.viteConfig=await o({},"build",i,"production"),this.pluginConfig=a(this.viteConfig),this.buildDir=t.resolve(this.viteConfig.root,this.viteConfig.build.outDir),this.nodeEnv=process.env.NODE_ENV||"production",this.isProd="production"===this.nodeEnv}clearBuildFolder(){s.existsSync(this.buildDir)&&s.rmSync(this.buildDir,{recursive:!0})}getIsProd(){return this.isProd}getNodeEnv(){return this.nodeEnv}getRunningBuildNames(){return this.runningBuild.map((({name:i})=>i))}promisifyProcess(i,s=!1){const t=new Promise(((t,e)=>{i.on("exit",(i=>{t(i)})),i.on("close",(i=>{t(i)})),i.on("error",(i=>{e(i)})),s&&i.stderr?.on("data",(i=>{const s=Buffer.from(i).toString();(s.includes("warning")||s.includes("WARNING"))&&t(1)}))}));return i.stdout?.pipe(process.stdout),i.stderr?.pipe(process.stderr),{promise:t,command:i}}async buildManifest(){console.info(e.blue(`Building routes manifest file: ${this.pluginConfig.routesParsing}`));const i="node"===this.pluginConfig.routesParsing,s=h.init({isProd:this.isProd,mode:this.params.mode},{root:this.viteConfig.root,clientFile:this.pluginConfig.clientFile});await p.get(s,{buildDir:this.viteConfig.build.outDir,viteAliases:this.viteConfig.resolve.alias}).buildRoutesManifest(i),i&&this.cleanupClientRoutes()}cleanupClientRoutes(){const{routeFiles:i}=u(this.buildDir),t=new Set(Object.values(i??[]));t.size&&t.forEach((i=>{const t=`${this.buildDir}/client/${i}`;try{const i=s.readFileSync(t,{encoding:"utf-8"}).replace(/(lazy:.*?\((.*?)\)),\s?".*?"\)/g,"$1)");s.writeFileSync(t,i)}catch(i){console.log(`Failed cleanup client route ${t}:`,i)}}))}unlockRobots(){const i=`${this.buildDir}/client/robots.txt`;if(!s.existsSync(i))return void console.warn(`Failed to unlock robots.txt, file not exist: ${i}`);const t=s.readFileSync(i,{encoding:"utf-8"}).replace(/Disallow: \/$/m,"Allow: /");s.writeFileSync(i,t,{encoding:"utf-8"}),console.info(e.blue("\nrobots.txt unlocked."))}eject(){const i=`${this.buildDir}/server/start.js`;s.writeFileSync(i,"import runProd from '@lomray/vite-ssr-boost/cli/run-prod.js';\n\nconst VERSION = process.env.VERSION || \"1.0.0\";\nconst PORT = process.env.PORT || 3000;\nconst IS_HOST = process.env.IS_HOST || \"0\";\nconst ONLY_CLIENT = process.env.ONLY_CLIENT || \"0\";\n\nawait runProd({\n version: VERSION,\n isHost: IS_HOST === '1',\n isPrintInfo: true,\n port: PORT,\n onlyClient: ONLY_CLIENT === '1',\n });\n",{encoding:"utf-8"})}createServerless(){const i=`${this.buildDir}/server/serverless.js`;s.writeFileSync(i,"import runServerless from '@lomray/vite-ssr-boost/cli/run-serverless.js';\n\nexport default await runServerless({ version: process.env.VERSION || \"1.0.0\" });\n",{encoding:"utf-8"})}async spawnBuild(s,t,e={}){const{mode:o,isNoWarnings:n}=this.params,{focusOnly:l=this.params.focusOnly,shouldWait:a=!1,env:c={}}=e,u=o?`--mode ${o}`:"",d=this.promisifyProcess(i.spawn(`vite build ${t} ${u} --emptyOutDir`,{signal:this.abortController.signal,stdio:[process.stdin,"pipe","pipe"],shell:!0,env:{...process.env,...c,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:r(l).isOnlyClient()?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}}),n);this.runningBuild.push({name:s,buildProcess:d}),a&&await this.waitLastBuild()}async waitLastBuild(){const i=this.runningBuild.at(-1);if(!i)return;const s=await i.buildProcess.promise;c(s,!0)}runPreviewMode(){this.hasPreviewModeExitListener||(process.on("exit",(()=>{this.abortController.abort()})),this.hasPreviewModeExitListener=!0);const{onFinish:i}=this.params;let s=this.runningBuild.length;const t=e=>{Buffer.from(e).toString().includes("built in")&&(s-=1,s||(this.runningBuild.forEach((({buildProcess:i})=>{i.command.stdout?.removeListener("data",t)})),l(this.isProd,this.viteConfig),i?.()))};this.runningBuild.forEach((({buildProcess:i})=>{i.command.stdout?.on("data",t)}))}async build(){await this.makeConfig(),await n(),this.clearBuildFolder();const{clientOptions:i,serverOptions:s,onFinish:t,isWatch:e,focusOnly:o,isEject:a,isServerless:c,isUnlockRobots:u}=this.params,{outDir:h}=this.viteConfig.build,p=r(o);this.abortController=new AbortController,this.runningBuild=[],p.isClient()&&await this.spawnBuild("client",`${i} --outDir ${h}/client`,{shouldWait:!e}),p.isServer()&&(await this.spawnBuild("server",`${s} --outDir ${h}/server --ssr ${this.pluginConfig.serverFile}`,{shouldWait:!e}),e||(await this.buildManifest(),a&&this.eject(),c&&this.createServerless()));const{entrypoint:f}=this.pluginConfig;if(f?.length&&p.isEntrypoint())for(const{name:i,type:s,serverFile:t,options:o=""}of f){const n=t&&"ssr"===s?`--ssr ${t}`:"";await this.spawnBuild(i,`${o} ${n} --outDir ${h}/${i}`,{shouldWait:!e,focusOnly:"ssr"===s?"server":"client",env:{SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME:i}})}e?this.runPreviewMode():(u&&this.unlockRobots(),l(this.isProd,this.viteConfig),d(this.buildDir),t?.())}}export{f as default};
2
2
  //# sourceMappingURL=build.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sources":["../../src/services/build.ts"],"sourcesContent":["import type childProcess from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport type { ResolvedConfig } from 'vite';\nimport { resolveConfig } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport { readMeta } from '@helpers/ssr-meta';\nimport ServerConfig from '@services/server-config';\nimport SsrManifest from '@services/ssr-manifest';\n\ninterface IBuildParams {\n mode: string;\n}\n\n/**\n * Build service\n */\nclass Build {\n /**\n * Is production build\n */\n public isProd: boolean;\n\n /**\n * Node environment\n */\n public nodeEnv: string;\n\n /**\n * Build folder\n */\n public buildDir: string;\n\n /**\n * Relative build dir\n */\n public outDir: string;\n\n /**\n * Server file\n */\n public serverFile: string;\n\n /**\n * Vite config\n */\n public viteConfig: ResolvedConfig;\n\n /**\n * Plugin config\n */\n public pluginConfig: IPluginConfig;\n\n /**\n * Build params\n */\n protected params: IBuildParams;\n\n /**\n * @constructor\n */\n constructor(params: IBuildParams) {\n this.params = params;\n }\n\n /**\n * Make config\n */\n public async makeConfig(): Promise<void> {\n const { mode } = this.params;\n\n this.viteConfig = await resolveConfig({}, 'build', mode, 'production');\n this.pluginConfig = getPluginConfig(this.viteConfig);\n this.buildDir = path.resolve(this.viteConfig.root, this.viteConfig.build.outDir);\n this.outDir = this.viteConfig.build.outDir;\n this.serverFile = this.pluginConfig.serverFile;\n this.nodeEnv = process.env.NODE_ENV || 'production';\n this.isProd = this.nodeEnv === 'production';\n }\n\n /**\n * Clear build folder\n */\n public clearBuildFolder(): void {\n // clear build folder\n if (fs.existsSync(this.buildDir)) {\n fs.rmSync(this.buildDir, { recursive: true });\n }\n }\n\n /**\n * Promisify spawn process\n */\n public promisifyProcess(\n command: childProcess.ChildProcess,\n isRejectWarnings = false,\n ): { promise: Promise<number | null | string>; command: childProcess.ChildProcess } {\n const promise = new Promise<number | null | string>((resolve, reject) => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code: number): void => {\n resolve(code);\n });\n\n command.on('error', (message: string): void => {\n reject(message);\n });\n\n if (isRejectWarnings) {\n command.stderr?.on('data', (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('warning') || msg.includes('WARNING')) {\n resolve(1);\n }\n });\n }\n });\n\n command.stdout?.pipe(process.stdout);\n command.stderr?.pipe(process.stderr);\n\n return { promise, command };\n }\n\n /**\n * Build assets manifest file\n */\n public async buildManifest(): Promise<void> {\n console.info(chalk.blue(`Building routes manifest file: ${this.pluginConfig.routesParsing}`));\n\n const isNodeParsing = this.pluginConfig.routesParsing === 'node';\n const serverConfig = ServerConfig.init(\n { isProd: this.isProd, mode: this.params.mode },\n { root: this.viteConfig.root, clientFile: this.pluginConfig.clientFile },\n );\n\n await SsrManifest.get(serverConfig, {\n buildDir: this.viteConfig.build.outDir,\n viteAliases: this.viteConfig.resolve.alias,\n }).buildRoutesManifest(isNodeParsing);\n\n if (isNodeParsing) {\n this.cleanupClientRoutes();\n }\n }\n\n /**\n * Remove pathId from client route files\n */\n private cleanupClientRoutes(): void {\n const { routeFiles } = readMeta(this.buildDir);\n const files = new Set(Object.values(routeFiles ?? []));\n\n if (!files.size) {\n return;\n }\n\n files.forEach((file) => {\n const filepath = `${this.buildDir}/client/${file}`;\n\n try {\n const result = fs\n .readFileSync(filepath, { encoding: 'utf-8' })\n .replace(/(lazy:.*?\\((.*?)\\)),\\s?\".*?\"\\)/g, '$1)');\n\n fs.writeFileSync(filepath, result);\n } catch (e) {\n console.log(`Failed cleanup client route ${filepath}:`, e);\n }\n });\n }\n\n /**\n * Change general directive Disallow to Allow in robots.txt.\n */\n public unlockRobots(): void {\n const robotsFile = `${this.buildDir}/client/robots.txt`;\n\n if (!fs.existsSync(robotsFile)) {\n console.warn(`Failed to unlock robots.txt, file not exist: ${robotsFile}`);\n\n return;\n }\n\n const data = fs\n .readFileSync(robotsFile, { encoding: 'utf-8' })\n .replace(/Disallow: \\/$/m, 'Allow: /');\n\n fs.writeFileSync(robotsFile, data, { encoding: 'utf-8' });\n\n console.info(chalk.blue('\\nrobots.txt unlocked.'));\n }\n\n /**\n * Eject cli to run app via node\n */\n public eject(): void {\n const entrypoint = `${this.buildDir}/server/start.js`;\n const script =\n \"import runProd from '@lomray/vite-ssr-boost/cli/run-prod.js';\\n\\n\" +\n 'const VERSION = process.env.VERSION || \"1.0.0\";\\n' +\n 'const PORT = process.env.PORT || 3000;\\n' +\n 'const IS_HOST = process.env.IS_HOST || \"0\";\\n' +\n 'const ONLY_CLIENT = process.env.ONLY_CLIENT || \"0\";\\n\\n' +\n `await runProd({\n version: VERSION,\n isHost: IS_HOST === '1',\n isPrintInfo: true,\n port: PORT,\n onlyClient: ONLY_CLIENT === '1',\n });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Create serverless entrypoint\n */\n public createServerless(): void {\n const entrypoint = `${this.buildDir}/server/serverless.js`;\n const script =\n \"import runServerless from '@lomray/vite-ssr-boost/cli/run-serverless.js';\\n\\n\" +\n `export default await runServerless({ version: process.env.VERSION || \"1.0.0\" });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n}\n\nexport default Build;\n"],"names":["Build","isProd","nodeEnv","buildDir","outDir","serverFile","viteConfig","pluginConfig","params","constructor","this","async","mode","resolveConfig","getPluginConfig","path","resolve","root","build","process","env","NODE_ENV","clearBuildFolder","fs","existsSync","rmSync","recursive","promisifyProcess","command","isRejectWarnings","promise","Promise","reject","on","code","message","stderr","buff","msg","Buffer","from","toString","includes","stdout","pipe","console","info","chalk","blue","routesParsing","isNodeParsing","serverConfig","ServerConfig","init","clientFile","SsrManifest","get","viteAliases","alias","buildRoutesManifest","cleanupClientRoutes","routeFiles","readMeta","files","Set","Object","values","size","forEach","file","filepath","result","readFileSync","encoding","replace","writeFileSync","e","log","unlockRobots","robotsFile","warn","data","eject","entrypoint","createServerless"],"mappings":"0QAmBA,MAAMA,EAIGC,OAKAC,QAKAC,SAKAC,OAKAC,WAKAC,WAKAC,aAKGC,OAKVC,YAAYD,GACVE,KAAKF,OAASA,CACf,CAKMG,mBACL,MAAMC,KAAEA,GAASF,KAAKF,OAEtBE,KAAKJ,iBAAmBO,EAAc,CAAE,EAAE,QAASD,EAAM,cACzDF,KAAKH,aAAeO,EAAgBJ,KAAKJ,YACzCI,KAAKP,SAAWY,EAAKC,QAAQN,KAAKJ,WAAWW,KAAMP,KAAKJ,WAAWY,MAAMd,QACzEM,KAAKN,OAASM,KAAKJ,WAAWY,MAAMd,OACpCM,KAAKL,WAAaK,KAAKH,aAAaF,WACpCK,KAAKR,QAAUiB,QAAQC,IAAIC,UAAY,aACvCX,KAAKT,OAA0B,eAAjBS,KAAKR,OACpB,CAKMoB,mBAEDC,EAAGC,WAAWd,KAAKP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,kCAAmC,OAE9CnD,EAAGoD,cAAcL,EAAUC,EAC5B,CAAC,MAAOK,GACP/B,QAAQgC,IAAI,+BAA+BP,KAAaM,EACzD,IAEJ,CAKME,eACL,MAAMC,EAAa,GAAGrE,KAAKP,6BAE3B,IAAKoB,EAAGC,WAAWuD,GAGjB,YAFAlC,QAAQmC,KAAK,gDAAgDD,KAK/D,MAAME,EAAO1D,EACViD,aAAaO,EAAY,CAAEN,SAAU,UACrCC,QAAQ,iBAAkB,YAE7BnD,EAAGoD,cAAcI,EAAYE,EAAM,CAAER,SAAU,UAE/C5B,QAAQC,KAAKC,EAAMC,KAAK,0BACzB,CAKMkC,QACL,MAAMC,EAAa,GAAGzE,KAAKP,2BAe3BoB,EAAGoD,cAAcQ,EAbf,2bAamC,CACnCV,SAAU,SAEb,CAKMW,mBACL,MAAMD,EAAa,GAAGzE,KAAKP,gCAK3BoB,EAAGoD,cAAcQ,EAHf,oKAGmC,CACnCV,SAAU,SAEb"}
1
+ {"version":3,"file":"build.js","sources":["../../src/services/build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport type { ResolvedConfig } from 'vite';\nimport { resolveConfig } from 'vite';\nimport viteResetCache from '@cli/helpers/vite-reset-cache';\nimport createFocusOnly from '@helpers/create-focus-only';\nimport { createDevMarker } from '@helpers/dev-marker';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport processStop from '@helpers/process-stop';\nimport { readMeta, removeMeta } from '@helpers/ssr-meta';\nimport ServerConfig from '@services/server-config';\nimport SsrManifest from '@services/ssr-manifest';\n\nexport interface IBuildParams {\n mode: string;\n onFinish?: () => void;\n clientOptions?: string;\n serverOptions?: string;\n focusOnly?: 'all' | 'app' | 'client' | 'server' | 'entrypoint';\n isWatch?: boolean;\n isUnlockRobots?: boolean;\n isEject?: boolean;\n isServerless?: boolean;\n isNoWarnings?: boolean;\n}\n\ninterface IBuildProcess {\n promise: Promise<number | null | string>;\n command: childProcess.ChildProcess;\n}\n\ninterface ISpawnBuildParams {\n shouldWait?: boolean;\n focusOnly?: IBuildParams['focusOnly'];\n env?: Record<string, string>;\n}\n\nexport interface IBuildEntrypoint {\n // entrypoint name\n name: string;\n type: 'spa' | 'ssr';\n // custom index file, default: indexFile from plugin config\n indexFile?: string;\n // custom entry file for replace in indexFile, default: undefined (do nothing)\n clientFile?: string;\n // custom server file, indexFile and clientFile will be ignored\n serverFile?: string;\n // additional options for vite build command\n options?: string;\n}\n\n/**\n * Build service\n */\nclass Build {\n /**\n * Is production build\n */\n protected isProd: boolean;\n\n /**\n * Node environment\n */\n protected nodeEnv: string;\n\n /**\n * Build folder\n */\n protected buildDir: string;\n\n /**\n * Vite config\n */\n protected viteConfig: ResolvedConfig;\n\n /**\n * Plugin config\n */\n protected pluginConfig: IPluginConfig;\n\n /**\n * Build params\n */\n protected params: IBuildParams = {\n mode: '',\n clientOptions: '',\n serverOptions: '',\n focusOnly: 'app',\n isWatch: false,\n isUnlockRobots: false,\n isEject: false,\n isServerless: false,\n isNoWarnings: false,\n };\n\n /**\n * Abort controller for builds\n */\n protected abortController: AbortController | null = null;\n\n /**\n * Running builds\n */\n protected runningBuild: { name: string; buildProcess: IBuildProcess }[] = [];\n\n /**\n * Listener for preview has attached\n */\n protected hasPreviewModeExitListener = false;\n\n /**\n * @constructor\n */\n public constructor(params: IBuildParams) {\n this.params = { ...this.params, ...params };\n }\n\n /**\n * Make config\n */\n protected async makeConfig(): Promise<void> {\n const { mode } = this.params;\n\n this.viteConfig = await resolveConfig({}, 'build', mode, 'production');\n this.pluginConfig = getPluginConfig(this.viteConfig);\n this.buildDir = path.resolve(this.viteConfig.root, this.viteConfig.build.outDir);\n this.nodeEnv = process.env.NODE_ENV || 'production';\n this.isProd = this.nodeEnv === 'production';\n }\n\n /**\n * Clear build folder\n */\n public clearBuildFolder(): void {\n // clear build folder\n if (fs.existsSync(this.buildDir)) {\n fs.rmSync(this.buildDir, { recursive: true });\n }\n }\n\n /**\n * Return is prod indicator value\n */\n public getIsProd(): boolean {\n return this.isProd;\n }\n\n /**\n * Return node env value\n */\n public getNodeEnv(): string {\n return this.nodeEnv;\n }\n\n /**\n * Return build names\n */\n public getRunningBuildNames(): string[] {\n return this.runningBuild.map(({ name }) => name);\n }\n\n /**\n * Promisify spawn process\n */\n protected promisifyProcess(\n command: childProcess.ChildProcess,\n isRejectWarnings = false,\n ): IBuildProcess {\n const promise = new Promise<number | null | string>((resolve, reject): void => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code: number): void => {\n resolve(code);\n });\n\n command.on('error', (message: string): void => {\n reject(message);\n });\n\n if (isRejectWarnings) {\n command.stderr?.on('data', (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('warning') || msg.includes('WARNING')) {\n resolve(1);\n }\n });\n }\n });\n\n command.stdout?.pipe(process.stdout);\n command.stderr?.pipe(process.stderr);\n\n return { promise, command };\n }\n\n /**\n * Build assets manifest file\n */\n protected async buildManifest(): Promise<void> {\n console.info(chalk.blue(`Building routes manifest file: ${this.pluginConfig.routesParsing}`));\n\n const isNodeParsing = this.pluginConfig.routesParsing === 'node';\n const serverConfig = ServerConfig.init(\n { isProd: this.isProd, mode: this.params.mode },\n { root: this.viteConfig.root, clientFile: this.pluginConfig.clientFile },\n );\n\n await SsrManifest.get(serverConfig, {\n buildDir: this.viteConfig.build.outDir,\n viteAliases: this.viteConfig.resolve.alias,\n }).buildRoutesManifest(isNodeParsing);\n\n if (isNodeParsing) {\n this.cleanupClientRoutes();\n }\n }\n\n /**\n * Remove pathId from client route files\n */\n private cleanupClientRoutes(): void {\n const { routeFiles } = readMeta(this.buildDir);\n const files = new Set(Object.values(routeFiles ?? []));\n\n if (!files.size) {\n return;\n }\n\n files.forEach((file) => {\n const filepath = `${this.buildDir}/client/${file}`;\n\n try {\n const result = fs\n .readFileSync(filepath, { encoding: 'utf-8' })\n .replace(/(lazy:.*?\\((.*?)\\)),\\s?\".*?\"\\)/g, '$1)');\n\n fs.writeFileSync(filepath, result);\n } catch (e) {\n console.log(`Failed cleanup client route ${filepath}:`, e);\n }\n });\n }\n\n /**\n * Change general directive Disallow to Allow in robots.txt.\n */\n protected unlockRobots(): void {\n const robotsFile = `${this.buildDir}/client/robots.txt`;\n\n if (!fs.existsSync(robotsFile)) {\n console.warn(`Failed to unlock robots.txt, file not exist: ${robotsFile}`);\n\n return;\n }\n\n const data = fs\n .readFileSync(robotsFile, { encoding: 'utf-8' })\n .replace(/Disallow: \\/$/m, 'Allow: /');\n\n fs.writeFileSync(robotsFile, data, { encoding: 'utf-8' });\n\n console.info(chalk.blue('\\nrobots.txt unlocked.'));\n }\n\n /**\n * Eject cli to run app via node\n */\n protected eject(): void {\n const entrypoint = `${this.buildDir}/server/start.js`;\n const script =\n \"import runProd from '@lomray/vite-ssr-boost/cli/run-prod.js';\\n\\n\" +\n 'const VERSION = process.env.VERSION || \"1.0.0\";\\n' +\n 'const PORT = process.env.PORT || 3000;\\n' +\n 'const IS_HOST = process.env.IS_HOST || \"0\";\\n' +\n 'const ONLY_CLIENT = process.env.ONLY_CLIENT || \"0\";\\n\\n' +\n `await runProd({\n version: VERSION,\n isHost: IS_HOST === '1',\n isPrintInfo: true,\n port: PORT,\n onlyClient: ONLY_CLIENT === '1',\n });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Create serverless entrypoint\n */\n protected createServerless(): void {\n const entrypoint = `${this.buildDir}/server/serverless.js`;\n const script =\n \"import runServerless from '@lomray/vite-ssr-boost/cli/run-serverless.js';\\n\\n\" +\n `export default await runServerless({ version: process.env.VERSION || \"1.0.0\" });\\n`;\n\n fs.writeFileSync(entrypoint, script, {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Build specified entrypoint\n */\n protected async spawnBuild(\n name: string,\n buildOptions: string,\n params: ISpawnBuildParams = {},\n ): Promise<void> {\n const { mode, isNoWarnings } = this.params;\n const { focusOnly = this.params.focusOnly, shouldWait = false, env = {} } = params;\n const modeOpt = mode ? `--mode ${mode}` : '';\n\n const buildProcess = this.promisifyProcess(\n childProcess.spawn(`vite build ${buildOptions} ${modeOpt} --emptyOutDir`, {\n signal: this.abortController!.signal,\n stdio: [process.stdin, 'pipe', 'pipe'],\n shell: true,\n env: {\n ...process.env,\n ...env,\n FORCE_COLOR: '2',\n SSR_BOOST_IS_SSR: createFocusOnly(focusOnly).isOnlyClient() ? '0' : '1',\n SSR_BOOST_ACTION: global.viteBoostAction,\n },\n }),\n isNoWarnings,\n );\n\n this.runningBuild.push({ name, buildProcess });\n\n if (!shouldWait) {\n return;\n }\n\n await this.waitLastBuild();\n }\n\n /**\n * Wait latest build and stop process in case error\n */\n protected async waitLastBuild(): Promise<void> {\n const latestProcess = this.runningBuild.at(-1);\n\n if (!latestProcess) {\n return;\n }\n\n const exitCode = await latestProcess.buildProcess.promise;\n\n processStop(exitCode, true);\n }\n\n /**\n * Run preview mode\n */\n protected runPreviewMode(): void {\n if (!this.hasPreviewModeExitListener) {\n process.on('exit', () => {\n this.abortController!.abort();\n });\n\n this.hasPreviewModeExitListener = true;\n }\n\n const { onFinish } = this.params;\n let buildCount = this.runningBuild.length;\n\n /**\n * Detect finished builds for process\n */\n const listener = (buff: Uint8Array): void => {\n const msg = Buffer.from(buff).toString();\n\n if (msg.includes('built in')) {\n buildCount -= 1;\n\n if (!buildCount) {\n this.runningBuild.forEach(({ buildProcess }) => {\n buildProcess.command.stdout?.removeListener('data', listener);\n });\n createDevMarker(this.isProd, this.viteConfig);\n onFinish?.();\n }\n }\n };\n\n /**\n * Listen output for call onFinish\n */\n this.runningBuild.forEach(({ buildProcess }) => {\n buildProcess.command.stdout?.on('data', listener);\n });\n }\n\n /**\n * Run app build\n */\n public async build(): Promise<void> {\n await this.makeConfig();\n // this is required step - build with different env may cause problems\n await viteResetCache();\n this.clearBuildFolder();\n\n const {\n clientOptions,\n serverOptions,\n onFinish,\n isWatch,\n focusOnly,\n isEject,\n isServerless,\n isUnlockRobots,\n } = this.params;\n const { outDir } = this.viteConfig.build;\n const focus = createFocusOnly(focusOnly);\n\n this.abortController = new AbortController();\n this.runningBuild = [];\n\n if (focus.isClient()) {\n /**\n * Build client\n */\n await this.spawnBuild('client', `${clientOptions} --outDir ${outDir}/client`, {\n shouldWait: !isWatch,\n });\n }\n\n /**\n * Build server\n */\n if (focus.isServer()) {\n await this.spawnBuild(\n 'server',\n `${serverOptions} --outDir ${outDir}/server --ssr ${this.pluginConfig.serverFile}`,\n {\n shouldWait: !isWatch,\n },\n );\n\n if (!isWatch) {\n await this.buildManifest();\n\n if (isEject) {\n this.eject();\n }\n\n if (isServerless) {\n this.createServerless();\n }\n }\n }\n\n /**\n * Build additional entrypoint\n */\n const { entrypoint } = this.pluginConfig;\n\n if (entrypoint?.length && focus.isEntrypoint()) {\n for (const { name, type, serverFile, options = '' } of entrypoint) {\n const cliOptions = serverFile && type === 'ssr' ? `--ssr ${serverFile}` : '';\n\n await this.spawnBuild(name, `${options} ${cliOptions} --outDir ${outDir}/${name}`, {\n shouldWait: !isWatch,\n focusOnly: type === 'ssr' ? 'server' : 'client',\n env: {\n SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME: name,\n },\n });\n }\n }\n\n /**\n * Preview mode\n */\n if (isWatch) {\n this.runPreviewMode();\n\n return;\n }\n\n if (isUnlockRobots) {\n this.unlockRobots();\n }\n\n createDevMarker(this.isProd, this.viteConfig);\n removeMeta(this.buildDir);\n onFinish?.();\n }\n}\n\nexport default Build;\n"],"names":["Build","isProd","nodeEnv","buildDir","viteConfig","pluginConfig","params","mode","clientOptions","serverOptions","focusOnly","isWatch","isUnlockRobots","isEject","isServerless","isNoWarnings","abortController","runningBuild","hasPreviewModeExitListener","constructor","this","async","resolveConfig","getPluginConfig","path","resolve","root","build","outDir","process","env","NODE_ENV","clearBuildFolder","fs","existsSync","rmSync","recursive","getIsProd","getNodeEnv","getRunningBuildNames","map","name","promisifyProcess","command","isRejectWarnings","promise","Promise","reject","on","code","message","stderr","buff","msg","Buffer","from","toString","includes","stdout","pipe","console","info","chalk","blue","routesParsing","isNodeParsing","serverConfig","ServerConfig","init","clientFile","SsrManifest","get","viteAliases","alias","buildRoutesManifest","cleanupClientRoutes","routeFiles","readMeta","files","Set","Object","values","size","forEach","file","filepath","result","readFileSync","encoding","replace","writeFileSync","e","log","unlockRobots","robotsFile","warn","data","eject","entrypoint","createServerless","buildOptions","shouldWait","modeOpt","buildProcess","childProcess","spawn","signal","stdio","stdin","shell","FORCE_COLOR","SSR_BOOST_IS_SSR","createFocusOnly","isOnlyClient","SSR_BOOST_ACTION","global","viteBoostAction","push","waitLastBuild","latestProcess","at","exitCode","processStop","runPreviewMode","abort","onFinish","buildCount","length","listener","removeListener","createDevMarker","makeConfig","viteResetCache","focus","AbortController","isClient","spawnBuild","isServer","serverFile","buildManifest","isEntrypoint","type","options","cliOptions","SSR_BOOST_CUSTOM_ENTRYPOINT_BUILD_NAME","removeMeta"],"mappings":"kgBAyDA,MAAMA,EAIMC,OAKAC,QAKAC,SAKAC,WAKAC,aAKAC,OAAuB,CAC/BC,KAAM,GACNC,cAAe,GACfC,cAAe,GACfC,UAAW,MACXC,SAAS,EACTC,gBAAgB,EAChBC,SAAS,EACTC,cAAc,EACdC,cAAc,GAMNC,gBAA0C,KAK1CC,aAAgE,GAKhEC,4BAA6B,EAKvCC,YAAmBb,GACjBc,KAAKd,OAAS,IAAKc,KAAKd,UAAWA,EACpC,CAKSe,mBACR,MAAMd,KAAEA,GAASa,KAAKd,OAEtBc,KAAKhB,iBAAmBkB,EAAc,CAAE,EAAE,QAASf,EAAM,cACzDa,KAAKf,aAAekB,EAAgBH,KAAKhB,YACzCgB,KAAKjB,SAAWqB,EAAKC,QAAQL,KAAKhB,WAAWsB,KAAMN,KAAKhB,WAAWuB,MAAMC,QACzER,KAAKlB,QAAU2B,QAAQC,IAAIC,UAAY,aACvCX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YAAa1F,IAOb0H,EAAMI,mBACFrH,KAAKoH,WACT,SACA,GAAG/H,cAA0BmB,kBAAuBR,KAAKf,aAAaqI,aACtE,CACErC,YAAa1F,IAIZA,UACGS,KAAKuH,gBAEP9H,GACFO,KAAK6E,QAGHnF,GACFM,KAAK+E,qBAQX,MAAMD,WAAEA,GAAe9E,KAAKf,aAE5B,GAAI6F,GAAY6B,QAAUM,EAAMO,eAC9B,IAAK,MAAMnG,KAAEA,EAAIoG,KAAEA,EAAIH,WAAEA,EAAUI,QAAEA,EAAU,MAAQ5C,EAAY,CACjE,MAAM6C,EAAaL,GAAuB,QAATG,EAAiB,SAASH,IAAe,SAEpEtH,KAAKoH,WAAW/F,EAAM,GAAGqG,KAAWC,cAAuBnH,KAAUa,IAAQ,CACjF4D,YAAa1F,EACbD,UAAoB,QAATmI,EAAiB,SAAW,SACvC/G,IAAK,CACHkH,uCAAwCvG,IAG7C,CAMC9B,EACFS,KAAKuG,kBAKH/G,GACFQ,KAAKyE,eAGPqC,EAAgB9G,KAAKnB,OAAQmB,KAAKhB,YAClC6I,EAAW7H,KAAKjB,UAChB0H,MACD"}
@@ -1,12 +1,14 @@
1
1
  import { Express } from 'express';
2
2
  import { Logger, ViteDevServer } from 'vite';
3
3
  import { IPluginConfig } from "../helpers/plugin-config.js";
4
+ import { IBuildEntrypoint } from "./build.js";
4
5
  interface IConfigOptions {
5
6
  isProd?: boolean;
6
7
  isHost?: boolean;
7
8
  isOnlyClient?: boolean;
8
9
  isModulePreload?: boolean;
9
10
  mode?: string;
11
+ entrypointName?: string;
10
12
  }
11
13
  interface IConfigParams {
12
14
  root: string;
@@ -36,14 +38,14 @@ declare class ServerConfig {
36
38
  * Add module preload scripts to server output
37
39
  */
38
40
  readonly isModulePreload: boolean;
39
- /**
40
- * SPA mode
41
- */
42
- readonly isSPA: boolean;
43
41
  /**
44
42
  * Env mode
45
43
  */
46
44
  readonly mode: string;
45
+ /**
46
+ * Run specified entrypoint
47
+ */
48
+ protected readonly entrypointName?: string;
47
49
  /**
48
50
  * Vite config - only for development
49
51
  */
@@ -57,9 +59,9 @@ declare class ServerConfig {
57
59
  */
58
60
  protected params: IConfigParams;
59
61
  /**
60
- * Default production params
62
+ * Default params
61
63
  */
62
- protected prodParams: Partial<IConfigParams>;
64
+ protected defaultParams: Partial<IConfigParams>;
63
65
  /**
64
66
  * Vite logger for dev mode or console for production
65
67
  */
@@ -74,7 +76,7 @@ declare class ServerConfig {
74
76
  /**
75
77
  * @constructor
76
78
  */
77
- protected constructor({ isProd, isHost, isOnlyClient, isModulePreload, mode, }: IConfigOptions, prodParams: Partial<IConfigParams>);
79
+ protected constructor({ entrypointName, isProd, isHost, isOnlyClient, isModulePreload, mode, }: IConfigOptions, prodParams: Partial<IConfigParams>);
78
80
  /**
79
81
  * Initialize service
80
82
  */
@@ -127,11 +129,11 @@ declare class ServerConfig {
127
129
  */
128
130
  getApp(): Express | undefined;
129
131
  /**
130
- * return plugin config
132
+ * Return plugin config
131
133
  * NOTE: only on development mode
132
134
  */
133
135
  /**
134
- * return plugin config
136
+ * Return plugin config
135
137
  * NOTE: only on development mode
136
138
  */
137
139
  getPluginConfig(): IPluginConfig | undefined;
@@ -156,5 +158,19 @@ declare class ServerConfig {
156
158
  * Set custom logger
157
159
  */
158
160
  setLogger(logger: Logger): void;
161
+ /**
162
+ * Apply config to specified entrypoint
163
+ */
164
+ /**
165
+ * Apply config to specified entrypoint
166
+ */
167
+ protected applyEntrypointConfig(): void;
168
+ /**
169
+ * Get current entrypoint
170
+ */
171
+ /**
172
+ * Get current entrypoint
173
+ */
174
+ protected getEntrypoint(): IBuildEntrypoint | undefined;
159
175
  }
160
176
  export { ServerConfig as default };
@@ -1,2 +1,2 @@
1
- import i from"node:fs";import t from"node:path";import s from"../helpers/plugin-config.js";import e from"./logger.js";class r{isProd;isHost;isModulePreload;isSPA;mode;vite;app;params;prodParams;logger;defaultBuildRoots=["./build","./dist"];constructor({isProd:i=!1,isHost:t=!1,isOnlyClient:s=!1,isModulePreload:e=!1,mode:r="production"},o){this.isProd=i,this.isHost=t,this.isSPA=s,this.isModulePreload=e,this.mode=r,this.prodParams={publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",port:3e3,...o},this.makeParams()}static init(i={},t={}){return new r(i,t)}getBuildDir(t){for(const s of[t,...this.defaultBuildRoots])if(s&&i.existsSync(s))return s;return t??this.defaultBuildRoots[0]}makeParams(){const i=this.getPluginConfig()??{},{config:s}=this.vite??{},r=s?.root??this.getBuildDir(this.prodParams.root),o=s?.publicDir??this.prodParams.publicDir,a=new URL(import.meta.url),l=i.pluginPath??t.resolve(t.dirname(a.pathname),"../"),h=i.indexFile??this.prodParams.indexFile,d=i.serverFile??this.prodParams.serverFile,n=i.clientFile??this.prodParams.clientFile,p="boolean"==typeof s?.server.host||this.isHost?"0.0.0.0":s?.server.host??this.prodParams.host,g=s?.server.port??(this.isProd?this.prodParams.port:5173);this.params={root:r,publicDir:o,pluginPath:l,indexFile:h,clientFile:n,serverFile:d,host:p,port:g,isSPA:this.isSPA,isProd:this.isProd},this.logger=this.vite?.config.logger??new e}setVite(i){this.vite=i,this.makeParams()}setApp(i){this.app=i}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?s(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}setLogger(i){this.logger=i}}export{r as default};
1
+ import t from"node:fs";import i from"node:path";import e from"../helpers/plugin-config.js";import r from"./logger.js";class s{isProd;isHost;isModulePreload;mode;entrypointName;vite;app;params;defaultParams;logger;defaultBuildRoots=["./build","./dist"];constructor({entrypointName:t,isProd:i=!1,isHost:e=!1,isOnlyClient:r=!1,isModulePreload:s=!1,mode:o="production"},n){this.isProd=i,this.isHost=e,this.isModulePreload=s,this.mode=o,this.entrypointName=t,this.defaultParams={publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",isSPA:r,...n},this.makeParams()}static init(t={},i={}){return new s(t,i)}getBuildDir(i){for(const e of[i,...this.defaultBuildRoots])if(e&&t.existsSync(e))return e;return i??this.defaultBuildRoots[0]}makeParams(){this.applyEntrypointConfig();const t=this.getPluginConfig()??{},{config:e}=this.vite??{},{root:s,publicDir:o,indexFile:n,clientFile:l,serverFile:a,host:p,isSPA:h}=this.defaultParams,g=new URL(import.meta.url),d=t.pluginPath??i.resolve(i.dirname(g.pathname),"../"),u=this.getEntrypoint(),m="boolean"==typeof e?.server.host||this.isHost?"0.0.0.0":e?.server.host??p,f=Number(e?.env.VITE_PORT??e?.server.port??this.defaultParams.port);this.params={root:e?.root??this.getBuildDir(s),publicDir:e?.publicDir??o,indexFile:t.indexFile??n,clientFile:t.clientFile??l,serverFile:t.serverFile??a,pluginPath:d,host:m,port:f,isSPA:u?"spa"===u.type:h,isProd:this.isProd},this.logger=this.vite?.config.logger??new r}setVite(t){this.vite=t,this.makeParams()}setApp(t){this.app=t}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?e(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}setLogger(t){this.logger=t}applyEntrypointConfig(){const t=this.getPluginConfig();if(!this.vite||!t||!this.entrypointName)return;const i=this.getEntrypoint();i&&["indexFile","clientFile","serverFile"].forEach((e=>{i[e]&&(t[e]=i[e])}))}getEntrypoint(){const t=this.vite?e(this.vite.config):void 0;return t?.entrypoint.find((({name:t})=>t===this.entrypointName))}}export{s as default};
2
2
  //# sourceMappingURL=server-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n isModulePreload?: boolean;\n mode?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n clientFile: string;\n serverFile: string;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * Add module preload scripts to server output\n */\n public readonly isModulePreload: boolean;\n\n /**\n * SPA mode\n */\n public readonly isSPA: boolean;\n\n /**\n * Env mode\n */\n public readonly mode: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default production params\n */\n protected prodParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * Default root dir\n */\n protected defaultBuildRoots = ['./build', './dist'];\n\n /**\n * @constructor\n */\n protected constructor(\n {\n isProd = false,\n isHost = false,\n isOnlyClient = false,\n isModulePreload = false,\n mode = 'production',\n }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.isModulePreload = isModulePreload;\n this.mode = mode;\n this.prodParams = {\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n port: 3000,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Lookup build folder\n */\n protected getBuildDir(root?: string): string {\n for (const dir of [root, ...this.defaultBuildRoots]) {\n if (dir && fs.existsSync(dir)) {\n return dir;\n }\n }\n\n return root ?? this.defaultBuildRoots[0];\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n\n const root = config?.root ?? this.getBuildDir(this.prodParams.root);\n const publicDir = config?.publicDir ?? this.prodParams.publicDir!;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(path.dirname(dirInfo.pathname), '../');\n const indexFile = pluginConfig.indexFile ?? this.prodParams.indexFile!;\n const serverFile = pluginConfig.serverFile ?? this.prodParams.serverFile!;\n const clientFile = pluginConfig.clientFile ?? this.prodParams.clientFile!;\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? this.prodParams.host!;\n const port = config?.server.port ?? (this.isProd ? this.prodParams.port! : 5173);\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n clientFile,\n serverFile,\n host,\n port,\n isSPA: this.isSPA,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Set custom logger\n */\n public setLogger(logger: Logger): void {\n this.logger = logger;\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isModulePreload","isSPA","mode","vite","app","params","prodParams","logger","defaultBuildRoots","constructor","isOnlyClient","this","publicDir","indexFile","serverFile","host","port","makeParams","static","options","prodOptions","getBuildDir","root","dir","fs","existsSync","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","clientFile","server","DefaultLogger","setVite","setApp","express","getVite","getApp","undefined","getParams","getLogger","setLogger"],"mappings":"sHAgCA,MAAMA,EAIYC,OAKAC,OAKAC,gBAKAC,MAKAC,KAKNC,KAKAC,IAKAC,OAKAC,WAKAC,OAKAC,kBAAoB,CAAC,UAAW,UAK1CC,aACEX,OACEA,GAAS,EAAKC,OACdA,GAAS,EAAKW,aACdA,GAAe,EAAKV,gBACpBA,GAAkB,EAAKE,KACvBA,EAAO,cAETI,GAEAK,KAAKb,OAASA,EACda,KAAKZ,OAASA,EACdY,KAAKV,MAAQS,EACbC,KAAKX,gBAAkBA,EACvBW,KAAKT,KAAOA,EACZS,KAAKL,WAAa,CAChBM,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,KAAM,OACHV,GAGLK,KAAKM,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAIvB,EAAasB,EAASC,EAClC,CAKSC,YAAYC,GACpB,IAAK,MAAMC,IAAO,CAACD,KAASX,KAAKH,mBAC/B,GAAIe,GAAOC,EAAGC,WAAWF,GACvB,OAAOA,EAIX,OAAOD,GAAQX,KAAKH,kBAAkB,EACvC,CAKSS,aACR,MAAMS,EAAgBf,KAAKgB,mBAAqB,CAAE,GAC5CC,OAAEA,GAAWjB,KAAKR,MAAQ,CAAA,EAE1BmB,EAAOM,GAAQN,MAAQX,KAAKU,YAAYV,KAAKL,WAAWgB,MACxDV,EAAYgB,GAAQhB,WAAaD,KAAKL,WAAWM,UACjDiB,EAAU,IAAIC,gBAAgBC,KAC9BC,EACJN,EAAaM,YAAcC,EAAKC,QAAQD,EAAKE,QAAQN,EAAQO,UAAW,OACpEvB,EAAYa,EAAab,WAAaF,KAAKL,WAAWO,UACtDC,EAAaY,EAAaZ,YAAcH,KAAKL,WAAWQ,WACxDuB,EAAaX,EAAaW,YAAc1B,KAAKL,WAAW+B,WACxDtB,EAC2B,kBAAxBa,GAAQU,OAAOvB,MAAsBJ,KAAKZ,OAC7C,UACA6B,GAAQU,OAAOvB,MAAQJ,KAAKL,WAAWS,KACvCC,EAAOY,GAAQU,OAAOtB,OAASL,KAAKb,OAASa,KAAKL,WAAWU,KAAQ,MAE3EL,KAAKN,OAAS,CACZiB,OACAV,YACAoB,aACAnB,YACAwB,aACAvB,aACAC,OACAC,OACAf,MAAOU,KAAKV,MACZH,OAAQa,KAAKb,QAEfa,KAAKJ,OAASI,KAAKR,MAAMyB,OAAOrB,QAAU,IAAIgC,CAC/C,CAKMC,QAAQrC,GACbQ,KAAKR,KAAOA,EAEZQ,KAAKM,YACN,CAKMwB,OAAOC,GACZ/B,KAAKP,IAAMsC,CACZ,CAMMC,UACL,OAAOhC,KAAKR,IACb,CAKMyC,SACL,OAAOjC,KAAKP,GACb,CAMMuB,kBACL,OAAOhB,KAAKR,KAAOwB,EAAgBhB,KAAKR,KAAKyB,aAAUiB,CACxD,CAKMC,YACL,OAAOnC,KAAKN,MACb,CAKM0C,YACL,OAAOpC,KAAKJ,MACb,CAKMyC,UAAUzC,GACfI,KAAKJ,OAASA,CACf"}
1
+ {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport type { IBuildEntrypoint } from '@services/build';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n isModulePreload?: boolean;\n mode?: string;\n entrypointName?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n clientFile: string;\n serverFile: string;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * Add module preload scripts to server output\n */\n public readonly isModulePreload: boolean;\n\n /**\n * Env mode\n */\n public readonly mode: string;\n\n /**\n * Run specified entrypoint\n */\n protected readonly entrypointName?: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default params\n */\n protected defaultParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * Default root dir\n */\n protected defaultBuildRoots = ['./build', './dist'];\n\n /**\n * @constructor\n */\n protected constructor(\n {\n entrypointName,\n isProd = false,\n isHost = false,\n isOnlyClient = false,\n isModulePreload = false,\n mode = 'production',\n }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isModulePreload = isModulePreload;\n this.mode = mode;\n this.entrypointName = entrypointName;\n this.defaultParams = {\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n isSPA: isOnlyClient,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Lookup build folder\n */\n protected getBuildDir(root?: string): string {\n for (const dir of [root, ...this.defaultBuildRoots]) {\n if (dir && fs.existsSync(dir)) {\n return dir;\n }\n }\n\n return root ?? this.defaultBuildRoots[0];\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n this.applyEntrypointConfig();\n\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n const {\n root,\n publicDir,\n indexFile,\n clientFile,\n serverFile,\n host: defaultHost,\n isSPA,\n } = this.defaultParams;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(path.dirname(dirInfo.pathname), '../');\n const entrypoint = this.getEntrypoint();\n\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? defaultHost!;\n const port = Number(config?.env.VITE_PORT ?? config?.server.port ?? this.defaultParams.port!);\n\n this.params = {\n root: config?.root ?? this.getBuildDir(root),\n publicDir: config?.publicDir ?? publicDir!,\n indexFile: pluginConfig.indexFile ?? indexFile!,\n clientFile: pluginConfig.clientFile ?? clientFile!,\n serverFile: pluginConfig.serverFile ?? serverFile!,\n pluginPath,\n host,\n port,\n isSPA: entrypoint ? entrypoint.type === 'spa' : isSPA!,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * Return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Set custom logger\n */\n public setLogger(logger: Logger): void {\n this.logger = logger;\n }\n\n /**\n * Apply config to specified entrypoint\n */\n protected applyEntrypointConfig(): void {\n const config = this.getPluginConfig();\n\n if (!this.vite || !config || !this.entrypointName) {\n return;\n }\n\n const entrypointConfig = this.getEntrypoint();\n\n // apply specified entrypoint config\n if (entrypointConfig) {\n (['indexFile', 'clientFile', 'serverFile'] as const).forEach((optName) => {\n if (entrypointConfig[optName]) {\n config[optName] = entrypointConfig[optName]!;\n }\n });\n }\n }\n\n /**\n * Get current entrypoint\n */\n protected getEntrypoint(): IBuildEntrypoint | undefined {\n const config = this.vite ? getPluginConfig(this.vite.config) : undefined;\n\n return config?.entrypoint.find(({ name }) => name === this.entrypointName);\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isModulePreload","mode","entrypointName","vite","app","params","defaultParams","logger","defaultBuildRoots","constructor","isOnlyClient","prodParams","this","publicDir","indexFile","serverFile","host","isSPA","makeParams","static","options","prodOptions","getBuildDir","root","dir","fs","existsSync","applyEntrypointConfig","pluginConfig","getPluginConfig","config","clientFile","defaultHost","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","entrypoint","getEntrypoint","server","port","Number","env","VITE_PORT","type","DefaultLogger","setVite","setApp","express","getVite","getApp","undefined","getParams","getLogger","setLogger","entrypointConfig","forEach","optName","find","name"],"mappings":"sHAkCA,MAAMA,EAIYC,OAKAC,OAKAC,gBAKAC,KAKGC,eAKTC,KAKAC,IAKAC,OAKAC,cAKAC,OAKAC,kBAAoB,CAAC,UAAW,UAK1CC,aACEP,eACEA,EAAcJ,OACdA,GAAS,EAAKC,OACdA,GAAS,EAAKW,aACdA,GAAe,EAAKV,gBACpBA,GAAkB,EAAKC,KACvBA,EAAO,cAETU,GAEAC,KAAKd,OAASA,EACdc,KAAKb,OAASA,EACda,KAAKZ,gBAAkBA,EACvBY,KAAKX,KAAOA,EACZW,KAAKV,eAAiBA,EACtBU,KAAKN,cAAgB,CACnBO,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,MAAOP,KACJC,GAGLC,KAAKM,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAIxB,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