@lomray/vite-ssr-boost 1.0.0-beta.33 → 1.0.0-beta.35

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/README.md CHANGED
@@ -196,6 +196,28 @@ Explore all commands and options:
196
196
  ssr-boost -h
197
197
  ```
198
198
 
199
+ ## WARNING
200
+ Route imports of the following types are supported:
201
+ ```typescript jsx
202
+ import { RouteObject } from 'react-router-dom';
203
+ import HomePage from './pages/home';
204
+
205
+ const importPath = './pages/home';
206
+
207
+ const routes: RouteObject[] = [
208
+ {
209
+ path: '/home',
210
+ Component: HomePage, // support
211
+ element: <AppLayout />, // support
212
+ lazy: () => import('./pages/home'), // support
213
+ lazy: () => import(importPath), // not support
214
+ lazy: () => { // not support
215
+ return import('./pages/home');
216
+ }
217
+ }
218
+ ];
219
+ ```
220
+
199
221
  ## Demo
200
222
  Explore [demo app](https://github.com/Lomray-Software/vite-template) to more understand.
201
223
 
package/cli/build.d.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  interface IBuildParams {
2
+ onFinish?: () => void;
3
+ mode?: string;
4
+ clientOptions?: string;
5
+ serverOptions?: string;
2
6
  isOnlyClient?: boolean;
3
7
  isWatch?: boolean;
4
- isEject?: boolean;
5
8
  isUnlockRobots?: boolean;
6
- clientOptions?: string;
7
- serverOptions?: string;
8
- mode?: string;
9
- onFinish?: () => void;
9
+ isEject?: boolean;
10
+ isNoWarnings?: boolean;
10
11
  }
11
12
  /**
12
13
  * Build production application
13
14
  */
14
- declare function build({ onFinish, isOnlyClient, isWatch, isUnlockRobots, isEject, clientOptions, serverOptions, mode, }: IBuildParams): Promise<void>;
15
+ declare function build({ onFinish, mode, clientOptions, serverOptions, isOnlyClient, isWatch, isUnlockRobots, isEject, isNoWarnings, }: IBuildParams): Promise<void>;
15
16
  export { build as default };
package/cli/build.js CHANGED
@@ -1,2 +1,2 @@
1
- import o from"node:child_process";import{performance as e}from"node:perf_hooks";import t from"chalk";import i from"./vite-reset-cache.js";import s from"../constants/cli-name.js";import{createDevMarker as r}from"../helpers/dev-marker.js";import n from"../services/build.js";async function a({onFinish:a,isOnlyClient:l=!1,isWatch:d=!1,isUnlockRobots:c=!1,isEject:m=!1,clientOptions:p="",serverOptions:u="",mode:O=""}){const f=e.now(),v=new n({mode:O}),S=["client"],$=new AbortController,_=O?`--mode ${O}`:"";await v.makeConfig(),await i(),v.clearBuildFolder();const b=v.promisifyProcess(o.spawn(`vite build ${p} --emptyOutDir --outDir ${v.outDir}/client ${_}`,{signal:$.signal,stdio:[process.stdin,"pipe",process.stderr],shell:!0,env:{...process.env,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:l?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}}));let g;if(d||await b,l||(g=v.promisifyProcess(o.spawn(`vite build ${u} --emptyOutDir --outDir ${v.outDir}/server --ssr ${v.serverFile} ${_}`,{signal:$.signal,stdio:[process.stdin,"pipe",process.stderr],shell:!0,env:{...process.env,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:l?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}})),d||(await g,await v.buildManifest(),m&&v.eject()),S.push("server")),d){process.on("exit",(()=>{$.abort()}));let o=l?1:2;const e=t=>{Buffer.from(t).toString().includes("built in")&&(o-=1,o||(b.command.stdout.removeListener("data",e),g?.command.stdout.removeListener("data",e),r(v.isProd,v.viteConfig),a?.()))};return b.command.stdout.on("data",e),void g?.command.stdout.on("data",e)}c&&v.unlockRobots(),r(v.isProd,v.viteConfig),a?.();const h=Math.ceil(e.now()-f),w=h>1e3?(h/1e3).toFixed(2):h,C=h>1e3?"s":"ms",R=t.dim(`${t.yellowBright(S.join(","))} built in ${t.reset(t.bold(w))} ${C}`);console.info(`\n ${t.green(`${t.bold(s.toUpperCase())}`)} ${R} ${v.isProd?"":t.redBright(`NODE_ENV=${v.nodeEnv}`)}\n`)}export{a as default};
1
+ import o from"node:child_process";import{performance as e}from"node:perf_hooks";import i from"chalk";import t from"./helpers/vite-reset-cache.js";import s from"../constants/cli-name.js";import{createDevMarker as r}from"../helpers/dev-marker.js";import n from"../helpers/process-stop.js";import l from"../services/build.js";async function a({onFinish:a,mode:c="",clientOptions:d="",serverOptions:p="",isOnlyClient:m=!1,isWatch:f=!1,isUnlockRobots:u=!1,isEject:O=!1,isNoWarnings:v=!1}){const S=e.now(),$=new l({mode:c}),h=["client"],_=new AbortController,b=c?`--mode ${c}`:"";await $.makeConfig(),await t(),$.clearBuildFolder();const g=$.promisifyProcess(o.spawn(`vite build ${d} --emptyOutDir --outDir ${$.outDir}/client ${b}`,{signal:_.signal,stdio:[process.stdin,"pipe","pipe"],shell:!0,env:{...process.env,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:m?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}}),v);if(!f){const o=await g;n(o,!0)}let w;if(!m){if(w=$.promisifyProcess(o.spawn(`vite build ${p} --emptyOutDir --outDir ${$.outDir}/server --ssr ${$.serverFile} ${b}`,{signal:_.signal,stdio:[process.stdin,"pipe","pipe"],shell:!0,env:{...process.env,FORCE_COLOR:"2",SSR_BOOST_IS_SSR:m?"0":"1",SSR_BOOST_ACTION:global.viteBoostAction}}),v),!f){const o=await w;n(o,!0),await $.buildManifest(),O&&$.eject()}h.push("server")}if(f){process.on("exit",(()=>{_.abort()}));let o=m?1:2;const e=i=>{Buffer.from(i).toString().includes("built in")&&(o-=1,o||(g.command.stdout.removeListener("data",e),w?.command.stdout.removeListener("data",e),r($.isProd,$.viteConfig),a?.()))};return g.command.stdout.on("data",e),void w?.command.stdout.on("data",e)}u&&$.unlockRobots(),r($.isProd,$.viteConfig),a?.();const C=Math.ceil(e.now()-S),R=C>1e3?(C/1e3).toFixed(2):C,B=C>1e3?"s":"ms",j=i.dim(`${i.yellowBright(h.join(","))} built in ${i.reset(i.bold(R))} ${B}`);console.info(`\n ${i.green(`${i.bold(s.toUpperCase())}`)} ${j} ${$.isProd?"":i.redBright(`NODE_ENV=${$.nodeEnv}`)}\n`)}export{a 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/vite-reset-cache';\nimport cliName from '@constants/cli-name';\nimport { createDevMarker } from '@helpers/dev-marker';\nimport Build from '@services/build';\n\ninterface IBuildParams {\n isOnlyClient?: boolean;\n isWatch?: boolean;\n isEject?: boolean;\n isUnlockRobots?: boolean;\n clientOptions?: string;\n serverOptions?: string;\n mode?: string;\n onFinish?: () => void;\n}\n\n/**\n * Build production application\n */\nasync function build({\n onFinish,\n isOnlyClient = false,\n isWatch = false,\n isUnlockRobots = false,\n isEject = false,\n clientOptions = '',\n serverOptions = '',\n mode = '',\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', process.stderr],\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 );\n\n if (!isWatch) {\n await clientProcess;\n }\n\n let serverProcess: Promise<unknown> | undefined;\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', process.stderr],\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 );\n\n if (!isWatch) {\n await serverProcess;\n await buildService.buildManifest();\n\n if (isEject) {\n buildService.eject();\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 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","isOnlyClient","isWatch","isUnlockRobots","isEject","clientOptions","serverOptions","mode","perfStart","performance","now","buildService","Build","types","controller","AbortController","modeOpt","makeConfig","viteResetCache","clearBuildFolder","clientProcess","promisifyProcess","childProcess","spawn","outDir","signal","stdio","process","stdin","stderr","shell","env","FORCE_COLOR","SSR_BOOST_IS_SSR","SSR_BOOST_ACTION","global","viteBoostAction","serverProcess","serverFile","buildManifest","eject","push","on","abort","buildCount","listener","buff","Buffer","from","toString","includes","stdout","removeListener","createDevMarker","isProd","viteConfig","unlockRobots","durationMs","Math","ceil","duration","toFixed","units","buildDurationString","chalk","dim","yellowBright","join","reset","bold","console","info","green","cliName","toUpperCase","redBright","nodeEnv"],"mappings":"iRAsBAA,eAAeC,GAAMC,SACnBA,EAAQC,aACRA,GAAe,EAAKC,QACpBA,GAAU,EAAKC,eACfA,GAAiB,EAAKC,QACtBA,GAAU,EAAKC,cACfA,EAAgB,GAAEC,cAClBA,EAAgB,GAAEC,KAClBA,EAAO,KAEP,MAAMC,EAAYC,EAAYC,MACxBC,EAAe,IAAIC,EAAM,CAAEL,SAC3BM,EAAQ,CAAC,UACTC,EAAa,IAAIC,gBACjBC,EAAUT,EAAO,UAAUA,IAAS,SAEpCI,EAAaM,mBAGbC,IACNP,EAAaQ,mBAKb,MAAMC,EAAgBT,EAAaU,iBACjCC,EAAaC,MACX,cAAclB,4BAAwCM,EAAaa,iBAAiBR,IACpF,CACES,OAAQX,EAAWW,OACnBC,MAAO,CAACC,QAAQC,MAAO,OAAQD,QAAQE,QACvCC,OAAO,EACPC,IAAK,IACAJ,QAAQI,IACXC,YAAa,IACbC,iBAAkBhC,EAAe,IAAM,IACvCiC,iBAAkBC,OAAOC,oBAUjC,IAAIC,EAsCJ,GA1CKnC,SACGkB,EAQHnB,IACHoC,EAAgB1B,EAAaU,iBAC3BC,EAAaC,MACX,cAAcjB,4BAAwCK,EAAaa,uBAAuBb,EAAa2B,cAActB,IACrH,CACES,OAAQX,EAAWW,OACnBC,MAAO,CAACC,QAAQC,MAAO,OAAQD,QAAQE,QACvCC,OAAO,EACPC,IAAK,IACAJ,QAAQI,IACXC,YAAa,IACbC,iBAAkBhC,EAAe,IAAM,IACvCiC,iBAAkBC,OAAOC,oBAM5BlC,UACGmC,QACA1B,EAAa4B,gBAEfnC,GACFO,EAAa6B,SAIjB3B,EAAM4B,KAAK,WAMTvC,EAAS,CACXyB,QAAQe,GAAG,QAAQ,KACjB5B,EAAW6B,OAAO,IAGpB,IAAIC,EAAa3C,EAAe,EAAI,EACpC,MAAM4C,EAAYC,IACJC,OAAOC,KAAKF,GAAMG,WAEtBC,SAAS,cACfN,GAAc,EAETA,IACHxB,EAAuB,QAAE+B,OAAOC,eAAe,OAAQP,GACvDR,GAAyB,QAAEc,OAAOC,eAAe,OAAQP,GACzDQ,EAAgB1C,EAAa2C,OAAQ3C,EAAa4C,YAClDvD,OAEH,EASH,OAHAoB,EAAuB,QAAE+B,OAAOT,GAAG,OAAQG,QAC3CR,GAAyB,QAAEc,OAAOT,GAAG,OAAQG,EAG9C,CAEG1C,GACFQ,EAAa6C,eAGfH,EAAgB1C,EAAa2C,OAAQ3C,EAAa4C,YAClDvD,MAEA,MAAMyD,EAAaC,KAAKC,KAAKlD,EAAYC,MAAQF,GAC3CoD,EAAWH,EAAa,KAAQA,EAAa,KAAMI,QAAQ,GAAKJ,EAChEK,EAAQL,EAAa,IAAO,IAAM,KAElCM,EAAsBC,EAAMC,IAChC,GAAGD,EAAME,aAAarD,EAAMsD,KAAK,kBAAkBH,EAAMI,MAAMJ,EAAMK,KAAKT,OAAcE,KAG1FQ,QAAQC,KACN,OAAOP,EAAMQ,MAAM,GAAGR,EAAMK,KAAKI,EAAQC,sBAAsBX,KAC7DpD,EAAa2C,OAAS,GAAKU,EAAMW,UAAU,YAAYhE,EAAaiE,eAG1E"}
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 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 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 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) as number;\n\n processStop(exitCode, true);\n }\n\n let serverProcess: Promise<unknown> | undefined;\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) as number;\n\n processStop(exitCode, true);\n await buildService.buildManifest();\n\n if (isEject) {\n buildService.eject();\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 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","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","processStop","serverProcess","serverFile","buildManifest","eject","push","on","abort","buildCount","listener","buff","Buffer","from","toString","includes","stdout","removeListener","createDevMarker","isProd","viteConfig","unlockRobots","durationMs","Math","ceil","duration","toFixed","units","buildDurationString","chalk","dim","yellowBright","join","reset","bold","console","info","green","cliName","toUpperCase","redBright","nodeEnv"],"mappings":"mUAwBAA,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,IAEf,MAAMC,EAAYC,EAAYC,MACxBC,EAAe,IAAIC,EAAM,CAAEZ,SAC3Ba,EAAQ,CAAC,UACTC,EAAa,IAAIC,gBACjBC,EAAUhB,EAAO,UAAUA,IAAS,SAEpCW,EAAaM,mBAGbC,IACNP,EAAaQ,mBAKb,MAAMC,EAAgBT,EAAaU,iBACjCC,EAAaC,MACX,cAActB,4BAAwCU,EAAaa,iBAAiBR,IACpF,CACES,OAAQX,EAAWW,OACnBC,MAAO,CAACC,QAAQC,MAAO,OAAQ,QAC/BC,OAAO,EACPC,IAAK,IACAH,QAAQG,IACXC,YAAa,IACbC,iBAAkB7B,EAAe,IAAM,IACvC8B,iBAAkBC,OAAOC,mBAI/B5B,GAGF,IAAKH,EAAS,CACZ,MAAMgC,QAAkBhB,EAExBiB,EAAYD,GAAU,EACvB,CAED,IAAIE,EAKJ,IAAKnC,EAAc,CAmBjB,GAlBAmC,EAAgB3B,EAAaU,iBAC3BC,EAAaC,MACX,cAAcrB,4BAAwCS,EAAaa,uBAAuBb,EAAa4B,cAAcvB,IACrH,CACES,OAAQX,EAAWW,OACnBC,MAAO,CAACC,QAAQC,MAAO,OAAQ,QAC/BC,OAAO,EACPC,IAAK,IACAH,QAAQG,IACXC,YAAa,IACbC,iBAAkB7B,EAAe,IAAM,IACvC8B,iBAAkBC,OAAOC,mBAI/B5B,IAGGH,EAAS,CACZ,MAAMgC,QAAkBE,EAExBD,EAAYD,GAAU,SAChBzB,EAAa6B,gBAEflC,GACFK,EAAa8B,OAEhB,CAED5B,EAAM6B,KAAK,SACZ,CAKD,GAAItC,EAAS,CACXuB,QAAQgB,GAAG,QAAQ,KACjB7B,EAAW8B,OAAO,IAGpB,IAAIC,EAAa1C,EAAe,EAAI,EACpC,MAAM2C,EAAYC,IACJC,OAAOC,KAAKF,GAAMG,WAEtBC,SAAS,cACfN,GAAc,EAETA,IACHzB,EAAuB,QAAEgC,OAAOC,eAAe,OAAQP,GACvDR,GAAyB,QAAEc,OAAOC,eAAe,OAAQP,GACzDQ,EAAgB3C,EAAa4C,OAAQ5C,EAAa6C,YAClDzD,OAEH,EASH,OAHAqB,EAAuB,QAAEgC,OAAOT,GAAG,OAAQG,QAC3CR,GAAyB,QAAEc,OAAOT,GAAG,OAAQG,EAG9C,CAEGzC,GACFM,EAAa8C,eAGfH,EAAgB3C,EAAa4C,OAAQ5C,EAAa6C,YAClDzD,MAEA,MAAM2D,EAAaC,KAAKC,KAAKnD,EAAYC,MAAQF,GAC3CqD,EAAWH,EAAa,KAAQA,EAAa,KAAMI,QAAQ,GAAKJ,EAChEK,EAAQL,EAAa,IAAO,IAAM,KAElCM,EAAsBC,EAAMC,IAChC,GAAGD,EAAME,aAAatD,EAAMuD,KAAK,kBAAkBH,EAAMI,MAAMJ,EAAMK,KAAKT,OAAcE,KAG1FQ,QAAQC,KACN,OAAOP,EAAMQ,MAAM,GAAGR,EAAMK,KAAKI,EAAQC,sBAAsBX,KAC7DrD,EAAa4C,OAAS,GAAKU,EAAMW,UAAU,YAAYjE,EAAakE,eAG1E"}
@@ -0,0 +1,2 @@
1
+ import o from"chalk";import t from"../../constants/cli-context.js";import i from"../../constants/cli-shortcuts.js";import r from"../../helpers/plugin-config.js";import e from"../../helpers/process-stop.js";let n=!1;function s(s){!async function(s){if(""===s||""===s)return void(t.server?.close((o=>e(o?1:0)))||e());if(n)return;const{config:c}=t,f=c?.getLogger(),{customShortcuts:l=[]}="object"==typeof c?.getVite()?.config?r(c.getVite().config):{},p=l.filter(Boolean).concat(i).filter((({isOnlyDev:o=!1})=>!o||o&&!c?.isProd));if("\r"===s)return f?.info("\r");"h"===s&&f?.info(["",o.bold(" Shortcuts"),...p.map((t=>o.dim(" press ")+o.bold(t.key)+o.dim(` to ${t.description}`)))].join("\n"));const m=p.find((({key:o})=>o===s));if(!m)return;n=!0,await m.action(t),n=!1}(s)}export{s as default};
2
+ //# sourceMappingURL=keyboard-input.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyboard-input.js","sources":["../../../src/cli/helpers/keyboard-input.ts"],"sourcesContent":["import chalk from 'chalk';\nimport cliContext from '@constants/cli-context';\nimport defaultShortcuts from '@constants/cli-shortcuts';\nimport getPluginConfig from '@helpers/plugin-config';\nimport processStop from '@helpers/process-stop';\n\nlet isActionRunning = false;\n\n/**\n * Handle keyboard press buttons\n */\nfunction onKeyPress(input: string): void {\n void runAction(input);\n}\n\n/**\n * Run shortcut\n */\nasync function runAction(input: string): Promise<void> {\n // ctrl+c or ctrl+d\n if (input === '\\x03' || input === '\\x04') {\n if (!cliContext.server?.close((e) => processStop(e ? 1 : 0))) {\n processStop();\n }\n\n return;\n }\n\n if (isActionRunning) {\n return;\n }\n\n const { config } = cliContext;\n const Logger = config?.getLogger();\n const { customShortcuts = [] } =\n typeof config?.getVite()?.config === 'object' ? getPluginConfig(config.getVite()!.config) : {};\n\n const shortcuts = customShortcuts\n .filter(Boolean)\n .concat(defaultShortcuts)\n .filter(({ isOnlyDev = false }) => !isOnlyDev || (isOnlyDev && !config?.isProd));\n\n // print empty line\n if (input === '\\r') {\n return Logger?.info('\\r');\n }\n\n // print help\n if (input === 'h') {\n Logger?.info(\n [\n '',\n chalk.bold(' Shortcuts'),\n ...shortcuts.map(\n (shortcut) =>\n chalk.dim(' press ') +\n chalk.bold(shortcut.key) +\n chalk.dim(` to ${shortcut.description}`),\n ),\n ].join('\\n'),\n );\n }\n\n // execute shortcut command\n const shortcut = shortcuts.find(({ key }) => key === input);\n\n if (!shortcut) {\n return;\n }\n\n isActionRunning = true;\n await shortcut.action(cliContext);\n isActionRunning = false;\n}\n\nexport default onKeyPress;\n"],"names":["isActionRunning","onKeyPress","input","async","cliContext","server","close","e","processStop","config","Logger","getLogger","customShortcuts","getVite","getPluginConfig","shortcuts","filter","Boolean","concat","defaultShortcuts","isOnlyDev","isProd","info","chalk","bold","map","shortcut","dim","key","description","join","find","action","runAction"],"mappings":"8MAMA,IAAIA,GAAkB,EAKtB,SAASC,EAAWC,IAOpBC,eAAyBD,GAEvB,GAAc,MAAVA,GAA8B,MAAVA,EAKtB,YAJKE,EAAWC,QAAQC,OAAOC,GAAMC,EAAYD,EAAI,EAAI,MACvDC,KAMJ,GAAIR,EACF,OAGF,MAAMS,OAAEA,GAAWL,EACbM,EAASD,GAAQE,aACjBC,gBAAEA,EAAkB,IACa,iBAA9BH,GAAQI,WAAWJ,OAAsBK,EAAgBL,EAAOI,UAAWJ,QAAU,CAAA,EAExFM,EAAYH,EACfI,OAAOC,SACPC,OAAOC,GACPH,QAAO,EAAGI,aAAY,MAAaA,GAAcA,IAAcX,GAAQY,SAG1E,GAAc,OAAVnB,EACF,OAAOQ,GAAQY,KAAK,MAIR,MAAVpB,GACFQ,GAAQY,KACN,CACE,GACAC,EAAMC,KAAK,kBACRT,EAAUU,KACVC,GACCH,EAAMI,IAAI,YACVJ,EAAMC,KAAKE,EAASE,KACpBL,EAAMI,IAAI,OAAOD,EAASG,kBAE9BC,KAAK,OAKX,MAAMJ,EAAWX,EAAUgB,MAAK,EAAGH,SAAUA,IAAQ1B,IAErD,IAAKwB,EACH,OAGF1B,GAAkB,QACZ0B,EAASM,OAAO5B,GACtBJ,GAAkB,CACpB,CA7DOiC,CAAU/B,EACjB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-reset-cache.js","sources":["../../../src/cli/helpers/vite-reset-cache.ts"],"sourcesContent":["import fs from 'node:fs';\nimport chalk from 'chalk';\nimport { resolveConfig } from 'vite';\n\n/**\n * Reset vite cache\n */\nasync function viteResetCache(): Promise<void> {\n const config = await resolveConfig({}, 'build');\n const { cacheDir } = config;\n\n if (fs.existsSync(cacheDir)) {\n fs.rmSync(cacheDir, { recursive: true, force: true });\n }\n\n console.info(chalk.dim(chalk.yellowBright('vite cache cleared.')));\n}\n\nexport default viteResetCache;\n"],"names":["async","viteResetCache","config","resolveConfig","cacheDir","fs","existsSync","rmSync","recursive","force","console","info","chalk","dim","yellowBright"],"mappings":"iFAOAA,eAAeC,IACb,MAAMC,QAAeC,EAAc,CAAE,EAAE,UACjCC,SAAEA,GAAaF,EAEjBG,EAAGC,WAAWF,IAChBC,EAAGE,OAAOH,EAAU,CAAEI,WAAW,EAAMC,OAAO,IAGhDC,QAAQC,KAAKC,EAAMC,IAAID,EAAME,aAAa,wBAC5C"}
package/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as o}from"fs";import e from"chalk";import{Command as t,Option as n}from"commander";import i from"./cli/build.js";import r from"./cli/keyboard-input.js";import s from"./cli/run-dev.js";import d from"./cli/run-docker-build.js";import a from"./cli/run-prod.js";import c from"./cli/vite-reset-cache.js";import l from"./constants/cli-actions.js";import p from"./constants/cli-context.js";import m from"./constants/cli-name.js";const{description:u,version:f}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),v=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},O=new t;O.name(m).description(u).version(f).hook("preAction",((o,e)=>{global.viteBoostAction=e.name()}));const w=new n("--host","Ability to access the local instance on other devices under the same network.").default(!1),k=new n("--only-client","Build/run only client side part.").default(!1),g=new n("--port [port]","Server port.").default(3e3),y=new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production");O.command(l.dev).description("Run development server.").addOption(w).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:o,resetCache:t,mode:n})=>{t&&await c();const i=async t=>{console.info(e.cyan("Starting the development server..."));const{server:i,config:r}=await s({version:f,isHost:o,isPrintInfo:t,mode:n});p.server=i,p.config=r};return p.reboot=i,v(),i()})),O.command(l.build).description("Create production build.").addOption(k).addOption(y).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)).action((async({onlyClient:o,clientOptions:e,serverOptions:t,mode:n,unlockRobots:r,eject:s})=>{await i({isOnlyClient:o,isUnlockRobots:r,isEject:s,clientOptions:e,serverOptions:t,mode:n})})),O.command(l.start).description("Run production server.").addOption(w).addOption(g).addOption(k).addOption(new n("--module-preload","Add module preload scripts to server output.").default(!1)).action((({host:o,port:e,onlyClient:t,modulePreload:n})=>{const i=async i=>{const{server:r,config:s}=await a({version:f,isHost:o,isPrintInfo:i,port:e,onlyClient:t,modulePreload:n});p.server=r,p.config=s};return p.reboot=i,v(),i()})),O.command(l.preview).description("Build and preview production.").addOption(k).addOption(w).addOption(g).addOption(y).action((async({host:o,port:t,onlyClient:n,mode:r})=>{global.viteBoostStartTime=performance.now();const s=async i=>{const{server:r,config:s}=await a({version:f,isHost:o,isPrintInfo:i,port:t,onlyClient:n});r.on("listening",(()=>{setTimeout((()=>{s.getLogger().info(e.yellow("\n Running preview mode... \n"))}),0)})),p.server=r,p.config=s};p.reboot=s,v();await i({mode:r,isWatch:!0,isOnlyClient:n,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{s()}})})),O.command(l.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(k).addOption(y).action((async({imageName:o,dockerOptions:e,dockerFile:t,onlyClient:n,mode:i})=>{await d({imageName:o,dockerOptions:e,dockerFile:t,isOnlyClient:n,mode:i})})),O.parse();
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 r from"./cli/helpers/keyboard-input.js";import s from"./cli/helpers/vite-reset-cache.js";import d from"./cli/run-dev.js";import a from"./cli/run-docker-build.js";import c from"./cli/run-prod.js";import l from"./constants/cli-actions.js";import p from"./constants/cli-context.js";import m from"./constants/cli-name.js";const{description:u,version:f}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),w=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},v=new n;v.name(m).description(u).version(f).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),h=new t("--only-client","Build/run only client side part.").default(!1),g=new t("--port [port]","Server port.").default(3e3),k=new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production");v.command(l.dev).description("Run development server.").addOption(O).addOption(new t("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).action((async({host:o,resetCache:n,mode:t})=>{n&&await s();const i=async n=>{console.info(e.cyan("Starting the development server..."));const{server:i,config:r}=await d({version:f,isHost:o,isPrintInfo:n,mode:t});p.server=i,p.config=r};return p.reboot=i,w(),i()})),v.command(l.build).description("Create production build.").addOption(h).addOption(k).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("")).addOption(new t("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new t("--eject","Produces entrypoint file to run app without cli").default(!1)).addOption(new t("--throw-warnings","The build will abort with an error if warnings occur in the process.").default(!1)).action((async({onlyClient:o,clientOptions:e,serverOptions:n,mode:t,unlockRobots:r,eject:s,throwWarnings:d})=>{await i({isOnlyClient:o,isUnlockRobots:r,isNoWarnings:d,isEject:s,clientOptions:e,serverOptions:n,mode:t})})),v.command(l.start).description("Run production server.").addOption(O).addOption(g).addOption(h).addOption(new t("--module-preload","Add module preload scripts to server output.").default(!1)).action((({host:o,port:e,onlyClient:n,modulePreload:t})=>{const i=async i=>{const{server:r,config:s}=await c({version:f,isHost:o,isPrintInfo:i,port:e,onlyClient:n,modulePreload:t});p.server=r,p.config=s};return p.reboot=i,w(),i()})),v.command(l.preview).description("Build and preview production.").addOption(h).addOption(O).addOption(g).addOption(k).action((async({host:o,port:n,onlyClient:t,mode:r})=>{global.viteBoostStartTime=performance.now();const s=async i=>{const{server:r,config:s}=await c({version:f,isHost:o,isPrintInfo:i,port:n,onlyClient:t});r.on("listening",(()=>{setTimeout((()=>{s.getLogger().info(e.yellow("\n Running preview mode... \n"))}),0)})),p.server=r,p.config=s};p.reboot=s,w();await i({mode:r,isWatch:!0,isOnlyClient:t,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{s()}})})),v.command(l.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new t("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new t("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(h).addOption(k).action((async({imageName:o,dockerOptions:e,dockerFile:n,onlyClient:t,mode:i})=>{await a({imageName:o,dockerOptions:e,dockerFile:n,isOnlyClient:t,mode:i})})),v.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 runDockerBuild from '@cli/run-docker-build';\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.')\n .env('VITE_ENV_MODE')\n .default('production');\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 }) => {\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({ 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 .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 .action(async ({ onlyClient, clientOptions, serverOptions, mode, unlockRobots, eject }) => {\n await runBuild({\n isOnlyClient: onlyClient,\n isUnlockRobots: unlockRobots,\n isEject: eject,\n clientOptions,\n serverOptions,\n mode,\n });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .addOption(\n new Option('--module-preload', 'Add module preload scripts to server output.').default(false),\n )\n .action(({ host, port, onlyClient, modulePreload }) => {\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 });\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 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 });\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(async ({ imageName, dockerOptions, dockerFile, onlyClient, mode }) => {\n await runDockerBuild({\n imageName,\n dockerOptions,\n dockerFile,\n isOnlyClient: onlyClient,\n mode,\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","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","runBuild","isOnlyClient","isUnlockRobots","isEject","start","port","modulePreload","runProd","preview","viteBoostStartTime","performance","now","setTimeout","getLogger","yellow","isWatch","onFinish","buildDocker","requiredOption","imageName","dockerOptions","dockerFile","runDockerBuild"],"mappings":";0bAkBA,MAAMA,YAAEA,EAAWC,QAAEA,GAAYC,KAAKC,MACpCC,EAAa,IAAIC,IAAI,6BAA8BC,KAAM,SAOrDC,EAAkB,KAClBC,QAAQC,MAAMC,QAChBF,QAAQC,MAAME,YAAW,GAC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ACA,6DAGHS,UACC,IAAIT,EACF,8BACA,yEAGHS,UAAUP,GACVO,UAAUL,GACVM,QAAOC,OAASyC,YAAWC,gBAAeC,aAAY1B,aAAYd,iBAC3DyC,EAAe,CACnBH,YACAC,gBACAC,aACApB,aAAcN,EACdd,QACA,IAGNxB,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 runDev from '@cli/run-dev';\nimport runDockerBuild from '@cli/run-docker-build';\nimport runProd from '@cli/run-prod';\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');\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 }) => {\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({ 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 .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 '--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 throwWarnings,\n }) => {\n await runBuild({\n isOnlyClient: onlyClient,\n isUnlockRobots: unlockRobots,\n isNoWarnings: throwWarnings,\n isEject: eject,\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(\n new Option('--module-preload', 'Add module preload scripts to server output.').default(false),\n )\n .action(({ host, port, onlyClient, modulePreload }) => {\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 });\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 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 });\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(async ({ imageName, dockerOptions, dockerFile, onlyClient, mode }) => {\n await runDockerBuild({\n imageName,\n dockerOptions,\n dockerFile,\n isOnlyClient: onlyClient,\n mode,\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","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","throwWarnings","runBuild","isOnlyClient","isUnlockRobots","isNoWarnings","isEject","start","port","modulePreload","runProd","preview","viteBoostStartTime","performance","now","setTimeout","getLogger","yellow","isWatch","onFinish","buildDocker","requiredOption","imageName","dockerOptions","dockerFile","runDockerBuild"],"mappings":";0cAkBA,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,cAMXX,EACGgB,QAAQC,EAAWC,KACnBlC,YAAY,2BACZmC,UAAUV,GACVU,UAAU,IAAIT,EAAO,gBAAiB,gCAAgCC,SAAQ,IAC9EQ,UAAU,IAAIT,EAAO,gBAAiB,aAAaK,IAAI,iBAAiBJ,QAAQ,gBAChFS,QAAOC,OAASC,OAAMC,aAAYC,WAC7BD,SACIE,IAGR,MAAMT,EAAUK,MAAOK,IACrBC,QAAQC,KAAKC,EAAMC,KAAK,uCAExB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBC,EAAO,CAAEhD,UAASiD,OAAQZ,EAAMI,cAAaF,SAE9EW,EAAWJ,O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AMC,OAAEA,SAAiBoB,EAAQ,CACvCnE,UACAiD,OAAQZ,EACRI,cACAwB,OACAZ,eAGFP,EAAOnC,GAAG,aAAa,KACrB6D,YAAW,KACTzB,EAAO0B,YAAY9B,KAAKC,EAAM8B,OAAO,kCAAkC,GACtE,EAAE,IAGPxB,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAG5BG,EAAWC,OAASpB,EAEpBzB,UAIMqD,EAAS,CACbpB,OACAoC,SAAS,EACTf,aAAcP,EACdC,cANmB,KAOnBC,cAPmB,KAQnBqB,SAAU,KACH7C,GAAS,GAEhB,IAGNhB,EACGgB,QAAQC,EAAW6C,aACnB9E,YAAY,8CACZ+E,eAAe,4BAA6B,sBAC5C5C,UACC,IAAIT,EACF,oCACA,6DAGHS,UACC,IAAIT,EACF,8BACA,yEAGHS,UAAUP,GACVO,UAAUL,GACVM,QAAOC,OAAS2C,YAAWC,gBAAeC,aAAY5B,aAAYd,iBAC3D2C,EAAe,CACnBH,YACAC,gBACAC,aACArB,aAAcP,EACdd,QACA,IAGNxB,EAAQb"}
@@ -1,2 +1,2 @@
1
- import t from"../components/with-suspense.js";import{keys as e}from"../interfaces/fc-route.js";const n=(t,e)=>{e&&(t.pathId=e)},o=async(o,s)=>{const r=await o();if(r.Component)return n(r,s),r;const p=r.default,a={Component:p};return e.forEach((t=>{p[t]&&(a[t]=p[t])})),p.Suspense&&(a.Component=t(p,p.Suspense)),n(a,s),a};export{o as default};
1
+ import t from"../components/with-suspense.js";import{keys as e}from"../interfaces/fc-route.js";const n=async(n,o)=>{const s=await n();if(s.Component)return{...s,pathId:o};const p=s.default,r={Component:p,pathId:o};return e.forEach((t=>{p[t]&&(r[t]=p[t])})),p.Suspense&&(r.Component=t(p,p.Suspense)),r};export{n as default};
2
2
  //# sourceMappingURL=import-route.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"import-route.js","sources":["../../src/helpers/import-route.ts"],"sourcesContent":["import type { ImmutableRouteKey } from '@remix-run/router/utils';\nimport type { IndexRouteObject, NonIndexRouteObject } from 'react-router-dom';\nimport withSuspense from '@components/with-suspense';\nimport type { FCCRoute, FCRoute } from '@interfaces/fc-route';\nimport { keys } from '@interfaces/fc-route';\n\nexport type IDynamicRoute = () => Promise<{ default: FCRoute | FCCRoute<any> }>;\n\nexport type IAsyncRoute =\n | Omit<IndexRouteObject, ImmutableRouteKey>\n | Omit<NonIndexRouteObject, ImmutableRouteKey>;\n\n/**\n * Assign route path id to component\n */\nconst assignId = (response: Record<string, any>, id?: string) => {\n if (!id) {\n return;\n }\n\n response['pathId'] = id;\n};\n\n/**\n * Import dynamic route\n */\nconst importRoute = async (route: IDynamicRoute, id?: string): Promise<IAsyncRoute> => {\n const resolved = await route();\n\n // fallback to react router export style\n if (resolved['Component']) {\n assignId(resolved, id);\n\n return resolved as IAsyncRoute;\n }\n\n const Component = resolved.default;\n const result = { Component };\n\n keys.forEach((key) => {\n if (Component[key]) {\n result[key] = Component[key];\n }\n });\n\n if (Component.Suspense) {\n result.Component = withSuspense(Component, Component.Suspense);\n }\n\n assignId(result, id);\n\n return result;\n};\n\nexport default importRoute;\n"],"names":["assignId","response","id","importRoute","async","route","resolved","Component","default","result","keys","forEach","key","Suspense","withSuspense"],"mappings":"+FAeA,MAAMA,EAAW,CAACC,EAA+BC,KAC1CA,IAILD,EAAiB,OAAIC,EAAE,EAMnBC,EAAcC,MAAOC,EAAsBH,KAC/C,MAAMI,QAAiBD,IAGvB,GAAIC,EAAoB,UAGtB,OAFAN,EAASM,EAAUJ,GAEZI,EAGT,MAAMC,EAAYD,EAASE,QACrBC,EAAS,CAAEF,aAcjB,OAZAG,EAAKC,SAASC,IACRL,EAAUK,KACZH,EAAOG,GAAOL,EAAUK,GACzB,IAGCL,EAAUM,WACZJ,EAAOF,UAAYO,EAAaP,EAAWA,EAAUM,WAGvDb,EAASS,EAAQP,GAEVO,CAAM"}
1
+ {"version":3,"file":"import-route.js","sources":["../../src/helpers/import-route.ts"],"sourcesContent":["import type { ImmutableRouteKey } from '@remix-run/router/utils';\nimport type { IndexRouteObject, NonIndexRouteObject } from 'react-router-dom';\nimport withSuspense from '@components/with-suspense';\nimport type { FCCRoute, FCRoute } from '@interfaces/fc-route';\nimport { keys } from '@interfaces/fc-route';\n\nexport type IDynamicRoute = () => Promise<{ default: FCRoute | FCCRoute<any> }>;\n\nexport type IAsyncRoute =\n | Omit<IndexRouteObject, ImmutableRouteKey>\n | Omit<NonIndexRouteObject, ImmutableRouteKey>;\n\n/**\n * Import dynamic route\n */\nconst importRoute = async (route: IDynamicRoute, id?: string): Promise<IAsyncRoute> => {\n const resolved = await route();\n\n // fallback to react router export style\n if (resolved['Component']) {\n return { ...resolved, pathId: id } as IAsyncRoute;\n }\n\n const Component = resolved.default;\n const result = { Component, pathId: id };\n\n keys.forEach((key) => {\n if (Component[key]) {\n result[key] = Component[key];\n }\n });\n\n if (Component.Suspense) {\n result.Component = withSuspense(Component, Component.Suspense);\n }\n\n return result;\n};\n\nexport default importRoute;\n"],"names":["importRoute","async","route","id","resolved","pathId","Component","default","result","keys","forEach","key","Suspense","withSuspense"],"mappings":"+FAeM,MAAAA,EAAcC,MAAOC,EAAsBC,KAC/C,MAAMC,QAAiBF,IAGvB,GAAIE,EAAoB,UACtB,MAAO,IAAKA,EAAUC,OAAQF,GAGhC,MAAMG,EAAYF,EAASG,QACrBC,EAAS,CAAEF,YAAWD,OAAQF,GAYpC,OAVAM,EAAKC,SAASC,IACRL,EAAUK,KACZH,EAAOG,GAAOL,EAAUK,GACzB,IAGCL,EAAUM,WACZJ,EAAOF,UAAYO,EAAaP,EAAWA,EAAUM,WAGhDJ,CAAM"}
@@ -1,5 +1,5 @@
1
1
  /**
2
2
  * Stop node process
3
3
  */
4
- declare const processStop: (code?: number) => never;
4
+ declare const processStop: (code?: number, isOnlyError?: boolean) => void;
5
5
  export { processStop as default };
@@ -1,2 +1,2 @@
1
- import o from"node:process";const e=(e=0)=>o.exit(e);export{e as default};
1
+ import o from"node:process";const e=(e=0,t=!1)=>{t&&0===e||o.exit(e)};export{e as default};
2
2
  //# sourceMappingURL=process-stop.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-stop.js","sources":["../../src/helpers/process-stop.ts"],"sourcesContent":["import process from 'node:process';\n\n/**\n * Stop node process\n */\nconst processStop = (code = 0) => process.exit(code);\n\nexport default processStop;\n"],"names":["processStop","code","process","exit"],"mappings":"4BAKA,MAAMA,EAAc,CAACC,EAAO,IAAMC,EAAQC,KAAKF"}
1
+ {"version":3,"file":"process-stop.js","sources":["../../src/helpers/process-stop.ts"],"sourcesContent":["import process from 'node:process';\n\n/**\n * Stop node process\n */\nconst processStop = (code = 0, isOnlyError = false) => {\n if (isOnlyError && code === 0) {\n return;\n }\n\n process.exit(code);\n};\n\nexport default processStop;\n"],"names":["processStop","code","isOnlyError","process","exit"],"mappings":"4BAKM,MAAAA,EAAc,CAACC,EAAO,EAAGC,GAAc,KACvCA,GAAwB,IAATD,GAInBE,EAAQC,KAAKH,EAAK"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/vite-ssr-boost",
3
- "version": "1.0.0-beta.33",
3
+ "version": "1.0.0-beta.35",
4
4
  "description": "Vite plugin for create awesome SSR or SPA applications on React.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -68,7 +68,7 @@ declare class Build {
68
68
  /**
69
69
  * Promisify spawn process
70
70
  */
71
- promisifyProcess(command: childProcess.ChildProcess): Promise<unknown>;
71
+ promisifyProcess(command: childProcess.ChildProcess, isRejectWarnings?: boolean): Promise<unknown>;
72
72
  /**
73
73
  * Build assets manifest file
74
74
  */
package/services/build.js CHANGED
@@ -1,2 +1,2 @@
1
- import i from"node:fs";import o from"node:path";import t from"chalk";import{resolveConfig as s}from"vite";import e from"../helpers/plugin-config.js";import n from"./server-config.js";import r from"./ssr-manifest.js";class l{isProd;nodeEnv;buildDir;outDir;serverFile;viteConfig;pluginConfig;params;constructor(i){this.params=i}async makeConfig(){const{mode:i}=this.params;this.viteConfig=await s({},"build",i,"production"===i?"production":"development"),this.pluginConfig=e(this.viteConfig),this.buildDir=o.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||"development",this.isProd="production"===this.nodeEnv}clearBuildFolder(){i.existsSync(this.buildDir)&&i.rmSync(this.buildDir,{recursive:!0})}promisifyProcess(i){const o=new Promise(((o,t)=>{i.on("exit",(i=>{o(i)})),i.on("close",(i=>{o(i)})),i.on("error",(i=>{t(i)}))}));return i.stdout?.pipe(process.stdout),i.stderr?.pipe(process.stderr),o.command=i,o}async buildManifest(){console.log(t.blue("Building routes manifest file..."));const i=n.init({isProd:this.isProd,mode:this.params.mode},{root:this.viteConfig.root});await r.get(i,{buildDir:this.viteConfig.build.outDir,viteAliases:this.viteConfig.resolve.alias}).buildRoutesManifest()}unlockRobots(){const o=`${this.buildDir}/client/robots.txt`;if(!i.existsSync(o))return void console.warn(`Failed to unlock robots.txt, file not exist: ${o}`);const s=i.readFileSync(o,{encoding:"utf-8"}).replace(/Disallow: \/$/m,"Allow: /");i.writeFileSync(o,s,{encoding:"utf-8"}),console.info(t.blue("\nrobots.txt unlocked."))}eject(){const o=`${this.buildDir}/server/start.js`;i.writeFileSync(o,"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"})}}export{l as default};
1
+ import i from"node:fs";import o from"node:path";import t from"chalk";import{resolveConfig as s}from"vite";import e from"../helpers/plugin-config.js";import n from"./server-config.js";import r from"./ssr-manifest.js";class l{isProd;nodeEnv;buildDir;outDir;serverFile;viteConfig;pluginConfig;params;constructor(i){this.params=i}async makeConfig(){const{mode:i}=this.params;this.viteConfig=await s({},"build",i,"production"===i?"production":"development"),this.pluginConfig=e(this.viteConfig),this.buildDir=o.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||"development",this.isProd="production"===this.nodeEnv}clearBuildFolder(){i.existsSync(this.buildDir)&&i.rmSync(this.buildDir,{recursive:!0})}promisifyProcess(i,o=!1){const t=new Promise(((t,s)=>{i.on("exit",(i=>{t(i)})),i.on("close",(i=>{t(i)})),i.on("error",(i=>{s(i)})),o&&i.stderr?.on("data",(i=>{const o=Buffer.from(i).toString();(o.includes("warning")||o.includes("WARNING"))&&t(1)}))}));return i.stdout?.pipe(process.stdout),i.stderr?.pipe(process.stderr),t.command=i,t}async buildManifest(){console.log(t.blue("Building routes manifest file..."));const i=n.init({isProd:this.isProd,mode:this.params.mode},{root:this.viteConfig.root});await r.get(i,{buildDir:this.viteConfig.build.outDir,viteAliases:this.viteConfig.resolve.alias}).buildRoutesManifest()}unlockRobots(){const o=`${this.buildDir}/client/robots.txt`;if(!i.existsSync(o))return void console.warn(`Failed to unlock robots.txt, file not exist: ${o}`);const s=i.readFileSync(o,{encoding:"utf-8"}).replace(/Disallow: \/$/m,"Allow: /");i.writeFileSync(o,s,{encoding:"utf-8"}),console.info(t.blue("\nrobots.txt unlocked."))}eject(){const o=`${this.buildDir}/server/start.js`;i.writeFileSync(o,"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"})}}export{l 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 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(\n {},\n 'build',\n mode,\n mode === 'production' ? 'production' : 'development',\n );\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 || 'development';\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(command: childProcess.ChildProcess): Promise<unknown> {\n const promise = 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 command.stdout?.pipe(process.stdout);\n command.stderr?.pipe(process.stderr);\n\n promise['command'] = command;\n\n return promise;\n }\n\n /**\n * Build assets manifest file\n */\n public async buildManifest(): Promise<void> {\n console.log(chalk.blue('Building routes manifest file...'));\n\n const serverConfig = ServerConfig.init(\n { isProd: this.isProd, mode: this.params.mode },\n { root: this.viteConfig.root },\n );\n\n await SsrManifest.get(serverConfig, {\n buildDir: this.viteConfig.build.outDir,\n viteAliases: this.viteConfig.resolve.alias,\n }).buildRoutesManifest();\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\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","promise","Promise","reject","on","code","message","stdout","pipe","stderr","console","log","chalk","blue","serverConfig","ServerConfig","init","SsrManifest","get","viteAliases","alias","buildRoutesManifest","unlockRobots","robotsFile","warn","data","readFileSync","encoding","replace","writeFileSync","info","eject","entrypoint"],"mappings":"wNAkBA,MAAMA,EAIGC,OAKAC,QAKAC,SAKAC,OAKAC,WAKAC,WAKAC,aAKGC,OAKVC,YAAYD,GACVE,KAAKF,OAASA,CACf,CAKMG,mBACL,MAAMC,KAAEA,GAASF,KAAKF,OAEtBE,KAAKJ,iBAAmBO,EACtB,GACA,QACAD,EACS,eAATA,EAAwB,aAAe,eAEzCF,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,cACvCX,KAAKT,OAA0B,eAAjBS,KAAKR,OACpB,CAKMoB,mBAEDC,EAAGC,WAAWd,KAAKP,WACrBoB,EAAGE,OAAOf,KAAKP,SAAU,CAAEuB,WAAW,GAEzC,CAKMC,iBAAiBC,GACtB,MAAMC,EAAU,IAAIC,SAAQ,CAACd,EAASe,KACpCH,EAAQI,GAAG,QAASC,IAClBjB,EAAQiB,EAAK,IAGfL,EAAQI,GAAG,SAAUC,IACnBjB,EAAQiB,EAAK,IAGfL,EAAQI,GAAG,SAAUE,IACnBH,EAAOG,EAAQ,GACf,IAQJ,OALAN,EAAQO,QAAQC,KAAKjB,QAAQgB,QAC7BP,EAAQS,QAAQD,KAAKjB,QAAQkB,QAE7BR,EAAiB,QAAID,EAEdC,CACR,CAKMlB,sBACL2B,QAAQC,IAAIC,EAAMC,KAAK,qCAEvB,MAAMC,EAAeC,EAAaC,KAChC,CAAE3C,OAAQS,KAAKT,OAAQW,KAAMF,KAAKF,OAAOI,MACzC,CAAEK,KAAMP,KAAKJ,WAAWW,aAGpB4B,EAAYC,IAAIJ,EAAc,CAClCvC,SAAUO,KAAKJ,WAAWY,MAAMd,OAChC2C,YAAarC,KAAKJ,WAAWU,QAAQgC,QACpCC,qBACJ,CAKMC,eACL,MAAMC,EAAa,GAAGzC,KAAKP,6BAE3B,IAAKoB,EAAGC,WAAW2B,GAGjB,YAFAb,QAAQc,KAAK,gDAAgDD,KAK/D,MAAME,EAAO9B,EACV+B,aAAaH,EAAY,CAAEI,SAAU,UACrCC,QAAQ,iBAAkB,YAE7BjC,EAAGkC,cAAcN,EAAYE,EAAM,CAAEE,SAAU,UAE/CjB,QAAQoB,KAAKlB,EAAMC,KAAK,0BACzB,CAKMkB,QACL,MAAMC,EAAa,GAAGlD,KAAKP,2BAe3BoB,EAAGkC,cAAcG,EAbf,2bAamC,CACnCL,SAAU,SAEb"}
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 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(\n {},\n 'build',\n mode,\n mode === 'production' ? 'production' : 'development',\n );\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 || 'development';\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<unknown> {\n const promise = new Promise((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 promise['command'] = command;\n\n return promise;\n }\n\n /**\n * Build assets manifest file\n */\n public async buildManifest(): Promise<void> {\n console.log(chalk.blue('Building routes manifest file...'));\n\n const serverConfig = ServerConfig.init(\n { isProd: this.isProd, mode: this.params.mode },\n { root: this.viteConfig.root },\n );\n\n await SsrManifest.get(serverConfig, {\n buildDir: this.viteConfig.build.outDir,\n viteAliases: this.viteConfig.resolve.alias,\n }).buildRoutesManifest();\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\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","log","chalk","blue","serverConfig","ServerConfig","init","SsrManifest","get","viteAliases","alias","buildRoutesManifest","unlockRobots","robotsFile","warn","data","readFileSync","encoding","replace","writeFileSync","info","eject","entrypoint"],"mappings":"wNAkBA,MAAMA,EAIGC,OAKAC,QAKAC,SAKAC,OAKAC,WAKAC,WAKAC,a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EAAc,CAClC9C,SAAUO,KAAKJ,WAAWY,MAAMd,OAChCkD,YAAa5C,KAAKJ,WAAWU,QAAQuC,QACpCC,qBACJ,CAKMC,eACL,MAAMC,EAAa,GAAGhD,KAAKP,6BAE3B,IAAKoB,EAAGC,WAAWkC,GAGjB,YAFAb,QAAQc,KAAK,gDAAgDD,KAK/D,MAAME,EAAOrC,EACVsC,aAAaH,EAAY,CAAEI,SAAU,UACrCC,QAAQ,iBAAkB,YAE7BxC,EAAGyC,cAAcN,EAAYE,EAAM,CAAEE,SAAU,UAE/CjB,QAAQoB,KAAKlB,EAAMC,KAAK,0BACzB,CAKMkB,QACL,MAAMC,EAAa,GAAGzD,KAAKP,2BAe3BoB,EAAGyC,cAAcG,EAbf,2bAamC,CACnCL,SAAU,SAEb"}
@@ -1,2 +1,2 @@
1
- import t from"node:fs";import e from"node:path";import s from"chalk";import i from"./prepare-server.js";import r from"./server-config.js";var o;!function(t){t.style="style",t.script="script",t.image="image",t.font="font"}(o||(o={}));const n="\r\n";class a{static instance=null;config;root;buildDir;manifestName="manifest.json";assetsManifest="assets-manifest.json";viteAliases;routesAssets=null;constructor(t,{buildDir:e,viteAliases:s}={}){this.config=t,this.root=t.getParams().root,this.buildDir=e,this.viteAliases=s??t.getVite()?.config?.resolve.alias}static get(t,e={}){return null===a.instance&&(a.instance=new a(t,e)),a.instance}getAssetsManifestFile(){return`${e.resolve(this.root,this.buildDir||"")}/server/${this.assetsManifest}`}loadClientManifest(){const s=e.resolve(this.root,`${this.buildDir||""}/client/${this.manifestName}`);if(!t.existsSync(s))return{};const i=JSON.parse(t.readFileSync(s,{encoding:"utf-8"}));return t.rmSync(s),i}loadAssetsManifest(){if(null!==this.routesAssets)return this.routesAssets;const e=this.getAssetsManifestFile();return t.existsSync(e)?(this.routesAssets=JSON.parse(t.readFileSync(e,{encoding:"utf-8"})),this.routesAssets):{}}async getRoutesIds(t,e){const i={};for(const r in t){const o=t[r],n=[e,r].filter(Boolean).join("-");if(o.lazy)try{const t=await o.lazy();i[n]=this.normalizeRoutePath(t?.pathId)}catch(t){console.error(s.red("Failed to load route:"),o.path,t)}else o.children&&Object.assign(i,await this.getRoutesIds(o.children,n))}return i}sortAssets(t){return t.sort(((t,e)=>t.weight===e.weight?Number(t.isNested)-Number(e.isNested):t.weight-e.weight))}getRouteAssets(t,e,s=!1){const i=[...e?.assets??[],...e?.css??[],e?.file].reduce(((t,i)=>{if(i){const r=this.getAssetType(i),o=e.isEntry&&e.file===i;r&&(t[i]={url:`/${i}`,weight:o?1.9:this.getAssetWeight(i),type:r,isNested:s,isPreload:!o})}return t}),{});return e.imports?.length&&e.imports.forEach((e=>{const s=t[e];s&&Object.assign(i,this.getRouteAssets(t,s,!0))})),i}async buildRoutesManifest(){const e=i.init(r.init({isProd:!0})),s=this.loadClientManifest(),{routes:o}=await e.loadEntrypoint(!1),n=await this.getRoutesIds(o),a=this.getRouteImportPostfix(),l={};Object.entries(n).forEach((([t,e])=>{const i=a.find((t=>void 0!==s[`${e}${t}`])),r=s[`${e}${i||""}`];l[t]=this.sortAssets(Object.values(this.getRouteAssets(s,r)))})),t.writeFileSync(this.getAssetsManifestFile(),JSON.stringify(l,null,2),{encoding:"utf-8"})}getAliases(){const t={};return this.viteAliases?.forEach((({find:e,replacement:s})=>{"string"==typeof e&&(t[e]=s)})),t}getRouteImportPostfix(){return["","/index"].map((t=>["",".js",".ts",".tsx"].map((e=>`${t}${e}`)))).flat()}normalizeRoutePath(t,s=!1){if(!t)return;let i="";if(t.startsWith("./")||t.startsWith("../"))i=e.resolve(this.root,t);else{const e=this.getAliases(),[s]=t.split("/");e[s]&&(i=t.replace(s,e[s]))}return i=i.split(e.win32.sep).join(e.posix.sep),s?i:i.replace(this.root,"").replace(/^\/|\/$/g,"")}getAssets(t){if(this.config.getVite())return this.getAssetsDev(t);const e=t?.map((({route:t})=>t.id)).filter(Boolean)??[];if(!e.length)return[];const s=this.loadAssetsManifest();return this.sortAssets(e.map((t=>s[t])).flat().filter(Boolean))}getAssetsDev(t){const e=t?.map((({route:t})=>this.normalizeRoutePath(t?.pathId,!0))).filter(Boolean)??[];if(!e.length)return[];let s={};const i=this.getRouteImportPostfix();return[`${this.root}/${this.config.getPluginConfig()?.clientFile??"client.ts"}`,...e].forEach((t=>{for(const e of i){const i=this.config.getVite()?.moduleGraph.getModuleById(`${t}${e}`);if(i){s={...s,...this.getModuleAssets(i)};break}}})),Object.values(s)}getModuleAssets(t,e=!1){if(!t?.clientImportedModules.size)return{};let i={};return t.clientImportedModules.forEach((t=>{const{file:r,clientImportedModules:n,transformResult:a}=t,l=r?.split(".").at(-1);if(r&&l&&["css","scss"].includes(l)){const t=a?.code.match(/__vite__css\s+=\s+"(?<css>.+)"/)?.groups?.css;if(t)try{i[r]={type:o.style,url:r,weight:this.getAssetWeight(r),content:JSON.parse(`{"style": "${t}"}`).style,isNested:e,isPreload:!1}}catch(t){console.warn(s.yellowBright("Failed to parse style: ",r))}}else n.size&&(i={...i,...this.getModuleAssets(t,!0)})})),i}getAssetWeight(t){switch(this.getAssetType(t)){case"style":return 1;case"script":return 2;default:return 3}}getAssetType(t){const e=t.split(".").at(-1)?.toLowerCase();switch(e){case"css":case"scss":return o.style;case"js":return o.script;case"svg":case"jpg":case"jpeg":case"png":case"webp":case"gif":case"ico":return o.image;case"ttf":case"otf":case"woff":case"woff2":return o.font;default:return null}}writeEarlyHits(t,e){e.write(`HTTP/1.1 103 Early Hints${n}`),t.forEach((({type:t,url:s})=>{t&&["style","script"].includes(t)&&e.write(`Link: <${s}>; rel=preload; as=${t}${n}`)})),e.write(n)}injectAssets({routerContext:t,html:e,res:s,hasEarlyHints:i=!1}){const r=this.getAssets(t?.matches),o=r.map((({type:t,url:e,isPreload:s,content:i=""})=>{switch(t){case"style":return this.config.getVite()?`<style data-vite-dev-id="${e}">${i}</style>`:`<link rel="stylesheet" href="${e}">`;case"script":return s?this.config.isModulePreload?`<link rel="modulepreload" as="script" crossorigin href="${e}">`:null:`<script async type="module" crossorigin src="${e}"><\/script>`}return null})).filter(Boolean);e.header=e.header.replace("</head>",`${o.join("\n")}</head>`),i&&o.length&&s.socket&&this.writeEarlyHits(r,s.socket)}}export{a as default};
1
+ import t from"node:fs";import e from"node:path";import s from"chalk";import i from"./prepare-server.js";import r from"./server-config.js";var o;!function(t){t.style="style",t.script="script",t.image="image",t.font="font"}(o||(o={}));const n="\r\n";class a{static instance=null;config;root;buildDir;manifestName="manifest.json";assetsManifest="assets-manifest.json";viteAliases;routesAssets=null;constructor(t,{buildDir:e,viteAliases:s}={}){this.config=t,this.root=t.getParams().root,this.buildDir=e,this.viteAliases=s??t.getVite()?.config?.resolve.alias}static get(t,e={}){return null===a.instance&&(a.instance=new a(t,e)),a.instance}getAssetsManifestFile(){return`${e.resolve(this.root,this.buildDir||"")}/server/${this.assetsManifest}`}loadClientManifest(){const s=e.resolve(this.root,`${this.buildDir||""}/client/${this.manifestName}`);if(!t.existsSync(s))return{};const i=JSON.parse(t.readFileSync(s,{encoding:"utf-8"}));return t.rmSync(s),i}loadAssetsManifest(){if(null!==this.routesAssets)return this.routesAssets;const e=this.getAssetsManifestFile();return t.existsSync(e)?(this.routesAssets=JSON.parse(t.readFileSync(e,{encoding:"utf-8"})),this.routesAssets):{}}async getRoutesIds(t,e){const i={};for(const r in t){const o=t[r],n=[e,r].filter(Boolean).join("-");if(o.lazy)try{const t=await o.lazy();i[n]=this.normalizeRoutePath(t?.pathId)}catch(t){console.error(s.red("Failed to load route:"),o.path,t)}else o.children&&Object.assign(i,await this.getRoutesIds(o.children,n))}return i}sortAssets(t){return t.sort(((t,e)=>t.weight===e.weight?Number(t.isNested)-Number(e.isNested):t.weight-e.weight))}getRouteAssets(t,e,s=!1){const i=[...e?.assets??[],...e?.css??[],e?.file].reduce(((t,i)=>{if(i){const r=this.getAssetType(i),o=e.isEntry&&e.file===i;r&&(t[i]={url:`/${i}`,weight:o?1.9:this.getAssetWeight(i),type:r,isNested:s,isPreload:!o})}return t}),{});return e?.imports?.length&&e.imports.forEach((e=>{const s=t[e];s&&Object.assign(i,this.getRouteAssets(t,s,!0))})),i}async buildRoutesManifest(){const e=i.init(r.init({isProd:!0})),s=this.loadClientManifest(),{routes:o}=await e.loadEntrypoint(!1),n=await this.getRoutesIds(o),a=this.getRouteImportPostfix(),l={};Object.entries(n).forEach((([t,e])=>{const i=a.find((t=>void 0!==s[`${e}${t}`])),r=s[`${e}${i||""}`];l[t]=this.sortAssets(Object.values(this.getRouteAssets(s,r)))})),t.writeFileSync(this.getAssetsManifestFile(),JSON.stringify(l,null,2),{encoding:"utf-8"})}getAliases(){const t={};return this.viteAliases?.forEach((({find:e,replacement:s})=>{"string"==typeof e&&(t[e]=s)})),t}getRouteImportPostfix(){return["","/index"].map((t=>["",".js",".ts",".tsx"].map((e=>`${t}${e}`)))).flat()}normalizeRoutePath(t,s=!1){if(!t)return;let i="";if(t.startsWith("./")||t.startsWith("../"))i=e.resolve(this.root,t);else{const e=this.getAliases(),[s]=t.split("/");e[s]&&(i=t.replace(s,e[s]))}return i=i.split(e.win32.sep).join(e.posix.sep),s?i:i.replace(this.root,"").replace(/^\/|\/$/g,"")}getAssets(t){if(this.config.getVite())return this.getAssetsDev(t);const e=t?.map((({route:t})=>t.id)).filter(Boolean)??[];if(!e.length)return[];const s=this.loadAssetsManifest();return this.sortAssets(e.map((t=>s[t])).flat().filter(Boolean))}getAssetsDev(t){const e=t?.map((({route:t})=>this.normalizeRoutePath(t?.pathId,!0))).filter(Boolean)??[];if(!e.length)return[];let s={};const i=this.getRouteImportPostfix();return[`${this.root}/${this.config.getPluginConfig()?.clientFile??"client.ts"}`,...e].forEach((t=>{for(const e of i){const i=this.config.getVite()?.moduleGraph.getModuleById(`${t}${e}`);if(i){s={...s,...this.getModuleAssets(i)};break}}})),Object.values(s)}getModuleAssets(t,e=!1){if(!t?.clientImportedModules.size)return{};let i={};return t.clientImportedModules.forEach((t=>{const{file:r,clientImportedModules:n,transformResult:a}=t,l=r?.split(".").at(-1);if(r&&l&&["css","scss"].includes(l)){const t=a?.code.match(/__vite__css\s+=\s+"(?<css>.+)"/)?.groups?.css;if(t)try{i[r]={type:o.style,url:r,weight:this.getAssetWeight(r),content:JSON.parse(`{"style": "${t}"}`).style,isNested:e,isPreload:!1}}catch(t){console.warn(s.yellowBright("Failed to parse style: ",r))}}else n.size&&(i={...i,...this.getModuleAssets(t,!0)})})),i}getAssetWeight(t){switch(this.getAssetType(t)){case"style":return 1;case"script":return 2;default:return 3}}getAssetType(t){const e=t.split(".").at(-1)?.toLowerCase();switch(e){case"css":case"scss":return o.style;case"js":return o.script;case"svg":case"jpg":case"jpeg":case"png":case"webp":case"gif":case"ico":return o.image;case"ttf":case"otf":case"woff":case"woff2":return o.font;default:return null}}writeEarlyHits(t,e){e.write(`HTTP/1.1 103 Early Hints${n}`),t.forEach((({type:t,url:s})=>{t&&["style","script"].includes(t)&&e.write(`Link: <${s}>; rel=preload; as=${t}${n}`)})),e.write(n)}injectAssets({routerContext:t,html:e,res:s,hasEarlyHints:i=!1}){const r=this.getAssets(t?.matches),o=r.map((({type:t,url:e,isPreload:s,content:i=""})=>{switch(t){case"style":return this.config.getVite()?`<style data-vite-dev-id="${e}">${i}</style>`:`<link rel="stylesheet" href="${e}">`;case"script":return s?this.config.isModulePreload?`<link rel="modulepreload" as="script" crossorigin href="${e}">`:null:`<script async type="module" crossorigin src="${e}"><\/script>`}return null})).filter(Boolean);e.header=e.header.replace("</head>",`${o.join("\n")}</head>`),i&&o.length&&s.socket&&this.writeEarlyHits(r,s.socket)}}export{a as default};
2
2
  //# sourceMappingURL=ssr-manifest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Socket } from 'node:net';\nimport path from 'node:path';\nimport type { AgnosticDataRouteMatch } from '@remix-run/router/dist/utils';\nimport chalk from 'chalk';\nimport type { RouteObject } from 'react-router-dom';\nimport type { Alias, ModuleNode } from 'vite';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerConfig from '@services/server-config';\n\ninterface ISsrManifestParams {\n buildDir?: string;\n viteAliases?: Alias[];\n}\n\ninterface IManifest {\n [path: string]: {\n assets: string[];\n css: string[];\n file: string;\n isEntry?: boolean;\n imports: string[];\n };\n}\n\nenum AssetType {\n style = 'style',\n script = 'script',\n image = 'image',\n font = 'font',\n}\n\ninterface IAsset {\n type: AssetType;\n url: string;\n weight: number;\n isNested: boolean;\n isPreload: boolean;\n content?: string;\n}\n\nconst CRLF = '\\r\\n';\n\n/**\n * Working with SSR Manifest file\n */\nclass SsrManifest {\n /**\n * Singleton\n */\n protected static instance: SsrManifest | null = null;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * Project root path\n */\n protected readonly root: string;\n\n /**\n * Build dir\n */\n protected readonly buildDir?: string;\n\n /**\n * Client manifest file name\n */\n protected readonly manifestName = 'manifest.json';\n\n /**\n * Assets manifest file name\n */\n protected readonly assetsManifest = 'assets-manifest.json';\n\n /**\n * Vite resolve aliases\n */\n protected readonly viteAliases?: Alias[];\n\n /**\n * Loaded assets manifest file\n */\n protected routesAssets: Record<string, IAsset[]> | null = null;\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, { buildDir, viteAliases }: ISsrManifestParams = {}) {\n this.config = config;\n this.root = config.getParams().root;\n this.buildDir = buildDir;\n this.viteAliases = viteAliases ?? config.getVite()?.config?.resolve.alias;\n }\n\n /**\n * Get singleton instance\n */\n public static get(config: ServerConfig, params: ISsrManifestParams = {}): SsrManifest {\n if (SsrManifest.instance === null) {\n SsrManifest.instance = new SsrManifest(config, params);\n }\n\n return SsrManifest.instance;\n }\n\n /**\n * Get assets manifest file name\n */\n protected getAssetsManifestFile(): string {\n const outDir = path.resolve(this.root, this.buildDir || '');\n\n return `${outDir}/server/${this.assetsManifest}`;\n }\n\n /**\n * Load client ssr manifest\n */\n protected loadClientManifest(): IManifest {\n const clientSsrManifest = path.resolve(\n this.root,\n `${this.buildDir || ''}/client/${this.manifestName}`,\n );\n\n if (!fs.existsSync(clientSsrManifest)) {\n return {};\n }\n\n const result = JSON.parse(\n fs.readFileSync(clientSsrManifest, { encoding: 'utf-8' }),\n ) as IManifest;\n\n fs.rmSync(clientSsrManifest);\n\n return result;\n }\n\n /**\n * Load assets manifest\n */\n protected loadAssetsManifest(): Record<string, IAsset[]> {\n if (this.routesAssets !== null) {\n return this.routesAssets;\n }\n\n const manifestFile = this.getAssetsManifestFile();\n\n if (!fs.existsSync(manifestFile)) {\n return {};\n }\n\n this.routesAssets = JSON.parse(fs.readFileSync(manifestFile, { encoding: 'utf-8' })) as Record<\n string,\n IAsset[]\n >;\n\n return this.routesAssets;\n }\n\n /**\n * Recursive walk routes and return id's with route import path\n */\n protected async getRoutesIds(\n routes: RouteObject[],\n index?: string,\n ): Promise<Record<string, string>> {\n const result = {};\n\n for (const routeIndex in routes) {\n const route = routes[routeIndex];\n const routeId = [index, routeIndex].filter(Boolean).join('-');\n\n if (route.lazy) {\n try {\n const resolvedRoute = await route.lazy();\n\n result[routeId] = this.normalizeRoutePath(resolvedRoute?.['pathId'] as string);\n } catch (e) {\n console.error(chalk.red('Failed to load route:'), route.path, e);\n }\n } else if (route.children) {\n Object.assign(result, await this.getRoutesIds(route.children, routeId));\n }\n }\n\n return result;\n }\n\n /**\n * Sort assets\n */\n protected sortAssets(assets: IAsset[]): IAsset[] {\n return assets.sort((a, b) =>\n a.weight === b.weight ? Number(a.isNested) - Number(b.isNested) : a.weight - b.weight,\n );\n }\n\n /**\n * Get recursive module assets\n */\n protected getRouteAssets(\n manifest: IManifest,\n module: IManifest[string],\n isNested = false,\n ): Record<string, IAsset> {\n const rootAssets = [...(module?.assets ?? []), ...(module?.css ?? []), module?.file];\n\n const assets = rootAssets.reduce((res, asset) => {\n if (asset) {\n const type = this.getAssetType(asset);\n const isEntry = module.isEntry && module.file === asset;\n\n // keep only js,css,image,fonts files\n if (type) {\n res[asset] = {\n url: `/${asset}`,\n weight: isEntry ? 1.9 : this.getAssetWeight(asset),\n type,\n isNested,\n isPreload: !isEntry,\n };\n }\n }\n\n return res;\n }, {} as Record<string, IAsset>);\n\n // nested assets\n if (module.imports?.length) {\n module.imports.forEach((nestedAsset) => {\n const nestedModule = manifest[nestedAsset];\n\n if (nestedModule) {\n Object.assign(assets, this.getRouteAssets(manifest, nestedModule, true));\n }\n });\n }\n\n return assets;\n }\n\n /**\n * Build routes manifest file\n */\n public async buildRoutesManifest(): Promise<void> {\n const prepareServer = PrepareServer.init(ServerConfig.init({ isProd: true }));\n const manifest = this.loadClientManifest();\n const { routes } = await prepareServer.loadEntrypoint(false);\n const routesPaths = await this.getRoutesIds(routes as RouteObject[]);\n const postfixes = this.getRouteImportPostfix();\n\n const result = {};\n\n // find route assets\n Object.entries(routesPaths).forEach(([routeId, routePath]) => {\n const routePostfix = postfixes.find((postfix) => {\n const filePath = `${routePath}${postfix}`;\n\n return manifest[filePath] !== undefined;\n });\n const routeFile = `${routePath}${routePostfix || ''}`;\n const routeMeta = manifest[routeFile];\n\n result[routeId] = this.sortAssets(Object.values(this.getRouteAssets(manifest, routeMeta)));\n });\n\n fs.writeFileSync(this.getAssetsManifestFile(), JSON.stringify(result, null, 2), {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Get vite aliases\n */\n protected getAliases(): Record<string, string> {\n const aliases = {};\n\n this.viteAliases?.forEach(({ find, replacement }) => {\n if (typeof find !== 'string') {\n return;\n }\n\n aliases[find] = replacement;\n });\n\n return aliases;\n }\n\n /**\n * Return route postfix\n */\n protected getRouteImportPostfix(): string[] {\n return ['', '/index']\n .map((prefix) => ['', '.js', '.ts', '.tsx'].map((ext) => `${prefix}${ext}`))\n .flat();\n }\n\n /**\n * Normalized route path\n */\n protected normalizeRoutePath(routePath?: string, withRoot = false): string | undefined {\n if (!routePath) {\n return;\n }\n\n let fullPath = '';\n\n // relative import\n if (routePath.startsWith('./') || routePath.startsWith('../')) {\n fullPath = path.resolve(this.root, routePath);\n } else {\n // alias import\n const aliases = this.getAliases();\n // get alias\n const [routeAlias] = routePath.split('/');\n\n if (aliases[routeAlias]) {\n fullPath = routePath.replace(routeAlias, aliases[routeAlias]);\n }\n }\n\n // normalize slashes\n fullPath = fullPath.split(path.win32.sep).join(path.posix.sep);\n\n if (withRoot) {\n return fullPath;\n }\n\n return fullPath.replace(this.root, '').replace(/^\\/|\\/$/g, '');\n }\n\n /**\n * Get route assets\n */\n protected getAssets(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n if (this.config.getVite()) {\n return this.getAssetsDev(routes);\n }\n\n const routeIds = routes?.map(({ route }) => route.id).filter(Boolean) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n const routesAssets = this.loadAssetsManifest();\n\n return this.sortAssets(\n routeIds\n .map((routeId) => routesAssets[routeId])\n .flat()\n .filter(Boolean),\n );\n }\n\n /**\n * Get development route assets\n */\n protected getAssetsDev(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n const routeIds =\n (routes\n ?.map(({ route }) => this.normalizeRoutePath(route?.['pathId'] as string, true))\n .filter(Boolean) as string[]) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n let assets: { [id: string]: IAsset } = {};\n const postfixes = this.getRouteImportPostfix();\n const rootId = `${this.root}/${this.config.getPluginConfig()?.clientFile ?? 'client.ts'}`;\n\n [rootId, ...routeIds].forEach((moduleId) => {\n for (const ext of postfixes) {\n const module = this.config.getVite()?.moduleGraph.getModuleById(`${moduleId}${ext}`);\n\n if (module) {\n assets = { ...assets, ...this.getModuleAssets(module) };\n break;\n }\n }\n });\n\n return Object.values(assets);\n }\n\n /**\n * Get module assets\n */\n protected getModuleAssets(module?: ModuleNode, isNested = false): { [id: string]: IAsset } {\n if (!module?.clientImportedModules.size) {\n return {};\n }\n\n let assets: { [id: string]: IAsset } = {};\n\n module.clientImportedModules.forEach((subModule) => {\n const { file, clientImportedModules, transformResult } = subModule;\n const ext = file?.split('.').at(-1);\n\n if (file && ext && ['css', 'scss'].includes(ext)) {\n // @TODO investigate better method?\n const code = transformResult?.code.match(/__vite__css\\s+=\\s+\"(?<css>.+)\"/)?.groups?.css;\n\n if (code) {\n try {\n assets[file] = {\n type: AssetType.style,\n url: file,\n weight: this.getAssetWeight(file),\n content: JSON.parse(`{\"style\": \"${code}\"}`).style,\n isNested,\n isPreload: false,\n };\n } catch (e) {\n console.warn(chalk.yellowBright('Failed to parse style: ', file));\n }\n }\n } else if (clientImportedModules.size) {\n assets = {\n ...assets,\n ...this.getModuleAssets(subModule, true),\n };\n }\n });\n\n return assets;\n }\n\n /**\n * Get asset weight\n */\n protected getAssetWeight(asset: string): number {\n const type = this.getAssetType(asset);\n\n switch (type) {\n case 'style':\n return 1;\n\n case 'script':\n return 2;\n\n default:\n return 3;\n }\n }\n\n /**\n * Get asset type\n */\n protected getAssetType(asset: string): AssetType | null {\n const ext = asset.split('.').at(-1)?.toLowerCase();\n\n switch (ext) {\n case 'css':\n case 'scss':\n return AssetType.style;\n\n case 'js':\n return AssetType.script;\n\n case 'svg':\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'webp':\n case 'gif':\n case 'ico':\n return AssetType.image;\n\n case 'ttf':\n case 'otf':\n case 'woff':\n case 'woff2':\n return AssetType.font;\n\n default:\n return null;\n }\n }\n\n /**\n * Write 103 Early Hits header\n */\n public writeEarlyHits(assets: IAsset[], socket: Socket): void {\n socket.write(`HTTP/1.1 103 Early Hints${CRLF}`);\n assets.forEach(({ type, url }) => {\n if (!type || !['style', 'script'].includes(type)) {\n return;\n }\n\n socket.write(`Link: <${url}>; rel=preload; as=${type}${CRLF}`);\n });\n socket.write(CRLF);\n }\n\n /**\n * Inject route assets to head html\n */\n public injectAssets({ routerContext, html, res, hasEarlyHints = false }: IRequestContext): void {\n const assets = this.getAssets(routerContext?.matches);\n const htmlAssets = assets\n .map(({ type, url, isPreload, content = '' }) => {\n switch (type) {\n case 'style':\n return this.config.getVite()\n ? `<style data-vite-dev-id=\"${url}\">${content}</style>`\n : `<link rel=\"stylesheet\" href=\"${url}\">`;\n\n case 'script':\n return isPreload\n ? this.config.isModulePreload\n ? // can reduce lighthouse performance\n `<link rel=\"modulepreload\" as=\"script\" crossorigin href=\"${url}\">`\n : null\n : `<script async type=\"module\" crossorigin src=\"${url}\"></script>`;\n }\n\n return null;\n })\n .filter(Boolean);\n\n html.header = html.header.replace('</head>', `${htmlAssets.join('\\n')}</head>`);\n\n if (hasEarlyHints && htmlAssets.length && res.socket) {\n this.writeEarlyHits(assets, res.socket);\n }\n }\n}\n\nexport default SsrManifest;\n"],"names":["AssetType","CRLF","SsrManifest","static","config","root","buildDir","manifestName","assetsManifest","viteAliases","routesAssets","constructor","this","getParams","getVite","resolve","alias","params","instance","getAssetsManifestFile","path","loadClientManifest","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","loadAssetsManifest","manifestFile","async","routes","index","routeIndex","route","routeId","filter","Boolean","join","lazy","resolvedRoute","normalizeRoutePath","e","console","error","chalk","red","children","Object","assign","getRoutesIds","sortAssets","assets","sort","a","b","weight","Number","isNested","getRouteAssets","manifest","module","css","file","reduce","res","asset","type","getAssetType","isEntry","url","getAssetWeight","isPreload","imports","length","forEach","nestedAsset","nestedModule","prepareServer","PrepareServer","init","ServerConfig","isProd","loadEntrypoint","routesPaths","postfixes","getRouteImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","values","writeFileSync","stringify","getAliases","aliases","replacement","map","prefix","ext","flat","withRoot","fullPath","startsWith","routeAlias","split","replace","win32","sep","posix","getAssets","getAssetsDev","routeIds","id","getPluginConfig","clientFile","moduleId","moduleGraph","getModuleById","getModuleAssets","clientImportedModules","size","subModule","transformResult","at","includes","code","match","groups","style","content","warn","yellowBright","toLowerCase","script","image","font","writeEarlyHits","socket","write","injectAssets","routerContext","html","hasEarlyHints","matches","htmlAssets","isModulePreload","header"],"mappings":"0IA0BA,IAAKA,GAAL,SAAKA,GACHA,EAAA,MAAA,Q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/D,MAEtC,IAAK,SACH,OAAOE,EACH/D,KAAKR,OAAOoJ,gBAEV,2DAA2D/E,MAC3D,KACF,gDAAgDA,gBAGxD,OAAO,IAAI,IAEZlC,OAAOC,SAEV4G,EAAKK,OAASL,EAAKK,OAAOzC,QAAQ,UAAW,GAAGuC,EAAW9G,KAAK,gBAE5D4G,GAAiBE,EAAW1E,QAAUT,EAAI4E,QAC5CpI,KAAKmI,eAAexF,EAAQa,EAAI4E,OAEnC"}
