@lomray/vite-ssr-boost 1.0.0-beta.3 → 1.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/browser/entry.d.ts +2 -2
  2. package/browser/entry.js.map +1 -1
  3. package/cli/build.d.ts +2 -1
  4. package/cli/build.js +1 -1
  5. package/cli/build.js.map +1 -1
  6. package/cli/run-dev.d.ts +2 -1
  7. package/cli/run-dev.js +1 -1
  8. package/cli/run-dev.js.map +1 -1
  9. package/cli/run-prod.d.ts +2 -1
  10. package/cli/run-prod.js +1 -1
  11. package/cli/run-prod.js.map +1 -1
  12. package/cli.js +1 -1
  13. package/cli.js.map +1 -1
  14. package/components/with-suspense.d.ts +7 -0
  15. package/components/with-suspense.js +2 -0
  16. package/components/with-suspense.js.map +1 -0
  17. package/helpers/import-route.d.ts +252 -0
  18. package/helpers/import-route.js +2 -0
  19. package/helpers/import-route.js.map +1 -0
  20. package/helpers/print-server-info.js +1 -1
  21. package/helpers/print-server-info.js.map +1 -1
  22. package/helpers/vite-aliases.d.ts +6 -0
  23. package/helpers/vite-aliases.js +2 -0
  24. package/helpers/vite-aliases.js.map +1 -0
  25. package/interfaces/fc-route.d.ts +10 -0
  26. package/interfaces/fc-route.js +2 -0
  27. package/interfaces/fc-route.js.map +1 -0
  28. package/interfaces/fc.d.ts +4 -0
  29. package/interfaces/fc.js +2 -0
  30. package/interfaces/fc.js.map +1 -0
  31. package/interfaces/route-object.d.ts +8 -0
  32. package/interfaces/route-object.js +2 -0
  33. package/interfaces/route-object.js.map +1 -0
  34. package/node/entry.d.ts +2 -2
  35. package/node/entry.js.map +1 -1
  36. package/node/server.js +1 -1
  37. package/node/server.js.map +1 -1
  38. package/package.json +7 -3
  39. package/plugin.d.ts +6 -3
  40. package/plugin.js +1 -1
  41. package/plugin.js.map +1 -1
  42. package/plugins/make-aliases.d.ts +11 -0
  43. package/plugins/make-aliases.js +2 -0
  44. package/plugins/make-aliases.js.map +1 -0
  45. package/plugins/normalize-route.d.ts +10 -0
  46. package/plugins/normalize-route.js +2 -0
  47. package/plugins/normalize-route.js.map +1 -0
  48. package/services/server-config.d.ts +6 -1
  49. package/services/server-config.js +1 -1
  50. package/services/server-config.js.map +1 -1
@@ -2,7 +2,7 @@
2
2
  import { Router as RemixRouter } from '@remix-run/router/dist/router';
3
3
  import { FC, PropsWithChildren } from 'react';
4
4
  import ReactDOM from 'react-dom/client';
5
- import { RouteObject } from 'react-router-dom';
5
+ import { TRouteObject } from "../interfaces/route-object.js";
6
6
  interface IAppClientProps<T = undefined> {
7
7
  client: T;
8
8
  }
