@lomray/vite-ssr-boost 1.0.0-beta.4 → 1.0.0-beta.5
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 +2 -1
- package/cli/build.js +1 -1
- package/cli/build.js.map +1 -1
- package/cli/run-dev.d.ts +2 -1
- package/cli/run-dev.js +1 -1
- package/cli/run-dev.js.map +1 -1
- package/cli/run-prod.d.ts +2 -1
- package/cli/run-prod.js +1 -1
- package/cli/run-prod.js.map +1 -1
- package/cli.js +1 -1
- package/cli.js.map +1 -1
- package/helpers/print-server-info.js +1 -1
- package/helpers/print-server-info.js.map +1 -1
- package/node/server.js +1 -1
- package/node/server.js.map +1 -1
- package/package.json +1 -1
- package/plugin.d.ts +3 -3
- package/plugin.js.map +1 -1
- package/services/server-config.d.ts +6 -1
- package/services/server-config.js +1 -1
- package/services/server-config.js.map +1 -1
package/cli/build.d.ts
CHANGED
|
@@ -3,9 +3,10 @@ interface IBuildParams {
|
|
|
3
3
|
isWatch?: boolean;
|
|
4
4
|
clientOptions?: string;
|
|
5
5
|
serverOptions?: string;
|
|
6
|
+
mode?: string;
|
|
6
7
|
}
|
|
7
8
|
/**
|
|
8
9
|
* Build production application
|
|
9
10
|
*/
|
|
10
|
-
declare function build({ isOnlyClient, isWatch, clientOptions, serverOptions, }: IBuildParams): Promise<void | [unknown, unknown]>;
|
|
11
|
+
declare function build({ isOnlyClient, isWatch, clientOptions, serverOptions, mode, }: IBuildParams): Promise<void | [unknown, unknown]>;
|
|
11
12
|
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{resolveConfig as r}from"vite";import t from"../constants/cli-name.js";import n from"../helpers/plugin-config.js";const s=e=>new Promise(((o,i)=>{e.on("exit",(e=>{o(e)})),e.on("close",(e=>{o(e)})),e.on("error",(e=>{i(e)}))}));async function l({isOnlyClient:l=!1,isWatch:a=!1,clientOptions:c="",serverOptions:p=""}){const
|
|
1
|
+
import e from"node:child_process";import{performance as o}from"node:perf_hooks";import i from"chalk";import{resolveConfig as r}from"vite";import t from"../constants/cli-name.js";import n from"../helpers/plugin-config.js";const s=e=>new Promise(((o,i)=>{e.on("exit",(e=>{o(e)})),e.on("close",(e=>{o(e)})),e.on("error",(e=>{i(e)}))}));async function l({isOnlyClient:l=!1,isWatch:a=!1,clientOptions:c="",serverOptions:p="",mode:m=""}){const d=o.now(),u=await r({},"build"),$=n(u),{outDir:f}=u.build,h=["client"],S=new AbortController,v=m?`--mode ${m}`:"",w=s(e.spawn(`vite build ${c} --emptyOutDir --outDir ${f}/client ${v}`,{signal:S.signal,stdio:"inherit",shell:!0,env:{...process.env,SSR_BOOST_IS_SSR:l?"0":"1"}}));let b;if(a||await w,l||(b=s(e.spawn(`vite build ${p} --emptyOutDir --outDir ${f}/server --ssr ${$.serverFile} ${v}`,{signal:S.signal,stdio:"inherit",shell:!0,env:{...process.env,SSR_BOOST_IS_SSR:l?"0":"1"}})),a||await b,h.push("server")),a){process.on("exit",(()=>{S.abort()}));const e=Promise.all([w,b]);return e.controller=S,e}const O=i.dim(`${i.yellowBright(h.join(","))} built in ${i.reset(i.bold(Math.ceil(o.now()-d)))} ms`);console.info(`\n ${i.green(`${i.bold(t.toUpperCase())}`)} ${O}\n`)}export{l 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 { resolveConfig } from 'vite';\nimport cliName from '@constants/cli-name';\nimport getPluginConfig from '@helpers/plugin-config';\n\ninterface IBuildParams {\n isOnlyClient?: boolean;\n isWatch?: boolean;\n clientOptions?: string;\n serverOptions?: string;\n}\n\n/**\n * Promisify spawn process\n */\nconst promisify = (command: childProcess.ChildProcess) =>\n new Promise((resolve, reject) => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code) => {\n resolve(code);\n });\n\n command.on('error', (message) => {\n reject(message);\n });\n });\n\n/**\n * Build production application\n */\nasync function build({\n isOnlyClient = false,\n isWatch = false,\n clientOptions = '',\n serverOptions = '',\n}: IBuildParams): Promise<void | [unknown, unknown]> {\n const perfStart = performance.now();\n const config = await resolveConfig({}, 'build');\n const pluginConfig = getPluginConfig(config);\n const { outDir } = config.build;\n const types = ['client'];\n const controller = new AbortController();\n\n // build client\n const clientProcess = promisify(\n childProcess.spawn(`vite build ${clientOptions} --emptyOutDir --outDir ${outDir}/client
|
|
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 { resolveConfig } from 'vite';\nimport cliName from '@constants/cli-name';\nimport getPluginConfig from '@helpers/plugin-config';\n\ninterface IBuildParams {\n isOnlyClient?: boolean;\n isWatch?: boolean;\n clientOptions?: string;\n serverOptions?: string;\n mode?: string;\n}\n\n/**\n * Promisify spawn process\n */\nconst promisify = (command: childProcess.ChildProcess) =>\n new Promise((resolve, reject) => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code) => {\n resolve(code);\n });\n\n command.on('error', (message) => {\n reject(message);\n });\n });\n\n/**\n * Build production application\n */\nasync function build({\n isOnlyClient = false,\n isWatch = false,\n clientOptions = '',\n serverOptions = '',\n mode = '',\n}: IBuildParams): Promise<void | [unknown, unknown]> {\n const perfStart = performance.now();\n const config = await resolveConfig({}, 'build');\n const pluginConfig = getPluginConfig(config);\n const { outDir } = config.build;\n const types = ['client'];\n const controller = new AbortController();\n const modeOpt = mode ? `--mode ${mode}` : '';\n\n // build client\n const clientProcess = promisify(\n childProcess.spawn(\n `vite build ${clientOptions} --emptyOutDir --outDir ${outDir}/client ${modeOpt}`,\n {\n signal: controller.signal,\n stdio: 'inherit',\n shell: true,\n env: {\n ...process.env,\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n },\n },\n ),\n );\n\n if (!isWatch) {\n await clientProcess;\n }\n\n let serverProcess;\n\n if (!isOnlyClient) {\n // build server\n serverProcess = promisify(\n childProcess.spawn(\n `vite build ${serverOptions} --emptyOutDir --outDir ${outDir}/server --ssr ${pluginConfig.serverFile} ${modeOpt}`,\n {\n signal: controller.signal,\n stdio: 'inherit',\n shell: true,\n env: {\n ...process.env,\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n },\n },\n ),\n );\n\n if (!isWatch) {\n await serverProcess;\n }\n\n types.push('server');\n }\n\n if (isWatch) {\n process.on('exit', () => {\n controller.abort();\n });\n\n const buildPromise = Promise.all([clientProcess, serverProcess]);\n\n buildPromise['controller'] = controller;\n\n return buildPromise;\n }\n\n const buildDurationString = chalk.dim(\n `${chalk.yellowBright(types.join(','))} built in ${chalk.reset(\n chalk.bold(Math.ceil(performance.now() - perfStart)),\n )} ms`,\n );\n\n console.info(\n `\\n ${chalk.green(`${chalk.bold(cliName.toUpperCase())}`)} ${buildDurationString}\\n`,\n );\n}\n\nexport default build;\n"],"names":["promisify","command","Promise","resolve","reject","on","code","message","async","build","isOnlyClient","isWatch","clientOptions","serverOptions","mode","perfStart","performance","now","config","resolveConfig","pluginConfig","getPluginConfig","outDir","types","controller","AbortController","modeOpt","clientProcess","childProcess","spawn","signal","stdio","shell","env","process","SSR_BOOST_IS_SSR","serverProcess","serverFile","push","abort","buildPromise","all","buildDurationString","chalk","dim","yellowBright","join","reset","bold","Math","ceil","console","info","green","cliName","toUpperCase"],"mappings":"6NAkBA,MAAMA,EAAaC,GACjB,IAAIC,SAAQ,CAACC,EAASC,KACpBH,EAAQI,GAAG,QAASC,IAClBH,EAAQG,EAAK,IAGfL,EAAQI,GAAG,SAAUC,IACnBH,EAAQG,EAAK,IAGfL,EAAQI,GAAG,SAAUE,IACnBH,EAAOG,EAAQ,GACf,IAMNC,eAAeC,GAAMC,aACnBA,GAAe,EAAKC,QACpBA,GAAU,EAAKC,cACfA,EAAgB,GAAEC,cAClBA,EAAgB,GAAEC,KAClBA,EAAO,KAEP,MAAMC,EAAYC,EAAYC,MACxBC,QAAeC,EAAc,CAAE,EAAE,SACjCC,EAAeC,EAAgBH,IAC/BI,OAAEA,GAAWJ,EAAOT,MACpBc,EAAQ,CAAC,UACTC,EAAa,IAAIC,gBACjBC,EAAUZ,EAAO,UAAUA,IAAS,GAGpCa,EAAgB3B,EACpB4B,EAAaC,MACX,cAAcjB,4BAAwCU,YAAiBI,IACvE,CACEI,OAAQN,EAAWM,OACnBC,MAAO,UACPC,OAAO,EACPC,IAAK,IACAC,QAAQD,IACXE,iBAAkBzB,EAAe,IAAM,QAU/C,IAAI0B,EA0BJ,GA9BKzB,SACGgB,EAKHjB,IAEH0B,EAAgBpC,EACd4B,EAAaC,MACX,cAAchB,4BAAwCS,kBAAuBF,EAAaiB,cAAcX,IACxG,CACEI,OAAQN,EAAWM,OACnBC,MAAO,UACPC,OAAO,EACPC,IAAK,IACAC,QAAQD,IACXE,iBAAkBzB,EAAe,IAAM,QAM1CC,SACGyB,EAGRb,EAAMe,KAAK,WAGT3B,EAAS,CACXuB,QAAQ7B,GAAG,QAAQ,KACjBmB,EAAWe,OAAO,IAGpB,MAAMC,EAAetC,QAAQuC,IAAI,CAACd,EAAeS,IAIjD,OAFAI,EAAyB,WAAIhB,EAEtBgB,CACR,CAED,MAAME,EAAsBC,EAAMC,IAChC,GAAGD,EAAME,aAAatB,EAAMuB,KAAK,kBAAkBH,EAAMI,MACvDJ,EAAMK,KAAKC,KAAKC,KAAKlC,EAAYC,MAAQF,WAI7CoC,QAAQC,KACN,OAAOT,EAAMU,MAAM,GAAGV,EAAMK,KAAKM,EAAQC,sBAAsBb,MAEnE"}
|
package/cli/run-dev.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ interface IRunDevParams {
|
|
|
5
5
|
version: string;
|
|
6
6
|
isHost?: boolean;
|
|
7
7
|
isPrintInfo?: boolean;
|
|
8
|
+
mode?: string;
|
|
8
9
|
}
|
|
9
10
|
interface IRunDevOut {
|
|
10
11
|
server: Server;
|
|
@@ -13,5 +14,5 @@ interface IRunDevOut {
|
|
|
13
14
|
/**
|
|
14
15
|
* Run development server
|
|
15
16
|
*/
|
|
16
|
-
declare function runDev({ version, isHost, isPrintInfo }: IRunDevParams): Promise<IRunDevOut>;
|
|
17
|
+
declare function runDev({ version, isHost, isPrintInfo, mode }: IRunDevParams): Promise<IRunDevOut>;
|
|
17
18
|
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
|
|
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};
|
|
2
2
|
//# sourceMappingURL=run-dev.js.map
|
package/cli/run-dev.js.map
CHANGED
|
@@ -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}\n\ninterface IRunDevOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run development server\n */\nasync function runDev({ version, isHost, isPrintInfo }: IRunDevParams): Promise<IRunDevOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init({ isHost });\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","global","viteBoostStartTime","performance","now","config","ServerConfig","init","run","createServer","server"],"mappings":"
|
|
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"}
|
package/cli/run-prod.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ interface IRunProdParams {
|
|
|
7
7
|
isHost?: boolean;
|
|
8
8
|
isPrintInfo?: boolean;
|
|
9
9
|
onlyClient?: boolean;
|
|
10
|
+
mode?: string;
|
|
10
11
|
}
|
|
11
12
|
interface IRunProdOut {
|
|
12
13
|
server: Server;
|
|
@@ -15,5 +16,5 @@ interface IRunProdOut {
|
|
|
15
16
|
/**
|
|
16
17
|
* Run production server
|
|
17
18
|
*/
|
|
18
|
-
declare function runProd({ version, isHost, isPrintInfo, port, onlyClient, }: IRunProdParams): Promise<IRunProdOut>;
|
|
19
|
+
declare function runProd({ version, isHost, isPrintInfo, port, mode, onlyClient, }: IRunProdParams): Promise<IRunProdOut>;
|
|
19
20
|
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
|
|
1
|
+
import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function e({version:e,isHost:n,isPrintInfo:s,port:t,mode:f,onlyClient:m=!1}){global.viteBoostStartTime=o.now();const a=i.init({isHost:n,isProd:!0,isOnlyClient:m,mode:f},{port:t}),{run:l}=await r(a);return{server:l({version:e,isPrintInfo:s}),config:a}}export{e as default};
|
|
2
2
|
//# sourceMappingURL=run-prod.js.map
|
package/cli/run-prod.js.map
CHANGED
|
@@ -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}\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 onlyClient = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init({ isHost, isProd: true, isOnlyClient: onlyClient }
|
|
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}\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 mode,\n onlyClient = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init(\n { isHost, isProd: true, isOnlyClient: onlyClient, mode },\n { port },\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","mode","onlyClient","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","run","createServer","server"],"mappings":"2HAsBAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,KACJA,EAAIC,WACJA,GAAa,IAEbC,OAAOC,mBAAqBC,EAAYC,MAExC,MAAMC,EAASC,EAAaC,KAC1B,CAAEX,SAAQY,QAAQ,EAAMC,aAAcT,EAAYD,QAClD,CAAED,UAEEY,IAAEA,SAAcC,EAAaN,GAEnC,MAAO,CACLO,OAAQF,EAAI,CAAEf,UAASE,gBACvBQ,SAEJ"}
|
package/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as o}from"fs";import
|
|
2
|
+
import{readFileSync as o}from"fs";import e from"chalk";import{Command as n,Option as t}from"commander";import i from"./cli/build.js";import s from"./cli/keyboard-input.js";import r from"./cli/run-dev.js";import a from"./cli/run-prod.js";import d from"./cli/vite-reset-cache.js";import c from"./constants/cli-actions.js";import p from"./constants/cli-context.js";import l from"./constants/cli-name.js";const{description:m,version:v}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),f=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",s).setEncoding("utf8").resume())},u=new n;u.name(l).description(m).version(v).hook("preAction",((o,e)=>{global.viteBoostAction=e.name()}));const O=new t("--host","Ability to access the local instance on other devices under the same network.").default(!1),w=new t("--only-client","Build/run only client side part.").default(!1),y=new t("--port [port]","Server port.").default(3e3),g=new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("");u.command(c.dev).description("Run development server.").addOption(O).addOption(new t("--reset-cache","Clear vite cache before run.").default(!1)).addOption(g).action((async({host:o,resetCache:e,mode:n})=>{e&&await d();const t=async e=>{const{server:t,config:i}=await r({version:v,isHost:o,isPrintInfo:e,mode:n});p.server=t,p.config=i};return p.reboot=t,f(),t()})),u.command(c.build).description("Create production build.").addOption(w).addOption(g).addOption(new t("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new t("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).action((async({onlyClient:o,clientOptions:e,serverOptions:n,mode:t})=>{await i({isOnlyClient:o,clientOptions:e,serverOptions:n,mode:t})})),u.command(c.start).description("Run production server.").addOption(O).addOption(y).addOption(w).addOption(g).action((({host:o,port:e,onlyClient:n,mode:t})=>{const i=async i=>{const{server:s,config:r}=await a({version:v,isHost:o,isPrintInfo:i,port:e,onlyClient:n,mode:t});p.server=s,p.config=r};return p.reboot=i,f(),i()})),u.command(c.preview).description("Build and preview production.").addOption(w).addOption(O).addOption(y).addOption(g).action((async({host:o,port:n,onlyClient:t,mode:s})=>{const r=async i=>{const{server:r,config:d}=await a({version:v,isHost:o,isPrintInfo:i,port:n,onlyClient:t,mode:s});r.on("listening",(()=>{setTimeout((()=>{d.getLogger().info(e.yellow("\n Running preview mode... \n"))}),0)})),p.server=r,p.config=d};p.reboot=r,f();const d=i({mode:s,isWatch:!0,isOnlyClient:t,clientOptions:"-w",serverOptions:"-w"});await Promise.all([r(),d])})),u.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/keyboard-input';\nimport runDev from '@cli/run-dev';\nimport runProd from '@cli/run-prod';\nimport viteResetCache from '@cli/vite-reset-cache';\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);\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 .action(async ({ host, resetCache }) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runDev({ version, isHost: host, isPrintInfo });\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(\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 .action(async ({ onlyClient, clientOptions, serverOptions }) => {\n await runBuild({ isOnlyClient: onlyClient, clientOptions, serverOptions });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .action(({ host, port, onlyClient }) => {\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 });\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 .action(async ({ host, port, onlyClient }) => {\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 });\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 const build = runBuild({\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n });\n\n await Promise.all([command(), build]);\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","command","CliActions","dev","addOption","action","async","host","resetCache","viteResetCache","isPrintInfo","server","config","runDev","isHost","cliContext","reboot","build","
|
|
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/keyboard-input';\nimport runDev from '@cli/run-dev';\nimport runProd from '@cli/run-prod';\nimport viteResetCache from '@cli/vite-reset-cache';\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.').env('VITE_ENV_MODE').default('');\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(envModeOption)\n .action(async ({ host, resetCache, mode }) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runDev({ version, isHost: host, isPrintInfo, mode });\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 .action(async ({ onlyClient, clientOptions, serverOptions, mode }) => {\n await runBuild({ isOnlyClient: onlyClient, clientOptions, serverOptions, mode });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .action(({ host, port, onlyClient, mode }) => {\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 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.preview)\n .description('Build and preview production.')\n .addOption(onlyClientOption)\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(envModeOption)\n .action(async ({ host, port, onlyClient, mode }) => {\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 mode,\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 const build = runBuild({\n mode,\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n });\n\n await Promise.all([command(), build]);\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","command","CliActions","dev","addOption","action","async","host","resetCache","mode","viteResetCache","isPrintInfo","server","config","runDev","isHost","cliContext","reboot","build","onlyClient","clientOptions","serverOptions","runBuild","isOnlyClient","start","port","runProd","preview","setTimeout","getLogger","info","chalk","yellow","isWatch","Promise","all"],"mappings":";iZAiBA,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,aAAaK,IAAI,iBAAiBJ,QAAQ,IAM5FX,EACGgB,QAAQC,EAAWC,KACnBlC,YAAY,2BACZmC,UAAUV,GACVU,UAAU,IAAIT,EAAO,gBAAiB,gCAAgCC,SAAQ,IAC9EQ,UAAUL,GACVM,QAAOC,OAASC,OAAMC,aAAYC,WAC7BD,SACIE,IAGR,MAAMT,EAAUK,MAAOK,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBC,EAAO,CAAE5C,UAAS6C,OAAQR,EAAMI,cAAaF,SAE9EO,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAO5B,OAJAG,EAAWC,OAAShB,EAEpBzB,IAEOyB,GAAS,IAGpBhB,EACGgB,QAAQC,EAAWgB,OACnBjD,YAAY,4BACZmC,UAAUP,GACVO,UAAUL,GACVK,UACC,IAAIT,EACF,oCACA,iFAECK,IAAI,6BACJJ,QAAQ,KAEZQ,UACC,IAAIT,EAAO,oCAAqC,uCAC7CK,IAAI,6BACJJ,QAAQ,KAEZS,QAAOC,OAASa,aAAYC,gBAAeC,gBAAeZ,iBACnDa,EAAS,CAAEC,aAAcJ,EAAYC,gBAAeC,gBAAeZ,QAAO,IAGpFxB,EACGgB,QAAQC,EAAWsB,OACnBvD,YAAY,0BACZmC,UAAUV,GACVU,UAAUN,GACVM,UAAUP,GACVO,UAAUL,GACVM,QAAO,EAAGE,OAAMkB,OAAMN,aAAYV,WACjC,MAAMR,EAAUK,MAAOK,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBa,EAAQ,CACvCxD,UACA6C,OAAQR,EACRI,cACAc,OACAN,aACAV,SAGFO,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAO5B,OAJAG,EAAWC,OAAShB,EAEpBzB,IAEOyB,GAAS,IAGpBhB,EACGgB,QAAQC,EAAWyB,SACnB1D,YAAY,iCACZmC,UAAUP,GACVO,UAAUV,GACVU,UAAUN,GACVM,UAAUL,GACVM,QAAOC,OAASC,OAAMkB,OAAMN,aAAYV,WACvC,MAAMR,EAAUK,MAAOK,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBa,EAAQ,CACvCxD,UACA6C,OAAQR,EACRI,cACAc,OACAN,aACAV,SAGFG,EAAO/B,GAAG,aAAa,KACrB+C,YAAW,KACTf,EAAOgB,YAAYC,KAAKC,EAAMC,OAAO,kCAAkC,GACtE,EAAE,IAGPhB,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAG5BG,EAAWC,OAAShB,EAEpBzB,IAEA,MACM0C,EAAQI,EAAS,CACrBb,OACAwB,SAAS,EACTV,aAAcJ,EACdC,cALmB,KAMnBC,cANmB,aASfa,QAAQC,IAAI,CAAClC,IAAWiB,GAAO,IAGzCjC,EAAQb"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{performance as o}from"node:perf_hooks";import e from"chalk";import r from"../constants/cli-actions.js";import s from"../constants/cli-name.js";import t from"./print-server-urls.js";import n from"./resolve-server-urls.js";async function i(i,a,{version:
|
|
1
|
+
import{performance as o}from"node:perf_hooks";import e from"chalk";import r from"../constants/cli-actions.js";import s from"../constants/cli-name.js";import t from"./print-server-urls.js";import n from"./resolve-server-urls.js";async function i(i,a,{version:m="unknown"}){const{action:l}=a.getPluginConfig()??{},{isProd:d,host:p}=a.getParams(),f=a.getLogger(),c=global.viteBoostStartTime??o.now(),g=e.dim(`ready in ${e.reset(e.bold(Math.ceil(o.now()-c)))} ms`);f.info(`\n ${e.green(`${e.bold(s.toUpperCase())} v${m}${d?e.blue(" PRODUCTION"):""}`)} ${g}\n`,{clear:!f.hasWarned});const h=a.getVite()?.config,v=await n(i,{host:p,isHttps:"boolean"==typeof h?.server.https&&h?.server.https,rawBase:h?.rawBase}),u=h?.mode??a.mode??"unknown";if(f.info(e.dim(e.green(" ➜"))+e.dim(" Mode: ")+e.bold(u)),d)t(v,(o=>f.info(o)));else{const o=a.getVite();o.resolvedUrls=v,o.printUrls()}l===r.dev&&f.info(e.dim(e.green(" ➜"))+e.dim(" press ")+e.bold("h")+e.dim(" to show help"))}export{i 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 type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport CliActions from '@constants/cli-actions';\nimport cliName from '@constants/cli-name';\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}\n\n/**\n * Print server info\n */\nasync function printServerInfo(\n server: Server,\n config: ServerConfig,\n { version = 'unknown' }: IPrintServerInfoParams,\n): Promise<void> {\n const { action } = config.getPluginConfig() ?? {};\n const { isProd, host } = config.getParams();\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}${isProd ? chalk.blue(' PRODUCTION') : ''}`,\n )} ${startupDurationString}\\n`,\n { clear: !Logger.hasWarned },\n );\n\n const viteConfig = config.getVite()?.config;\n const resolvedUrls = await resolveServerUrls(server, {\n host,\n isHttps: typeof viteConfig?.server.https === 'boolean' ? viteConfig?.server.https : false,\n rawBase: viteConfig?.['rawBase'],\n });\n\n if (!isProd) {\n const vite = config.getVite()!;\n\n vite.resolvedUrls = resolvedUrls;\n vite.printUrls();\n } else {\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","server","config","version","action","getPluginConfig","isProd","host","getParams","Logger","getLogger","perfStart","global","viteBoostStartTime","performance","now","startupDurationString","chalk","dim","reset","bold","Math","ceil","info","green","cliName","toUpperCase","blue","clear","hasWarned","viteConfig","getVite","resolvedUrls","resolveServerUrls","isHttps","https","rawBase","printServerUrls","msg","vite","printUrls","CliActions","dev"],"mappings":"oOAgBAA,eAAeC,EACbC,EACAC,GACAC,QAAEA,EAAU,YAEZ,MAAMC,OAAEA,GAAWF,EAAOG,mBAAqB,CAAA,GACzCC,OAAEA,EAAMC,KAAEA,GAASL,EAAOM,YAE1BC,EAASP,EAAOQ,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,mBAAmBvB,IAAUG,EAASW,EAAMU,KAAK,eAAiB,UACpFX,MACN,CAAEY,OAAQnB,EAAOoB,YAGnB,MAAMC,EAAa5B,EAAO6B,WAAW7B,OAC/B8B,QAAqBC,EAAkBhC,EAAQ,CACnDM,OACA2B,QAA6C,kBAA7BJ,GAAY7B,OAAOkC,OAAsBL,GAAY7B,OAAOkC,MAC5EC,QAASN,GAAsB,
|
|
1
|
+
{"version":3,"file":"print-server-info.js","sources":["../../src/helpers/print-server-info.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport CliActions from '@constants/cli-actions';\nimport cliName from '@constants/cli-name';\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}\n\n/**\n * Print server info\n */\nasync function printServerInfo(\n server: Server,\n config: ServerConfig,\n { version = 'unknown' }: IPrintServerInfoParams,\n): Promise<void> {\n const { action } = config.getPluginConfig() ?? {};\n const { isProd, host } = config.getParams();\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}${isProd ? chalk.blue(' PRODUCTION') : ''}`,\n )} ${startupDurationString}\\n`,\n { clear: !Logger.hasWarned },\n );\n\n const viteConfig = config.getVite()?.config;\n const resolvedUrls = await resolveServerUrls(server, {\n host,\n isHttps: typeof viteConfig?.server.https === 'boolean' ? viteConfig?.server.https : false,\n rawBase: viteConfig?.['rawBase'],\n });\n const mode = viteConfig?.mode ?? config.mode ?? 'unknown';\n\n Logger.info(chalk.dim(chalk.green(' ➜')) + chalk.dim(' Mode: ') + chalk.bold(mode));\n\n if (!isProd) {\n const vite = config.getVite()!;\n\n vite.resolvedUrls = resolvedUrls;\n vite.printUrls();\n } else {\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","server","config","version","action","getPluginConfig","isProd","host","getParams","Logger","getLogger","perfStart","global","viteBoostStartTime","performance","now","startupDurationString","chalk","dim","reset","bold","Math","ceil","info","green","cliName","toUpperCase","blue","clear","hasWarned","viteConfig","getVite","resolvedUrls","resolveServerUrls","isHttps","https","rawBase","mode","printServerUrls","msg","vite","printUrls","CliActions","dev"],"mappings":"oOAgBAA,eAAeC,EACbC,EACAC,GACAC,QAAEA,EAAU,YAEZ,MAAMC,OAAEA,GAAWF,EAAOG,mBAAqB,CAAA,GACzCC,OAAEA,EAAMC,KAAEA,GAASL,EAAOM,YAE1BC,EAASP,EAAOQ,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,mBAAmBvB,IAAUG,EAASW,EAAMU,KAAK,eAAiB,UACpFX,MACN,CAAEY,OAAQnB,EAAOoB,YAGnB,MAAMC,EAAa5B,EAAO6B,WAAW7B,OAC/B8B,QAAqBC,EAAkBhC,EAAQ,CACnDM,OACA2B,QAA6C,kBAA7BJ,GAAY7B,OAAOkC,OAAsBL,GAAY7B,OAAOkC,MAC5EC,QAASN,GAAsB,UAE3BO,EAAOP,GAAYO,MAAQnC,EAAOmC,MAAQ,UAIhD,GAFA5B,EAAOc,KAAKN,EAAMC,IAAID,EAAMO,MAAM,QAAUP,EAAMC,IAAI,eAAiBD,EAAMG,KAAKiB,IAE7E/B,EAMHgC,EAAgBN,GAAeO,GAAQ9B,EAAOc,KAAKgB,SANxC,CACX,MAAMC,EAAOtC,EAAO6B,UAEpBS,EAAKR,aAAeA,EACpBQ,EAAKC,WACN,CAIGrC,IAAWsC,EAAWC,KACxBlC,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"path";import r from"compression";import o from"express";import t from"../helpers/print-server-info.js";import s from"../services/prepare-server.js";async function n(n){const i=o();if(n.setApp(i),n.isProd){const{root:t,publicDir:s,isSPA:a}=n.getParams();i.use(r()),a||i.use(((e,r,o)=>{"/index.html"===e.url&&(e.url="/index-not-found.html"),o()})),i.use(o.static(e.resolve(`${t}/${s}`),{index:!!a&&void 0}))}else{const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom"});i.use(e.middlewares),n.setVite(e)}const a=s.init(n);return n.isSPA?i.use("*",((e,r,o)=>{(async()=>{try{const o=(await a.loadHtml(e)).join("");r.send(o)}catch(e){o(e)}})()})):(await a.onAppCreated(),i.use("*",((e,r,o)=>{(async()=>{try{const[{render:o,onRequest:t,onRouterReady:s,onShellReady:i,onResponse:p,onShellError:l,onError:
|
|
1
|
+
import e from"path";import r from"compression";import o from"express";import t from"../helpers/print-server-info.js";import s from"../services/prepare-server.js";async function n(n){const i=o();if(n.setApp(i),n.isProd){const{root:t,publicDir:s,isSPA:a}=n.getParams();i.use(r()),a||i.use(((e,r,o)=>{"/index.html"===e.url&&(e.url="/index-not-found.html"),o()})),i.use(o.static(e.resolve(`${t}/${s}`),{index:!!a&&void 0}))}else{const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:n.mode});i.use(e.middlewares),n.setVite(e)}const a=s.init(n);return n.isSPA?i.use("*",((e,r,o)=>{(async()=>{try{const o=(await a.loadHtml(e)).join("");r.send(o)}catch(e){o(e)}})()})):(await a.onAppCreated(),i.use("*",((e,r,o)=>{(async()=>{try{const[{render:o,onRequest:t,onRouterReady:s,onShellReady:i,onResponse:p,onShellError:l,onError:d,getState:m},c]=await Promise.all([a.loadEntrypoint(),a.loadHtml(e)]),{appProps:u}=await(t?.(e,r))??{},[h,f]=c,v={req:e,res:r,appProps:u??{},html:{header:h,footer:f}};await o(n,v,{onRouterReady:s,onShellReady:i,onShellError:l,onResponse:p,onError:d,getState:m})}catch(e){o(e)}})()}))),{run:({version:e,isPrintInfo:r=!0}={})=>{const{port:o,host:s}=n.getParams();n.isHost&&!n.isProd&&(n.getVite().config.server.host=s);const a=i.listen(o,s,(()=>{r&&t(a,n,{version:e})}));return a}}}export{n as default};
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
package/node/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express();\n\n config.setApp(app);\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 });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n } else {\n const { root, publicDir, isSPA } = config.getParams();\n\n app.use(compression());\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, res, next) => {\n if (req.url === '/index.html') {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n app.use(\n express.static(path.resolve(`${root}/${publicDir}`), {\n index: isSPA ? undefined : false,\n }),\n );\n }\n\n const prepareServer = PrepareServer.init(config);\n\n // SSR mode\n if (!config.isSPA) {\n await prepareServer.onAppCreated();\n\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [\n {\n render,\n onRequest,\n onRouterReady,\n onShellReady,\n onResponse,\n onShellError,\n onError,\n getState,\n },\n clientHtml,\n ] = await Promise.all([prepareServer.loadEntrypoint(), prepareServer.loadHtml(req)]);\n const { appProps } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, {\n onRouterReady,\n onShellReady,\n onShellError,\n onResponse,\n onError,\n getState,\n });\n } catch (e) {\n next(e);\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 next(e);\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\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 = app.listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(server, config, { version });\n });\n\n return server;\n },\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","setApp","isProd","root","publicDir","isSPA","getParams","use","compression","req","res","next","url","static","path","resolve","index","undefined","vite","import","server","middlewareMode","watch","usePolling","interval","appType","middlewares","setVite","prepareServer","PrepareServer","init","html","loadHtml","join","send","e","onAppCreated","render","onRequest","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","clientHtml","Promise","all","loadEntrypoint","appProps","header","footer","context","run","version","isPrintInfo","port","host","isHost","getVite","listen","printServerInfo"],"mappings":"kKAgBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAIZ,GAFAF,EAAOG,OAAOF,GAETD,EAAOI,
|
|
1
|
+
{"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express();\n\n config.setApp(app);\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 } else {\n const { root, publicDir, isSPA } = config.getParams();\n\n app.use(compression());\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, res, next) => {\n if (req.url === '/index.html') {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n app.use(\n express.static(path.resolve(`${root}/${publicDir}`), {\n index: isSPA ? undefined : false,\n }),\n );\n }\n\n const prepareServer = PrepareServer.init(config);\n\n // SSR mode\n if (!config.isSPA) {\n await prepareServer.onAppCreated();\n\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [\n {\n render,\n onRequest,\n onRouterReady,\n onShellReady,\n onResponse,\n onShellError,\n onError,\n getState,\n },\n clientHtml,\n ] = await Promise.all([prepareServer.loadEntrypoint(), prepareServer.loadHtml(req)]);\n const { appProps } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, {\n onRouterReady,\n onShellReady,\n onShellError,\n onResponse,\n onError,\n getState,\n });\n } catch (e) {\n next(e);\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 next(e);\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\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 = app.listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(server, config, { version });\n });\n\n return server;\n },\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","setApp","isProd","root","publicDir","isSPA","getParams","use","compression","req","res","next","url","static","path","resolve","index","undefined","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","middlewares","setVite","prepareServer","PrepareServer","init","html","loadHtml","join","send","e","onAppCreated","render","onRequest","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","clientHtml","Promise","all","loadEntrypoint","appProps","header","footer","context","run","version","isPrintInfo","port","host","isHost","getVite","listen","printServerInfo"],"mappings":"kKAgBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAIZ,GAFAF,EAAOG,OAAOF,GAETD,EAAOI,OAwBL,CACL,MAAMC,KAAEA,EAAIC,UAAEA,EAASC,MAAEA,GAAUP,EAAOQ,YAE1CP,EAAIQ,IAAIC,KAEHH,GAEHN,EAAIQ,KAAI,CAACE,EAAKC,EAAKC,KACD,gBAAZF,EAAIG,MACNH,EAAIG,IAAM,yBAGZD,GAAM,IAIVZ,EAAIQ,IACFP,EAAQa,OAAOC,EAAKC,QAAQ,GAAGZ,KAAQC,KAAc,CACnDY,QAAOX,QAAQY,IAGpB,KA7CmB,CAIlB,MAAMC,cACEC,OAAO,SACbtB,aAAa,CACbuB,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAM5B,EAAO4B,OAIf3B,EAAIQ,IAAIW,EAAKS,aAEb7B,EAAO8B,QAAQV,EAChB,CAuBD,MAAMW,EAAgBC,EAAcC,KAAKjC,GA4DzC,OAzDKA,EAAOO,MA4CVN,EAAIQ,IAAI,KAAK,CAACE,EAAKC,EAAKC,KACjB,WACH,IACE,MAAMqB,SAAcH,EAAcI,SAASxB,IAAMyB,KAAK,IAEtDxB,EAAIyB,KAAKH,EACV,CAAC,MAAOI,GACPzB,EAAKyB,EACN,CACF,EARI,EAQD,WApDAP,EAAcQ,eAEpBtC,EAAIQ,IAAI,KAAK,CAACE,EAAKC,EAAKC,KACjB,WACH,IACE,OACE2B,OACEA,EAAMC,UACNA,EAASC,cACTA,EAAaC,aACbA,EAAYC,WACZA,EAAUC,aACVA,EAAYC,QACZA,EAAOC,SACPA,GAEFC,SACQC,QAAQC,IAAI,CAACnB,EAAcoB,iBAAkBpB,EAAcI,SAASxB,MACxEyC,SAAEA,SAAoBX,IAAY9B,EAAKC,KAAS,IAC/CyC,EAAQC,GAAUN,EAEnBO,EAA2B,CAC/B5C,MACAC,MACAwC,SAAUA,GAAY,CAAE,EACxBlB,KAAM,CAAEmB,SAAQC,iBAGZd,EAAOxC,EAAQuD,EAAS,CAC5Bb,gBACAC,eACAE,eACAD,aACAE,UACAC,YAEH,CAAC,MAAOT,GACPzB,EAAKyB,EACN,CACF,EApCI,EAoCD,KAiBD,CACLkB,IAAK,EAAGC,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAAS5D,EAAOQ,YAG1BR,EAAO6D,SAAW7D,EAAOI,SAC3BJ,EAAO8D,UAAW9D,OAAOsB,OAAOsC,KAAOA,GAGzC,MAAMtC,EAASrB,EAAI8D,OAAOJ,EAAMC,GAAM,KAC/BF,GAIAM,EAAgB1C,EAAQtB,EAAQ,CAAEyD,WAAU,IAGnD,OAAOnC,CAAM,EAGnB"}
|
package/package.json
CHANGED
package/plugin.d.ts
CHANGED
|
@@ -15,8 +15,8 @@ interface IPluginOptions {
|
|
|
15
15
|
}[];
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* Init
|
|
18
|
+
* Init plugin
|
|
19
19
|
* @constructor
|
|
20
20
|
*/
|
|
21
|
-
declare function
|
|
22
|
-
export {
|
|
21
|
+
declare function ViteSsrBoostPlugin(options?: IPluginOptions): Plugin[];
|
|
22
|
+
export { ViteSsrBoostPlugin as default, IPluginOptions };
|
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 ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\n\nexport interface IPluginOptions {\n indexFile?: string; // default: index.html\n serverFile?: string; // default: server.ts\n abortDelay?: number; // How long the server waits for data before giving up. default: 10000 (10 sec)\n hasLazyRoutePlugin?: boolean; // Possibility to use custom export route component @see FCRoute interface\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions; // Read aliases from tsconfig\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 abortDelay: 10000,\n hasLazyRoutePlugin: true,\n tsconfigAliases: true,\n};\n\n/**\n * Init
|
|
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 ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\n\nexport interface IPluginOptions {\n indexFile?: string; // default: index.html\n serverFile?: string; // default: server.ts\n abortDelay?: number; // How long the server waits for data before giving up. default: 10000 (10 sec)\n hasLazyRoutePlugin?: boolean; // Possibility to use custom export route component @see FCRoute interface\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions; // Read aliases from tsconfig\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 abortDelay: 10000,\n hasLazyRoutePlugin: true,\n tsconfigAliases: true,\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 as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\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 config(config, { ssrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: process.env.SSR_BOOST_IS_SSR === '1' || action === 'dev',\n };\n\n if (!ssrBuild) {\n return config;\n }\n\n return {\n ...config,\n publicDir: false,\n };\n },\n },\n ];\n\n const { hasLazyRoutePlugin, tsconfigAliases } = mergedOptions;\n\n if (hasLazyRoutePlugin) {\n plugins.push(ViteNormalizeRouterPlugin());\n }\n\n if (tsconfigAliases) {\n plugins.push(\n ViteMakeAliasesPlugin(typeof tsconfigAliases === 'boolean' ? undefined : tsconfigAliases),\n );\n }\n\n return plugins;\n}\n\nexport default ViteSsrBoostPlugin;\n"],"names":["defaultOptions","indexFile","serverFile","abortDelay","hasLazyRoutePlugin","tsconfigAliases","ViteSsrBoostPlugin","options","dirInfo","URL","url","action","global","viteBoostAction","mergedOptions","plugins","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","CliActions","dev","config","ssrBuild","define","__IS_SSR__","process","env","SSR_BOOST_IS_SSR","publicDir","push","ViteNormalizeRouterPlugin","ViteMakeAliasesPlugin","undefined"],"mappings":"kMAuBA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,IACZC,oBAAoB,EACpBC,iBAAiB,GAOnB,SAASC,EAAmBC,EAA0B,IACpD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAASC,OAAOC,gBAChBC,EAAgC,IAAKd,KAAmBO,GAExDQ,EAAoB,CACxB,CACEC,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVL,EACHM,WAAYC,EAAKC,QAAQd,EAAQe,UACjCZ,SACAa,MAAOb,IAAWc,EAAWC,KAE/BC,OAAM,CAACA,GAAQC,SAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,GACrBC,WAA6C,MAAjCC,QAAQC,IAAIC,kBAAuC,QAAXtB,GAGjDiB,EAIE,IACFD,EACHO,WAAW,GALJP,MAWTvB,mBAAEA,EAAkBC,gBAAEA,GAAoBS,EAYhD,OAVIV,GACFW,EAAQoB,KAAKC,KAGX/B,GACFU,EAAQoB,KACNE,EAAiD,kBAApBhC,OAAgCiC,EAAYjC,IAItEU,CACT"}
|
|
@@ -6,6 +6,7 @@ interface IConfigOptions {
|
|
|
6
6
|
isHost?: boolean;
|
|
7
7
|
isOnlyClient?: boolean;
|
|
8
8
|
prodParams?: Partial<IConfigParams>;
|
|
9
|
+
mode?: string;
|
|
9
10
|
}
|
|
10
11
|
interface IConfigParams {
|
|
11
12
|
root: string;
|
|
@@ -35,6 +36,10 @@ declare class ServerConfig {
|
|
|
35
36
|
* SPA mode
|
|
36
37
|
*/
|
|
37
38
|
readonly isSPA: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Env mode
|
|
41
|
+
*/
|
|
42
|
+
readonly mode?: string;
|
|
38
43
|
/**
|
|
39
44
|
* Vite config - only for development
|
|
40
45
|
*/
|
|
@@ -61,7 +66,7 @@ declare class ServerConfig {
|
|
|
61
66
|
/**
|
|
62
67
|
* @constructor
|
|
63
68
|
*/
|
|
64
|
-
protected constructor({ isProd, isHost, isOnlyClient }: IConfigOptions, prodParams: Partial<IConfigParams>);
|
|
69
|
+
protected constructor({ isProd, isHost, isOnlyClient, mode }: IConfigOptions, prodParams: Partial<IConfigParams>);
|
|
65
70
|
/**
|
|
66
71
|
* Initialize service
|
|
67
72
|
*/
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import r from"node:path";import t from"../helpers/plugin-config.js";import i from"./logger.js";class s{isProd;isHost;isSPA;vite;app;params;prodParams;logger;constructor({isProd:r=!1,isHost:t=!1,isOnlyClient:i=!1},
|
|
1
|
+
import r from"node:path";import t from"../helpers/plugin-config.js";import i from"./logger.js";class s{isProd;isHost;isSPA;mode;vite;app;params;prodParams;logger;constructor({isProd:r=!1,isHost:t=!1,isOnlyClient:i=!1,mode:s},e){this.isProd=r,this.isHost=t,this.isSPA=i,this.mode=s,this.prodParams={root:"./build",publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",port:3e3,abortDelay:1e4,...e},this.makeParams()}static init(r={},t={}){return new s(r,t)}makeParams(){const t=this.getPluginConfig()??{},{config:s}=this.vite??{},e=s?.root??this.prodParams.root??"",o=s?.publicDir??this.prodParams.publicDir,a=new URL(import.meta.url),h=t.pluginPath??r.resolve(`../${r.dirname(a.pathname)}`),p=t.indexFile??this.prodParams.indexFile,l=t.serverFile??this.prodParams.serverFile,n="boolean"==typeof s?.server.host||this.isHost?"0.0.0.0":s?.server.host??this.prodParams.host,m=s?.server.port??(this.isProd?this.prodParams.port:5173),d=t.abortDelay??this.prodParams.abortDelay;this.params={root:e,publicDir:o,pluginPath:h,indexFile:p,serverFile:l,host:n,port:m,abortDelay:d,isSPA:this.isSPA,isProd:this.isProd},this.logger=this.vite?.config.logger??new i}setVite(r){this.vite=r,this.makeParams()}setApp(r){this.app=r}setAbortDelay(r){this.prodParams.abortDelay=r,this.params.abortDelay=r}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?t(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}}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 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 prodParams?: Partial<IConfigParams>;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n serverFile: string;\n abortDelay: number;\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 * SPA mode\n */\n public readonly isSPA: boolean;\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 * @constructor\n */\n protected constructor(\n { isProd = false, isHost = false, isOnlyClient = false }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.prodParams = {\n root: './build',\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 abortDelay: 10000,\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 * 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.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 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 const abortDelay = pluginConfig.abortDelay ?? this.prodParams.abortDelay!;\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n serverFile,\n host,\n port,\n abortDelay,\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 * Set custom abort delay\n */\n public setAbortDelay(ms: number): void {\n this.prodParams.abortDelay = ms;\n this.params.abortDelay = ms;\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\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isSPA","vite","app","params","prodParams","logger","constructor","isOnlyClient","this","root","publicDir","indexFile","serverFile","host","port","abortDelay","makeParams","static","options","prodOptions","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","server","DefaultLogger","setVite","setApp","express","setAbortDelay","ms","getVite","getApp","undefined","getParams","getLogger"],"mappings":"+
|
|
1
|
+
{"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import 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 prodParams?: Partial<IConfigParams>;\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 serverFile: string;\n abortDelay: number;\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 * 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 * @constructor\n */\n protected constructor(\n { isProd = false, isHost = false, isOnlyClient = false, mode }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.mode = mode;\n this.prodParams = {\n root: './build',\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 abortDelay: 10000,\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 * 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.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 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 const abortDelay = pluginConfig.abortDelay ?? this.prodParams.abortDelay!;\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n serverFile,\n host,\n port,\n abortDelay,\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 * Set custom abort delay\n */\n public setAbortDelay(ms: number): void {\n this.prodParams.abortDelay = ms;\n this.params.abortDelay = ms;\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\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isSPA","mode","vite","app","params","prodParams","logger","constructor","isOnlyClient","this","root","publicDir","indexFile","serverFile","host","port","abortDelay","makeParams","static","options","prodOptions","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","server","DefaultLogger","setVite","setApp","express","setAbortDelay","ms","getVite","getApp","undefined","getParams","getLogger"],"mappings":"+FA+BA,MAAMA,EAIYC,OAKAC,OAKAC,MAKAC,KAKNC,KAKAC,IAKAC,OAKAC,WAKAC,OAKVC,aACET,OAAEA,GAAS,EAAKC,OAAEA,GAAS,EAAKS,aAAEA,GAAe,EAAKP,KAAEA,GACxDI,GAEAI,KAAKX,OAASA,EACdW,KAAKV,OAASA,EACdU,KAAKT,MAAQQ,EACbC,KAAKR,KAAOA,EACZQ,KAAKJ,WAAa,CAChBK,KAAM,UACNC,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,KAAM,IACNC,WAAY,OACTX,GAGLI,KAAKQ,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAIvB,EAAasB,EAASC,EAClC,CAKSH,aACR,MAAMI,EAAgBZ,KAAKa,mBAAqB,CAAE,GAC5CC,OAAEA,GAAWd,KAAKP,MAAQ,CAAA,EAE1BQ,EAAOa,GAAQb,MAAQD,KAAKJ,WAAWK,MAAQ,GAC/CC,EAAYY,GAAQZ,WAAaF,KAAKJ,WAAWM,UACjDa,EAAU,IAAIC,gBAAgBC,KAC9BC,EACJN,EAAaM,YAAcC,EAAKC,QAAQ,MAAMD,EAAKE,QAAQN,EAAQO,aAC/DnB,EAAYS,EAAaT,WAAaH,KAAKJ,WAAWO,UACtDC,EAAaQ,EAAaR,YAAcJ,KAAKJ,WAAWQ,WACxDC,EAC2B,kBAAxBS,GAAQS,OAAOlB,MAAsBL,KAAKV,OAC7C,UACAwB,GAAQS,OAAOlB,MAAQL,KAAKJ,WAAWS,KACvCC,EAAOQ,GAAQS,OAAOjB,OAASN,KAAKX,OAASW,KAAKJ,WAAWU,KAAQ,MACrEC,EAAaK,EAAaL,YAAcP,KAAKJ,WAAWW,WAE9DP,KAAKL,OAAS,CACZM,OACAC,YACAgB,aACAf,YACAC,aACAC,OACAC,OACAC,aACAhB,MAAOS,KAAKT,MACZF,OAAQW,KAAKX,QAEfW,KAAKH,OAASG,KAAKP,MAAMqB,OAAOjB,QAAU,IAAI2B,CAC/C,CAKMC,QAAQhC,GACbO,KAAKP,KAAOA,EAEZO,KAAKQ,YACN,CAKMkB,OAAOC,GACZ3B,KAAKN,IAAMiC,CACZ,CAKMC,cAAcC,GACnB7B,KAAKJ,WAAWW,WAAasB,EAC7B7B,KAAKL,OAAOY,WAAasB,CAC1B,CAMMC,UACL,OAAO9B,KAAKP,IACb,CAKMsC,SACL,OAAO/B,KAAKN,GACb,CAMMmB,kBACL,OAAOb,KAAKP,KAAOoB,EAAgBb,KAAKP,KAAKqB,aAAUkB,CACxD,CAKMC,YACL,OAAOjC,KAAKL,MACb,CAKMuC,YACL,OAAOlC,KAAKH,MACb"}
|