1
+ {"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":["import fs from 'node:fs';\nimport type { Socket } from 'node:net';\nimport path from 'node:path';\nimport type { AgnosticDataRouteMatch } from '@remix-run/router/dist/utils';\nimport chalk from 'chalk';\nimport type { RouteObject } from 'react-router-dom';\nimport type { Alias, ModuleNode } from 'vite';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport ServerConfig from '@services/server-config';\n\ninterface ISsrManifestParams {\n buildDir?: string;\n viteAliases?: Alias[];\n}\n\ninterface IManifest {\n [path: string]: {\n assets: string[];\n css: string[];\n file: string;\n isEntry?: boolean;\n imports: string[];\n };\n}\n\nenum AssetType {\n style = 'style',\n script = 'script',\n image = 'image',\n font = 'font',\n}\n\ninterface IAsset {\n type: AssetType;\n url: string;\n weight: number;\n isNested: boolean;\n isPreload: boolean;\n content?: string;\n}\n\nconst CRLF = '\\r\\n';\n\n/**\n * Working with SSR Manifest file\n */\nclass SsrManifest {\n /**\n * Singleton\n */\n protected static instance: SsrManifest | null = null;\n\n /**\n * Server config\n */\n protected readonly config: ServerConfig;\n\n /**\n * Project root path\n */\n protected readonly root: string;\n\n /**\n * Build dir\n */\n protected readonly buildDir?: string;\n\n /**\n * Client manifest file name\n */\n protected readonly manifestName = 'manifest.json';\n\n /**\n * Assets manifest file name\n */\n protected readonly assetsManifest = 'assets-manifest.json';\n\n /**\n * Vite resolve aliases\n */\n protected readonly viteAliases?: Alias[];\n\n /**\n * Loaded assets manifest file\n */\n protected routesAssets: Record<string, IAsset[]> | null = null;\n\n /**\n * @constructor\n */\n protected constructor(config: ServerConfig, { buildDir, viteAliases }: ISsrManifestParams = {}) {\n this.config = config;\n this.root = config.getParams().root;\n this.buildDir = buildDir;\n this.viteAliases = viteAliases ?? config.getVite()?.config?.resolve.alias;\n }\n\n /**\n * Get singleton instance\n */\n public static get(config: ServerConfig, params: ISsrManifestParams = {}): SsrManifest {\n if (SsrManifest.instance === null) {\n SsrManifest.instance = new SsrManifest(config, params);\n }\n\n return SsrManifest.instance;\n }\n\n /**\n * Get assets manifest file name\n */\n protected getAssetsManifestFile(): string {\n const outDir = path.resolve(this.root, this.buildDir || '');\n\n return `${outDir}/server/${this.assetsManifest}`;\n }\n\n /**\n * Load client ssr manifest\n */\n protected loadClientManifest(): IManifest {\n const clientSsrManifest = path.resolve(\n this.root,\n `${this.buildDir || ''}/client/${this.manifestName}`,\n );\n\n if (!fs.existsSync(clientSsrManifest)) {\n return {};\n }\n\n const result = JSON.parse(\n fs.readFileSync(clientSsrManifest, { encoding: 'utf-8' }),\n ) as IManifest;\n\n fs.rmSync(clientSsrManifest);\n\n return result;\n }\n\n /**\n * Load assets manifest\n */\n protected loadAssetsManifest(): Record<string, IAsset[]> {\n if (this.routesAssets !== null) {\n return this.routesAssets;\n }\n\n const manifestFile = this.getAssetsManifestFile();\n\n if (!fs.existsSync(manifestFile)) {\n return {};\n }\n\n this.routesAssets = JSON.parse(fs.readFileSync(manifestFile, { encoding: 'utf-8' })) as Record<\n string,\n IAsset[]\n >;\n\n return this.routesAssets;\n }\n\n /**\n * Recursive walk routes and return id's with route import path\n */\n protected async getRoutesIds(\n routes: RouteObject[],\n index?: string,\n ): Promise<Record<string, string>> {\n const result = {};\n\n for (const routeIndex in routes) {\n const route = routes[routeIndex];\n const routeId = [index, routeIndex].filter(Boolean).join('-');\n\n if (route.lazy) {\n try {\n const resolvedRoute = await route.lazy();\n\n result[routeId] = this.normalizeRoutePath(resolvedRoute?.['pathId'] as string);\n } catch (e) {\n console.error(chalk.red('Failed to load route:'), route.path, e);\n }\n } else if (route.children) {\n Object.assign(result, await this.getRoutesIds(route.children, routeId));\n }\n }\n\n return result;\n }\n\n /**\n * Sort assets\n */\n protected sortAssets(assets: IAsset[]): IAsset[] {\n return assets.sort((a, b) =>\n a.weight === b.weight ? Number(a.isNested) - Number(b.isNested) : a.weight - b.weight,\n );\n }\n\n /**\n * Get recursive module assets\n */\n protected getRouteAssets(\n manifest: IManifest,\n module: IManifest[string],\n isNested = false,\n ): Record<string, IAsset> {\n const rootAssets = [...(module?.assets ?? []), ...(module?.css ?? []), module?.file];\n\n const assets = rootAssets.reduce((res, asset) => {\n if (asset) {\n const type = this.getAssetType(asset);\n const isEntry = module.isEntry && module.file === asset;\n\n // keep only js,css,image,fonts files\n if (type) {\n res[asset] = {\n url: `/${asset}`,\n weight: isEntry ? 1.9 : this.getAssetWeight(asset),\n type,\n isNested,\n isPreload: !isEntry,\n };\n }\n }\n\n return res;\n }, {} as Record<string, IAsset>);\n\n // nested assets\n if (module?.imports?.length) {\n module.imports.forEach((nestedAsset) => {\n const nestedModule = manifest[nestedAsset];\n\n if (nestedModule) {\n Object.assign(assets, this.getRouteAssets(manifest, nestedModule, true));\n }\n });\n }\n\n return assets;\n }\n\n /**\n * Build routes manifest file\n */\n public async buildRoutesManifest(): Promise<void> {\n const prepareServer = PrepareServer.init(ServerConfig.init({ isProd: true }));\n const manifest = this.loadClientManifest();\n const { routes } = await prepareServer.loadEntrypoint(false);\n const routesPaths = await this.getRoutesIds(routes as RouteObject[]);\n const postfixes = this.getRouteImportPostfix();\n\n const result = {};\n\n // find route assets\n Object.entries(routesPaths).forEach(([routeId, routePath]) => {\n const routePostfix = postfixes.find((postfix) => {\n const filePath = `${routePath}${postfix}`;\n\n return manifest[filePath] !== undefined;\n });\n const routeFile = `${routePath}${routePostfix || ''}`;\n const routeMeta = manifest[routeFile];\n\n result[routeId] = this.sortAssets(Object.values(this.getRouteAssets(manifest, routeMeta)));\n });\n\n fs.writeFileSync(this.getAssetsManifestFile(), JSON.stringify(result, null, 2), {\n encoding: 'utf-8',\n });\n }\n\n /**\n * Get vite aliases\n */\n protected getAliases(): Record<string, string> {\n const aliases = {};\n\n this.viteAliases?.forEach(({ find, replacement }) => {\n if (typeof find !== 'string') {\n return;\n }\n\n aliases[find] = replacement;\n });\n\n return aliases;\n }\n\n /**\n * Return route postfix\n */\n protected getRouteImportPostfix(): string[] {\n return ['', '/index']\n .map((prefix) => ['', '.js', '.ts', '.tsx'].map((ext) => `${prefix}${ext}`))\n .flat();\n }\n\n /**\n * Normalized route path\n */\n protected normalizeRoutePath(routePath?: string, withRoot = false): string | undefined {\n if (!routePath) {\n return;\n }\n\n let fullPath = '';\n\n // relative import\n if (routePath.startsWith('./') || routePath.startsWith('../')) {\n fullPath = path.resolve(this.root, routePath);\n } else {\n // alias import\n const aliases = this.getAliases();\n // get alias\n const [routeAlias] = routePath.split('/');\n\n if (aliases[routeAlias]) {\n fullPath = routePath.replace(routeAlias, aliases[routeAlias]);\n }\n }\n\n // normalize slashes\n fullPath = fullPath.split(path.win32.sep).join(path.posix.sep);\n\n if (withRoot) {\n return fullPath;\n }\n\n return fullPath.replace(this.root, '').replace(/^\\/|\\/$/g, '');\n }\n\n /**\n * Get route assets\n */\n protected getAssets(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n if (this.config.getVite()) {\n return this.getAssetsDev(routes);\n }\n\n const routeIds = routes?.map(({ route }) => route.id).filter(Boolean) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n const routesAssets = this.loadAssetsManifest();\n\n return this.sortAssets(\n routeIds\n .map((routeId) => routesAssets[routeId])\n .flat()\n .filter(Boolean),\n );\n }\n\n /**\n * Get development route assets\n */\n protected getAssetsDev(routes?: AgnosticDataRouteMatch[]): IAsset[] {\n const routeIds =\n (routes\n ?.map(({ route }) => this.normalizeRoutePath(route?.['pathId'] as string, true))\n .filter(Boolean) as string[]) ?? [];\n\n if (!routeIds.length) {\n return [];\n }\n\n let assets: { [id: string]: IAsset } = {};\n const postfixes = this.getRouteImportPostfix();\n const rootId = `${this.root}/${this.config.getPluginConfig()?.clientFile ?? 'client.ts'}`;\n\n [rootId, ...routeIds].forEach((moduleId) => {\n for (const ext of postfixes) {\n const module = this.config.getVite()?.moduleGraph.getModuleById(`${moduleId}${ext}`);\n\n if (module) {\n assets = { ...assets, ...this.getModuleAssets(module) };\n break;\n }\n }\n });\n\n return Object.values(assets);\n }\n\n /**\n * Get module assets\n */\n protected getModuleAssets(module?: ModuleNode, isNested = false): { [id: string]: IAsset } {\n if (!module?.clientImportedModules.size) {\n return {};\n }\n\n let assets: { [id: string]: IAsset } = {};\n\n module.clientImportedModules.forEach((subModule) => {\n const { file, clientImportedModules, transformResult } = subModule;\n const ext = file?.split('.').at(-1);\n\n if (file && ext && ['css', 'scss'].includes(ext)) {\n // @TODO investigate better method?\n const code = transformResult?.code.match(/__vite__css\\s+=\\s+\"(?<css>.+)\"/)?.groups?.css;\n\n if (code) {\n try {\n assets[file] = {\n type: AssetType.style,\n url: file,\n weight: this.getAssetWeight(file),\n content: JSON.parse(`{\"style\": \"${code}\"}`).style,\n isNested,\n isPreload: false,\n };\n } catch (e) {\n console.warn(chalk.yellowBright('Failed to parse style: ', file));\n }\n }\n } else if (clientImportedModules.size) {\n assets = {\n ...assets,\n ...this.getModuleAssets(subModule, true),\n };\n }\n });\n\n return assets;\n }\n\n /**\n * Get asset weight\n */\n protected getAssetWeight(asset: string): number {\n const type = this.getAssetType(asset);\n\n switch (type) {\n case 'style':\n return 1;\n\n case 'script':\n return 2;\n\n default:\n return 3;\n }\n }\n\n /**\n * Get asset type\n */\n protected getAssetType(asset: string): AssetType | null {\n const ext = asset.split('.').at(-1)?.toLowerCase();\n\n switch (ext) {\n case 'css':\n case 'scss':\n return AssetType.style;\n\n case 'js':\n return AssetType.script;\n\n case 'svg':\n case 'jpg':\n case 'jpeg':\n case 'png':\n case 'webp':\n case 'gif':\n case 'ico':\n return AssetType.image;\n\n case 'ttf':\n case 'otf':\n case 'woff':\n case 'woff2':\n return AssetType.font;\n\n default:\n return null;\n }\n }\n\n /**\n * Write 103 Early Hits header\n */\n public writeEarlyHits(assets: IAsset[], socket: Socket): void {\n socket.write(`HTTP/1.1 103 Early Hints${CRLF}`);\n assets.forEach(({ type, url }) => {\n if (!type || !['style', 'script'].includes(type)) {\n return;\n }\n\n socket.write(`Link: <${url}>; rel=preload; as=${type}${CRLF}`);\n });\n socket.write(CRLF);\n }\n\n /**\n * Inject route assets to head html\n */\n public injectAssets({ routerContext, html, res, hasEarlyHints = false }: IRequestContext): void {\n const assets = this.getAssets(routerContext?.matches);\n const htmlAssets = assets\n .map(({ type, url, isPreload, content = '' }) => {\n switch (type) {\n case 'style':\n return this.config.getVite()\n ? `<style data-vite-dev-id=\"${url}\">${content}</style>`\n : `<link rel=\"stylesheet\" href=\"${url}\">`;\n\n case 'script':\n return isPreload\n ? this.config.isModulePreload\n ? // can reduce lighthouse performance\n `<link rel=\"modulepreload\" as=\"script\" crossorigin href=\"${url}\">`\n : null\n : `<script async type=\"module\" crossorigin src=\"${url}\"></script>`;\n }\n\n return null;\n })\n .filter(Boolean);\n\n html.header = html.header.replace('</head>', `${htmlAssets.join('\\n')}</head>`);\n\n if (hasEarlyHints && htmlAssets.length && res.socket) {\n this.writeEarlyHits(assets, res.socket);\n }\n }\n}\n\nexport default SsrManifest;\n"],"names":["AssetType","CRLF","SsrManifest","static","config","root","buildDir","manifestName","assetsManifest","viteAliases","routesAssets","constructor","this","getParams","getVite","resolve","alias","params","instance","getAssetsManifestFile","path","loadClientManifest","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","loadAssetsManifest","manifestFile","async","routes","index","routeIndex","route","routeId","filter","Boolean","join","lazy","resolvedRoute","normalizeRoutePath","e","console","error","chalk","red","children","Object","assign","getRoutesIds","sortAssets","assets","sort","a","b","weight","Number","isNested","getRouteAssets","manifest","module","css","file","reduce","res","asset","type","getAssetType","isEntry","url","getAssetWeight","isPreload","imports","length","forEach","nestedAsset","nestedModule","prepareServer","PrepareServer","init","ServerConfig","isProd","loadEntrypoint","routesPaths","postfixes","getRouteImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","values","writeFileSync","stringify","getAliases","aliases","replacement","map","prefix","ext","flat","withRoot","fullPath","startsWith","routeAlias","split","replace","win32","sep","posix","getAssets","getAssetsDev","routeIds","id","getPluginConfig","clientFile","moduleId","moduleGraph","getModuleById","getModuleAssets","clientImportedModules","size","subModule","transformResult","at","includes","code","match","groups","style","content","warn","yellowBright","toLowerCase","script","image","font","writeEarlyHits","socket","write","injectAssets","routerContext","html","hasEarlyHints","matches","htmlAssets","isModulePreload","header"],"mappings":"0IA0BA,IAAKA,GAAL,SAAKA,GACHA,EAAA,MAAA,QACAA,EAAA,OAAA,SACAA,EAAA,MAAA,QACAA,EAAA,KAAA,MACD,CALD,CAAKA,IAAAA,EAKJ,CAAA,IAWD,MAAMC,EAAO,OAKb,MAAMC,EAIMC,gBAAsC,KAK7BC,OAKAC,KAKAC,SAKAC,aAAe,gBAKfC,eAAiB,uBAKjBC,YAKTC,aAAgD,KAK1DC,YAAsBP,GAAsBE,SAAEA,EAAQG,YAAEA,GAAoC,CAAA,GAC1FG,KAAKR,OAASA,EACdQ,KAAKP,KAAOD,EAAOS,YAAYR,KAC/BO,KAAKN,SAAWA,EAChBM,KAAKH,YAAcA,GAAeL,EAAOU,WAAWV,QAAQW,QAAQC,KACrE,CAKMb,WAAWC,EAAsBa,EAA6B,IAKnE,OAJ6B,OAAzBf,EAAYgB,WACdhB,EAAYgB,SAAW,IAAIhB,EAAYE,EAAQa,IAG1Cf,EAAYgB,QACpB,CAKSC,wBAGR,MAAO,GAFQC,EAAKL,QAAQH,KAAKP,KAAMO,KAAKN,UAAY,cAE7BM,KAAKJ,gBACjC,CAKSa,qBACR,MAAMC,EAAoBF,EAAKL,QAC7BH,KAAKP,KACL,GA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AEnB,QACE,OAAO,KAEZ,CAKMC,eAAexF,EAAkByF,GACtCA,EAAOC,MAAM,2BAA2BhJ,KACxCsD,EAAOuB,SAAQ,EAAGR,OAAMG,UACjBH,GAAS,CAAC,QAAS,UAAU6D,SAAS7D,IAI3C0E,EAAOC,MAAM,UAAUxE,uBAAyBH,IAAOrE,IAAO,IAEhE+I,EAAOC,MAAMhJ,EACd,CAKMiJ,cAAaC,cAAEA,EAAaC,KAAEA,EAAIhF,IAAEA,EAAGiF,cAAEA,GAAgB,IAC9D,MAAM9F,EAAS3C,KAAKwG,UAAU+B,GAAeG,SACvCC,EAAahG,EAChBgD,KAAI,EAAGjC,OAAMG,MAAKE,YAAW6D,UAAU,OACtC,OAAQlE,GACN,IAAK,QACH,OAAO1D,KAAKR,OAAOU,UACf,4BAA4B2D,MAAQ+D,YACpC,gCAAgC/D,MAEtC,IAAK,SACH,OAAOE,EACH/D,KAAKR,OAAOoJ,gBAEV,2DAA2D/E,MAC3D,KACF,gDAAgDA,gBAGxD,OAAO,IAAI,IAEZlC,OAAOC,SAEV4G,EAAKK,OAASL,EAAKK,OAAOzC,QAAQ,UAAW,GAAGuC,EAAW9G,KAAK,gBAE5D4G,GAAiBE,EAAW1E,QAAUT,EAAI4E,QAC5CpI,KAAKmI,eAAexF,EAAQa,EAAI4E,OAEnC"}
@@ -1,2 +0,0 @@
1
- import o from"chalk";import t from"../constants/cli-context.js";import i from"../constants/cli-shortcuts.js";import r from"../helpers/plugin-config.js";import e from"../helpers/process-stop.js";let n=!1;function s(s){!async function(s){if(""===s||""===s)return void(t.server?.close((o=>e(o?1:0)))||e());if(n)return;const{config:c}=t,f=c?.getLogger(),{customShortcuts:l=[]}="object"==typeof c?.getVite()?.config?r(c.getVite().config):{},p=l.filter(Boolean).concat(i).filter((({isOnlyDev:o=!1})=>!o||o&&!c?.isProd));if("\r"===s)return f?.info("\r");"h"===s&&f?.info(["",o.bold(" Shortcuts"),...p.map((t=>o.dim(" press ")+o.bold(t.key)+o.dim(` to ${t.description}`)))].join("\n"));const m=p.find((({key:o})=>o===s));if(!m)return;n=!0,await m.action(t),n=!1}(s)}export{s as default};
2
- //# sourceMappingURL=keyboard-input.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"keyboard-input.js","sources":["../../src/cli/keyboard-input.ts"],"sourcesContent":["import chalk from 'chalk';\nimport cliContext from '@constants/cli-context';\nimport defaultShortcuts from '@constants/cli-shortcuts';\nimport getPluginConfig from '@helpers/plugin-config';\nimport processStop from '@helpers/process-stop';\n\nlet isActionRunning = false;\n\n/**\n * Handle keyboard press buttons\n */\nfunction onKeyPress(input: string): void {\n void runAction(input);\n}\n\n/**\n * Run shortcut\n */\nasync function runAction(input: string): Promise<void> {\n // ctrl+c or ctrl+d\n if (input === '\\x03' || input === '\\x04') {\n if (!cliContext.server?.close((e) => processStop(e ? 1 : 0))) {\n processStop();\n }\n\n return;\n }\n\n if (isActionRunning) {\n return;\n }\n\n const { config } = cliContext;\n const Logger = config?.getLogger();\n const { customShortcuts = [] } =\n typeof config?.getVite()?.config === 'object' ? getPluginConfig(config.getVite()!.config) : {};\n\n const shortcuts = customShortcuts\n .filter(Boolean)\n .concat(defaultShortcuts)\n .filter(({ isOnlyDev = false }) => !isOnlyDev || (isOnlyDev && !config?.isProd));\n\n // print empty line\n if (input === '\\r') {\n return Logger?.info('\\r');\n }\n\n // print help\n if (input === 'h') {\n Logger?.info(\n [\n '',\n chalk.bold(' Shortcuts'),\n ...shortcuts.map(\n (shortcut) =>\n chalk.dim(' press ') +\n chalk.bold(shortcut.key) +\n chalk.dim(` to ${shortcut.description}`),\n ),\n ].join('\\n'),\n );\n }\n\n // execute shortcut command\n const shortcut = shortcuts.find(({ key }) => key === input);\n\n if (!shortcut) {\n return;\n }\n\n isActionRunning = true;\n await shortcut.action(cliContext);\n isActionRunning = false;\n}\n\nexport default onKeyPress;\n"],"names":["isActionRunning","onKeyPress","input","async","cliContext","server","close","e","processStop","config","Logger","getLogger","customShortcuts","getVite","getPluginConfig","shortcuts","filter","Boolean","concat","defaultShortcuts","isOnlyDev","isProd","info","chalk","bold","map","shortcut","dim","key","description","join","find","action","runAction"],"mappings":"kMAMA,IAAIA,GAAkB,EAKtB,SAASC,EAAWC,IAOpBC,eAAyBD,GAEvB,GAAc,MAAVA,GAA8B,MAAVA,EAKtB,YAJKE,EAAWC,QAAQC,OAAOC,GAAMC,EAAYD,EAAI,EAAI,MACvDC,KAMJ,GAAIR,EACF,OAGF,MAAMS,OAAEA,GAAWL,EACbM,EAASD,GAAQE,aACjBC,gBAAEA,EAAkB,IACa,iBAA9BH,GAAQI,WAAWJ,OAAsBK,EAAgBL,EAAOI,UAAWJ,QAAU,CAAA,EAExFM,EAAYH,EACfI,OAAOC,SACPC,OAAOC,GACPH,QAAO,EAAGI,aAAY,MAAaA,GAAcA,IAAcX,GAAQY,SAG1E,GAAc,OAAVnB,EACF,OAAOQ,GAAQY,KAAK,MAIR,MAAVpB,GACFQ,GAAQY,KACN,CACE,GACAC,EAAMC,KAAK,kBACRT,EAAUU,KACVC,GACCH,EAAMI,IAAI,YACVJ,EAAMC,KAAKE,EAASE,KACpBL,EAAMI,IAAI,OAAOD,EAASG,kBAE9BC,KAAK,OAKX,MAAMJ,EAAWX,EAAUgB,MAAK,EAAGH,SAAUA,IAAQ1B,IAErD,IAAKwB,EACH,OAGF1B,GAAkB,QACZ0B,EAASM,OAAO5B,GACtBJ,GAAkB,CACpB,CA7DOiC,CAAU/B,EACjB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"vite-reset-cache.js","sources":["../../src/cli/vite-reset-cache.ts"],"sourcesContent":["import fs from 'node:fs';\nimport chalk from 'chalk';\nimport { resolveConfig } from 'vite';\n\n/**\n * Reset vite cache\n */\nasync function viteResetCache(): Promise<void> {\n const config = await resolveConfig({}, 'build');\n const { cacheDir } = config;\n\n if (fs.existsSync(cacheDir)) {\n fs.rmSync(cacheDir, { recursive: true, force: true });\n }\n\n console.info(chalk.dim(chalk.yellowBright('vite cache cleared.')));\n}\n\nexport default viteResetCache;\n"],"names":["async","viteResetCache","config","resolveConfig","cacheDir","fs","existsSync","rmSync","recursive","force","console","info","chalk","dim","yellowBright"],"mappings":"iFAOAA,eAAeC,IACb,MAAMC,QAAeC,EAAc,CAAE,EAAE,UACjCC,SAAEA,GAAaF,EAEjBG,EAAGC,WAAWF,IAChBC,EAAGE,OAAOH,EAAU,CAAEI,WAAW,EAAMC,OAAO,IAGhDC,QAAQC,KAAKC,EAAMC,IAAID,EAAME,aAAa,wBAC5C"}