@@ -17,5 +17,5 @@ interface IEntryClientOptions<T> {
17
17
  /**
18
18
  * Render client side application
19
19
  */
20
- declare function entry<TAppProps>(App: TApp<TAppProps>, routes: RouteObject[], { init }?: IEntryClientOptions<TAppProps>): Promise<ReactDOM.Root | void>;
20
+ declare function entry<TAppProps>(App: TApp<TAppProps>, routes: TRouteObject[], { init }?: IEntryClientOptions<TAppProps>): Promise<ReactDOM.Root | void>;
21
21
  export { entry as default, IAppClientProps, IInitPropsParams, TApp, IEntryClientOptions };
@@ -1 +1 @@
1
- {"version":3,"file":"entry.js","sources":["../../src/browser/entry.tsx"],"sourcesContent":["import type { Router as RemixRouter } from '@remix-run/router/dist/router';\nimport type { FC, PropsWithChildren } from 'react';\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport type { RouteObject } from 'react-router-dom';\nimport { createBrowserRouter, matchRoutes, RouterProvider } from 'react-router-dom';\nimport { IS_SSR_MODE } from '@constants/common';\n\nexport interface IAppClientProps<T = undefined> {\n client: T;\n}\n\nexport interface IInitPropsParams {\n isSSRMode: boolean;\n router: RemixRouter;\n}\n\nexport type TApp<T> = FC<PropsWithChildren<IAppClientProps<T>>>;\n\nexport interface IEntryClientOptions<T> {\n init?: (params: IInitPropsParams) => Promise<T>;\n}\n\n/**\n * Render client side application\n */\nasync function entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: RouteObject[],\n { init }: IEntryClientOptions<TAppProps> = {},\n): Promise<ReactDOM.Root | void> {\n const lazyMatches = matchRoutes(routes, window.location)?.filter((m) => m.route.lazy);\n\n // Load the lazy matches and update the routes before creating router,\n // so we can hydrate the SSR-rendered content synchronously\n if (lazyMatches && lazyMatches?.length > 0) {\n await Promise.all(\n lazyMatches.map(async (m) => {\n const routeModule = await m.route.lazy?.();\n\n Object.assign(m.route, {\n ...routeModule,\n lazy: undefined,\n });\n }),\n );\n }\n\n const router = createBrowserRouter(routes);\n const root = document.getElementById('root') as HTMLElement;\n const appProps = (await init?.({ isSSRMode: IS_SSR_MODE, router })) as TAppProps;\n\n const AppComponent: FC = () => (\n <App client={appProps}>\n <RouterProvider router={router} />\n </App>\n );\n\n if (!IS_SSR_MODE) {\n return ReactDOM.createRoot(root).render(<AppComponent />);\n }\n\n return ReactDOM.hydrateRoot(root, <AppComponent />);\n}\n\nexport default entry;\n"],"names":["async","entry","App","routes","init","lazyMatches","matchRoutes","window","location","filter","m","route","lazy","length","Promise","all","map","routeModule","Object","assign","undefined","router","createBrowserRouter","root","document","getElementById","appProps","isSSRMode","IS_SSR_MODE","AppComponent","React","createElement","client","RouterProvider","ReactDOM","hydrateRoot","createRoot","render"],"mappings":"sMA0BAA,eAAeC,EACbC,EACAC,GACAC,KAAEA,GAAyC,CAAA,GAE3C,MAAMC,EAAcC,EAAYH,EAAQI,OAAOC,WAAWC,QAAQC,GAAMA,EAAEC,MAAMC,OAI5EP,GAAeA,GAAaQ,OAAS,SACjCC,QAAQC,IACZV,EAAYW,KAAIhB,MAAOU,IACrB,MAAMO,QAAoBP,EAAEC,MAAMC,UAElCM,OAAOC,OAAOT,EAAEC,MAAO,IAClBM,EACHL,UAAMQ,GACN,KAKR,MAAMC,EAASC,EAAoBnB,GAC7BoB,EAAOC,SAASC,eAAe,QAC/BC,QAAkBtB,IAAO,CAAEuB,UAAWC,EAAaP,YAEnDQ,EAAmB,IACvBC,EAAAC,cAAC7B,EAAG,CAAC8B,OAAQN,GACXI,EAACC,cAAAE,GAAeZ,OAAQA,KAI5B,OAAKO,EAIEM,EAASC,YAAYZ,EAAMO,EAACC,cAAAF,EAAe,OAHzCK,EAASE,WAAWb,GAAMc,OAAOP,EAAAC,cAACF,EAAY,MAIzD"}
1
+ {"version":3,"file":"entry.js","sources":["../../src/browser/entry.tsx"],"sourcesContent":["import type { Router as RemixRouter } from '@remix-run/router/dist/router';\nimport type { FC, PropsWithChildren } from 'react';\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport type { RouteObject } from 'react-router-dom';\nimport { createBrowserRouter, matchRoutes, RouterProvider } from 'react-router-dom';\nimport { IS_SSR_MODE } from '@constants/common';\nimport type { TRouteObject } from '@interfaces/route-object';\n\nexport interface IAppClientProps<T = undefined> {\n client: T;\n}\n\nexport interface IInitPropsParams {\n isSSRMode: boolean;\n router: RemixRouter;\n}\n\nexport type TApp<T> = FC<PropsWithChildren<IAppClientProps<T>>>;\n\nexport interface IEntryClientOptions<T> {\n init?: (params: IInitPropsParams) => Promise<T>;\n}\n\n/**\n * Render client side application\n */\nasync function entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: TRouteObject[],\n { init }: IEntryClientOptions<TAppProps> = {},\n): Promise<ReactDOM.Root | void> {\n const lazyMatches = matchRoutes(routes as RouteObject[], window.location)?.filter(\n (m) => m.route.lazy,\n );\n\n // Load the lazy matches and update the routes before creating router,\n // so we can hydrate the SSR-rendered content synchronously\n if (lazyMatches && lazyMatches?.length > 0) {\n await Promise.all(\n lazyMatches.map(async (m) => {\n const routeModule = await m.route.lazy?.();\n\n Object.assign(m.route, {\n ...routeModule,\n lazy: undefined,\n });\n }),\n );\n }\n\n const router = createBrowserRouter(routes as RouteObject[]);\n const root = document.getElementById('root') as HTMLElement;\n const appProps = (await init?.({ isSSRMode: IS_SSR_MODE, router })) as TAppProps;\n\n const AppComponent: FC = () => (\n <App client={appProps}>\n <RouterProvider router={router} />\n </App>\n );\n\n if (!IS_SSR_MODE) {\n return ReactDOM.createRoot(root).render(<AppComponent />);\n }\n\n return ReactDOM.hydrateRoot(root, <AppComponent />);\n}\n\nexport default entry;\n"],"names":["async","entry","App","routes","init","lazyMatches","matchRoutes","window","location","filter","m","route","lazy","length","Promise","all","map","routeModule","Object","assign","undefined","router","createBrowserRouter","root","document","getElementById","appProps","isSSRMode","IS_SSR_MODE","AppComponent","React","createElement","client","RouterProvider","ReactDOM","hydrateRoot","createRoot","render"],"mappings":"sMA2BAA,eAAeC,EACbC,EACAC,GACAC,KAAEA,GAAyC,CAAA,GAE3C,MAAMC,EAAcC,EAAYH,EAAyBI,OAAOC,WAAWC,QACxEC,GAAMA,EAAEC,MAAMC,OAKbP,GAAeA,GAAaQ,OAAS,SACjCC,QAAQC,IACZV,EAAYW,KAAIhB,MAAOU,IACrB,MAAMO,QAAoBP,EAAEC,MAAMC,UAElCM,OAAOC,OAAOT,EAAEC,MAAO,IAClBM,EACHL,UAAMQ,GACN,KAKR,MAAMC,EAASC,EAAoBnB,GAC7BoB,EAAOC,SAASC,eAAe,QAC/BC,QAAkBtB,IAAO,CAAEuB,UAAWC,EAAaP,YAEnDQ,EAAmB,IACvBC,EAAAC,cAAC7B,EAAG,CAAC8B,OAAQN,GACXI,EAACC,cAAAE,GAAeZ,OAAQA,KAI5B,OAAKO,EAIEM,EAASC,YAAYZ,EAAMO,EAACC,cAAAF,EAAe,OAHzCK,EAASE,WAAWb,GAAMc,OAAOP,EAAAC,cAACF,EAAY,MAIzD"}
package/cli/build.d.ts CHANGED
@@ -3,9 +3,10 @@ interface IBuildParams {
3
3
  isWatch?: boolean;
4
4
  clientOptions?: string;
5
5
  serverOptions?: string;
6
+ mode?: string;
6
7
  }
7
8
  /**
8
9
  * Build production application
9
10
  */
10
- declare function build({ isOnlyClient, isWatch, clientOptions, serverOptions, }: IBuildParams): Promise<void | [unknown, unknown]>;
11
+ declare function build({ isOnlyClient, isWatch, clientOptions, serverOptions, mode, }: IBuildParams): Promise<void | [unknown, unknown]>;
11
12
  export { build as default };
package/cli/build.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:child_process";import{performance as o}from"node:perf_hooks";import i from"chalk";import{resolveConfig as r}from"vite";import t from"../constants/cli-name.js";import n from"../helpers/plugin-config.js";const s=e=>new Promise(((o,i)=>{e.on("exit",(e=>{o(e)})),e.on("close",(e=>{o(e)})),e.on("error",(e=>{i(e)}))}));async function l({isOnlyClient:l=!1,isWatch:a=!1,clientOptions:c="",serverOptions:p=""}){const m=o.now(),u=await r({},"build"),d=n(u),{outDir:f}=u.build,h=["client"],S=new AbortController,v=s(e.spawn(`vite build ${c} --emptyOutDir --outDir ${f}/client`,{signal:S.signal,stdio:"inherit",shell:!0,env:{...process.env,SSR_BOOST_IS_SSR:l?"0":"1"}}));let w;if(a||await v,l||(w=s(e.spawn(`vite build ${p} --emptyOutDir --outDir ${f}/server --ssr ${d.serverFile}`,{signal:S.signal,stdio:"inherit",shell:!0,env:{...process.env,SSR_BOOST_IS_SSR:l?"0":"1"}})),a||await w,h.push("server")),a){process.on("exit",(()=>{S.abort()}));const e=Promise.all([v,w]);return e.controller=S,e}const $=i.dim(`${i.yellowBright(h.join(","))} built in ${i.reset(i.bold(Math.ceil(o.now()-m)))} ms`);console.info(`\n ${i.green(`${i.bold(t.toUpperCase())}`)} ${$}\n`)}export{l as default};
1
+ import e from"node:child_process";import{performance as o}from"node:perf_hooks";import i from"chalk";import{resolveConfig as r}from"vite";import t from"../constants/cli-name.js";import n from"../helpers/plugin-config.js";const s=e=>new Promise(((o,i)=>{e.on("exit",(e=>{o(e)})),e.on("close",(e=>{o(e)})),e.on("error",(e=>{i(e)}))}));async function l({isOnlyClient:l=!1,isWatch:a=!1,clientOptions:c="",serverOptions:p="",mode:m=""}){const d=o.now(),u=await r({},"build"),$=n(u),{outDir:f}=u.build,h=["client"],S=new AbortController,v=m?`--mode ${m}`:"",w=s(e.spawn(`vite build ${c} --emptyOutDir --outDir ${f}/client ${v}`,{signal:S.signal,stdio:"inherit",shell:!0,env:{...process.env,SSR_BOOST_IS_SSR:l?"0":"1"}}));let b;if(a||await w,l||(b=s(e.spawn(`vite build ${p} --emptyOutDir --outDir ${f}/server --ssr ${$.serverFile} ${v}`,{signal:S.signal,stdio:"inherit",shell:!0,env:{...process.env,SSR_BOOST_IS_SSR:l?"0":"1"}})),a||await b,h.push("server")),a){process.on("exit",(()=>{S.abort()}));const e=Promise.all([w,b]);return e.controller=S,e}const O=i.dim(`${i.yellowBright(h.join(","))} built in ${i.reset(i.bold(Math.ceil(o.now()-d)))} ms`);console.info(`\n ${i.green(`${i.bold(t.toUpperCase())}`)} ${O}\n`)}export{l as default};
2
2
  //# sourceMappingURL=build.js.map
package/cli/build.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sources":["../../src/cli/build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport { resolveConfig } from 'vite';\nimport cliName from '@constants/cli-name';\nimport getPluginConfig from '@helpers/plugin-config';\n\ninterface IBuildParams {\n isOnlyClient?: boolean;\n isWatch?: boolean;\n clientOptions?: string;\n serverOptions?: string;\n}\n\n/**\n * Promisify spawn process\n */\nconst promisify = (command: childProcess.ChildProcess) =>\n new Promise((resolve, reject) => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code) => {\n resolve(code);\n });\n\n command.on('error', (message) => {\n reject(message);\n });\n });\n\n/**\n * Build production application\n */\nasync function build({\n isOnlyClient = false,\n isWatch = false,\n clientOptions = '',\n serverOptions = '',\n}: IBuildParams): Promise<void | [unknown, unknown]> {\n const perfStart = performance.now();\n const config = await resolveConfig({}, 'build');\n const pluginConfig = getPluginConfig(config);\n const { outDir } = config.build;\n const types = ['client'];\n const controller = new AbortController();\n\n // build client\n const clientProcess = promisify(\n childProcess.spawn(`vite build ${clientOptions} --emptyOutDir --outDir ${outDir}/client`, {\n signal: controller.signal,\n stdio: 'inherit',\n shell: true,\n env: {\n ...process.env,\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n },\n }),\n );\n\n if (!isWatch) {\n await clientProcess;\n }\n\n let serverProcess;\n\n if (!isOnlyClient) {\n // build server\n serverProcess = promisify(\n childProcess.spawn(\n `vite build ${serverOptions} --emptyOutDir --outDir ${outDir}/server --ssr ${pluginConfig.serverFile}`,\n {\n signal: controller.signal,\n stdio: 'inherit',\n shell: true,\n env: {\n ...process.env,\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n },\n },\n ),\n );\n\n if (!isWatch) {\n await serverProcess;\n }\n\n types.push('server');\n }\n\n if (isWatch) {\n process.on('exit', () => {\n controller.abort();\n });\n\n const buildPromise = Promise.all([clientProcess, serverProcess]);\n\n buildPromise['controller'] = controller;\n\n return buildPromise;\n }\n\n const buildDurationString = chalk.dim(\n `${chalk.yellowBright(types.join(','))} built in ${chalk.reset(\n chalk.bold(Math.ceil(performance.now() - perfStart)),\n )} ms`,\n );\n\n console.info(\n `\\n ${chalk.green(`${chalk.bold(cliName.toUpperCase())}`)} ${buildDurationString}\\n`,\n );\n}\n\nexport default build;\n"],"names":["promisify","command","Promise","resolve","reject","on","code","message","async","build","isOnlyClient","isWatch","clientOptions","serverOptions","perfStart","performance","now","config","resolveConfig","pluginConfig","getPluginConfig","outDir","types","controller","AbortController","clientProcess","childProcess","spawn","signal","stdio","shell","env","process","SSR_BOOST_IS_SSR","serverProcess","serverFile","push","abort","buildPromise","all","buildDurationString","chalk","dim","yellowBright","join","reset","bold","Math","ceil","console","info","green","cliName","toUpperCase"],"mappings":"6NAiBA,MAAMA,EAAaC,GACjB,IAAIC,SAAQ,CAACC,EAASC,KACpBH,EAAQI,GAAG,QAASC,IAClBH,EAAQG,EAAK,IAGfL,EAAQI,GAAG,SAAUC,IACnBH,EAAQG,EAAK,IAGfL,EAAQI,GAAG,SAAUE,IACnBH,EAAOG,EAAQ,GACf,IAMNC,eAAeC,GAAMC,aACnBA,GAAe,EAAKC,QACpBA,GAAU,EAAKC,cACfA,EAAgB,GAAEC,cAClBA,EAAgB,KAEhB,MAAMC,EAAYC,EAAYC,MACxBC,QAAeC,EAAc,CAAE,EAAE,SACjCC,EAAeC,EAAgBH,IAC/BI,OAAEA,GAAWJ,EAAOR,MACpBa,EAAQ,CAAC,UACTC,EAAa,IAAIC,gBAGjBC,EAAgBzB,EACpB0B,EAAaC,MAAM,cAAcf,4BAAwCS,WAAiB,CACxFO,OAAQL,EAAWK,OACnBC,MAAO,UACPC,OAAO,EACPC,IAAK,IACAC,QAAQD,IACXE,iBAAkBvB,EAAe,IAAM,QAS7C,IAAIwB,EA0BJ,GA9BKvB,SACGc,EAKHf,IAEHwB,EAAgBlC,EACd0B,EAAaC,MACX,cAAcd,4BAAwCQ,kBAAuBF,EAAagB,aAC1F,CACEP,OAAQL,EAAWK,OACnBC,MAAO,UACPC,OAAO,EACPC,IAAK,IACAC,QAAQD,IACXE,iBAAkBvB,EAAe,IAAM,QAM1CC,SACGuB,EAGRZ,EAAMc,KAAK,WAGTzB,EAAS,CACXqB,QAAQ3B,GAAG,QAAQ,KACjBkB,EAAWc,OAAO,IAGpB,MAAMC,EAAepC,QAAQqC,IAAI,CAACd,EAAeS,IAIjD,OAFAI,EAAyB,WAAIf,EAEtBe,CACR,CAED,MAAME,EAAsBC,EAAMC,IAChC,GAAGD,EAAME,aAAarB,EAAMsB,KAAK,kBAAkBH,EAAMI,MACvDJ,EAAMK,KAAKC,KAAKC,KAAKjC,EAAYC,MAAQF,WAI7CmC,QAAQC,KACN,OAAOT,EAAMU,MAAM,GAAGV,EAAMK,KAAKM,EAAQC,sBAAsBb,MAEnE"}
1
+ {"version":3,"file":"build.js","sources":["../../src/cli/build.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport { resolveConfig } from 'vite';\nimport cliName from '@constants/cli-name';\nimport getPluginConfig from '@helpers/plugin-config';\n\ninterface IBuildParams {\n isOnlyClient?: boolean;\n isWatch?: boolean;\n clientOptions?: string;\n serverOptions?: string;\n mode?: string;\n}\n\n/**\n * Promisify spawn process\n */\nconst promisify = (command: childProcess.ChildProcess) =>\n new Promise((resolve, reject) => {\n command.on('exit', (code) => {\n resolve(code);\n });\n\n command.on('close', (code) => {\n resolve(code);\n });\n\n command.on('error', (message) => {\n reject(message);\n });\n });\n\n/**\n * Build production application\n */\nasync function build({\n isOnlyClient = false,\n isWatch = false,\n clientOptions = '',\n serverOptions = '',\n mode = '',\n}: IBuildParams): Promise<void | [unknown, unknown]> {\n const perfStart = performance.now();\n const config = await resolveConfig({}, 'build');\n const pluginConfig = getPluginConfig(config);\n const { outDir } = config.build;\n const types = ['client'];\n const controller = new AbortController();\n const modeOpt = mode ? `--mode ${mode}` : '';\n\n // build client\n const clientProcess = promisify(\n childProcess.spawn(\n `vite build ${clientOptions} --emptyOutDir --outDir ${outDir}/client ${modeOpt}`,\n {\n signal: controller.signal,\n stdio: 'inherit',\n shell: true,\n env: {\n ...process.env,\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n },\n },\n ),\n );\n\n if (!isWatch) {\n await clientProcess;\n }\n\n let serverProcess;\n\n if (!isOnlyClient) {\n // build server\n serverProcess = promisify(\n childProcess.spawn(\n `vite build ${serverOptions} --emptyOutDir --outDir ${outDir}/server --ssr ${pluginConfig.serverFile} ${modeOpt}`,\n {\n signal: controller.signal,\n stdio: 'inherit',\n shell: true,\n env: {\n ...process.env,\n SSR_BOOST_IS_SSR: isOnlyClient ? '0' : '1',\n },\n },\n ),\n );\n\n if (!isWatch) {\n await serverProcess;\n }\n\n types.push('server');\n }\n\n if (isWatch) {\n process.on('exit', () => {\n controller.abort();\n });\n\n const buildPromise = Promise.all([clientProcess, serverProcess]);\n\n buildPromise['controller'] = controller;\n\n return buildPromise;\n }\n\n const buildDurationString = chalk.dim(\n `${chalk.yellowBright(types.join(','))} built in ${chalk.reset(\n chalk.bold(Math.ceil(performance.now() - perfStart)),\n )} ms`,\n );\n\n console.info(\n `\\n ${chalk.green(`${chalk.bold(cliName.toUpperCase())}`)} ${buildDurationString}\\n`,\n );\n}\n\nexport default build;\n"],"names":["promisify","command","Promise","resolve","reject","on","code","message","async","build","isOnlyClient","isWatch","clientOptions","serverOptions","mode","perfStart","performance","now","config","resolveConfig","pluginConfig","getPluginConfig","outDir","types","controller","AbortController","modeOpt","clientProcess","childProcess","spawn","signal","stdio","shell","env","process","SSR_BOOST_IS_SSR","serverProcess","serverFile","push","abort","buildPromise","all","buildDurationString","chalk","dim","yellowBright","join","reset","bold","Math","ceil","console","info","green","cliName","toUpperCase"],"mappings":"6NAkBA,MAAMA,EAAaC,GACjB,IAAIC,SAAQ,CAACC,EAASC,KACpBH,EAAQI,GAAG,QAASC,IAClBH,EAAQG,EAAK,IAGfL,EAAQI,GAAG,SAAUC,IACnBH,EAAQG,EAAK,IAGfL,EAAQI,GAAG,SAAUE,IACnBH,EAAOG,EAAQ,GACf,IAMNC,eAAeC,GAAMC,aACnBA,GAAe,EAAKC,QACpBA,GAAU,EAAKC,cACfA,EAAgB,GAAEC,cAClBA,EAAgB,GAAEC,KAClBA,EAAO,KAEP,MAAMC,EAAYC,EAAYC,MACxBC,QAAeC,EAAc,CAAE,EAAE,SACjCC,EAAeC,EAAgBH,IAC/BI,OAAEA,GAAWJ,EAAOT,MACpBc,EAAQ,CAAC,UACTC,EAAa,IAAIC,gBACjBC,EAAUZ,EAAO,UAAUA,IAAS,GAGpCa,EAAgB3B,EACpB4B,EAAaC,MACX,cAAcjB,4BAAwCU,YAAiBI,IACvE,CACEI,OAAQN,EAAWM,OACnBC,MAAO,UACPC,OAAO,EACPC,IAAK,IACAC,QAAQD,IACXE,iBAAkBzB,EAAe,IAAM,QAU/C,IAAI0B,EA0BJ,GA9BKzB,SACGgB,EAKHjB,IAEH0B,EAAgBpC,EACd4B,EAAaC,MACX,cAAchB,4BAAwCS,kBAAuBF,EAAaiB,cAAcX,IACxG,CACEI,OAAQN,EAAWM,OACnBC,MAAO,UACPC,OAAO,EACPC,IAAK,IACAC,QAAQD,IACXE,iBAAkBzB,EAAe,IAAM,QAM1CC,SACGyB,EAGRb,EAAMe,KAAK,WAGT3B,EAAS,CACXuB,QAAQ7B,GAAG,QAAQ,KACjBmB,EAAWe,OAAO,IAGpB,MAAMC,EAAetC,QAAQuC,IAAI,CAACd,EAAeS,IAIjD,OAFAI,EAAyB,WAAIhB,EAEtBgB,CACR,CAED,MAAME,EAAsBC,EAAMC,IAChC,GAAGD,EAAME,aAAatB,EAAMuB,KAAK,kBAAkBH,EAAMI,MACvDJ,EAAMK,KAAKC,KAAKC,KAAKlC,EAAYC,MAAQF,WAI7CoC,QAAQC,KACN,OAAOT,EAAMU,MAAM,GAAGV,EAAMK,KAAKM,EAAQC,sBAAsBb,MAEnE"}
package/cli/run-dev.d.ts CHANGED
@@ -5,6 +5,7 @@ interface IRunDevParams {
5
5
  version: string;
6
6
  isHost?: boolean;
7
7
  isPrintInfo?: boolean;
8
+ mode?: string;
8
9
  }
9
10
  interface IRunDevOut {
10
11
  server: Server;
@@ -13,5 +14,5 @@ interface IRunDevOut {
13
14
  /**
14
15
  * Run development server
15
16
  */
16
- declare function runDev({ version, isHost, isPrintInfo }: IRunDevParams): Promise<IRunDevOut>;
17
+ declare function runDev({ version, isHost, isPrintInfo, mode }: IRunDevParams): Promise<IRunDevOut>;
17
18
  export { runDev as default };
package/cli/run-dev.js CHANGED
@@ -1,2 +1,2 @@
1
- import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function s({version:s,isHost:e,isPrintInfo:n}){global.viteBoostStartTime=o.now();const t=i.init({isHost:e}),{run:f}=await r(t);return{server:f({version:s,isPrintInfo:n}),config:t}}export{s as default};
1
+ import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import e from"../services/server-config.js";async function i({version:i,isHost:s,isPrintInfo:n,mode:t}){global.viteBoostStartTime=o.now();const f=e.init({isHost:s,mode:t}),{run:m}=await r(f);return{server:m({version:i,isPrintInfo:n}),config:f}}export{i as default};
2
2
  //# sourceMappingURL=run-dev.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-dev.js","sources":["../../src/cli/run-dev.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunDevParams {\n version: string;\n isHost?: boolean;\n isPrintInfo?: boolean;\n}\n\ninterface IRunDevOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run development server\n */\nasync function runDev({ version, isHost, isPrintInfo }: IRunDevParams): Promise<IRunDevOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init({ isHost });\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runDev;\n"],"names":["async","runDev","version","isHost","isPrintInfo","global","viteBoostStartTime","performance","now","config","ServerConfig","init","run","createServer","server"],"mappings":"2HAmBAA,eAAeC,GAAOC,QAAEA,EAAOC,OAAEA,EAAMC,YAAEA,IACvCC,OAAOC,mBAAqBC,EAAYC,MAExC,MAAMC,EAASC,EAAaC,KAAK,CAAER,YAC7BS,IAAEA,SAAcC,EAAaJ,GAEnC,MAAO,CACLK,OAAQF,EAAI,CAAEV,UAASE,gBACvBK,SAEJ"}
1
+ {"version":3,"file":"run-dev.js","sources":["../../src/cli/run-dev.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunDevParams {\n version: string;\n isHost?: boolean;\n isPrintInfo?: boolean;\n mode?: string;\n}\n\ninterface IRunDevOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run development server\n */\nasync function runDev({ version, isHost, isPrintInfo, mode }: IRunDevParams): Promise<IRunDevOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init({ isHost, mode });\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runDev;\n"],"names":["async","runDev","version","isHost","isPrintInfo","mode","global","viteBoostStartTime","performance","now","config","ServerConfig","init","run","createServer","server"],"mappings":"2HAoBAA,eAAeC,GAAOC,QAAEA,EAAOC,OAAEA,EAAMC,YAAEA,EAAWC,KAAEA,IACpDC,OAAOC,mBAAqBC,EAAYC,MAExC,MAAMC,EAASC,EAAaC,KAAK,CAAET,SAAQE,UACrCQ,IAAEA,SAAcC,EAAaJ,GAEnC,MAAO,CACLK,OAAQF,EAAI,CAAEX,UAASE,gBACvBM,SAEJ"}
package/cli/run-prod.d.ts CHANGED
@@ -7,6 +7,7 @@ interface IRunProdParams {
7
7
  isHost?: boolean;
8
8
  isPrintInfo?: boolean;
9
9
  onlyClient?: boolean;
10
+ mode?: string;
10
11
  }
11
12
  interface IRunProdOut {
12
13
  server: Server;
@@ -15,5 +16,5 @@ interface IRunProdOut {
15
16
  /**
16
17
  * Run production server
17
18
  */
18
- declare function runProd({ version, isHost, isPrintInfo, port, onlyClient, }: IRunProdParams): Promise<IRunProdOut>;
19
+ declare function runProd({ version, isHost, isPrintInfo, port, mode, onlyClient, }: IRunProdParams): Promise<IRunProdOut>;
19
20
  export { runProd as default };
package/cli/run-prod.js CHANGED
@@ -1,2 +1,2 @@
1
- import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function n({version:n,isHost:s,isPrintInfo:t,port:e,onlyClient:f=!1}){global.viteBoostStartTime=o.now();const a=i.init({isHost:s,isProd:!0,isOnlyClient:f},{port:e}),{run:l}=await r(a);return{server:l({version:n,isPrintInfo:t}),config:a}}export{n as default};
1
+ import{performance as o}from"node:perf_hooks";import r from"../node/server.js";import i from"../services/server-config.js";async function e({version:e,isHost:n,isPrintInfo:s,port:t,mode:f,onlyClient:m=!1}){global.viteBoostStartTime=o.now();const a=i.init({isHost:n,isProd:!0,isOnlyClient:m,mode:f},{port:t}),{run:l}=await r(a);return{server:l({version:e,isPrintInfo:s}),config:a}}export{e as default};
2
2
  //# sourceMappingURL=run-prod.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-prod.js","sources":["../../src/cli/run-prod.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunProdParams {\n version: string;\n port?: number;\n isHost?: boolean;\n isPrintInfo?: boolean;\n onlyClient?: boolean; // SPA mode\n}\n\ninterface IRunProdOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run production server\n */\nasync function runProd({\n version,\n isHost,\n isPrintInfo,\n port,\n onlyClient = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init({ isHost, isProd: true, isOnlyClient: onlyClient }, { port });\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runProd;\n"],"names":["async","runProd","version","isHost","isPrintInfo","port","onlyClient","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","run","createServer","server"],"mappings":"2HAqBAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,WACJA,GAAa,IAEbC,OAAOC,mBAAqBC,EAAYC,MAExC,MAAMC,EAASC,EAAaC,KAAK,CAAEV,SAAQW,QAAQ,EAAMC,aAAcT,GAAc,CAAED,UACjFW,IAAEA,SAAcC,EAAaN,GAEnC,MAAO,CACLO,OAAQF,EAAI,CAAEd,UAASE,gBACvBO,SAEJ"}
1
+ {"version":3,"file":"run-prod.js","sources":["../../src/cli/run-prod.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport createServer from '@node/server';\nimport ServerConfig from '@services/server-config';\n\ninterface IRunProdParams {\n version: string;\n port?: number;\n isHost?: boolean;\n isPrintInfo?: boolean;\n onlyClient?: boolean; // SPA mode\n mode?: string;\n}\n\ninterface IRunProdOut {\n server: Server;\n config: ServerConfig;\n}\n\n/**\n * Run production server\n */\nasync function runProd({\n version,\n isHost,\n isPrintInfo,\n port,\n mode,\n onlyClient = false,\n}: IRunProdParams): Promise<IRunProdOut> {\n global.viteBoostStartTime = performance.now();\n\n const config = ServerConfig.init(\n { isHost, isProd: true, isOnlyClient: onlyClient, mode },\n { port },\n );\n const { run } = await createServer(config);\n\n return {\n server: run({ version, isPrintInfo }),\n config,\n };\n}\n\nexport default runProd;\n"],"names":["async","runProd","version","isHost","isPrintInfo","port","mode","onlyClient","global","viteBoostStartTime","performance","now","config","ServerConfig","init","isProd","isOnlyClient","run","createServer","server"],"mappings":"2HAsBAA,eAAeC,GAAQC,QACrBA,EAAOC,OACPA,EAAMC,YACNA,EAAWC,KACXA,EAAIC,KACJA,EAAIC,WACJA,GAAa,IAEbC,OAAOC,mBAAqBC,EAAYC,MAExC,MAAMC,EAASC,EAAaC,KAC1B,CAAEX,SAAQY,QAAQ,EAAMC,aAAcT,EAAYD,QAClD,CAAED,UAEEY,IAAEA,SAAcC,EAAaN,GAEnC,MAAO,CACLO,OAAQF,EAAI,CAAEf,UAASE,gBACvBQ,SAEJ"}
package/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as o}from"fs";import t from"chalk";import{Command as n,Option as e}from"commander";import i from"./cli/build.js";import s from"./cli/keyboard-input.js";import r from"./cli/run-dev.js";import c from"./cli/run-prod.js";import a from"./cli/vite-reset-cache.js";import p from"./constants/cli-actions.js";import d from"./constants/cli-context.js";import l from"./constants/cli-name.js";const{description:m,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",s).setEncoding("utf8").resume())},u=new n;u.name(l).description(m).version(f).hook("preAction",((o,t)=>{global.viteBoostAction=t.name()}));const O=new e("--host","Ability to access the local instance on other devices under the same network.").default(!1),w=new e("--only-client","Build/run only client side part.").default(!1),y=new e("--port [port]","Server port.").default(3e3);u.command(p.dev).description("Run development server.").addOption(O).addOption(new e("--reset-cache","Clear vite cache before run.").default(!1)).action((async({host:o,resetCache:t})=>{t&&await a();const n=async t=>{const{server:n,config:e}=await r({version:f,isHost:o,isPrintInfo:t});d.server=n,d.config=e};return d.reboot=n,v(),n()})),u.command(p.build).description("Create production build.").addOption(w).addOption(new e("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new e("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).action((async({onlyClient:o,clientOptions:t,serverOptions:n})=>{await i({isOnlyClient:o,clientOptions:t,serverOptions:n})})),u.command(p.start).description("Run production server.").addOption(O).addOption(y).addOption(w).action((({host:o,port:t,onlyClient:n})=>{const e=async e=>{const{server:i,config:s}=await c({version:f,isHost:o,isPrintInfo:e,port:t,onlyClient:n});d.server=i,d.config=s};return d.reboot=e,v(),e()})),u.command(p.preview).description("Build and preview production.").addOption(w).addOption(O).addOption(y).action((async({host:o,port:n,onlyClient:e})=>{const s=async i=>{const{server:s,config:r}=await c({version:f,isHost:o,isPrintInfo:i,port:n,onlyClient:e});s.on("listening",(()=>{setTimeout((()=>{r.getLogger().info(t.yellow("\n Running preview mode... \n"))}),0)})),d.server=s,d.config=r};d.reboot=s,v();const r=i({isWatch:!0,isOnlyClient:e,clientOptions:"-w",serverOptions:"-w"});await Promise.all([s(),r])})),u.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 s from"./cli/keyboard-input.js";import r from"./cli/run-dev.js";import a from"./cli/run-prod.js";import d from"./cli/vite-reset-cache.js";import c from"./constants/cli-actions.js";import p from"./constants/cli-context.js";import l from"./constants/cli-name.js";const{description:m,version:v}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),f=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",s).setEncoding("utf8").resume())},u=new n;u.name(l).description(m).version(v).hook("preAction",((o,e)=>{global.viteBoostAction=e.name()}));const O=new t("--host","Ability to access the local instance on other devices under the same network.").default(!1),w=new t("--only-client","Build/run only client side part.").default(!1),y=new t("--port [port]","Server port.").default(3e3),g=new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("");u.command(c.dev).description("Run development server.").addOption(O).addOption(new t("--reset-cache","Clear vite cache before run.").default(!1)).addOption(g).action((async({host:o,resetCache:e,mode:n})=>{e&&await d();const t=async e=>{const{server:t,config:i}=await r({version:v,isHost:o,isPrintInfo:e,mode:n});p.server=t,p.config=i};return p.reboot=t,f(),t()})),u.command(c.build).description("Create production build.").addOption(w).addOption(g).addOption(new t("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new t("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).action((async({onlyClient:o,clientOptions:e,serverOptions:n,mode:t})=>{await i({isOnlyClient:o,clientOptions:e,serverOptions:n,mode:t})})),u.command(c.start).description("Run production server.").addOption(O).addOption(y).addOption(w).addOption(g).action((({host:o,port:e,onlyClient:n,mode:t})=>{const i=async i=>{const{server:s,config:r}=await a({version:v,isHost:o,isPrintInfo:i,port:e,onlyClient:n,mode:t});p.server=s,p.config=r};return p.reboot=i,f(),i()})),u.command(c.preview).description("Build and preview production.").addOption(w).addOption(O).addOption(y).addOption(g).action((async({host:o,port:n,onlyClient:t,mode:s})=>{const r=async i=>{const{server:r,config:d}=await a({version:v,isHost:o,isPrintInfo:i,port:n,onlyClient:t,mode:s});r.on("listening",(()=>{setTimeout((()=>{d.getLogger().info(e.yellow("\n Running preview mode... \n"))}),0)})),p.server=r,p.config=d};p.reboot=r,f();const d=i({mode:s,isWatch:!0,isOnlyClient:t,clientOptions:"-w",serverOptions:"-w"});await Promise.all([r(),d])})),u.parse();
3
3
  //# sourceMappingURL=cli.js.map
package/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from 'fs';\nimport chalk from 'chalk';\nimport { Command, Option } from 'commander';\nimport runBuild from '@cli/build';\nimport onKeyPress from '@cli/keyboard-input';\nimport runDev from '@cli/run-dev';\nimport runProd from '@cli/run-prod';\nimport viteResetCache from '@cli/vite-reset-cache';\nimport CliActions from '@constants/cli-actions';\nimport cliContext from '@constants/cli-context';\nimport cliName from '@constants/cli-name';\n\n/**\n * Parse package meta\n */\nconst { description, version } = JSON.parse(\n readFileSync(new URL('./package.json', import.meta.url), 'utf8'),\n) as { name: string; description: string; version: string };\n\n/**\n * Enable shortcuts\n * listen keyboard command\n */\nconst enableShortcuts = (): void => {\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.on('data', onKeyPress).setEncoding('utf8').resume();\n }\n};\n\nconst program = new Command();\n\nprogram\n .name(cliName)\n .description(description)\n .version(version)\n .hook('preAction', (_, actionCommand) => {\n // pass cli action to plugin config\n global.viteBoostAction = actionCommand.name();\n });\n\n/**\n * Common options\n */\nconst hostOption = new Option(\n '--host',\n 'Ability to access the local instance on other devices under the same network.',\n).default(false);\nconst onlyClientOption = new Option('--only-client', 'Build/run only client side part.').default(\n false,\n);\nconst portOption = new Option('--port [port]', 'Server port.').default(3000);\n\n/**\n * Cli commands\n */\n\nprogram\n .command(CliActions.dev)\n .description('Run development server.')\n .addOption(hostOption)\n .addOption(new Option('--reset-cache', 'Clear vite cache before run.').default(false))\n .action(async ({ host, resetCache }) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runDev({ version, isHost: host, isPrintInfo });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.build)\n .description('Create production build.')\n .addOption(onlyClientOption)\n .addOption(\n new Option(\n '--client-options [client-options]',\n 'Pass vite build options for client. Example: --client-options=\"--ssrManifest\"',\n )\n .env('VITE_BUILD_CLIENT_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option('--server-options [server-options]', 'Pass vite build options for server.')\n .env('VITE_BUILD_SERVER_OPTIONS')\n .default(''),\n )\n .action(async ({ onlyClient, clientOptions, serverOptions }) => {\n await runBuild({ isOnlyClient: onlyClient, clientOptions, serverOptions });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .action(({ host, port, onlyClient }) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.preview)\n .description('Build and preview production.')\n .addOption(onlyClientOption)\n .addOption(hostOption)\n .addOption(portOption)\n .action(async ({ host, port, onlyClient }) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n });\n\n server.on('listening', () => {\n setTimeout(() => {\n config.getLogger().info(chalk.yellow('\\n Running preview mode... \\n'));\n }, 0);\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n const buildOptions = '-w';\n const build = runBuild({\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n });\n\n await Promise.all([command(), build]);\n });\n\nprogram.parse();\n"],"names":["description","version","JSON","parse","readFileSync","URL","url","enableShortcuts","process","stdin","isTTY","setRawMode","on","onKeyPress","setEncoding","resume","program","Command","name","cliName","hook","_","actionCommand","global","viteBoostAction","hostOption","Option","default","onlyClientOption","portOption","command","CliActions","dev","addOption","action","async","host","resetCache","viteResetCache","isPrintInfo","server","config","runDev","isHost","cliContext","reboot","build","env","onlyClient","clientOptions","serverOptions","runBuild","isOnlyClient","start","port","runProd","preview","setTimeout","getLogger","info","chalk","yellow","isWatch","Promise","all"],"mappings":";iZAiBA,MAAMA,YAAEA,EAAWC,QAAEA,GAAYC,KAAKC,MACpCC,EAAa,IAAIC,IAAI,6BAA8BC,KAAM,SAOrDC,EAAkB,KAClBC,QAAQC,MAAMC,QAChBF,QAAQC,MAAME,YAAW,GACzBH,QAAQC,MAAMG,GAAG,OAAQC,GAAYC,YAAY,QAAQC,SAC1D,EAGGC,EAAU,IAAIC,EAEpBD,EACGE,KAAKC,GACLnB,YAAYA,GACZC,QAAQA,GACRmB,KAAK,aAAa,CAACC,EAAGC,KAErBC,OAAOC,gBAAkBF,EAAcJ,MAAM,IAMjD,MAAMO,EAAa,IAAIC,EACrB,SACA,iFACAC,SAAQ,GACJC,EAAmB,IAAIF,EAAO,gBAAiB,oCAAoCC,SACvF,GAEIE,EAAa,IAAIH,EAAO,gBAAiB,gBAAgBC,QAAQ,KAMvEX,EACGc,QAAQC,EAAWC,KACnBhC,YAAY,2BACZiC,UAAUR,GACVQ,UAAU,IAAIP,EAAO,gBAAiB,gCAAgCC,SAAQ,IAC9EO,QAAOC,OAASC,OAAMC,iBACjBA,SACIC,IAGR,MAAMR,EAAUK,MAAOI,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBC,EAAO,CAAEzC,UAAS0C,OAAQP,EAAMG,gBAEjEK,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAO5B,OAJAG,EAAWC,OAASf,EAEpBvB,IAEOuB,GAAS,IAGpBd,EACGc,QAAQC,EAAWe,OACnB9C,YAAY,4BACZiC,UAAUL,GACVK,UACC,IAAIP,EACF,oCACA,iFAECqB,IAAI,6BACJpB,QAAQ,KAEZM,UACC,IAAIP,EAAO,oCAAqC,uCAC7CqB,IAAI,6BACJpB,QAAQ,KAEZO,QAAOC,OAASa,aAAYC,gBAAeC,0BACpCC,EAAS,CAAEC,aAAcJ,EAAYC,gBAAeC,iBAAgB,IAG9ElC,EACGc,QAAQC,EAAWsB,OACnBrD,YAAY,0BACZiC,UAAUR,GACVQ,UAAUJ,GACVI,UAAUL,GACVM,QAAO,EAAGE,OAAMkB,OAAMN,iBACrB,MAAMlB,EAAUK,MAAOI,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBc,EAAQ,CACvCtD,UACA0C,OAAQP,EACRG,cACAe,OACAN,eAGFJ,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAO5B,OAJAG,EAAWC,OAASf,EAEpBvB,IAEOuB,GAAS,IAGpBd,EACGc,QAAQC,EAAWyB,SACnBxD,YAAY,iCACZiC,UAAUL,GACVK,UAAUR,GACVQ,UAAUJ,GACVK,QAAOC,OAASC,OAAMkB,OAAMN,iBAC3B,MAAMlB,EAAUK,MAAOI,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBc,EAAQ,CACvCtD,UACA0C,OAAQP,EACRG,cACAe,OACAN,eAGFR,EAAO5B,GAAG,aAAa,KACrB6C,YAAW,KACThB,EAAOiB,YAAYC,KAAKC,EAAMC,OAAO,kCAAkC,GACtE,EAAE,IAGPjB,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAG5BG,EAAWC,OAASf,EAEpBvB,IAEA,MACMuC,EAAQK,EAAS,CACrBW,SAAS,EACTV,aAAcJ,EACdC,cAJmB,KAKnBC,cALmB,aAQfa,QAAQC,IAAI,CAAClC,IAAWgB,GAAO,IAGzC9B,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/keyboard-input';\nimport runDev from '@cli/run-dev';\nimport runProd from '@cli/run-prod';\nimport viteResetCache from '@cli/vite-reset-cache';\nimport CliActions from '@constants/cli-actions';\nimport cliContext from '@constants/cli-context';\nimport cliName from '@constants/cli-name';\n\n/**\n * Parse package meta\n */\nconst { description, version } = JSON.parse(\n readFileSync(new URL('./package.json', import.meta.url), 'utf8'),\n) as { name: string; description: string; version: string };\n\n/**\n * Enable shortcuts\n * listen keyboard command\n */\nconst enableShortcuts = (): void => {\n if (process.stdin.isTTY) {\n process.stdin.setRawMode(true);\n process.stdin.on('data', onKeyPress).setEncoding('utf8').resume();\n }\n};\n\nconst program = new Command();\n\nprogram\n .name(cliName)\n .description(description)\n .version(version)\n .hook('preAction', (_, actionCommand) => {\n // pass cli action to plugin config\n global.viteBoostAction = actionCommand.name();\n });\n\n/**\n * Common options\n */\nconst hostOption = new Option(\n '--host',\n 'Ability to access the local instance on other devices under the same network.',\n).default(false);\nconst onlyClientOption = new Option('--only-client', 'Build/run only client side part.').default(\n false,\n);\nconst portOption = new Option('--port [port]', 'Server port.').default(3000);\nconst envModeOption = new Option('--mode [mode]', 'Env mode.').env('VITE_ENV_MODE').default('');\n\n/**\n * Cli commands\n */\n\nprogram\n .command(CliActions.dev)\n .description('Run development server.')\n .addOption(hostOption)\n .addOption(new Option('--reset-cache', 'Clear vite cache before run.').default(false))\n .addOption(envModeOption)\n .action(async ({ host, resetCache, mode }) => {\n if (resetCache) {\n await viteResetCache();\n }\n\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runDev({ version, isHost: host, isPrintInfo, mode });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.build)\n .description('Create production build.')\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .addOption(\n new Option(\n '--client-options [client-options]',\n 'Pass vite build options for client. Example: --client-options=\"--ssrManifest\"',\n )\n .env('VITE_BUILD_CLIENT_OPTIONS')\n .default(''),\n )\n .addOption(\n new Option('--server-options [server-options]', 'Pass vite build options for server.')\n .env('VITE_BUILD_SERVER_OPTIONS')\n .default(''),\n )\n .action(async ({ onlyClient, clientOptions, serverOptions, mode }) => {\n await runBuild({ isOnlyClient: onlyClient, clientOptions, serverOptions, mode });\n });\n\nprogram\n .command(CliActions.start)\n .description('Run production server.')\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(onlyClientOption)\n .addOption(envModeOption)\n .action(({ host, port, onlyClient, mode }) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n mode,\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n return command();\n });\n\nprogram\n .command(CliActions.preview)\n .description('Build and preview production.')\n .addOption(onlyClientOption)\n .addOption(hostOption)\n .addOption(portOption)\n .addOption(envModeOption)\n .action(async ({ host, port, onlyClient, mode }) => {\n const command = async (isPrintInfo?: boolean): Promise<void> => {\n const { server, config } = await runProd({\n version,\n isHost: host,\n isPrintInfo,\n port,\n onlyClient,\n mode,\n });\n\n server.on('listening', () => {\n setTimeout(() => {\n config.getLogger().info(chalk.yellow('\\n Running preview mode... \\n'));\n }, 0);\n });\n\n cliContext.server = server;\n cliContext.config = config;\n };\n\n cliContext.reboot = command;\n\n enableShortcuts();\n\n const buildOptions = '-w';\n const build = runBuild({\n mode,\n isWatch: true,\n isOnlyClient: onlyClient,\n clientOptions: buildOptions,\n serverOptions: buildOptions,\n });\n\n await Promise.all([command(), build]);\n });\n\nprogram.parse();\n"],"names":["description","version","JSON","parse","readFileSync","URL","url","enableShortcuts","process","stdin","isTTY","setRawMode","on","onKeyPress","setEncoding","resume","program","Command","name","cliName","hook","_","actionCommand","global","viteBoostAction","hostOption","Option","default","onlyClientOption","portOption","envModeOption","env","command","CliActions","dev","addOption","action","async","host","resetCache","mode","viteResetCache","isPrintInfo","server","config","runDev","isHost","cliContext","reboot","build","onlyClient","clientOptions","serverOptions","runBuild","isOnlyClient","start","port","runProd","preview","setTimeout","getLogger","info","chalk","yellow","isWatch","Promise","all"],"mappings":";iZAiBA,MAAMA,YAAEA,EAAWC,QAAEA,GAAYC,KAAKC,MACpCC,EAAa,IAAIC,IAAI,6BAA8BC,KAAM,SAOrDC,EAAkB,KAClBC,QAAQC,MAAMC,QAChBF,QAAQC,MAAME,YAAW,GACzBH,QAAQC,MAAMG,GAAG,OAAQC,GAAYC,YAAY,QAAQC,SAC1D,EAGGC,EAAU,IAAIC,EAEpBD,EACGE,KAAKC,GACLnB,YAAYA,GACZC,QAAQA,GACRmB,KAAK,aAAa,CAACC,EAAGC,KAErBC,OAAOC,gBAAkBF,EAAcJ,MAAM,IAMjD,MAAMO,EAAa,IAAIC,EACrB,SACA,iFACAC,SAAQ,GACJC,EAAmB,IAAIF,EAAO,gBAAiB,oCAAoCC,SACvF,GAEIE,EAAa,IAAIH,EAAO,gBAAiB,gBAAgBC,QAAQ,KACjEG,EAAgB,IAAIJ,EAAO,gBAAiB,aAAaK,IAAI,iBAAiBJ,QAAQ,IAM5FX,EACGgB,QAAQC,EAAWC,KACnBlC,YAAY,2BACZmC,UAAUV,GACVU,UAAU,IAAIT,EAAO,gBAAiB,gCAAgCC,SAAQ,IAC9EQ,UAAUL,GACVM,QAAOC,OAASC,OAAMC,aAAYC,WAC7BD,SACIE,IAGR,MAAMT,EAAUK,MAAOK,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBC,EAAO,CAAE5C,UAAS6C,OAAQR,EAAMI,cAAaF,SAE9EO,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAO5B,OAJAG,EAAWC,OAAShB,EAEpBzB,IAEOyB,GAAS,IAGpBhB,EACGgB,QAAQC,EAAWgB,OACnBjD,YAAY,4BACZmC,UAAUP,GACVO,UAAUL,GACVK,UACC,IAAIT,EACF,oCACA,iFAECK,IAAI,6BACJJ,QAAQ,KAEZQ,UACC,IAAIT,EAAO,oCAAqC,uCAC7CK,IAAI,6BACJJ,QAAQ,KAEZS,QAAOC,OAASa,aAAYC,gBAAeC,gBAAeZ,iBACnDa,EAAS,CAAEC,aAAcJ,EAAYC,gBAAeC,gBAAeZ,QAAO,IAGpFxB,EACGgB,QAAQC,EAAWsB,OACnBvD,YAAY,0BACZmC,UAAUV,GACVU,UAAUN,GACVM,UAAUP,GACVO,UAAUL,GACVM,QAAO,EAAGE,OAAMkB,OAAMN,aAAYV,WACjC,MAAMR,EAAUK,MAAOK,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBa,EAAQ,CACvCxD,UACA6C,OAAQR,EACRI,cACAc,OACAN,aACAV,SAGFO,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAO5B,OAJAG,EAAWC,OAAShB,EAEpBzB,IAEOyB,GAAS,IAGpBhB,EACGgB,QAAQC,EAAWyB,SACnB1D,YAAY,iCACZmC,UAAUP,GACVO,UAAUV,GACVU,UAAUN,GACVM,UAAUL,GACVM,QAAOC,OAASC,OAAMkB,OAAMN,aAAYV,WACvC,MAAMR,EAAUK,MAAOK,IACrB,MAAMC,OAAEA,EAAMC,OAAEA,SAAiBa,EAAQ,CACvCxD,UACA6C,OAAQR,EACRI,cACAc,OACAN,aACAV,SAGFG,EAAO/B,GAAG,aAAa,KACrB+C,YAAW,KACTf,EAAOgB,YAAYC,KAAKC,EAAMC,OAAO,kCAAkC,GACtE,EAAE,IAGPhB,EAAWJ,OAASA,EACpBI,EAAWH,OAASA,CAAM,EAG5BG,EAAWC,OAAShB,EAEpBzB,IAEA,MACM0C,EAAQI,EAAS,CACrBb,OACAwB,SAAS,EACTV,aAAcJ,EACdC,cALmB,KAMnBC,cANmB,aASfa,QAAQC,IAAI,CAAClC,IAAWiB,GAAO,IAGzCjC,EAAQb"}
@@ -0,0 +1,7 @@
1
+ import { FC } from 'react';
2
+ import { FCAny, FCC } from "../interfaces/fc.js";
3
+ /**
4
+ * Wrap component in suspense
5
+ */
6
+ declare const withSuspense: <T extends Record<string, any>>(Component: FCAny<T>, Suspense: FCC<Record<string, any>>) => FC<T>;
7
+ export { withSuspense as default };
@@ -0,0 +1,2 @@
1
+ import t from"hoist-non-react-statics";import e from"react";const r=(r,o)=>{const n=t=>e.createElement(o,null,e.createElement(r,{...t}));return t(n,r),n};export{r as default};
2
+ //# sourceMappingURL=with-suspense.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"with-suspense.js","sources":["../../src/components/with-suspense.tsx"],"sourcesContent":["import hoistNonReactStatics from 'hoist-non-react-statics';\nimport type { FC } from 'react';\nimport React from 'react';\nimport type { FCAny, FCC } from '@interfaces/fc';\n\n/**\n * Wrap component in suspense\n */\nconst withSuspense = <T extends Record<string, any>>(\n Component: FCAny<T>,\n Suspense: FCC<Record<string, any>>,\n): FC<T> => {\n const Element: FC<T> = (props) => (\n <Suspense>\n <Component {...props} />\n </Suspense>\n );\n\n hoistNonReactStatics(Element, Component);\n\n return Element;\n};\n\nexport default withSuspense;\n"],"names":["withSuspense","Component","Suspense","Element","props","React","createElement","hoistNonReactStatics"],"mappings":"4DAQA,MAAMA,EAAe,CACnBC,EACAC,KAEA,MAAMC,EAAkBC,GACtBC,EAAAC,cAACJ,EAAQ,KACPG,EAAAC,cAACL,EAAc,IAAAG,KAMnB,OAFAG,EAAqBJ,EAASF,GAEvBE,CAAO"}
@@ -0,0 +1,252 @@
1
+ /// <reference types="node" />
2
+ import { IndexRouteObject, NonIndexRouteObject } from 'react-router-dom';
3
+ import { FCCRoute, FCRoute } from "../interfaces/fc-route.js";
4
+ declare enum ResultType {
5
+ data = "data",
6
+ deferred = "deferred",
7
+ redirect = "redirect",
8
+ error = "error"
9
+ }
10
+ /**
11
+ * Successful result from a loader or action
12
+ */
13
+ interface SuccessResult {
14
+ type: ResultType.data;
15
+ data: any;
16
+ statusCode?: number;
17
+ headers?: Headers;
18
+ }
19
+ /**
20
+ * Successful defer() result from a loader or action
21
+ */
22
+ interface DeferredResult {
23
+ type: ResultType.deferred;
24
+ deferredData: DeferredData;
25
+ statusCode?: number;
26
+ headers?: Headers;
27
+ }
28
+ /**
29
+ * Redirect result from a loader or action
30
+ */
31
+ interface RedirectResult {
32
+ type: ResultType.redirect;
33
+ status: number;
34
+ location: string;
35
+ revalidate: boolean;
36
+ }
37
+ /**
38
+ * Unsuccessful result from a loader or action
39
+ */
40
+ interface ErrorResult {
41
+ type: ResultType.error;
42
+ error: any;
43
+ headers?: Headers;
44
+ }
45
+ /**
46
+ * Result from a loader or action - potentially successful or unsuccessful
47
+ */
48
+ type DataResult = SuccessResult | DeferredResult | RedirectResult | ErrorResult;
49
+ type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
50
+ type UpperCaseFormMethod = Uppercase<LowerCaseFormMethod>;
51
+ /**
52
+ * Active navigation/fetcher form methods are exposed in lowercase on the
53
+ * RouterState
54
+ */
55
+ type FormMethod = LowerCaseFormMethod;
56
+ /**
57
+ * In v7, active navigation/fetcher form methods are exposed in uppercase on the
58
+ * RouterState. This is to align with the normalization done via fetch().
59
+ */
60
+ type V7_FormMethod = UpperCaseFormMethod;
61
+ type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data";
62
+ /**
63
+ * @private
64
+ * Internal interface to pass around for action submissions, not intended for
65
+ * external consumption
66
+ */
67
+ interface Submission {
68
+ formMethod: FormMethod | V7_FormMethod;
69
+ formAction: string;
70
+ formEncType: FormEncType;
71
+ formData: FormData;
72
+ }
73
+ /**
74
+ * @private
75
+ * Arguments passed to route loader/action functions. Same for now but we keep
76
+ * this as a private implementation detail in case they diverge in the future.
77
+ */
78
+ interface DataFunctionArgs {
79
+ request: Request;
80
+ params: Params;
81
+ context?: any;
82
+ }
83
+ /**
84
+ * Arguments passed to loader functions
85
+ */
86
+ interface LoaderFunctionArgs extends DataFunctionArgs {
87
+ }
88
+ /**
89
+ * Arguments passed to action functions
90
+ */
91
+ interface ActionFunctionArgs extends DataFunctionArgs {
92
+ }
93
+ /**
94
+ * Loaders and actions can return anything except `undefined` (`null` is a
95
+ * valid return value if there is no data to return). Responses are preferred
96
+ * and will ease any future migration to Remix
97
+ */
98
+ type DataFunctionValue = Response | NonNullable<unknown> | null;
99
+ /**
100
+ * Route loader function signature
101
+ */
102
+ interface LoaderFunction {
103
+ (args: LoaderFunctionArgs): Promise<DataFunctionValue> | DataFunctionValue;
104
+ }
105
+ /**
106
+ * Route action function signature
107
+ */
108
+ interface ActionFunction {
109
+ (args: ActionFunctionArgs): Promise<DataFunctionValue> | DataFunctionValue;
110
+ }
111
+ /**
112
+ * Route shouldRevalidate function signature. This runs after any submission
113
+ * (navigation or fetcher), so we flatten the navigation/fetcher submission
114
+ * onto the arguments. It shouldn't matter whether it came from a navigation
115
+ * or a fetcher, what really matters is the URLs and the formData since loaders
116
+ * have to re-run based on the data models that were potentially mutated.
117
+ */
118
+ interface ShouldRevalidateFunction {
119
+ (args: {
120
+ currentUrl: URL;
121
+ currentParams: AgnosticDataRouteMatch["params"];
122
+ nextUrl: URL;
123
+ nextParams: AgnosticDataRouteMatch["params"];
124
+ formMethod?: Submission["formMethod"];
125
+ formAction?: Submission["formAction"];
126
+ formEncType?: Submission["formEncType"];
127
+ formData?: Submission["formData"];
128
+ actionResult?: DataResult;
129
+ defaultShouldRevalidate: boolean;
130
+ }): boolean;
131
+ }
132
+ /**
133
+ * Keys we cannot change from within a lazy() function. We spread all other keys
134
+ * onto the route. Either they're meaningful to the router, or they'll get
135
+ * ignored.
136
+ */
137
+ type ImmutableRouteKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children";
138
+ /**
139
+ * lazy() function to load a route definition, which can add non-matching
140
+ * related properties to a route
141
+ */
142
+ interface LazyRouteFunction<R extends AgnosticRouteObject> {
143
+ (): Promise<Omit<R, ImmutableRouteKey>>;
144
+ }
145
+ /**
146
+ * Base RouteObject with common props shared by all types of routes
147
+ */
148
+ type AgnosticBaseRouteObject = {
149
+ caseSensitive?: boolean;
150
+ path?: string;
151
+ id?: string;
152
+ loader?: LoaderFunction;
153
+ action?: ActionFunction;
154
+ hasErrorBoundary?: boolean;
155
+ shouldRevalidate?: ShouldRevalidateFunction;
156
+ handle?: any;
157
+ lazy?: LazyRouteFunction<AgnosticBaseRouteObject>;
158
+ };
159
+ /**
160
+ * Index routes must not have children
161
+ */
162
+ type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {
163
+ children?: undefined;
164
+ index: true;
165
+ };
166
+ /**
167
+ * Non-index routes may have children, but cannot have index
168
+ */
169
+ type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {
170
+ children?: AgnosticRouteObject[];
171
+ index?: false;
172
+ };
173
+ /**
174
+ * A route object represents a logical route, with (optionally) its child
175
+ * routes organized in a tree-like structure.
176
+ */
177
+ type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject;
178
+ type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {
179
+ id: string;
180
+ };
181
+ type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {
182
+ children?: AgnosticDataRouteObject[];
183
+ id: string;
184
+ };
185
+ /**
186
+ * A data route object, which is just a RouteObject with a required unique ID
187
+ */
188
+ type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject;
189
+ /**
190
+ * The parameters that were parsed from the URL path.
191
+ */
192
+ type Params<Key extends string = string> = {
193
+ readonly [key in Key]: string | undefined;
194
+ };
195
+ /**
196
+ * A RouteMatch contains info about how a route matched a URL.
197
+ */
198
+ interface AgnosticRouteMatch<ParamKey extends string = string, RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject> {
199
+ /**
200
+ * The names and values of dynamic parameters in the URL.
201
+ */
202
+ params: Params<ParamKey>;
203
+ /**
204
+ * The portion of the URL pathname that was matched.
205
+ */
206
+ pathname: string;
207
+ /**
208
+ * The portion of the URL pathname that was matched before child routes.
209
+ */
210
+ pathnameBase: string;
211
+ /**
212
+ * The route object that was used to match.
213
+ */
214
+ route: RouteObjectType;
215
+ }
216
+ interface AgnosticDataRouteMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {
217
+ }
218
+ declare class DeferredData {
219
+ private pendingKeysSet;
220
+ private controller;
221
+ private abortPromise;
222
+ private unlistenAbortSignal;
223
+ private subscribers;
224
+ data: Record<string, unknown>;
225
+ init?: ResponseInit;
226
+ deferredKeys: string[];
227
+ constructor(data: Record<string, unknown>, responseInit?: ResponseInit);
228
+ private trackPromise;
229
+ private onSettle;
230
+ private emit;
231
+ subscribe(fn: (aborted: boolean, settledKey?: string) => void): () => boolean;
232
+ cancel(): void;
233
+ resolveData(signal: AbortSignal): Promise<boolean>;
234
+ get done(): boolean;
235
+ get unwrappedData(): {};
236
+ get pendingKeys(): string[];
237
+ }
238
+ type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
239
+ /**
240
+ * A redirect response. Sets the status code and the `Location` header.
241
+ * Defaults to "302 Found".
242
+ */
243
+ declare const redirect: RedirectFunction;
244
+ type IDynamicRoute = () => Promise<{
245
+ default: FCRoute | FCCRoute<any>;
246
+ }>;
247
+ type IAsyncRoute = Omit<IndexRouteObject, ImmutableRouteKey> | Omit<NonIndexRouteObject, ImmutableRouteKey>;
248
+ /**
249
+ * Import dynamic route
250
+ */
251
+ declare const importRoute: (route: IDynamicRoute) => Promise<IAsyncRoute>;
252
+ export { importRoute as default, IDynamicRoute, IAsyncRoute };
@@ -0,0 +1,2 @@
1
+ import e from"../components/with-suspense.js";import{keys as o}from"../interfaces/fc-route.js";const s=async s=>{const t=(await s()).default,n={Component:t};return o.forEach((e=>{t[e]&&(n[e]=t[e])})),t.Suspense&&(n.Component=e(t,t.Suspense)),n};export{s as default};
2
+ //# sourceMappingURL=import-route.js.map
@@ -0,0 +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 * Import dynamic route\n */\nconst importRoute = async (route: IDynamicRoute): Promise<IAsyncRoute> => {\n const Component = (await route()).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 return result;\n};\n\nexport default importRoute;\n"],"names":["importRoute","async","route","Component","default","result","keys","forEach","key","Suspense","withSuspense"],"mappings":"+FAeA,MAAMA,EAAcC,MAAOC,IACzB,MAAMC,SAAmBD,KAASE,QAC5BC,EAAS,CAAEF,aAYjB,OAVAG,EAAKC,SAASC,IACRL,EAAUK,KACZH,EAAOG,GAAOL,EAAUK,GACzB,IAGCL,EAAUM,WACZJ,EAAOF,UAAYO,EAAaP,EAAWA,EAAUM,WAGhDJ,CAAM"}
@@ -1,2 +1,2 @@
1
- import{performance as o}from"node:perf_hooks";import e from"chalk";import r from"../constants/cli-actions.js";import s from"../constants/cli-name.js";import t from"./print-server-urls.js";import n from"./resolve-server-urls.js";async function i(i,a,{version:l="unknown"}){const{action:m}=a.getPluginConfig()??{},{isProd:p,host:f}=a.getParams(),c=a.getLogger(),d=global.viteBoostStartTime??o.now(),g=e.dim(`ready in ${e.reset(e.bold(Math.ceil(o.now()-d)))} ms`);c.info(`\n ${e.green(`${e.bold(s.toUpperCase())} v${l}${p?e.blue(" PRODUCTION"):""}`)} ${g}\n`,{clear:!c.hasWarned});const h=a.getVite()?.config,v=await n(i,{host:f,isHttps:"boolean"==typeof h?.server.https&&h?.server.https,rawBase:h?.rawBase});if(p)t(v,(o=>c.info(o)));else{const o=a.getVite();o.resolvedUrls=v,o.printUrls()}m===r.dev&&c.info(e.dim(e.green(" ➜"))+e.dim(" press ")+e.bold("h")+e.dim(" to show help"))}export{i as default};
1
+ import{performance as o}from"node:perf_hooks";import e from"chalk";import r from"../constants/cli-actions.js";import s from"../constants/cli-name.js";import t from"./print-server-urls.js";import n from"./resolve-server-urls.js";async function i(i,a,{version:m="unknown"}){const{action:l}=a.getPluginConfig()??{},{isProd:d,host:p}=a.getParams(),f=a.getLogger(),c=global.viteBoostStartTime??o.now(),g=e.dim(`ready in ${e.reset(e.bold(Math.ceil(o.now()-c)))} ms`);f.info(`\n ${e.green(`${e.bold(s.toUpperCase())} v${m}${d?e.blue(" PRODUCTION"):""}`)} ${g}\n`,{clear:!f.hasWarned});const h=a.getVite()?.config,v=await n(i,{host:p,isHttps:"boolean"==typeof h?.server.https&&h?.server.https,rawBase:h?.rawBase}),u=h?.mode??a.mode??"unknown";if(f.info(e.dim(e.green(" ➜"))+e.dim(" Mode: ")+e.bold(u)),d)t(v,(o=>f.info(o)));else{const o=a.getVite();o.resolvedUrls=v,o.printUrls()}l===r.dev&&f.info(e.dim(e.green(" ➜"))+e.dim(" press ")+e.bold("h")+e.dim(" to show help"))}export{i as default};
2
2
  //# sourceMappingURL=print-server-info.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"print-server-info.js","sources":["../../src/helpers/print-server-info.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport CliActions from '@constants/cli-actions';\nimport cliName from '@constants/cli-name';\nimport printServerUrls from '@helpers/print-server-urls';\nimport resolveServerUrls from '@helpers/resolve-server-urls';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrintServerInfoParams {\n version?: string;\n}\n\n/**\n * Print server info\n */\nasync function printServerInfo(\n server: Server,\n config: ServerConfig,\n { version = 'unknown' }: IPrintServerInfoParams,\n): Promise<void> {\n const { action } = config.getPluginConfig() ?? {};\n const { isProd, host } = config.getParams();\n\n const Logger = config.getLogger();\n const perfStart = global.viteBoostStartTime ?? performance.now();\n const startupDurationString = chalk.dim(\n `ready in ${chalk.reset(chalk.bold(Math.ceil(performance.now() - perfStart)))} ms`,\n );\n\n Logger.info(\n `\\n ${chalk.green(\n `${chalk.bold(cliName.toUpperCase())} v${version}${isProd ? chalk.blue(' PRODUCTION') : ''}`,\n )} ${startupDurationString}\\n`,\n { clear: !Logger.hasWarned },\n );\n\n const viteConfig = config.getVite()?.config;\n const resolvedUrls = await resolveServerUrls(server, {\n host,\n isHttps: typeof viteConfig?.server.https === 'boolean' ? viteConfig?.server.https : false,\n rawBase: viteConfig?.['rawBase'],\n });\n\n if (!isProd) {\n const vite = config.getVite()!;\n\n vite.resolvedUrls = resolvedUrls;\n vite.printUrls();\n } else {\n printServerUrls(resolvedUrls, (msg) => Logger.info(msg));\n }\n\n if (action === CliActions.dev) {\n Logger.info(\n chalk.dim(chalk.green(' ➜')) +\n chalk.dim(' press ') +\n chalk.bold('h') +\n chalk.dim(' to show help'),\n );\n }\n}\n\nexport default printServerInfo;\n"],"names":["async","printServerInfo","server","config","version","action","getPluginConfig","isProd","host","getParams","Logger","getLogger","perfStart","global","viteBoostStartTime","performance","now","startupDurationString","chalk","dim","reset","bold","Math","ceil","info","green","cliName","toUpperCase","blue","clear","hasWarned","viteConfig","getVite","resolvedUrls","resolveServerUrls","isHttps","https","rawBase","printServerUrls","msg","vite","printUrls","CliActions","dev"],"mappings":"oOAgBAA,eAAeC,EACbC,EACAC,GACAC,QAAEA,EAAU,YAEZ,MAAMC,OAAEA,GAAWF,EAAOG,mBAAqB,CAAA,GACzCC,OAAEA,EAAMC,KAAEA,GAASL,EAAOM,YAE1BC,EAASP,EAAOQ,YAChBC,EAAYC,OAAOC,oBAAsBC,EAAYC,MACrDC,EAAwBC,EAAMC,IAClC,YAAYD,EAAME,MAAMF,EAAMG,KAAKC,KAAKC,KAAKR,EAAYC,MAAQJ,WAGnEF,EAAOc,KACL,OAAON,EAAMO,MACX,GAAGP,EAAMG,KAAKK,EAAQC,mBAAmBvB,IAAUG,EAASW,EAAMU,KAAK,eAAiB,UACpFX,MACN,CAAEY,OAAQnB,EAAOoB,YAGnB,MAAMC,EAAa5B,EAAO6B,WAAW7B,OAC/B8B,QAAqBC,EAAkBhC,EAAQ,CACnDM,OACA2B,QAA6C,kBAA7BJ,GAAY7B,OAAOkC,OAAsBL,GAAY7B,OAAOkC,MAC5EC,QAASN,GAAsB,UAGjC,GAAKxB,EAMH+B,EAAgBL,GAAeM,GAAQ7B,EAAOc,KAAKe,SANxC,CACX,MAAMC,EAAOrC,EAAO6B,UAEpBQ,EAAKP,aAAeA,EACpBO,EAAKC,WACN,CAIGpC,IAAWqC,EAAWC,KACxBjC,EAAOc,KACLN,EAAMC,IAAID,EAAMO,MAAM,QACpBP,EAAMC,IAAI,YACVD,EAAMG,KAAK,KACXH,EAAMC,IAAI,iBAGlB"}
1
+ {"version":3,"file":"print-server-info.js","sources":["../../src/helpers/print-server-info.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport chalk from 'chalk';\nimport CliActions from '@constants/cli-actions';\nimport cliName from '@constants/cli-name';\nimport printServerUrls from '@helpers/print-server-urls';\nimport resolveServerUrls from '@helpers/resolve-server-urls';\nimport type ServerConfig from '@services/server-config';\n\ninterface IPrintServerInfoParams {\n version?: string;\n}\n\n/**\n * Print server info\n */\nasync function printServerInfo(\n server: Server,\n config: ServerConfig,\n { version = 'unknown' }: IPrintServerInfoParams,\n): Promise<void> {\n const { action } = config.getPluginConfig() ?? {};\n const { isProd, host } = config.getParams();\n\n const Logger = config.getLogger();\n const perfStart = global.viteBoostStartTime ?? performance.now();\n const startupDurationString = chalk.dim(\n `ready in ${chalk.reset(chalk.bold(Math.ceil(performance.now() - perfStart)))} ms`,\n );\n\n Logger.info(\n `\\n ${chalk.green(\n `${chalk.bold(cliName.toUpperCase())} v${version}${isProd ? chalk.blue(' PRODUCTION') : ''}`,\n )} ${startupDurationString}\\n`,\n { clear: !Logger.hasWarned },\n );\n\n const viteConfig = config.getVite()?.config;\n const resolvedUrls = await resolveServerUrls(server, {\n host,\n isHttps: typeof viteConfig?.server.https === 'boolean' ? viteConfig?.server.https : false,\n rawBase: viteConfig?.['rawBase'],\n });\n const mode = viteConfig?.mode ?? config.mode ?? 'unknown';\n\n Logger.info(chalk.dim(chalk.green(' ➜')) + chalk.dim(' Mode: ') + chalk.bold(mode));\n\n if (!isProd) {\n const vite = config.getVite()!;\n\n vite.resolvedUrls = resolvedUrls;\n vite.printUrls();\n } else {\n printServerUrls(resolvedUrls, (msg) => Logger.info(msg));\n }\n\n if (action === CliActions.dev) {\n Logger.info(\n chalk.dim(chalk.green(' ➜')) +\n chalk.dim(' press ') +\n chalk.bold('h') +\n chalk.dim(' to show help'),\n );\n }\n}\n\nexport default printServerInfo;\n"],"names":["async","printServerInfo","server","config","version","action","getPluginConfig","isProd","host","getParams","Logger","getLogger","perfStart","global","viteBoostStartTime","performance","now","startupDurationString","chalk","dim","reset","bold","Math","ceil","info","green","cliName","toUpperCase","blue","clear","hasWarned","viteConfig","getVite","resolvedUrls","resolveServerUrls","isHttps","https","rawBase","mode","printServerUrls","msg","vite","printUrls","CliActions","dev"],"mappings":"oOAgBAA,eAAeC,EACbC,EACAC,GACAC,QAAEA,EAAU,YAEZ,MAAMC,OAAEA,GAAWF,EAAOG,mBAAqB,CAAA,GACzCC,OAAEA,EAAMC,KAAEA,GAASL,EAAOM,YAE1BC,EAASP,EAAOQ,YAChBC,EAAYC,OAAOC,oBAAsBC,EAAYC,MACrDC,EAAwBC,EAAMC,IAClC,YAAYD,EAAME,MAAMF,EAAMG,KAAKC,KAAKC,KAAKR,EAAYC,MAAQJ,WAGnEF,EAAOc,KACL,OAAON,EAAMO,MACX,GAAGP,EAAMG,KAAKK,EAAQC,mBAAmBvB,IAAUG,EAASW,EAAMU,KAAK,eAAiB,UACpFX,MACN,CAAEY,OAAQnB,EAAOoB,YAGnB,MAAMC,EAAa5B,EAAO6B,WAAW7B,OAC/B8B,QAAqBC,EAAkBhC,EAAQ,CACnDM,OACA2B,QAA6C,kBAA7BJ,GAAY7B,OAAOkC,OAAsBL,GAAY7B,OAAOkC,MAC5EC,QAASN,GAAsB,UAE3BO,EAAOP,GAAYO,MAAQnC,EAAOmC,MAAQ,UAIhD,GAFA5B,EAAOc,KAAKN,EAAMC,IAAID,EAAMO,MAAM,QAAUP,EAAMC,IAAI,eAAiBD,EAAMG,KAAKiB,IAE7E/B,EAMHgC,EAAgBN,GAAeO,GAAQ9B,EAAOc,KAAKgB,SANxC,CACX,MAAMC,EAAOtC,EAAO6B,UAEpBS,EAAKR,aAAeA,EACpBQ,EAAKC,WACN,CAIGrC,IAAWsC,EAAWC,KACxBlC,EAAOc,KACLN,EAAMC,IAAID,EAAMO,MAAM,QACpBP,EAAMC,IAAI,YACVD,EAAMG,KAAK,KACXH,EAAMC,IAAI,iBAGlB"}
@@ -0,0 +1,6 @@
1
+ import { Alias } from 'vite';
2
+ /**
3
+ * Set vite aliases
4
+ */
5
+ declare const viteAliases: (aliases: [string, string][], root?: string) => Alias[];
6
+ export { viteAliases as default };
@@ -0,0 +1,2 @@
1
+ import{fileURLToPath as e,URL as r}from"node:url";const a=e=>e.replace("./","/").replace(/([^:]\/)\/+/g,"$1"),p=(p,t="")=>p.map((([p,l])=>({find:p,replacement:e(new r(`${t}${a(l)}`,import.meta.url))})));export{p as default};
2
+ //# sourceMappingURL=vite-aliases.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-aliases.js","sources":["../../src/helpers/vite-aliases.ts"],"sourcesContent":["import { fileURLToPath, URL } from 'node:url';\nimport type { Alias } from 'vite';\n\nconst cleanupPath = (path: string) => path.replace('./', '/').replace(/([^:]\\/)\\/+/g, '$1');\n\n/**\n * Set vite aliases\n */\nconst viteAliases = (aliases: [string, string][], root = ''): Alias[] =>\n aliases.map(([find, path]) => ({\n find,\n replacement: fileURLToPath(new URL(`${root}${cleanupPath(path)}`, import.meta.url)),\n }));\n\nexport default viteAliases;\n"],"names":["cleanupPath","path","replace","viteAliases","aliases","root","map","find","replacement","fileURLToPath","URL","url"],"mappings":"kDAGA,MAAMA,EAAeC,GAAiBA,EAAKC,QAAQ,KAAM,KAAKA,QAAQ,eAAgB,MAKhFC,EAAc,CAACC,EAA6BC,EAAO,KACvDD,EAAQE,KAAI,EAAEC,EAAMN,MAAW,CAC7BM,OACAC,YAAaC,EAAc,IAAIC,EAAI,GAAGL,IAAOL,EAAYC,iBAAqBU"}
@@ -0,0 +1,10 @@
1
+ import { FC, PropsWithChildren } from 'react';
2
+ import { RouteObject } from 'react-router/dist/lib/context';
3
+ declare const keys: readonly ["loader", "action", "ErrorBoundary", "errorElement"];
4
+ type IRouteParams = Pick<RouteObject, (typeof keys)[number]> & {
5
+ Suspense?: FC;
6
+ };
7
+ type FCRoute<TProps = Record<string, any>> = FC<TProps> & IRouteParams;
8
+ type FCCRoute<TProps = Record<string, any>> = FC<PropsWithChildren<TProps>> & IRouteParams;
9
+ export type { FCRoute, FCCRoute, IRouteParams };
10
+ export { keys };
@@ -0,0 +1,2 @@
1
+ const r=["loader","action","ErrorBoundary","errorElement"];export{r as keys};
2
+ //# sourceMappingURL=fc-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fc-route.js","sources":["../../src/interfaces/fc-route.ts"],"sourcesContent":["import type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router/dist/lib/context';\n\nconst keys = ['loader', 'action', 'ErrorBoundary', 'errorElement'] as const;\n\ntype IRouteParams = Pick<RouteObject, (typeof keys)[number]> & { Suspense?: FC };\n\ntype FCRoute<TProps = Record<string, any>> = FC<TProps> & IRouteParams;\ntype FCCRoute<TProps = Record<string, any>> = FC<PropsWithChildren<TProps>> & IRouteParams;\n\nexport type { FCRoute, FCCRoute, IRouteParams };\n\nexport { keys };\n"],"names":["keys"],"mappings":"AAGM,MAAAA,EAAO,CAAC,SAAU,SAAU,gBAAiB"}
@@ -0,0 +1,4 @@
1
+ import { FC, PropsWithChildren } from 'react';
2
+ type FCC<T extends Record<string, any>> = FC<PropsWithChildren<T>>;
3
+ type FCAny<T extends Record<string, any>> = FC<T> | FCC<T>;
4
+ export { FCC, FCAny };
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=fc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fc.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,8 @@
1
+ import { RouteObject } from 'react-router-dom';
2
+ import { IDynamicRoute } from "../helpers/import-route.js";
3
+ type TRouteObjectNR = Omit<RouteObject, 'lazy' | 'children'> & {
4
+ lazyNR?: IDynamicRoute;
5
+ children?: TRouteObject[];
6
+ };
7
+ type TRouteObject = RouteObject | TRouteObjectNR;
8
+ export { TRouteObjectNR, TRouteObject };
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=route-object.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-object.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/node/entry.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Express, Request } from 'express';
2
2
  import { Response as ExpressResponse } from "express";
3
3
  import { FC, PropsWithChildren } from 'react';
4
- import { RouteObject } from 'react-router-dom';
4
+ import { TRouteObject } from "../interfaces/route-object.js";
5
5
  import { IRenderOptions, TRender } from "./render.js";
6
6
  import ServerConfig from "../services/server-config.js";
7
7
  interface IInitServerRequestOut<T = Record<string, any>> {
@@ -33,5 +33,5 @@ interface IEntryServerOptions<TAppProps = Record<string, any>> {
33
33
  /**
34
34
  * Render server side application
35
35
  */
36
- declare function entry<TAppProps>(App: TApp<TAppProps>, routes: RouteObject[], { init }?: IEntryServerOptions<TAppProps>): IPrepareRenderOut<TAppProps>;
36
+ declare function entry<TAppProps>(App: TApp<TAppProps>, routes: TRouteObject[], { init }?: IEntryServerOptions<TAppProps>): IPrepareRenderOut<TAppProps>;
37
37
  export { entry as default, IInitServerRequestOut, IEntrypointOptions, IPrepareRenderOut, IAppServerProps, TApp, IEntryServerOptions };
package/node/entry.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"entry.js","sources":["../../src/node/entry.tsx"],"sourcesContent":["import type { Express, Request, Response as ExpressResponse } from 'express';\nimport type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router-dom';\nimport { createStaticHandler } from 'react-router-dom/server.mjs';\nimport type { IRenderOptions, IRenderParams, TRender } from '@node/render';\nimport render from '@node/render';\nimport type ServerConfig from '@services/server-config';\n\nexport interface IInitServerRequestOut<T = Record<string, any>> {\n appProps?: T;\n}\n\nexport interface IEntrypointOptions<TAppProps = Record<string, any>> {\n onServerCreated?: (app: Express) => Promise<void> | void;\n onRequest?: (\n req: Request,\n res: ExpressResponse,\n ) => Promise<IInitServerRequestOut<TAppProps>> | IInitServerRequestOut<TAppProps>;\n onRouterReady?: IRenderOptions<TAppProps>['onRouterReady'];\n onShellReady?: IRenderOptions<TAppProps>['onShellReady'];\n onShellError?: IRenderOptions<TAppProps>['onShellError'];\n onResponse?: IRenderOptions<TAppProps>['onResponse'];\n onError?: IRenderOptions<TAppProps>['onError'];\n getState?: IRenderOptions<TAppProps>['getState'];\n}\n\nexport interface IPrepareRenderOut<TAppProps = Record<string, any>> {\n render: TRender;\n init: IEntryServerOptions<TAppProps>['init'];\n}\n\nexport interface IAppServerProps<T = Record<string, any>> {\n server: T;\n}\n\nexport type TApp<T> = FC<PropsWithChildren<Record<string, any> & IAppServerProps<T>>>;\n\nexport interface IEntryServerOptions<TAppProps = Record<string, any>> {\n init?: (params: {\n config: ServerConfig;\n }) => IEntrypointOptions<TAppProps> | Promise<IEntrypointOptions<TAppProps>>;\n}\n\n/**\n * Render server side application\n */\nfunction entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: RouteObject[],\n { init }: IEntryServerOptions<TAppProps> = {},\n): IPrepareRenderOut<TAppProps> {\n const handler = createStaticHandler(routes);\n\n return {\n render: render.bind(null, { handler, App } as IRenderParams<TAppProps>) as TRender,\n init,\n };\n}\n\nexport default entry;\n"],"names":["entry","App","routes","init","handler","createStaticHandler","render","bind"],"mappings":"6FA8CA,SAASA,EACPC,EACAC,GACAC,KAAEA,GAAyC,CAAA,GAE3C,MAAMC,EAAUC,EAAoBH,GAEpC,MAAO,CACLI,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASH,QACrCE,OAEJ"}
1
+ {"version":3,"file":"entry.js","sources":["../../src/node/entry.tsx"],"sourcesContent":["import type { Express, Request, Response as ExpressResponse } from 'express';\nimport type { FC, PropsWithChildren } from 'react';\nimport type { RouteObject } from 'react-router-dom';\nimport { createStaticHandler } from 'react-router-dom/server.mjs';\nimport type { TRouteObject } from '@interfaces/route-object';\nimport type { IRenderOptions, IRenderParams, TRender } from '@node/render';\nimport render from '@node/render';\nimport type ServerConfig from '@services/server-config';\n\nexport interface IInitServerRequestOut<T = Record<string, any>> {\n appProps?: T;\n}\n\nexport interface IEntrypointOptions<TAppProps = Record<string, any>> {\n onServerCreated?: (app: Express) => Promise<void> | void;\n onRequest?: (\n req: Request,\n res: ExpressResponse,\n ) => Promise<IInitServerRequestOut<TAppProps>> | IInitServerRequestOut<TAppProps>;\n onRouterReady?: IRenderOptions<TAppProps>['onRouterReady'];\n onShellReady?: IRenderOptions<TAppProps>['onShellReady'];\n onShellError?: IRenderOptions<TAppProps>['onShellError'];\n onResponse?: IRenderOptions<TAppProps>['onResponse'];\n onError?: IRenderOptions<TAppProps>['onError'];\n getState?: IRenderOptions<TAppProps>['getState'];\n}\n\nexport interface IPrepareRenderOut<TAppProps = Record<string, any>> {\n render: TRender;\n init: IEntryServerOptions<TAppProps>['init'];\n}\n\nexport interface IAppServerProps<T = Record<string, any>> {\n server: T;\n}\n\nexport type TApp<T> = FC<PropsWithChildren<Record<string, any> & IAppServerProps<T>>>;\n\nexport interface IEntryServerOptions<TAppProps = Record<string, any>> {\n init?: (params: {\n config: ServerConfig;\n }) => IEntrypointOptions<TAppProps> | Promise<IEntrypointOptions<TAppProps>>;\n}\n\n/**\n * Render server side application\n */\nfunction entry<TAppProps>(\n App: TApp<TAppProps>,\n routes: TRouteObject[],\n { init }: IEntryServerOptions<TAppProps> = {},\n): IPrepareRenderOut<TAppProps> {\n const handler = createStaticHandler(routes as RouteObject[]);\n\n return {\n render: render.bind(null, { handler, App } as IRenderParams<TAppProps>) as TRender,\n init,\n };\n}\n\nexport default entry;\n"],"names":["entry","App","routes","init","handler","createStaticHandler","render","bind"],"mappings":"6FA+CA,SAASA,EACPC,EACAC,GACAC,KAAEA,GAAyC,CAAA,GAE3C,MAAMC,EAAUC,EAAoBH,GAEpC,MAAO,CACLI,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASH,QACrCE,OAEJ"}
package/node/server.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"path";import r from"compression";import o from"express";import t from"../helpers/print-server-info.js";import s from"../services/prepare-server.js";async function n(n){const i=o();if(n.setApp(i),n.isProd){const{root:t,publicDir:s,isSPA:a}=n.getParams();i.use(r()),a||i.use(((e,r,o)=>{"/index.html"===e.url&&(e.url="/index-not-found.html"),o()})),i.use(o.static(e.resolve(`${t}/${s}`),{index:!!a&&void 0}))}else{const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom"});i.use(e.middlewares),n.setVite(e)}const a=s.init(n);return n.isSPA?i.use("*",((e,r,o)=>{(async()=>{try{const o=(await a.loadHtml(e)).join("");r.send(o)}catch(e){o(e)}})()})):(await a.onAppCreated(),i.use("*",((e,r,o)=>{(async()=>{try{const[{render:o,onRequest:t,onRouterReady:s,onShellReady:i,onResponse:p,onShellError:l,onError:c,getState:d},m]=await Promise.all([a.loadEntrypoint(),a.loadHtml(e)]),{appProps:u}=await(t?.(e,r))??{},[h,f]=m,v={req:e,res:r,appProps:u??{},html:{header:h,footer:f}};await o(n,v,{onRouterReady:s,onShellReady:i,onShellError:l,onResponse:p,onError:c,getState:d})}catch(e){o(e)}})()}))),{run:({version:e,isPrintInfo:r=!0}={})=>{const{port:o,host:s}=n.getParams();n.isHost&&!n.isProd&&(n.getVite().config.server.host=s);const a=i.listen(o,s,(()=>{r&&t(a,n,{version:e})}));return a}}}export{n as default};
1
+ import e from"path";import r from"compression";import o from"express";import t from"../helpers/print-server-info.js";import s from"../services/prepare-server.js";async function n(n){const i=o();if(n.setApp(i),n.isProd){const{root:t,publicDir:s,isSPA:a}=n.getParams();i.use(r()),a||i.use(((e,r,o)=>{"/index.html"===e.url&&(e.url="/index-not-found.html"),o()})),i.use(o.static(e.resolve(`${t}/${s}`),{index:!!a&&void 0}))}else{const e=await(await import("vite")).createServer({server:{middlewareMode:!0,watch:{usePolling:!0,interval:100}},appType:"custom",mode:n.mode});i.use(e.middlewares),n.setVite(e)}const a=s.init(n);return n.isSPA?i.use("*",((e,r,o)=>{(async()=>{try{const o=(await a.loadHtml(e)).join("");r.send(o)}catch(e){o(e)}})()})):(await a.onAppCreated(),i.use("*",((e,r,o)=>{(async()=>{try{const[{render:o,onRequest:t,onRouterReady:s,onShellReady:i,onResponse:p,onShellError:l,onError:d,getState:m},c]=await Promise.all([a.loadEntrypoint(),a.loadHtml(e)]),{appProps:u}=await(t?.(e,r))??{},[h,f]=c,v={req:e,res:r,appProps:u??{},html:{header:h,footer:f}};await o(n,v,{onRouterReady:s,onShellReady:i,onShellError:l,onResponse:p,onError:d,getState:m})}catch(e){o(e)}})()}))),{run:({version:e,isPrintInfo:r=!0}={})=>{const{port:o,host:s}=n.getParams();n.isHost&&!n.isProd&&(n.getVite().config.server.host=s);const a=i.listen(o,s,(()=>{r&&t(a,n,{version:e})}));return a}}}export{n as default};
2
2
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express();\n\n config.setApp(app);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n } else {\n const { root, publicDir, isSPA } = config.getParams();\n\n app.use(compression());\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, res, next) => {\n if (req.url === '/index.html') {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n app.use(\n express.static(path.resolve(`${root}/${publicDir}`), {\n index: isSPA ? undefined : false,\n }),\n );\n }\n\n const prepareServer = PrepareServer.init(config);\n\n // SSR mode\n if (!config.isSPA) {\n await prepareServer.onAppCreated();\n\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [\n {\n render,\n onRequest,\n onRouterReady,\n onShellReady,\n onResponse,\n onShellError,\n onError,\n getState,\n },\n clientHtml,\n ] = await Promise.all([prepareServer.loadEntrypoint(), prepareServer.loadHtml(req)]);\n const { appProps } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, {\n onRouterReady,\n onShellReady,\n onShellError,\n onResponse,\n onError,\n getState,\n });\n } catch (e) {\n next(e);\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n next(e);\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = app.listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(server, config, { version });\n });\n\n return server;\n },\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","setApp","isProd","root","publicDir","isSPA","getParams","use","compression","req","res","next","url","static","path","resolve","index","undefined","vite","import","server","middlewareMode","watch","usePolling","interval","appType","middlewares","setVite","prepareServer","PrepareServer","init","html","loadHtml","join","send","e","onAppCreated","render","onRequest","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","clientHtml","Promise","all","loadEntrypoint","appProps","header","footer","context","run","version","isPrintInfo","port","host","isHost","getVite","listen","printServerInfo"],"mappings":"kKAgBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAIZ,GAFAF,EAAOG,OAAOF,GAETD,EAAOI,OAuBL,CACL,MAAMC,KAAEA,EAAIC,UAAEA,EAASC,MAAEA,GAAUP,EAAOQ,YAE1CP,EAAIQ,IAAIC,KAEHH,GAEHN,EAAIQ,KAAI,CAACE,EAAKC,EAAKC,KACD,gBAAZF,EAAIG,MACNH,EAAIG,IAAM,yBAGZD,GAAM,IAIVZ,EAAIQ,IACFP,EAAQa,OAAOC,EAAKC,QAAQ,GAAGZ,KAAQC,KAAc,CACnDY,QAAOX,QAAQY,IAGpB,KA5CmB,CAIlB,MAAMC,cACEC,OAAO,SACbtB,aAAa,CACbuB,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,WAIX1B,EAAIQ,IAAIW,EAAKQ,aAEb5B,EAAO6B,QAAQT,EAChB,CAuBD,MAAMU,EAAgBC,EAAcC,KAAKhC,GA4DzC,OAzDKA,EAAOO,MA4CVN,EAAIQ,IAAI,KAAK,CAACE,EAAKC,EAAKC,KACjB,WACH,IACE,MAAMoB,SAAcH,EAAcI,SAASvB,IAAMwB,KAAK,IAEtDvB,EAAIwB,KAAKH,EACV,CAAC,MAAOI,GACPxB,EAAKwB,EACN,CACF,EARI,EAQD,WApDAP,EAAcQ,eAEpBrC,EAAIQ,IAAI,KAAK,CAACE,EAAKC,EAAKC,KACjB,WACH,IACE,OACE0B,OACEA,EAAMC,UACNA,EAASC,cACTA,EAAaC,aACbA,EAAYC,WACZA,EAAUC,aACVA,EAAYC,QACZA,EAAOC,SACPA,GAEFC,SACQC,QAAQC,IAAI,CAACnB,EAAcoB,iBAAkBpB,EAAcI,SAASvB,MACxEwC,SAAEA,SAAoBX,IAAY7B,EAAKC,KAAS,IAC/CwC,EAAQC,GAAUN,EAEnBO,EAA2B,CAC/B3C,MACAC,MACAuC,SAAUA,GAAY,CAAE,EACxBlB,KAAM,CAAEmB,SAAQC,iBAGZd,EAAOvC,EAAQsD,EAAS,CAC5Bb,gBACAC,eACAE,eACAD,aACAE,UACAC,YAEH,CAAC,MAAOT,GACPxB,EAAKwB,EACN,CACF,EApCI,EAoCD,KAiBD,CACLkB,IAAK,EAAGC,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAAS3D,EAAOQ,YAG1BR,EAAO4D,SAAW5D,EAAOI,SAC3BJ,EAAO6D,UAAW7D,OAAOsB,OAAOqC,KAAOA,GAGzC,MAAMrC,EAASrB,EAAI6D,OAAOJ,EAAMC,GAAM,KAC/BF,GAIAM,EAAgBzC,EAAQtB,EAAQ,CAAEwD,WAAU,IAGnD,OAAOlC,CAAM,EAGnB"}
1
+ {"version":3,"file":"server.js","sources":["../../src/node/server.ts"],"sourcesContent":["import type { Server } from 'node:net';\nimport path from 'path';\nimport compression from 'compression';\nimport express from 'express';\nimport printServerInfo from '@helpers/print-server-info';\nimport type { IRequestContext } from '@node/render';\nimport PrepareServer from '@services/prepare-server';\nimport type ServerConfig from '@services/server-config';\n\nexport interface ICreateServerOut {\n run: (options?: { version?: string; isPrintInfo?: boolean }) => Server;\n}\n\n/**\n * Create SSR server\n */\nasync function createServer(config: ServerConfig): Promise<ICreateServerOut> {\n const app = express();\n\n config.setApp(app);\n\n if (!config.isProd) {\n // Create Vite server in middleware mode and configure the app type as\n // 'custom', disabling Vite's own HTML serving logic so parent server\n // can take control\n const vite = await (\n await import('vite')\n ).createServer({\n server: {\n middlewareMode: true,\n watch: {\n // During tests, we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n },\n appType: 'custom',\n mode: config.mode,\n });\n\n // Use vite's connect instance as middleware\n app.use(vite.middlewares);\n\n config.setVite(vite);\n } else {\n const { root, publicDir, isSPA } = config.getParams();\n\n app.use(compression());\n\n if (!isSPA) {\n // ignore index.html file in SSR mode\n app.use((req, res, next) => {\n if (req.url === '/index.html') {\n req.url = '/index-not-found.html';\n }\n\n next();\n });\n }\n\n app.use(\n express.static(path.resolve(`${root}/${publicDir}`), {\n index: isSPA ? undefined : false,\n }),\n );\n }\n\n const prepareServer = PrepareServer.init(config);\n\n // SSR mode\n if (!config.isSPA) {\n await prepareServer.onAppCreated();\n\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const [\n {\n render,\n onRequest,\n onRouterReady,\n onShellReady,\n onResponse,\n onShellError,\n onError,\n getState,\n },\n clientHtml,\n ] = await Promise.all([prepareServer.loadEntrypoint(), prepareServer.loadHtml(req)]);\n const { appProps } = (await onRequest?.(req, res)) ?? {};\n const [header, footer] = clientHtml;\n\n const context: IRequestContext = {\n req,\n res,\n appProps: appProps ?? {},\n html: { header, footer },\n };\n\n await render(config, context, {\n onRouterReady,\n onShellReady,\n onShellError,\n onResponse,\n onError,\n getState,\n });\n } catch (e) {\n next(e);\n }\n })();\n });\n } else {\n // SPA mode, redirect any request to index.html\n app.use('*', (req, res, next) => {\n void (async () => {\n try {\n const html = (await prepareServer.loadHtml(req)).join('');\n\n res.send(html);\n } catch (e) {\n next(e);\n }\n })();\n });\n }\n\n return {\n run: ({ version, isPrintInfo = true } = {}): Server => {\n const { port, host } = config.getParams();\n\n // update resolved host for print network link\n if (config.isHost && !config.isProd) {\n config.getVite()!.config.server.host = host;\n }\n\n const server = app.listen(port, host, () => {\n if (!isPrintInfo) {\n return;\n }\n\n void printServerInfo(server, config, { version });\n });\n\n return server;\n },\n };\n}\n\nexport default createServer;\n"],"names":["async","createServer","config","app","express","setApp","isProd","root","publicDir","isSPA","getParams","use","compression","req","res","next","url","static","path","resolve","index","undefined","vite","import","server","middlewareMode","watch","usePolling","interval","appType","mode","middlewares","setVite","prepareServer","PrepareServer","init","html","loadHtml","join","send","e","onAppCreated","render","onRequest","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","clientHtml","Promise","all","loadEntrypoint","appProps","header","footer","context","run","version","isPrintInfo","port","host","isHost","getVite","listen","printServerInfo"],"mappings":"kKAgBAA,eAAeC,EAAaC,GAC1B,MAAMC,EAAMC,IAIZ,GAFAF,EAAOG,OAAOF,GAETD,EAAOI,OAwBL,CACL,MAAMC,KAAEA,EAAIC,UAAEA,EAASC,MAAEA,GAAUP,EAAOQ,YAE1CP,EAAIQ,IAAIC,KAEHH,GAEHN,EAAIQ,KAAI,CAACE,EAAKC,EAAKC,KACD,gBAAZF,EAAIG,MACNH,EAAIG,IAAM,yBAGZD,GAAM,IAIVZ,EAAIQ,IACFP,EAAQa,OAAOC,EAAKC,QAAQ,GAAGZ,KAAQC,KAAc,CACnDY,QAAOX,QAAQY,IAGpB,KA7CmB,CAIlB,MAAMC,cACEC,OAAO,SACbtB,aAAa,CACbuB,OAAQ,CACNC,gBAAgB,EAChBC,MAAO,CAGLC,YAAY,EACZC,SAAU,MAGdC,QAAS,SACTC,KAAM5B,EAAO4B,OAIf3B,EAAIQ,IAAIW,EAAKS,aAEb7B,EAAO8B,QAAQV,EAChB,CAuBD,MAAMW,EAAgBC,EAAcC,KAAKjC,GA4DzC,OAzDKA,EAAOO,MA4CVN,EAAIQ,IAAI,KAAK,CAACE,EAAKC,EAAKC,KACjB,WACH,IACE,MAAMqB,SAAcH,EAAcI,SAASxB,IAAMyB,KAAK,IAEtDxB,EAAIyB,KAAKH,EACV,CAAC,MAAOI,GACPzB,EAAKyB,EACN,CACF,EARI,EAQD,WApDAP,EAAcQ,eAEpBtC,EAAIQ,IAAI,KAAK,CAACE,EAAKC,EAAKC,KACjB,WACH,IACE,OACE2B,OACEA,EAAMC,UACNA,EAASC,cACTA,EAAaC,aACbA,EAAYC,WACZA,EAAUC,aACVA,EAAYC,QACZA,EAAOC,SACPA,GAEFC,SACQC,QAAQC,IAAI,CAACnB,EAAcoB,iBAAkBpB,EAAcI,SAASxB,MACxEyC,SAAEA,SAAoBX,IAAY9B,EAAKC,KAAS,IAC/CyC,EAAQC,GAAUN,EAEnBO,EAA2B,CAC/B5C,MACAC,MACAwC,SAAUA,GAAY,CAAE,EACxBlB,KAAM,CAAEmB,SAAQC,iBAGZd,EAAOxC,EAAQuD,EAAS,CAC5Bb,gBACAC,eACAE,eACAD,aACAE,UACAC,YAEH,CAAC,MAAOT,GACPzB,EAAKyB,EACN,CACF,EApCI,EAoCD,KAiBD,CACLkB,IAAK,EAAGC,UAASC,eAAc,GAAS,CAAA,KACtC,MAAMC,KAAEA,EAAIC,KAAEA,GAAS5D,EAAOQ,YAG1BR,EAAO6D,SAAW7D,EAAOI,SAC3BJ,EAAO8D,UAAW9D,OAAOsB,OAAOsC,KAAOA,GAGzC,MAAMtC,EAASrB,EAAI8D,OAAOJ,EAAMC,GAAM,KAC/BF,GAIAM,EAAgB1C,EAAQtB,EAAQ,CAAEyD,WAAU,IAGnD,OAAOnC,CAAM,EAGnB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/vite-ssr-boost",
3
- "version": "1.0.0-beta.3",
3
+ "version": "1.0.0-beta.5",
4
4
  "description": "Vite plugin for create awesome SSR or SPA applications on React.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -36,8 +36,8 @@
36
36
  "commander": "^10.0.1",
37
37
  "compression": "^1.7.4",
38
38
  "express": "^4.18.2",
39
- "react-dom": "^18.2.0",
40
- "react-router-dom": "^6.12.1"
39
+ "hjson": "^3.2.2",
40
+ "hoist-non-react-statics": "^3.3.2"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@commitlint/cli": "^17.6.5",
@@ -47,6 +47,8 @@
47
47
  "@rollup/plugin-terser": "^0.4.3",
48
48
  "@types/compression": "^1.7.2",
49
49
  "@types/express": "^4.17.17",
50
+ "@types/hjson": "^2.4.3",
51
+ "@types/hoist-non-react-statics": "^3.3.1",
50
52
  "@types/react-dom": "^18.2.5",
51
53
  "@typescript-eslint/eslint-plugin": "^5.59.11",
52
54
  "@zerollup/ts-transform-paths": "^1.7.18",
@@ -68,6 +70,8 @@
68
70
  "typescript": "^4.9.5"
69
71
  },
70
72
  "peerDependencies": {
73
+ "react-dom": ">=18.2.0",
74
+ "react-router-dom": ">=6.12.1",
71
75
  "vite": "^4.3.9"
72
76
  },
73
77
  "bin": {
package/plugin.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { Plugin } from 'vite';
2
2
  import { ICliContext } from "./constants/cli-context.js";
3
+ import { IPluginOptions as IMakeAliasesPluginOptions } from "./plugins/make-aliases.js";
3
4
  interface IPluginOptions {
4
5
  indexFile?: string;
5
6
  serverFile?: string;
6
7
  abortDelay?: number;
8
+ hasLazyRoutePlugin?: boolean;
9
+ tsconfigAliases?: boolean | IMakeAliasesPluginOptions;
7
10
  customShortcuts?: {
8
11
  key: string;
9
12
  description: string;
@@ -12,8 +15,8 @@ interface IPluginOptions {
12
15
  }[];
13
16
  }
14
17
  /**
15
- * Init insane vite ssr plugin
18
+ * Init plugin
16
19
  * @constructor
17
20
  */
18
- declare function ViteSsrInsanePlugin(options?: IPluginOptions): Plugin[];
19
- export { ViteSsrInsanePlugin as default, IPluginOptions };
21
+ declare function ViteSsrBoostPlugin(options?: IPluginOptions): Plugin[];
22
+ export { ViteSsrBoostPlugin as default, IPluginOptions };
package/plugin.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:path";import n from"./constants/cli-actions.js";import t from"./constants/plugin-name.js";const i={indexFile:"index.html",serverFile:"server.ts",abortDelay:1e4};function o(o={}){const r=new URL(import.meta.url),s=global.viteBoostAction,a={...i,...o};return[{name:t,enforce:"pre",pluginOptions:{...a,pluginPath:e.dirname(r.pathname),action:s,isDev:s===n.dev},config:(e,{ssrBuild:n})=>(e.define={...e.define??{},__IS_SSR__:"1"===process.env.SSR_BOOST_IS_SSR||"dev"===s},n?{...e,publicDir:!1}:e)}]}export{o as default};
1
+ import e from"node:path";import i from"./constants/cli-actions.js";import o from"./constants/plugin-name.js";import n from"./plugins/make-aliases.js";import s from"./plugins/normalize-route.js";const t={indexFile:"index.html",serverFile:"server.ts",abortDelay:1e4,hasLazyRoutePlugin:!0,tsconfigAliases:!0};function a(a={}){const r=new URL(import.meta.url),l=global.viteBoostAction,p={...t,...a},m=[{name:o,enforce:"pre",pluginOptions:{...p,pluginPath:e.dirname(r.pathname),action:l,isDev:l===i.dev},config:(e,{ssrBuild:i})=>(e.define={...e.define??{},__IS_SSR__:"1"===process.env.SSR_BOOST_IS_SSR||"dev"===l},i?{...e,publicDir:!1}:e)}],{hasLazyRoutePlugin:u,tsconfigAliases:c}=p;return u&&m.push(s()),c&&m.push(n("boolean"==typeof c?void 0:c)),m}export{a as default};
2
2
  //# sourceMappingURL=plugin.js.map
package/plugin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Plugin } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport type { ICliContext } from '@constants/cli-context';\nimport PLUGIN_NAME from '@constants/plugin-name';\n\nexport interface IPluginOptions {\n indexFile?: string; // default: index.html\n serverFile?: string; // default: server.ts\n abortDelay?: number; // How long the server waits for data before giving up. default: 10000 (10 sec)\n customShortcuts?: {\n key: string;\n description: string;\n action: (cliContext: ICliContext) => Promise<void> | void;\n isOnlyDev?: boolean;\n }[];\n}\n\nconst defaultOptions: IPluginOptions = {\n indexFile: 'index.html',\n serverFile: 'server.ts',\n abortDelay: 10000,\n};\n\n/**\n * Init insane vite ssr plugin\n * @constructor\n */\nfunction ViteSsrInsanePlugin(options: IPluginOptions = {}): Plugin[] {\n const dirInfo = new URL(import.meta.url);\n const action = global.viteBoostAction as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n // @ts-ignore save custom options\n pluginOptions: {\n ...mergedOptions,\n pluginPath: path.dirname(dirInfo.pathname),\n action,\n isDev: action === CliActions.dev,\n },\n config(config, { ssrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: process.env.SSR_BOOST_IS_SSR === '1' || action === 'dev',\n };\n\n if (!ssrBuild) {\n return config;\n }\n\n return {\n ...config,\n publicDir: false,\n };\n },\n },\n ];\n}\n\nexport default ViteSsrInsanePlugin;\n"],"names":["defaultOptions","indexFile","serverFile","abortDelay","ViteSsrInsanePlugin","options","dirInfo","URL","url","action","global","viteBoostAction","mergedOptions","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","CliActions","dev","config","ssrBuild","define","__IS_SSR__","process","env","SSR_BOOST_IS_SSR","publicDir"],"mappings":"6GAkBA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,KAOd,SAASC,EAAoBC,EAA0B,IACrD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAASC,OAAOC,gBAChBC,EAAgC,IAAKZ,KAAmBK,GAE9D,MAAO,CACL,CACEQ,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVJ,EACHK,WAAYC,EAAKC,QAAQb,EAAQc,UACjCX,SACAY,MAAOZ,IAAWa,EAAWC,KAE/BC,OAAM,CAACA,GAAQC,SAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,GACrBC,WAA6C,MAAjCC,QAAQC,IAAIC,kBAAuC,QAAXrB,GAGjDgB,EAIE,IACFD,EACHO,WAAW,GALJP,IAUjB"}
1
+ {"version":3,"file":"plugin.js","sources":["../src/plugin.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Plugin } from 'vite';\nimport CliActions from '@constants/cli-actions';\nimport type { ICliContext } from '@constants/cli-context';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport ViteMakeAliasesPlugin from '@plugins/make-aliases';\nimport type { IPluginOptions as IMakeAliasesPluginOptions } from '@plugins/make-aliases';\nimport ViteNormalizeRouterPlugin from '@plugins/normalize-route';\n\nexport interface IPluginOptions {\n indexFile?: string; // default: index.html\n serverFile?: string; // default: server.ts\n abortDelay?: number; // How long the server waits for data before giving up. default: 10000 (10 sec)\n hasLazyRoutePlugin?: boolean; // Possibility to use custom export route component @see FCRoute interface\n tsconfigAliases?: boolean | IMakeAliasesPluginOptions; // Read aliases from tsconfig\n customShortcuts?: {\n key: string;\n description: string;\n action: (cliContext: ICliContext) => Promise<void> | void;\n isOnlyDev?: boolean;\n }[];\n}\n\nconst defaultOptions: IPluginOptions = {\n indexFile: 'index.html',\n serverFile: 'server.ts',\n abortDelay: 10000,\n hasLazyRoutePlugin: true,\n tsconfigAliases: true,\n};\n\n/**\n * Init plugin\n * @constructor\n */\nfunction ViteSsrBoostPlugin(options: IPluginOptions = {}): Plugin[] {\n const dirInfo = new URL(import.meta.url);\n const action = global.viteBoostAction as CliActions;\n const mergedOptions: IPluginOptions = { ...defaultOptions, ...options };\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n // @ts-ignore save custom options\n pluginOptions: {\n ...mergedOptions,\n pluginPath: path.dirname(dirInfo.pathname),\n action,\n isDev: action === CliActions.dev,\n },\n config(config, { ssrBuild }) {\n config.define = {\n ...(config.define ?? {}),\n __IS_SSR__: process.env.SSR_BOOST_IS_SSR === '1' || action === 'dev',\n };\n\n if (!ssrBuild) {\n return config;\n }\n\n return {\n ...config,\n publicDir: false,\n };\n },\n },\n ];\n\n const { hasLazyRoutePlugin, tsconfigAliases } = mergedOptions;\n\n if (hasLazyRoutePlugin) {\n plugins.push(ViteNormalizeRouterPlugin());\n }\n\n if (tsconfigAliases) {\n plugins.push(\n ViteMakeAliasesPlugin(typeof tsconfigAliases === 'boolean' ? undefined : tsconfigAliases),\n );\n }\n\n return plugins;\n}\n\nexport default ViteSsrBoostPlugin;\n"],"names":["defaultOptions","indexFile","serverFile","abortDelay","hasLazyRoutePlugin","tsconfigAliases","ViteSsrBoostPlugin","options","dirInfo","URL","url","action","global","viteBoostAction","mergedOptions","plugins","name","PLUGIN_NAME","enforce","pluginOptions","pluginPath","path","dirname","pathname","isDev","CliActions","dev","config","ssrBuild","define","__IS_SSR__","process","env","SSR_BOOST_IS_SSR","publicDir","push","ViteNormalizeRouterPlugin","ViteMakeAliasesPlugin","undefined"],"mappings":"kMAuBA,MAAMA,EAAiC,CACrCC,UAAW,aACXC,WAAY,YACZC,WAAY,IACZC,oBAAoB,EACpBC,iBAAiB,GAOnB,SAASC,EAAmBC,EAA0B,IACpD,MAAMC,EAAU,IAAIC,gBAAgBC,KAC9BC,EAASC,OAAOC,gBAChBC,EAAgC,IAAKd,KAAmBO,GAExDQ,EAAoB,CACxB,CACEC,KAAMC,EACNC,QAAS,MAETC,cAAe,IACVL,EACHM,WAAYC,EAAKC,QAAQd,EAAQe,UACjCZ,SACAa,MAAOb,IAAWc,EAAWC,KAE/BC,OAAM,CAACA,GAAQC,SAAEA,MACfD,EAAOE,OAAS,IACVF,EAAOE,QAAU,GACrBC,WAA6C,MAAjCC,QAAQC,IAAIC,kBAAuC,QAAXtB,GAGjDiB,EAIE,IACFD,EACHO,WAAW,GALJP,MAWTvB,mBAAEA,EAAkBC,gBAAEA,GAAoBS,EAYhD,OAVIV,GACFW,EAAQoB,KAAKC,KAGX/B,GACFU,EAAQoB,KACNE,EAAiD,kBAApBhC,OAAgCiC,EAAYjC,IAItEU,CACT"}
@@ -0,0 +1,11 @@
1
+ import { Plugin } from 'vite';
2
+ interface IPluginOptions {
3
+ root?: string;
4
+ tsconfig?: string;
5
+ }
6
+ /**
7
+ * Read tsconfig file and set vite aliases
8
+ * @constructor
9
+ */
10
+ declare function ViteMakeAliasesPlugin(options?: IPluginOptions): Plugin;
11
+ export { ViteMakeAliasesPlugin as default, IPluginOptions };
@@ -0,0 +1,2 @@
1
+ import e from"node:fs";import o from"node:path";import s from"node:process";import r from"hjson";import t from"../constants/plugin-name.js";import n from"../helpers/vite-aliases.js";const i=`${t}-make-aliases`,a=e=>e.replace("/*","");function c(t={}){const{root:c,tsconfig:p}=t,f=c??s.cwd(),m=o.resolve(f,p??"tsconfig.json"),l=[];if(e.existsSync(m)){const o=r.parse(e.readFileSync(m,{encoding:"utf-8"})),s=o?.compilerOptions?.paths??{};Object.entries(s).forEach((([e,o])=>{l.push([a(e),a(o[0])])}))}else console.error(`${i}: tsconfig not exist in "${m}"`);return{name:i,config(e){if(l.length){const o=e.resolve??{},s=o.alias??[],r=Array.isArray(s)?s:Object.entries(s).map((([e,o])=>({find:e,replacement:o})));r.push(...n(l,`${f}/${e?.root??""}`)),e.resolve={...o,alias:r}}return e}}}export{c as default};
2
+ //# sourceMappingURL=make-aliases.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make-aliases.js","sources":["../../src/plugins/make-aliases.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport Hjson from 'hjson';\nimport type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\nimport ViteAliases from '@helpers/vite-aliases';\n\nexport interface IPluginOptions {\n root?: string; // default: cwd()\n tsconfig?: string; // default: tsconfig.json\n}\n\nconst pluginName = `${PLUGIN_NAME}-make-aliases`;\nconst cleanupAlias = (str: string): string => str.replace('/*', '');\n\n/**\n * Read tsconfig file and set vite aliases\n * @constructor\n */\nfunction ViteMakeAliasesPlugin(options: IPluginOptions = {}): Plugin {\n const { root, tsconfig } = options;\n const projectRoot = root ?? process.cwd();\n const tsconfigPath = path.resolve(projectRoot, tsconfig ?? 'tsconfig.json');\n const aliases: [string, string][] = [];\n\n if (!fs.existsSync(tsconfigPath)) {\n console.error(`${pluginName}: tsconfig not exist in \"${tsconfigPath}\"`);\n } else {\n const tsJson = Hjson.parse(fs.readFileSync(tsconfigPath, { encoding: 'utf-8' }));\n const paths: Record<string, string[]> = tsJson?.compilerOptions?.paths ?? {};\n\n Object.entries(paths).forEach(([alias, aliasPaths]) => {\n aliases.push([cleanupAlias(alias), cleanupAlias(aliasPaths[0])]);\n });\n }\n\n return {\n name: pluginName,\n config(config) {\n if (aliases.length) {\n const resolveConfig = config.resolve ?? {};\n const defaultAliases = resolveConfig.alias ?? [];\n const normalizedAliases = Array.isArray(defaultAliases)\n ? defaultAliases\n : Object.entries(defaultAliases).map(([find, val]) => ({ find, replacement: val }));\n\n normalizedAliases.push(...ViteAliases(aliases, `${projectRoot}/${config?.root ?? ''}`));\n\n config.resolve = {\n ...resolveConfig,\n alias: normalizedAliases,\n };\n }\n\n return config;\n },\n };\n}\n\nexport default ViteMakeAliasesPlugin;\n"],"names":["pluginName","PLUGIN_NAME","cleanupAlias","str","replace","ViteMakeAliasesPlugin","options","root","tsconfig","projectRoot","process","cwd","tsconfigPath","path","resolve","aliases","fs","existsSync","tsJson","Hjson","parse","readFileSync","encoding","paths","compilerOptions","Object","entries","forEach","alias","aliasPaths","push","console","error","name","config","length","resolveConfig","defaultAliases","normalizedAliases","Array","isArray","map","find","val","replacement","ViteAliases"],"mappings":"sLAaA,MAAMA,EAAa,GAAGC,iBAChBC,EAAgBC,GAAwBA,EAAIC,QAAQ,KAAM,IAMhE,SAASC,EAAsBC,EAA0B,IACvD,MAAMC,KAAEA,EAAIC,SAAEA,GAAaF,EACrBG,EAAcF,GAAQG,EAAQC,MAC9BC,EAAeC,EAAKC,QAAQL,EAAaD,GAAY,iBACrDO,EAA8B,GAEpC,GAAKC,EAAGC,WAAWL,GAEZ,CACL,MAAMM,EAASC,EAAMC,MAAMJ,EAAGK,aAAaT,EAAc,CAAEU,SAAU,WAC/DC,EAAkCL,GAAQM,iBAAiBD,OAAS,CAAA,EAE1EE,OAAOC,QAAQH,GAAOI,SAAQ,EAAEC,EAAOC,MACrCd,EAAQe,KAAK,CAAC5B,EAAa0B,GAAQ1B,EAAa2B,EAAW,KAAK,GAEnE,MARCE,QAAQC,MAAM,GAAGhC,6BAAsCY,MAUzD,MAAO,CACLqB,KAAMjC,EACNkC,OAAOA,GACL,GAAInB,EAAQoB,OAAQ,CAClB,MAAMC,EAAgBF,EAAOpB,SAAW,GAClCuB,EAAiBD,EAAcR,OAAS,GACxCU,EAAoBC,MAAMC,QAAQH,GACpCA,EACAZ,OAAOC,QAAQW,GAAgBI,KAAI,EAAEC,EAAMC,MAAU,CAAED,OAAME,YAAaD,MAE9EL,EAAkBR,QAAQe,EAAY9B,EAAS,GAAGN,KAAeyB,GAAQ3B,MAAQ,OAEjF2B,EAAOpB,QAAU,IACZsB,EACHR,MAAOU,EAEV,CAED,OAAOJ,CACR,EAEL"}
@@ -0,0 +1,10 @@
1
+ import { Plugin } from 'vite';
2
+ /**
3
+ * Add possibility to export route components like FCRoute or FCCRoute
4
+ * USAGE: { path: '/', lazyNR: () => import('./pages/home') }
5
+ * @see FCRoute
6
+ * @see FCCRoute
7
+ * @constructor
8
+ */
9
+ declare function ViteNormalizeRouterPlugin(): Plugin;
10
+ export { ViteNormalizeRouterPlugin as default };
@@ -0,0 +1,2 @@
1
+ import t from"../constants/plugin-name.js";const r=r=>`import n from '${t}/helpers/import-route';${r}`.replace(/(lazyNR)(:\s*)(\(\)\s*=>\s*import\([^)]+\))/gs,"lazy$2()=>n($3)");function s(){return{name:`${t}-normalize-route`,transform:(t,s)=>{if(/^.*\.(js|ts|tsx)$/.test(s)&&(t=>/\[.*{.*path:.*lazyNR:.+import/s.test(t))(t))return{code:r(t),map:{mappings:""}}}}}export{s as default};
2
+ //# sourceMappingURL=normalize-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize-route.js","sources":["../../src/plugins/normalize-route.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport PLUGIN_NAME from '@constants/plugin-name';\n\n/**\n * Detect route file\n */\nconst isRoutesFile = (code: string): boolean => /\\[.*{.*path:.*lazyNR:.+import/s.test(code);\n\n/**\n * Add normalize wrapper to lazy imports\n */\nconst normalizeRoutes = (code: string): string =>\n `import n from '${PLUGIN_NAME}/helpers/import-route';${code}`.replace(\n /(lazyNR)(:\\s*)(\\(\\)\\s*=>\\s*import\\([^)]+\\))/gs,\n 'lazy$2()=>n($3)',\n );\n\n/**\n * Add possibility to export route components like FCRoute or FCCRoute\n * USAGE: { path: '/', lazyNR: () => import('./pages/home') }\n * @see FCRoute\n * @see FCCRoute\n * @constructor\n */\nfunction ViteNormalizeRouterPlugin(): Plugin {\n return {\n name: `${PLUGIN_NAME}-normalize-route`,\n transform: (code, id) => {\n if (!/^.*\\.(js|ts|tsx)$/.test(id) || !isRoutesFile(code)) {\n return;\n }\n\n return {\n code: normalizeRoutes(code),\n map: { mappings: '' },\n };\n },\n };\n}\n\nexport default ViteNormalizeRouterPlugin;\n"],"names":["normalizeRoutes","code","PLUGIN_NAME","replace","ViteNormalizeRouterPlugin","name","transform","id","test","isRoutesFile","map","mappings"],"mappings":"2CAMA,MAKMA,EAAmBC,GACvB,kBAAkBC,2BAAqCD,IAAOE,QAC5D,gDACA,mBAUJ,SAASC,IACP,MAAO,CACLC,KAAM,GAAGH,oBACTI,UAAW,CAACL,EAAMM,KAChB,GAAK,oBAAoBC,KAAKD,IAtBf,CAACN,GAA0B,iCAAiCO,KAAKP,GAsB1CQ,CAAaR,GAInD,MAAO,CACLA,KAAMD,EAAgBC,GACtBS,IAAK,CAAEC,SAAU,IAClB,EAGP"}
@@ -6,6 +6,7 @@ interface IConfigOptions {
6
6
  isHost?: boolean;
7
7
  isOnlyClient?: boolean;
8
8
  prodParams?: Partial<IConfigParams>;
9
+ mode?: string;
9
10
  }
10
11
  interface IConfigParams {
11
12
  root: string;
@@ -35,6 +36,10 @@ declare class ServerConfig {
35
36
  * SPA mode
36
37
  */
37
38
  readonly isSPA: boolean;
39
+ /**
40
+ * Env mode
41
+ */
42
+ readonly mode?: string;
38
43
  /**
39
44
  * Vite config - only for development
40
45
  */
@@ -61,7 +66,7 @@ declare class ServerConfig {
61
66
  /**
62
67
  * @constructor
63
68
  */
64
- protected constructor({ isProd, isHost, isOnlyClient }: IConfigOptions, prodParams: Partial<IConfigParams>);
69
+ protected constructor({ isProd, isHost, isOnlyClient, mode }: IConfigOptions, prodParams: Partial<IConfigParams>);
65
70
  /**
66
71
  * Initialize service
67
72
  */
@@ -1,2 +1,2 @@
1
- import r from"node:path";import t from"../helpers/plugin-config.js";import i from"./logger.js";class s{isProd;isHost;isSPA;vite;app;params;prodParams;logger;constructor({isProd:r=!1,isHost:t=!1,isOnlyClient:i=!1},s){this.isProd=r,this.isHost=t,this.isSPA=i,this.prodParams={root:"./build",publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",port:3e3,abortDelay:1e4,...s},this.makeParams()}static init(r={},t={}){return new s(r,t)}makeParams(){const t=this.getPluginConfig()??{},{config:s}=this.vite??{},e=s?.root??this.prodParams.root??"",o=s?.publicDir??this.prodParams.publicDir,a=new URL(import.meta.url),p=t.pluginPath??r.resolve(`../${r.dirname(a.pathname)}`),h=t.indexFile??this.prodParams.indexFile,l=t.serverFile??this.prodParams.serverFile,n="boolean"==typeof s?.server.host||this.isHost?"0.0.0.0":s?.server.host??this.prodParams.host,m=s?.server.port??(this.isProd?this.prodParams.port:5173),g=t.abortDelay??this.prodParams.abortDelay;this.params={root:e,publicDir:o,pluginPath:p,indexFile:h,serverFile:l,host:n,port:m,abortDelay:g,isSPA:this.isSPA,isProd:this.isProd},this.logger=this.vite?.config.logger??new i}setVite(r){this.vite=r,this.makeParams()}setApp(r){this.app=r}setAbortDelay(r){this.prodParams.abortDelay=r,this.params.abortDelay=r}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?t(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}}export{s as default};
1
+ import r from"node:path";import t from"../helpers/plugin-config.js";import i from"./logger.js";class s{isProd;isHost;isSPA;mode;vite;app;params;prodParams;logger;constructor({isProd:r=!1,isHost:t=!1,isOnlyClient:i=!1,mode:s},e){this.isProd=r,this.isHost=t,this.isSPA=i,this.mode=s,this.prodParams={root:"./build",publicDir:"/client",indexFile:"/client/index.html",serverFile:"/server/server.js",host:"127.0.0.1",port:3e3,abortDelay:1e4,...e},this.makeParams()}static init(r={},t={}){return new s(r,t)}makeParams(){const t=this.getPluginConfig()??{},{config:s}=this.vite??{},e=s?.root??this.prodParams.root??"",o=s?.publicDir??this.prodParams.publicDir,a=new URL(import.meta.url),h=t.pluginPath??r.resolve(`../${r.dirname(a.pathname)}`),p=t.indexFile??this.prodParams.indexFile,l=t.serverFile??this.prodParams.serverFile,n="boolean"==typeof s?.server.host||this.isHost?"0.0.0.0":s?.server.host??this.prodParams.host,m=s?.server.port??(this.isProd?this.prodParams.port:5173),d=t.abortDelay??this.prodParams.abortDelay;this.params={root:e,publicDir:o,pluginPath:h,indexFile:p,serverFile:l,host:n,port:m,abortDelay:d,isSPA:this.isSPA,isProd:this.isProd},this.logger=this.vite?.config.logger??new i}setVite(r){this.vite=r,this.makeParams()}setApp(r){this.app=r}setAbortDelay(r){this.prodParams.abortDelay=r,this.params.abortDelay=r}getVite(){return this.vite}getApp(){return this.app}getPluginConfig(){return this.vite?t(this.vite.config):void 0}getParams(){return this.params}getLogger(){return this.logger}}export{s as default};
2
2
  //# sourceMappingURL=server-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n prodParams?: Partial<IConfigParams>;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n serverFile: string;\n abortDelay: number;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * SPA mode\n */\n public readonly isSPA: boolean;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default production params\n */\n protected prodParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * @constructor\n */\n protected constructor(\n { isProd = false, isHost = false, isOnlyClient = false }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.prodParams = {\n root: './build',\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n port: 3000,\n abortDelay: 10000,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n\n const root = config?.root ?? this.prodParams.root ?? '';\n const publicDir = config?.publicDir ?? this.prodParams.publicDir!;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(`../${path.dirname(dirInfo.pathname)}`);\n const indexFile = pluginConfig.indexFile ?? this.prodParams.indexFile!;\n const serverFile = pluginConfig.serverFile ?? this.prodParams.serverFile!;\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? this.prodParams.host!;\n const port = config?.server.port ?? (this.isProd ? this.prodParams.port! : 5173);\n const abortDelay = pluginConfig.abortDelay ?? this.prodParams.abortDelay!;\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n serverFile,\n host,\n port,\n abortDelay,\n isSPA: this.isSPA,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Set custom abort delay\n */\n public setAbortDelay(ms: number): void {\n this.prodParams.abortDelay = ms;\n this.params.abortDelay = ms;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isSPA","vite","app","params","prodParams","logger","constructor","isOnlyClient","this","root","publicDir","indexFile","serverFile","host","port","abortDelay","makeParams","static","options","prodOptions","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","server","DefaultLogger","setVite","setApp","express","setAbortDelay","ms","getVite","getApp","undefined","getParams","getLogger"],"mappings":"+FA8BA,MAAMA,EAIYC,OAKAC,OAKAC,MAKNC,KAKAC,IAKAC,OAKAC,WAKAC,OAKVC,aACER,OAAEA,GAAS,EAAKC,OAAEA,GAAS,EAAKQ,aAAEA,GAAe,GACjDH,GAEAI,KAAKV,OAASA,EACdU,KAAKT,OAASA,EACdS,KAAKR,MAAQO,EACbC,KAAKJ,WAAa,CAChBK,KAAM,UACNC,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,KAAM,IACNC,WAAY,OACTX,GAGLI,KAAKQ,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAItB,EAAaqB,EAASC,EAClC,CAKSH,aACR,MAAMI,EAAgBZ,KAAKa,mBAAqB,CAAE,GAC5CC,OAAEA,GAAWd,KAAKP,MAAQ,CAAA,EAE1BQ,EAAOa,GAAQb,MAAQD,KAAKJ,WAAWK,MAAQ,GAC/CC,EAAYY,GAAQZ,WAAaF,KAAKJ,WAAWM,UACjDa,EAAU,IAAIC,gBAAgBC,KAC9BC,EACJN,EAAaM,YAAcC,EAAKC,QAAQ,MAAMD,EAAKE,QAAQN,EAAQO,aAC/DnB,EAAYS,EAAaT,WAAaH,KAAKJ,WAAWO,UACtDC,EAAaQ,EAAaR,YAAcJ,KAAKJ,WAAWQ,WACxDC,EAC2B,kBAAxBS,GAAQS,OAAOlB,MAAsBL,KAAKT,OAC7C,UACAuB,GAAQS,OAAOlB,MAAQL,KAAKJ,WAAWS,KACvCC,EAAOQ,GAAQS,OAAOjB,OAASN,KAAKV,OAASU,KAAKJ,WAAWU,KAAQ,MACrEC,EAAaK,EAAaL,YAAcP,KAAKJ,WAAWW,WAE9DP,KAAKL,OAAS,CACZM,OACAC,YACAgB,aACAf,YACAC,aACAC,OACAC,OACAC,aACAf,MAAOQ,KAAKR,MACZF,OAAQU,KAAKV,QAEfU,KAAKH,OAASG,KAAKP,MAAMqB,OAAOjB,QAAU,IAAI2B,CAC/C,CAKMC,QAAQhC,GACbO,KAAKP,KAAOA,EAEZO,KAAKQ,YACN,CAKMkB,OAAOC,GACZ3B,KAAKN,IAAMiC,CACZ,CAKMC,cAAcC,GACnB7B,KAAKJ,WAAWW,WAAasB,EAC7B7B,KAAKL,OAAOY,WAAasB,CAC1B,CAMMC,UACL,OAAO9B,KAAKP,IACb,CAKMsC,SACL,OAAO/B,KAAKN,GACb,CAMMmB,kBACL,OAAOb,KAAKP,KAAOoB,EAAgBb,KAAKP,KAAKqB,aAAUkB,CACxD,CAKMC,YACL,OAAOjC,KAAKL,MACb,CAKMuC,YACL,OAAOlC,KAAKH,MACb"}
1
+ {"version":3,"file":"server-config.js","sources":["../../src/services/server-config.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Express } from 'express';\nimport type { Logger, ViteDevServer } from 'vite';\nimport type { IPluginConfig } from '@helpers/plugin-config';\nimport getPluginConfig from '@helpers/plugin-config';\nimport DefaultLogger from '@services/logger';\n\ninterface IConfigOptions {\n isProd?: boolean;\n isHost?: boolean;\n isOnlyClient?: boolean; // SPA mode\n prodParams?: Partial<IConfigParams>;\n mode?: string;\n}\n\ninterface IConfigParams {\n root: string;\n publicDir: string;\n pluginPath: string;\n isProd: boolean;\n isSPA: boolean;\n indexFile: string;\n serverFile: string;\n abortDelay: number;\n host: string;\n port: number;\n}\n\n/**\n * Server config\n */\nclass ServerConfig {\n /**\n * Production build\n */\n public readonly isProd: boolean;\n\n /**\n * Server host mode\n */\n public readonly isHost: boolean;\n\n /**\n * SPA mode\n */\n public readonly isSPA: boolean;\n\n /**\n * Env mode\n */\n public readonly mode?: string;\n\n /**\n * Vite config - only for development\n */\n protected vite?: ViteDevServer;\n\n /**\n * Express application\n */\n protected app?: Express;\n\n /**\n * Config params\n */\n protected params: IConfigParams;\n\n /**\n * Default production params\n */\n protected prodParams: Partial<IConfigParams>;\n\n /**\n * Vite logger for dev mode or console for production\n */\n protected logger: Logger;\n\n /**\n * @constructor\n */\n protected constructor(\n { isProd = false, isHost = false, isOnlyClient = false, mode }: IConfigOptions,\n prodParams: Partial<IConfigParams>,\n ) {\n this.isProd = isProd;\n this.isHost = isHost;\n this.isSPA = isOnlyClient;\n this.mode = mode;\n this.prodParams = {\n root: './build',\n publicDir: '/client', // default for production,\n indexFile: '/client/index.html',\n serverFile: '/server/server.js',\n host: '127.0.0.1',\n port: 3000,\n abortDelay: 10000,\n ...prodParams,\n };\n\n this.makeParams();\n }\n\n /**\n * Initialize service\n */\n public static init(\n options: IConfigOptions = {},\n prodOptions: Partial<IConfigParams> = {},\n ): ServerConfig {\n return new ServerConfig(options, prodOptions);\n }\n\n /**\n * Make config params\n */\n protected makeParams(): void {\n const pluginConfig = (this.getPluginConfig() ?? {}) as Partial<IPluginConfig>;\n const { config } = this.vite ?? {};\n\n const root = config?.root ?? this.prodParams.root ?? '';\n const publicDir = config?.publicDir ?? this.prodParams.publicDir!;\n const dirInfo = new URL(import.meta.url);\n const pluginPath =\n pluginConfig.pluginPath ?? path.resolve(`../${path.dirname(dirInfo.pathname)}`);\n const indexFile = pluginConfig.indexFile ?? this.prodParams.indexFile!;\n const serverFile = pluginConfig.serverFile ?? this.prodParams.serverFile!;\n const host =\n typeof config?.server.host === 'boolean' || this.isHost\n ? '0.0.0.0'\n : config?.server.host ?? this.prodParams.host!;\n const port = config?.server.port ?? (this.isProd ? this.prodParams.port! : 5173);\n const abortDelay = pluginConfig.abortDelay ?? this.prodParams.abortDelay!;\n\n this.params = {\n root,\n publicDir,\n pluginPath,\n indexFile,\n serverFile,\n host,\n port,\n abortDelay,\n isSPA: this.isSPA,\n isProd: this.isProd,\n };\n this.logger = this.vite?.config.logger ?? new DefaultLogger();\n }\n\n /**\n * Set vite server\n */\n public setVite(vite: ViteDevServer): void {\n this.vite = vite;\n\n this.makeParams();\n }\n\n /**\n * Set express server\n */\n public setApp(express: Express): void {\n this.app = express;\n }\n\n /**\n * Set custom abort delay\n */\n public setAbortDelay(ms: number): void {\n this.prodParams.abortDelay = ms;\n this.params.abortDelay = ms;\n }\n\n /**\n * Return vite dev server\n * NOTE: only on development mode\n */\n public getVite(): ViteDevServer | undefined {\n return this.vite;\n }\n\n /**\n * Return express server\n */\n public getApp(): Express | undefined {\n return this.app;\n }\n\n /**\n * return plugin config\n * NOTE: only on development mode\n */\n public getPluginConfig(): IPluginConfig | undefined {\n return this.vite ? getPluginConfig(this.vite.config) : undefined;\n }\n\n /**\n * Return config params\n */\n public getParams(): IConfigParams {\n return this.params;\n }\n\n /**\n * Get server logger\n */\n public getLogger(): Logger {\n return this.logger;\n }\n}\n\nexport default ServerConfig;\n"],"names":["ServerConfig","isProd","isHost","isSPA","mode","vite","app","params","prodParams","logger","constructor","isOnlyClient","this","root","publicDir","indexFile","serverFile","host","port","abortDelay","makeParams","static","options","prodOptions","pluginConfig","getPluginConfig","config","dirInfo","URL","url","pluginPath","path","resolve","dirname","pathname","server","DefaultLogger","setVite","setApp","express","setAbortDelay","ms","getVite","getApp","undefined","getParams","getLogger"],"mappings":"+FA+BA,MAAMA,EAIYC,OAKAC,OAKAC,MAKAC,KAKNC,KAKAC,IAKAC,OAKAC,WAKAC,OAKVC,aACET,OAAEA,GAAS,EAAKC,OAAEA,GAAS,EAAKS,aAAEA,GAAe,EAAKP,KAAEA,GACxDI,GAEAI,KAAKX,OAASA,EACdW,KAAKV,OAASA,EACdU,KAAKT,MAAQQ,EACbC,KAAKR,KAAOA,EACZQ,KAAKJ,WAAa,CAChBK,KAAM,UACNC,UAAW,UACXC,UAAW,qBACXC,WAAY,oBACZC,KAAM,YACNC,KAAM,IACNC,WAAY,OACTX,GAGLI,KAAKQ,YACN,CAKMC,YACLC,EAA0B,GAC1BC,EAAsC,CAAA,GAEtC,OAAO,IAAIvB,EAAasB,EAASC,EAClC,CAKSH,aACR,MAAMI,EAAgBZ,KAAKa,mBAAqB,CAAE,GAC5CC,OAAEA,GAAWd,KAAKP,MAAQ,CAAA,EAE1BQ,EAAOa,GAAQb,MAAQD,KAAKJ,WAAWK,MAAQ,GAC/CC,EAAYY,GAAQZ,WAAaF,KAAKJ,WAAWM,UACjDa,EAAU,IAAIC,gBAAgBC,KAC9BC,EACJN,EAAaM,YAAcC,EAAKC,QAAQ,MAAMD,EAAKE,QAAQN,EAAQO,aAC/DnB,EAAYS,EAAaT,WAAaH,KAAKJ,WAAWO,UACtDC,EAAaQ,EAAaR,YAAcJ,KAAKJ,WAAWQ,WACxDC,EAC2B,kBAAxBS,GAAQS,OAAOlB,MAAsBL,KAAKV,OAC7C,UACAwB,GAAQS,OAAOlB,MAAQL,KAAKJ,WAAWS,KACvCC,EAAOQ,GAAQS,OAAOjB,OAASN,KAAKX,OAASW,KAAKJ,WAAWU,KAAQ,MACrEC,EAAaK,EAAaL,YAAcP,KAAKJ,WAAWW,WAE9DP,KAAKL,OAAS,CACZM,OACAC,YACAgB,aACAf,YACAC,aACAC,OACAC,OACAC,aACAhB,MAAOS,KAAKT,MACZF,OAAQW,KAAKX,QAEfW,KAAKH,OAASG,KAAKP,MAAMqB,OAAOjB,QAAU,IAAI2B,CAC/C,CAKMC,QAAQhC,GACbO,KAAKP,KAAOA,EAEZO,KAAKQ,YACN,CAKMkB,OAAOC,GACZ3B,KAAKN,IAAMiC,CACZ,CAKMC,cAAcC,GACnB7B,KAAKJ,WAAWW,WAAasB,EAC7B7B,KAAKL,OAAOY,WAAasB,CAC1B,CAMMC,UACL,OAAO9B,KAAKP,IACb,CAKMsC,SACL,OAAO/B,KAAKN,GACb,CAMMmB,kBACL,OAAOb,KAAKP,KAAOoB,EAAgBb,KAAKP,KAAKqB,aAAUkB,CACxD,CAKMC,YACL,OAAOjC,KAAKL,MACb,CAKMuC,YACL,OAAOlC,KAAKH,MACb"}